The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat(create): port the redesigned Create surface from LU Labs (1:1, local-only)
purpleeaeff3045ab7
diff --git a/src/components/create/CreateTopControls.tsx b/src/components/create/CreateTopControls.tsxdeleted file mode 100644index 488e0671..00000000--- a/src/components/create/CreateTopControls.tsx+++ /dev/null@@ -1,235 +0,0 @@-import { useEffect, useRef, useState } from 'react'-import { Image as ImageIcon, Film, Loader2, Power, ChevronDown, Check } from 'lucide-react'-import { useCreateStore } from '../../stores/createStore'-import { backendCall } from '../../api/backend'-import { classifyModel, checkComfyConnection } from '../../api/comfyui'--/**- * Create view's top controls (lives inside the app Header when the- * user is on the Create tab). Pattern mirrors the chat header:- * - Model picker — the active image OR video model, driven by- * `useCreateStore.mode`. Dropdown picks from the lists discovered- * by useCreate() (`imageModelList` / `videoModelList`).- * - Lichtschalter — green when ComfyUI is running, red when not,- * amber-with-spinner while transitioning. Click flips it.- *- * The mode switcher (Image ↔ Video) is exposed here too so the user can- * flip without scrolling down into the ParamPanel.- */-export function CreateTopControls() {- const {- mode, setMode,- imageModel, setImageModel,- videoModel, setVideoModel,- imageModelList, videoModelList,- comfyRunning, setComfyRunning,- } = useCreateStore()-- const [open, setOpen] = useState(false)- const [comfyBusy, setComfyBusy] = useState<'starting' | 'stopping' | null>(null)- const startPollRef = useRef<number | null>(null)-- // Close the dropdown when the user clicks somewhere else.- useEffect(() => {- if (!open) return- const onDoc = (e: MouseEvent) => {- const target = e.target as HTMLElement | null- if (!target || !target.closest('[data-create-top-picker]')) setOpen(false)- }- document.addEventListener('mousedown', onDoc)- return () => document.removeEventListener('mousedown', onDoc)- }, [open])-- // Heartbeat poll whenever the toggle lives in the header (independent of- // whether the full CreateView is mounted). Keeps the Lichtschalter in- // sync when the user starts/stops ComfyUI from another place (Settings,- // OS tray, etc.) without mounting the heavy useCreate hook.- useEffect(() => {- let cancelled = false- const tick = async () => {- if (cancelled) return- try {- const alive = await checkComfyConnection()- if (!cancelled) setComfyRunning(alive)- } catch { /* keep previous state */ }- }- tick() // fire once on mount- const id = window.setInterval(tick, 5000)- return () => { cancelled = true; clearInterval(id) }- }, [setComfyRunning])-- // Always clean up the start-polling interval on unmount.- useEffect(() => () => {- if (startPollRef.current != null) {- clearInterval(startPollRef.current)- startPollRef.current = null- }- }, [])-- // Bulletproof: reported on Discord by @phantomderp (2026-04-24) and- // @diimmortalis (2026-04-22) — opening the picker crashes the app when- // the list field is not an array. Can happen with stale persisted state- // from a very old LU install, Zustand rehydration racing the first render,- // a corrupted localStorage entry, or an old .exe that predates aa31bab.- // `Array.isArray` catches undefined / null / object / string — anything- // weird — and hands the render a safe empty array.- const rawList = mode === 'image' ? imageModelList : videoModelList- const activeList = Array.isArray(rawList) ? rawList : []- const activeModel = mode === 'image' ? imageModel : videoModel- const onPickModel = (name: string) => {- if (mode === 'image') {- const type = classifyModel(name)- setImageModel(name, type)- } else {- setVideoModel(name)- }- setOpen(false)- }-- const onToggleComfy = async () => {- if (comfyBusy) return- if (comfyRunning) {- setComfyBusy('stopping')- try { await backendCall('stop_comfyui') } catch { }- setComfyRunning(false)- setComfyBusy(null)- return- }-- // START path — ComfyUI's first boot takes 5–15 s (Python startup,- // model index build, etc.). The old 800 ms optimistic reset fell- // back to "red/off" before the server was ready, which the user- // correctly reported as broken. Instead: keep the amber spinner- // UNTIL checkComfyConnection() returns 200, or give up after ~60 s.- setComfyBusy('starting')- try { await backendCall('start_comfyui') } catch { /* surfaced via poll */ }-- // Stop any previous poll (in case the user mashed the button).- if (startPollRef.current != null) {- clearInterval(startPollRef.current)- startPollRef.current = null- }-- const startedAt = Date.now()- const MAX_WAIT_MS = 60_000- startPollRef.current = window.setInterval(async () => {- const alive = await checkComfyConnection()- if (alive) {- if (startPollRef.current != null) {- clearInterval(startPollRef.current)- startPollRef.current = null- }- setComfyRunning(true)- setComfyBusy(null)- } else if (Date.now() - startedAt > MAX_WAIT_MS) {- // Giving up — surface a clear red state. The user can retry.- if (startPollRef.current != null) {- clearInterval(startPollRef.current)- startPollRef.current = null- }- setComfyRunning(false)- setComfyBusy(null)- }- }, 1500)- }-- const toggleTitle = comfyBusy- ? (comfyBusy === 'starting' ? 'Starting ComfyUI…' : 'Stopping ComfyUI…')- : (comfyRunning ? 'ComfyUI running — click to stop' : 'ComfyUI stopped — click to start')-- return (- <div className="flex items-center gap-1 min-w-0" data-create-top-picker>- {/* Image / Video mode switch */}- <div className="flex items-center rounded-md border border-gray-200 dark:border-white/10 overflow-hidden">- <button- onClick={() => setMode('image')}- className={`px-2 h-[22px] flex items-center gap-1 text-[0.6rem] font-medium transition-colors ${mode === 'image'- ? 'bg-gray-200 dark:bg-white/10 text-gray-900 dark:text-white'- : 'text-gray-500 hover:text-gray-800 dark:hover:text-gray-200'- }`}- title="Image mode"- >- <ImageIcon size={11} />- <span className="hidden sm:inline">Image</span>- </button>- <button- onClick={() => setMode('video')}- className={`px-2 h-[22px] flex items-center gap-1 text-[0.6rem] font-medium transition-colors ${mode === 'video'- ? 'bg-gray-200 dark:bg-white/10 text-gray-900 dark:text-white'- : 'text-gray-500 hover:text-gray-800 dark:hover:text-gray-200'- }`}- title="Video mode"- >- <Film size={11} />- <span className="hidden sm:inline">Video</span>- </button>- </div>-- {/* Model picker */}- <div className="relative">- <button- onClick={() => setOpen((v) => !v)}- className="flex items-center gap-1 h-[22px] px-2 rounded-md text-[0.65rem] text-gray-700 dark:text-gray-200 bg-gray-100 dark:bg-white/5 hover:bg-gray-200 dark:hover:bg-white/10 transition-colors max-w-[120px] sm:max-w-[220px]"- title={activeModel || `Select ${mode} model`}- >- <span className="truncate">{activeModel || `No ${mode} model`}</span>- <ChevronDown size={10} className={open ? 'rotate-180 transition-transform' : 'transition-transform'} />- </button>-- {open && (- <div className="absolute top-[26px] right-0 min-w-[240px] max-h-[340px] overflow-y-auto rounded-md border border-gray-200 dark:border-white/10 bg-white dark:bg-[#151515] shadow-lg z-50">- {activeList.length === 0 ? (- <div className="px-3 py-2 text-[0.65rem] text-gray-500">- {comfyRunning ? `No ${mode} models installed yet` : 'Start ComfyUI to load models'}- </div>- ) : (- activeList.map((m) => (- <button- key={m.name}- onClick={() => onPickModel(m.name)}- className={`w-full text-left px-3 py-1.5 text-[0.65rem] flex items-center justify-between gap-2 transition-colors ${activeModel === m.name- ? 'bg-gray-100 dark:bg-white/10 text-gray-900 dark:text-white'- : 'text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-white/5'- }`}- >- <span className="truncate">{m.name}</span>- {activeModel === m.name && <Check size={11} />}- </button>- ))- )}- </div>- )}- </div>-- {/* ComfyUI power toggle (Lichtschalter) — same shape as the chat- header's Ollama toggle so the two look identical. */}- <button- onClick={onToggleComfy}- disabled={!!comfyBusy}- title={toggleTitle}- aria-label={toggleTitle}- className={`relative flex items-center h-[18px] w-[34px] rounded-full transition-colors duration-200 ${comfyBusy- ? 'bg-amber-500/25 border border-amber-400/40'- : comfyRunning- ? 'bg-green-500/25 border border-green-400/50'- : 'bg-red-500/20 border border-red-400/40 hover:bg-red-500/30'- }`}- >- <span- className={`absolute top-[1px] flex items-center justify-center w-[14px] h-[14px] rounded-full shadow-sm transition-all duration-200 ${comfyBusy- ? 'left-[9px] bg-amber-400'- : comfyRunning- ? 'left-[18px] bg-green-400'- : 'left-[1px] bg-red-400'- }`}- >- {comfyBusy ? (- <Loader2 size={9} className="animate-spin text-gray-900" />- ) : (- <Power size={9} className="text-gray-900" />- )}- </span>- </button>- </div>- )-}diff --git a/src/components/create/CreateView.tsx b/src/components/create/CreateView.tsxdeleted file mode 100644index 7fefbd94..00000000--- a/src/components/create/CreateView.tsx+++ /dev/null@@ -1,1066 +0,0 @@-import { useEffect, useState, useCallback, useRef } from 'react'-import { Image, Video, WifiOff, Loader2, AlertTriangle, RefreshCw, ChevronDown, FolderOpen, HardDriveDownload, CheckCircle2, XCircle, Download, Pause, Play, X as XIcon, Upload, ImagePlus, PackageOpen, FileVideo } from 'lucide-react'-import { backendCall } from '../../api/backend'-import { freeMemory, uploadImage, isI2VModel } from '../../api/comfyui'-import { startModelDownload, getDownloadProgress, pauseDownload, cancelDownload, resumeDownload } from '../../api/discover'-import { useCreate } from '../../hooks/useCreate'-import { useCreateStore } from '../../stores/createStore'-import { useUIStore } from '../../stores/uiStore'-import { Modal } from '../ui/Modal'-import { PromptInput } from './PromptInput'-import { ParamPanel } from './ParamPanel'-import { OutputDisplay } from './OutputDisplay'-import { Gallery } from './Gallery'-import { log } from '../../lib/logger'--/**- * Bug A (v2.4.5): one-click install of VHS_VideoCombine so video generation- * produces actual .mp4 files instead of animated .webp fallbacks. Pops when- * useCreate detects webpOnly capability and sets vhsInstallPrompt in the- * store; resolves with the user's choice and useCreate continues / cancels.- */-function VhsInstallModal() {- const vhsInstallPrompt = useCreateStore((s) => s.vhsInstallPrompt)- const open = vhsInstallPrompt !== null-- const choose = (choice: 'install' | 'webp' | 'cancel') => {- if (vhsInstallPrompt) vhsInstallPrompt(choice)- }-- return (- <Modal open={open} onClose={() => choose('cancel')} title="Install MP4 support?">- <div className="space-y-4 text-sm text-gray-200">- <div className="flex items-start gap-3 p-3 rounded-lg bg-yellow-500/5 border border-yellow-500/15">- <FileVideo size={18} className="text-yellow-400 shrink-0 mt-0.5" />- <div className="space-y-1.5">- <p className="text-yellow-200 font-medium text-[13px]">- Your ComfyUI doesn't have <code className="px-1 py-0.5 rounded bg-black/40 text-yellow-300 font-mono text-[11px]">VHS_VideoCombine</code>- </p>- <p className="text-[11px] text-yellow-100/80 leading-relaxed">- Without it, video generation falls back to <code className="font-mono text-[10px] bg-black/40 px-1 rounded">SaveAnimatedWEBP</code> and produces an animated <code className="font-mono text-[10px] bg-black/40 px-1 rounded">.webp</code> file instead of a real <code className="font-mono text-[10px] bg-black/40 px-1 rounded">.mp4</code> video.- </p>- </div>- </div>-- <div className="text-[11px] text-gray-400 leading-relaxed">- The installer runs <code className="font-mono bg-white/5 px-1 rounded">git clone</code> on{' '}- <a- href="https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite"- target="_blank"- rel="noreferrer"- className="text-blue-400 hover:text-blue-300 underline"- >- Kosinkadink/ComfyUI-VideoHelperSuite- </a>- {' '}(~5 MB) into your <code className="font-mono bg-white/5 px-1 rounded">ComfyUI/custom_nodes/</code> folder, runs <code className="font-mono bg-white/5 px-1 rounded">pip install</code> for its requirements, and restarts ComfyUI. Takes about 30 seconds.- </div>-- <div className="flex flex-col gap-2 pt-1">- <button- onClick={() => choose('install')}- className="w-full px-4 py-2 rounded-lg bg-blue-500/20 hover:bg-blue-500/30 border border-blue-500/30 text-blue-200 text-sm font-medium transition-colors flex items-center justify-center gap-2"- >- <Download size={14} />- Install VHS_VideoCombine + continue- </button>- <button- onClick={() => choose('webp')}- className="w-full px-4 py-2 rounded-lg bg-white/5 hover:bg-white/10 border border-white/10 text-gray-300 text-xs font-medium transition-colors"- >- Continue anyway with animated .webp- </button>- <button- onClick={() => choose('cancel')}- className="w-full px-4 py-1.5 rounded-lg hover:bg-white/5 text-gray-500 hover:text-gray-300 text-xs transition-colors"- >- Cancel generation- </button>- </div>- </div>- </Modal>- )-}--/** Inline download button — stays on Create view, shows progress with pause/cancel */-function DownloadButton({ url, subfolder, filename, onDone }: { url: string; subfolder: string; filename: string; onDone: () => void }) {- const [state, setState] = useState<'idle' | 'downloading' | 'paused' | 'done' | 'error'>('idle')- const [pct, setPct] = useState(0)- const [speed, setSpeed] = useState('')- const pollRef = useRef<ReturnType<typeof setInterval> | null>(null)-- const startPolling = () => {- if (pollRef.current) clearInterval(pollRef.current)- pollRef.current = setInterval(async () => {- try {- const prog = await getDownloadProgress()- const d = prog[filename]- if (!d) return- if (d.total > 0) setPct(Math.round(d.progress / d.total * 100))- if (d.speed > 0) setSpeed((d.speed / 1024 / 1024).toFixed(1) + ' MB/s')- if (d.status === 'complete') {- if (pollRef.current) clearInterval(pollRef.current)- setState('done')- window.dispatchEvent(new CustomEvent('comfyui-model-downloaded'))- onDone()- } else if (d.status === 'error') {- if (pollRef.current) clearInterval(pollRef.current)- setState('error')- } else if (d.status === 'paused') {- setState('paused')- } else {- setState('downloading')- }- } catch { /* keep polling */ }- }, 1500)- }-- const handleStart = async () => {- setState('downloading')- try {- await startModelDownload(url, subfolder, filename)- startPolling()- } catch { setState('error') }- }-- const handlePause = async () => {- await pauseDownload(filename)- setState('paused')- }-- const handleResume = async () => {- await resumeDownload(filename, url, subfolder)- setState('downloading')- startPolling()- }-- const handleCancel = async () => {- if (pollRef.current) clearInterval(pollRef.current)- await cancelDownload(filename)- setState('idle')- setPct(0)- }-- useEffect(() => { return () => { if (pollRef.current) clearInterval(pollRef.current) } }, [])-- if (state === 'done') return <span className="text-[9px] text-emerald-400 font-medium px-2 py-0.5">Installed</span>- if (state === 'error') return (- <button onClick={handleStart} className="shrink-0 flex items-center gap-1 px-2 py-0.5 rounded bg-red-500/20 hover:bg-red-500/30 text-red-300 text-[9px] font-medium transition-colors">- <Download size={9} /> Retry- </button>- )- if (state === 'downloading') return (- <span className="shrink-0 flex items-center gap-1 text-[9px] font-medium">- <span className="text-blue-300 min-w-[32px]">{pct}%</span>- {speed && <span className="text-gray-500">{speed}</span>}- <button onClick={handlePause} className="p-0.5 rounded hover:bg-white/10 text-yellow-400" title="Pause"><Pause size={9} /></button>- <button onClick={handleCancel} className="p-0.5 rounded hover:bg-white/10 text-red-400" title="Cancel"><XIcon size={9} /></button>- </span>- )- if (state === 'paused') return (- <span className="shrink-0 flex items-center gap-1 text-[9px] font-medium">- <span className="text-yellow-400">{pct}% paused</span>- <button onClick={handleResume} className="p-0.5 rounded hover:bg-white/10 text-emerald-400" title="Resume"><Play size={9} /></button>- <button onClick={handleCancel} className="p-0.5 rounded hover:bg-white/10 text-red-400" title="Cancel"><XIcon size={9} /></button>- </span>- )- return (- <button onClick={handleStart} className="shrink-0 flex items-center gap-1 px-2 py-0.5 rounded bg-red-500/20 hover:bg-red-500/30 text-red-300 text-[9px] font-medium transition-colors">- <Download size={9} /> Download- </button>- )-}--interface ComfyStatus {- running: boolean- starting: boolean- found: boolean- path: string | null- logs: string[]- processAlive?: boolean-}--export function CreateView() {- const {- connected, imageModels, videoModels, samplerList, schedulerList,- videoBackend, modelsLoaded, modelLoadError, checkConnection, fetchModels, runPreflight, generate, cancel,- } = useCreate()- const { mode, setMode, imageSubMode, videoSubMode, error, preflightReady, preflightErrors, preflightWarnings, videoModel, setVideoModel, i2vImage, setI2vImage, i2iImage, setI2iImage, denoise, setDenoise } = useCreateStore()-- const [status, setStatus] = useState<ComfyStatus | null>(null)- const [startupLogs, setStartupLogs] = useState<string[]>([])- const [retrying, setRetrying] = useState(false)- const [showParams, setShowParams] = useState(false)- const [comfyPathInput, setComfyPathInput] = useState('')- const [pathSaving, setPathSaving] = useState(false)- const [pathError, setPathError] = useState('')- const [installing, setInstalling] = useState(false)- const [installLogs, setInstallLogs] = useState<string[]>([])- const [installError, setInstallError] = useState('')- // P14: same Python pre-flight as the onboarding ComfyUI step. On a fresh- // Windows box `python` is the Microsoft Store stub which exit-1's- // `pip install`, leaving a half-cloned ComfyUI dir on disk. The Install- // button below now runs python_check first, kicks off install_python via- // winget if needed, and only then triggers install_comfyui.- const [pyInstalling, setPyInstalling] = useState(false)- const [pyInstallLogs, setPyInstallLogs] = useState<string[]>([])- const [pyInstallError, setPyInstallError] = useState('')- const pyInstallPollRef = useRef<ReturnType<typeof setInterval> | null>(null)- const [showConnected, setShowConnected] = useState(true)- // Bug B (v2.4.5 — dethlux GH #38): track when "ComfyUI loading..." started- // so we can swap the indefinite spinner for actionable UI after 60s. The- // process can be alive but the server never comes up (CUDA OOM, missing- // wheels, Python stub) and users were left staring at a spinner forever.- const [loadingStartedAt, setLoadingStartedAt] = useState<number | null>(null)- const [nowTick, setNowTick] = useState(Date.now())- const [showStartupLogs, setShowStartupLogs] = useState(false)- const [killing, setKilling] = useState(false)- const [i2vUploading, setI2vUploading] = useState(false)- const [i2vDragOver, setI2vDragOver] = useState(false)- const [i2vUploadError, setI2vUploadError] = useState<string | null>(null)- const [i2iUploading, setI2iUploading] = useState(false)- const [i2iDragOver, setI2iDragOver] = useState(false)- const [i2iUploadError, setI2iUploadError] = useState<string | null>(null)- const installPollRef = useRef<ReturnType<typeof setInterval> | null>(null)- const pollRef = useRef<ReturnType<typeof setInterval> | null>(null)- // Imperative refs for the file inputs. The previous label-wraps-input- // pattern relied on the browser firing a synthetic click on the- // display:none input, which silently stopped working in some Tauri 2- // webview builds (Discord reload__, GH disc #35 SadeSyu — "Upload button- // doesn't react"). Using `inputRef.current.click()` from a button onClick- // bypasses that fragility — same pattern as ChatInput's clip button.- const i2iFileInputRef = useRef<HTMLInputElement>(null)- const i2vFileInputRef = useRef<HTMLInputElement>(null)- const pollIdRef = useRef(0)- const hideTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)-- const pollStatus = useCallback(async () => {- try {- const data: ComfyStatus = await backendCall('comfyui_status')- setStatus(data)- if (data.logs?.length > 0) setStartupLogs(data.logs)-- if (data.running) {- const wasConnected = await checkConnection()- if (wasConnected) fetchModels()- return true- }- } catch {- // Status poll failed silently- }- return false- }, [checkConnection, fetchModels])-- useEffect(() => {- const id = ++pollIdRef.current- let stopped = false-- const init = async () => {- const ready = await pollStatus()- if (ready || stopped || id !== pollIdRef.current) return-- pollRef.current = setInterval(async () => {- if (stopped || id !== pollIdRef.current) {- if (pollRef.current) clearInterval(pollRef.current)- return- }- const ready = await pollStatus()- if (ready && pollRef.current) {- clearInterval(pollRef.current)- pollRef.current = null- }- }, 3000)- }- init()-- return () => {- stopped = true- if (pollRef.current) { clearInterval(pollRef.current); pollRef.current = null }- }- }, [pollStatus])-- // Auto-hide connected bar after 10s- useEffect(() => {- if (connected === true) {- setShowConnected(true)- hideTimerRef.current = setTimeout(() => setShowConnected(false), 10000)- return () => { if (hideTimerRef.current) clearTimeout(hideTimerRef.current) }- }- }, [connected])-- // Flash-attention availability (David 2026-06-11): measured 4-5x faster- // WAN-class video sampling vs pytorch SDPA on a 12 GB 3060. The backend- // probes the SAME python that runs ComfyUI (cached, real import test) and- // start_comfyui auto-passes --use-flash-attention when present — this hint- // only nudges users who don't have it. One check per connect.- const [flashAttn, setFlashAttn] = useState<{ available: boolean; reason?: string } | null>(null)- useEffect(() => {- if (connected !== true || flashAttn !== null) return- let cancelled = false- backendCall('check_flash_attention')- .then((r: { available: boolean; reason?: string }) => { if (!cancelled) setFlashAttn(r) })- .catch(() => { /* probe unavailable — show nothing */ })- return () => { cancelled = true }- }, [connected, flashAttn])-- // Track when ComfyUI loading actually started (Bug B). Reset on connect.- const isStartingNow = status?.starting || status?.processAlive- useEffect(() => {- if (isStartingNow && !connected) {- setLoadingStartedAt((prev) => prev ?? Date.now())- } else if (connected) {- setLoadingStartedAt(null)- setShowStartupLogs(false)- }- }, [isStartingNow, connected])-- // Drive the "elapsed seconds" display once a startup is in progress.- useEffect(() => {- if (loadingStartedAt === null) return- const id = setInterval(() => setNowTick(Date.now()), 1000)- return () => clearInterval(id)- }, [loadingStartedAt])-- // nowTick (1s interval) is kept only to re-evaluate the 60s "taking too- // long" threshold below — no elapsed-seconds is shown to the user anymore.- const loadingElapsedMs = loadingStartedAt ? nowTick - loadingStartedAt : 0- const loadingTooLong = loadingElapsedMs > 60_000-- const killStuckComfyui = async () => {- setKilling(true)- try {- await backendCall('stop_comfyui')- } catch { /* may already be down */ }- setLoadingStartedAt(null)- setTimeout(() => pollStatus(), 1500)- setKilling(false)- }-- const retryConnect = async () => {- setRetrying(true)- try { await backendCall('start_comfyui') } catch { /* ignore */ }- setTimeout(async () => {- await pollStatus()- setRetrying(false)- }, 3000)- }-- // Re-run preflight when mode or video model changes- useEffect(() => {- if (connected === true && modelsLoaded) {- runPreflight()- }- }, [mode, videoModel, connected, modelsLoaded, runPreflight])-- // Image-to-Video is now an explicit sub-mode (set from the main screen),- // mirroring the image T2I/I2I switch. When the user is in I2V we show the- // input-image dropzone below.- const isI2V = mode === 'video' && videoSubMode === 'i2v'-- // Keep the selected video model valid for the chosen T2V/I2V sub-mode. Runs- // on sub-mode toggle AND when the model list finishes loading, so the- // main-screen switch works without the Advanced panel being mounted.- useEffect(() => {- if (mode !== 'video' || videoModels.length === 0) return- const wantI2V = videoSubMode === 'i2v'- const filtered = videoModels.filter((m) => (wantI2V ? isI2VModel(m.name) : !isI2VModel(m.name)))- if (filtered.length === 0) return- if (!filtered.some((m) => m.name === videoModel)) {- setVideoModel(filtered[0].name)- }- }, [mode, videoSubMode, videoModels, videoModel, setVideoModel])-- const handleI2vUpload = async (file: File) => {- if (!file.type.startsWith('image/')) return- setI2vUploadError(null)- setI2vUploading(true)- try {- const filename = await uploadImage(file)- setI2vImage(filename)- } catch (err) {- // Surface the real reason in the UI, not just the log (konata 2026-06-14):- // uploadImage throws a specific message (empty/unreadable source, or- // ComfyUI's actual error body) — show it so the user sees + can report- // WHY, instead of the upload silently doing nothing.- log.error('[CreateView] I2V image upload failed', { err })- setI2vUploadError(err instanceof Error ? err.message : String(err))- }- setI2vUploading(false)- }-- const handleI2vDrop = (e: React.DragEvent) => {- e.preventDefault()- setI2vDragOver(false)- const file = e.dataTransfer.files[0]- if (file) handleI2vUpload(file)- }-- const handleI2iUpload = async (file: File) => {- if (!file.type.startsWith('image/')) return- setI2iUploadError(null)- setI2iUploading(true)- try {- const filename = await uploadImage(file)- setI2iImage(filename)- } catch (err) {- log.error('[CreateView] I2I image upload failed', { err })- setI2iUploadError(err instanceof Error ? err.message : String(err))- }- setI2iUploading(false)- }-- const handleI2iDrop = (e: React.DragEvent) => {- e.preventDefault()- setI2iDragOver(false)- const file = e.dataTransfer.files[0]- if (file) handleI2iUpload(file)- }-- const isStarting = status?.starting || status?.processAlive- const notFound = status && !status.found && !status.running-- // Empty-state when ComfyUI is connected + model scan finished but no models- // are installed for the current mode. Prevents the "click Create → crash"- // bug reported by users who opened Create without downloading a model first.- const currentModeModels = mode === 'image' ? imageModels : videoModels- const showNoModelsEmptyState = connected === true && modelsLoaded && currentModeModels.length === 0-- return (- <div className="h-full flex flex-col">- {/* Setup wizard. Also hidden during Python install so the user- doesn't see the "ComfyUI not found" panel flickering above the- Python progress card. */}- {notFound && !installing && !pyInstalling && (- <div className="border-b border-red-500/20">- <div className="p-4 bg-red-500/5 space-y-3">- <div className="flex items-center gap-2 text-red-400 text-sm font-medium">- <WifiOff size={14} />- ComfyUI not found- </div>- <div className="bg-neutral-900 rounded-lg p-4 space-y-4 border border-white/5">- <div>- <p className="text-[10px] text-gray-500 uppercase tracking-wider mb-2">Auto-install</p>- <button- onClick={async () => {- // P14 pre-flight: ensure Python is installed before- // ComfyUI's pip install. Newbies on a fresh Windows- // hit the Microsoft Store stub otherwise.- setPyInstallError('')- let pythonOk = false- try {- const probe: any = await backendCall('python_check')- pythonOk = !!probe?.available- } catch { pythonOk = false }-- if (!pythonOk) {- setPyInstalling(true)- setPyInstallLogs(['Installing Python 3.12 via winget…'])- try {- await backendCall('install_python')- } catch (err) {- setPyInstalling(false)- setPyInstallError(err instanceof Error ? err.message : 'Could not start Python install')- return- }- pythonOk = await new Promise<boolean>((resolve) => {- pyInstallPollRef.current = setInterval(async () => {- try {- const data: any = await backendCall('install_python_status')- setPyInstallLogs(data.logs || [])- if (data.status === 'complete' || data.status === 'already_installed') {- if (pyInstallPollRef.current) clearInterval(pyInstallPollRef.current)- setPyInstalling(false)- resolve(true)- } else if (data.status === 'error') {- if (pyInstallPollRef.current) clearInterval(pyInstallPollRef.current)- setPyInstalling(false)- const lastLog = (data.logs?.length ? data.logs[data.logs.length - 1] : '') as string- setPyInstallError(lastLog || 'Python install failed')- resolve(false)- }- } catch { /* keep polling */ }- }, 2000)- })- if (!pythonOk) return- }-- setInstalling(true)- setInstallError('')- setInstallLogs([])- try {- await backendCall('install_comfyui')- installPollRef.current = setInterval(async () => {- try {- const data = await backendCall('install_comfyui_status')- setInstallLogs(data.logs || [])- if (data.status === 'complete') {- if (installPollRef.current) clearInterval(installPollRef.current)- setInstalling(false)- setTimeout(() => pollStatus(), 2000)- } else if (data.status === 'error') {- if (installPollRef.current) clearInterval(installPollRef.current)- // The Rust side surfaces the actual failure as the- // last log line (`update("error", &err)` appends to- // `logs`). Falling back to "Failed" lost every- // diagnostic — users saw "ComfyUI not responding"- // with no clue that git or Python wasn't installed.- const lastLog = (data.logs?.length ? data.logs[data.logs.length - 1] : '') as string- setInstallError(lastLog || data.error || 'Install failed — see logs above for details')- setInstalling(false)- }- } catch { /* keep polling */ }- }, 2000)- } catch {- setInstallError('Failed to start')- setInstalling(false)- }- }}- className="px-3 py-1.5 rounded-lg bg-white/10 hover:bg-white/15 text-white text-xs font-medium transition-colors"- >- Install ComfyUI- </button>- </div>- <div className="border-t border-white/5 pt-3">- <p className="text-[10px] text-gray-500 uppercase tracking-wider mb-2">Manual path</p>- <div className="flex gap-2">- <div className="flex-1 relative">- <FolderOpen size={12} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-500" />- <input- value={comfyPathInput}- onChange={(e) => { setComfyPathInput(e.target.value); setPathError('') }}- placeholder="C:\ComfyUI"- className="w-full pl-8 pr-3 py-1.5 rounded-lg bg-white/5 border border-white/10 text-xs text-white placeholder-gray-600 focus:outline-none focus:border-white/20"- />- </div>- <button- onClick={async () => {- if (!comfyPathInput.trim()) { setPathError('Enter a path'); return }- setPathSaving(true)- setPathError('')- try {- const data = await backendCall('set_comfyui_path', { path: comfyPathInput.trim() })- if (data.status === 'ok') setTimeout(() => pollStatus(), 2000)- else setPathError(data.error || 'Invalid')- } catch { setPathError('Failed') }- setPathSaving(false)- }}- disabled={pathSaving}- className="px-3 py-1.5 rounded-lg bg-white/10 hover:bg-white/15 disabled:opacity-50 text-white text-xs transition-colors"- >- {pathSaving ? <Loader2 size={12} className="animate-spin" /> : 'Connect'}- </button>- </div>- {pathError && <p className="text-[10px] text-red-400 mt-1">{pathError}</p>}- </div>- </div>- </div>- </div>- )}-- {/* P14: Installing Python — shown while winget pulls Python.Python.3.12.- Sits above the ComfyUI install card so the dependency chain (Python- → ComfyUI) is visible from a single click. */}- {pyInstalling && (- <div className="border-b border-white/5">- <div className="p-3 bg-white/5 space-y-2">- <div className="flex items-center gap-2 text-gray-300 text-xs">- <Loader2 size={12} className="animate-spin" />- Installing Python 3.12 (~30 MB)...- </div>- {pyInstallLogs.length > 0 && (- <div className="bg-black rounded-lg p-2 max-h-32 overflow-y-auto font-mono text-[10px] text-gray-500">- {pyInstallLogs.slice(-10).map((log, i) => <div key={i} className="truncate">{log}</div>)}- </div>- )}- </div>- </div>- )}- {pyInstallError && !pyInstalling && (- <div className="border-b border-white/5 px-3 py-2 text-[10px] text-red-400 whitespace-pre-line">{pyInstallError}</div>- )}-- {/* Installing */}- {installing && (- <div className="border-b border-white/5">- <div className="p-3 bg-white/5 space-y-2">- <div className="flex items-center gap-2 text-gray-300 text-xs">- <Loader2 size={12} className="animate-spin" />- Installing ComfyUI...- </div>- {installLogs.length > 0 && (- <div className="bg-black rounded-lg p-2 max-h-32 overflow-y-auto font-mono text-[10px] text-gray-500">- {installLogs.slice(-10).map((log, i) => <div key={i} className="truncate">{log}</div>)}- </div>- )}- {installError && <p className="text-[10px] text-red-400">{installError}</p>}- </div>- </div>- )}-- {/* Starting — within first 60s show simple spinner;- after 60s swap to actionable "stuck" UI (Bug B / GH #38). */}- {isStarting && !connected && !loadingTooLong && (- <div className="flex items-center gap-2 px-4 py-2 bg-white/5 border-b border-white/5 text-gray-400 text-xs">- <Loader2 size={12} className="animate-spin" />- <span>ComfyUI loading...</span>- </div>- )}- {isStarting && !connected && loadingTooLong && (- <div className="border-b border-orange-500/15 bg-orange-500/5">- <div className="px-4 py-3 space-y-2 text-xs">- <div className="flex items-start justify-between gap-3">- <div className="flex items-start gap-2 text-orange-300">- <AlertTriangle size={14} className="shrink-0 mt-0.5" />- <div className="space-y-1">- <p className="font-medium">ComfyUI is taking unusually long</p>- <p className="text-[10px] text-orange-200/70 leading-relaxed">- The process is alive but its web server hasn't responded. This usually means a CUDA / PyTorch wheel mismatch, an out-of-memory crash, or a custom-node import error. Check the startup logs below before restarting — they often name the failing module.- </p>- </div>- </div>- <div className="flex items-center gap-1 shrink-0">- <button- onClick={() => setShowStartupLogs((v) => !v)}- className="px-2 py-1 rounded bg-white/10 hover:bg-white/15 text-white text-[10px] transition-colors"- >- {showStartupLogs ? 'Hide logs' : 'View logs'}- </button>- <button- onClick={killStuckComfyui}- disabled={killing}- className="flex items-center gap-1 px-2 py-1 rounded bg-red-500/20 hover:bg-red-500/30 disabled:opacity-50 text-red-200 text-[10px] transition-colors"- title="Kill the stuck ComfyUI process"- >- {killing ? <Loader2 size={10} className="animate-spin" /> : <XIcon size={10} />}- Kill process- </button>- <button- onClick={retryConnect}- disabled={retrying}- className="flex items-center gap-1 px-2 py-1 rounded bg-white/10 hover:bg-white/15 text-white text-[10px] transition-colors"- >- <RefreshCw size={10} className={retrying ? 'animate-spin' : ''} />- Restart- </button>- </div>- </div>- {showStartupLogs && (- <div className="bg-black rounded-lg p-2 max-h-48 overflow-y-auto font-mono text-[10px] text-gray-400">- {startupLogs.length > 0- ? startupLogs.slice(-30).map((log, i) => <div key={i} className="whitespace-pre-wrap break-all">{log}</div>)- : <div className="text-gray-600 italic">No startup logs captured yet — ComfyUI hasn't emitted anything to stdout.</div>}- </div>- )}- </div>- </div>- )}-- {/* Not responding — suppress while ComfyUI is being installed (the dir- appears mid-install, but the server obviously isn't up yet, so this- banner used to flash for the whole install duration which made users- think something was wrong) */}- {status && !status.running && status.found && !isStarting && !connected && !installing && (- <div className="flex items-center justify-between px-4 py-2 bg-orange-500/5 border-b border-orange-500/10 text-xs">- <div className="flex items-center gap-2 text-orange-400">- <AlertTriangle size={12} />- <span>ComfyUI not responding</span>- </div>- <button onClick={retryConnect} disabled={retrying}- className="flex items-center gap-1 px-2 py-1 rounded bg-white/10 hover:bg-white/15 text-white text-[10px] transition-colors">- <RefreshCw size={10} className={retrying ? 'animate-spin' : ''} /> Retry- </button>- </div>- )}-- {/* Connected — auto-hides after 10s */}- {connected === true && showConnected && (- <div className="flex items-center justify-between px-4 py-1.5 bg-emerald-500/5 border-b border-emerald-500/10 text-emerald-400 text-[11px] transition-opacity">- <span>{imageModels.length} model{imageModels.length !== 1 ? 's' : ''} loaded</span>- <button onClick={fetchModels} className="flex items-center gap-1 text-emerald-500/60 hover:text-emerald-400 transition-colors">- <RefreshCw size={10} /> Refresh- </button>- </div>- )}-- {/* Main content — hide while installing or while ComfyUI is missing,- since the user can't do anything with the params / gallery / prompt- input until install finishes (the install panel + the not-found- banner each provide the next-step UI on their own; showing the- mode switcher + empty gallery + dead Generate button below them- was just visual noise) */}- {!installing && !notFound && (- <div className="flex-1 flex overflow-hidden">- {/* Main content */}- <div className="flex-1 flex flex-col overflow-hidden p-4 gap-3">- {/* Mode switcher */}- <div className="flex items-center justify-between">- <div className="flex gap-0.5 p-0.5 bg-gray-100 dark:bg-white/5 rounded-lg">- <button- onClick={() => setMode('image')}- className={`flex items-center gap-1.5 px-2.5 h-[24px] rounded-md text-[0.65rem] font-medium transition-all ${- mode === 'image' ? 'bg-white dark:bg-white/10 text-gray-900 dark:text-white shadow-sm' : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'- }`}- >- <Image size={11} /> Image- </button>- <button- onClick={() => setMode('video')}- className={`flex items-center gap-1.5 px-2.5 h-[24px] rounded-md text-[0.65rem] font-medium transition-all ${- mode === 'video' ? 'bg-white dark:bg-white/10 text-gray-900 dark:text-white shadow-sm' : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'- }`}- >- <Video size={11} /> Video- </button>- </div>-- <div className="flex items-center gap-1">- {connected && (- <button- onClick={async () => {- await freeMemory()- setShowConnected(true)- // Brief flash to confirm- const el = document.getElementById('unload-btn')- if (el) { el.textContent = 'Freed!'; setTimeout(() => { el.textContent = '' }, 1500) }- }}- className="flex items-center gap-1 px-2 py-1 rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-400 hover:text-gray-700 dark:hover:text-gray-300 text-[10px] transition-colors"- title="Unload models and free memory"- aria-label="Unload models and free memory"- >- <HardDriveDownload size={12} />- <span id="unload-btn"></span>- </button>- )}- <button- onClick={() => setShowParams(!showParams)}- title={showParams ? 'Hide advanced settings' : 'Show advanced settings'}- aria-expanded={showParams}- aria-label="Toggle advanced settings"- className={`flex items-center gap-1 px-2 h-[24px] rounded-md text-[0.65rem] font-medium transition-colors ${showParams ? 'bg-gray-200 dark:bg-white/10 text-gray-800 dark:text-gray-200' : 'hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500'}`}- >- Advanced Settings- <ChevronDown size={13} className={`transition-transform ${showParams ? 'rotate-180' : ''}`} />- </button>- </div>- </div>-- {/* No models installed — show empty-state with CTA to Model Manager */}- {showNoModelsEmptyState && (- <div className="flex-1 min-h-0 flex items-center justify-center p-6">- <div className="max-w-sm w-full flex flex-col items-center text-center gap-4 rounded-xl border border-gray-200 dark:border-white/5 bg-gray-50 dark:bg-white/[0.03] p-6">- <div className="w-12 h-12 rounded-full bg-white/5 border border-white/10 flex items-center justify-center">- <PackageOpen size={22} className="text-gray-400" />- </div>- <div className="space-y-1">- <h3 className="text-sm font-medium text-gray-900 dark:text-white">- No {mode} models installed- </h3>- <p className="text-[11px] text-gray-500 dark:text-gray-400 leading-relaxed">- Install {mode === 'image' ? 'an image' : 'a video'} model from the Model Manager before you can generate.- {mode === 'image' ? ' Try Z-Image Turbo or SDXL for a quick start.' : ' Try Wan 2.1 or AnimateDiff for a quick start.'}- </p>- </div>- <button- onClick={() => useUIStore.getState().setView('models')}- className="px-4 py-1.5 rounded-lg bg-white/10 hover:bg-white/15 text-white text-xs font-medium transition-colors flex items-center gap-2"- >- <Download size={12} />- Go to Model Manager- </button>- <button- onClick={fetchModels}- className="text-[10px] text-gray-500 hover:text-gray-300 transition-colors flex items-center gap-1"- >- <RefreshCw size={10} />- Already downloaded? Refresh list- </button>- </div>- </div>- )}-- {/* Pre-flight status */}- {!showNoModelsEmptyState && connected === true && modelsLoaded && preflightReady !== null && (- <>- {preflightReady && preflightWarnings.length === 0 && (- <div className="w-full max-w-[70%] mx-auto flex items-center gap-2 px-3 py-1.5 rounded-lg bg-emerald-500/5 border border-emerald-500/10 text-emerald-400 text-[10px]">- <CheckCircle2 size={11} />- Ready to generate- </div>- )}- {preflightReady && preflightWarnings.length > 0 && (- <div className="w-full max-w-[70%] mx-auto space-y-1">- {preflightWarnings.map((w, i) => (- <div key={i} className="flex items-start gap-2 px-3 py-1.5 rounded-lg bg-yellow-500/5 border border-yellow-500/10 text-yellow-400 text-[10px]">- <AlertTriangle size={11} className="shrink-0 mt-0.5" />- <span>{w}</span>- </div>- ))}- </div>- )}- {!preflightReady && preflightErrors.length > 0 && (- <div className="w-full max-w-[70%] mx-auto space-y-1">- {preflightErrors.map((e, i) => (- <div key={i} className="flex items-center gap-2 px-3 py-1.5 rounded-lg bg-red-500/5 border border-red-500/10 text-red-400 text-[10px]">- <XCircle size={11} className="shrink-0" />- <span className="flex-1">{e.message}</span>- {e.downloadUrl && e.downloadFilename && e.downloadSubfolder && (- <DownloadButton url={e.downloadUrl!} subfolder={e.downloadSubfolder!} filename={e.downloadFilename!} onDone={() => runPreflight()} />- )}- </div>- ))}- </div>- )}- </>- )}-- {/* Video info — suppressed when empty-state is showing (redundant) */}- {!showNoModelsEmptyState && mode === 'video' && (videoBackend === 'none' || videoModels.length === 0) && connected === true && (- <div className="w-full max-w-[70%] mx-auto flex items-center gap-2 px-3 py-2 rounded-lg bg-yellow-500/5 border border-yellow-500/10 text-yellow-400 text-[11px]">- <AlertTriangle size={12} />- No video models found- </div>- )}-- {/* Flash-attention nudge — deliberately colorless/minimal (David- 2026-06-11). Only when the probe POSITIVELY said it's missing;- remote ComfyUI is excluded (we can't see that python). */}- {!showNoModelsEmptyState && mode === 'video' && connected === true && flashAttn?.available === false && flashAttn.reason !== 'remote' && (- <p className="w-full max-w-[70%] mx-auto px-1 text-[10px] leading-relaxed text-gray-500">- flash attention is not installed in ComfyUI's Python — video generation runs ~4× slower without it.{' '}- <a- href="https://huggingface.co/lldacing/flash-attention-windows-wheel"- target="_blank"- rel="noreferrer"- className="underline hover:text-gray-400"- >- prebuilt wheels- </a>- {' '}· pick the file matching your torch/CUDA/Python, pip install it into ComfyUI's Python, restart ComfyUI- </p>- )}-- {/* I2V Image Upload — shown when SVD or FramePack model is selected */}- {!showNoModelsEmptyState && isI2V && connected === true && (- <div- onDragOver={(e) => { e.preventDefault(); setI2vDragOver(true) }}- onDragLeave={() => setI2vDragOver(false)}- onDrop={handleI2vDrop}- className={`relative w-full max-w-[70%] mx-auto rounded-lg border-2 transition-colors ${- i2vDragOver- ? 'border-blue-400 bg-blue-500/10'- : i2vImage- ? 'border-emerald-500/30 bg-emerald-500/5'- : 'border-white/10 bg-white/[0.02] hover:border-white/20'- }`}- >- {i2vImage ? (- <div className="flex items-center justify-between px-3 py-2">- <div className="flex items-center gap-2 text-emerald-400 text-[11px]">- <CheckCircle2 size={12} />- <span className="truncate max-w-[200px]">{i2vImage}</span>- </div>- <div className="flex items-center gap-1">- <button- type="button"- onClick={() => i2vFileInputRef.current?.click()}- className="cursor-pointer px-2 py-0.5 rounded text-[10px] text-gray-400 hover:text-white hover:bg-white/10 transition-colors"- >- Replace- </button>- <button- onClick={() => setI2vImage(null)}- className="p-0.5 rounded text-gray-500 hover:text-red-400 hover:bg-white/10 transition-colors"- title="Remove image"- >- <XIcon size={10} />- </button>- </div>- </div>- ) : (- <button- type="button"- onClick={() => i2vFileInputRef.current?.click()}- className="w-full flex flex-col items-center gap-1 px-3 py-3 cursor-pointer focus:outline-none"- >- {i2vUploading ? (- <Loader2 size={16} className="animate-spin text-gray-400" />- ) : (- <ImagePlus size={16} className="text-gray-500" />- )}- <span className="text-[11px] text-gray-400">- {i2vUploading ? 'Uploading...' : 'Drop or click to upload input image'}- </span>- <span className="text-[9px] text-gray-600">- Image-to-Video: animates your input image guided by the prompt- </span>- </button>- )}- {i2vUploadError && (- <p className="px-3 pb-2 text-[10px] text-red-400 leading-snug break-words">{i2vUploadError}</p>- )}- <input- ref={i2vFileInputRef}- type="file" accept="image/*"- className="sr-only"- onChange={(e) => { const f = e.target.files?.[0]; if (f) handleI2vUpload(f); e.target.value = '' }}- />- </div>- )}-- {/* I2I Image Upload + Denoise Slider — shown when Image sub-tab is "Image to Image" */}- {!showNoModelsEmptyState && mode === 'image' && imageSubMode === 'img2img' && connected === true && (- <div className="w-full max-w-[70%] mx-auto space-y-2">- <div- onDragOver={(e) => { e.preventDefault(); setI2iDragOver(true) }}- onDragLeave={() => setI2iDragOver(false)}- onDrop={handleI2iDrop}- className={`relative rounded-lg border-2 transition-colors ${- i2iDragOver- ? 'border-blue-400 bg-blue-500/10'- : i2iImage- ? 'border-emerald-500/30 bg-emerald-500/5'- : 'border-white/10 bg-white/[0.02] hover:border-white/20'- }`}- >- {i2iImage ? (- <div className="flex items-center justify-between px-3 py-2">- <div className="flex items-center gap-2 text-emerald-400 text-[11px]">- <CheckCircle2 size={12} />- <span className="truncate max-w-[200px]">{i2iImage}</span>- </div>- <div className="flex items-center gap-1">- <button- type="button"- onClick={() => i2iFileInputRef.current?.click()}- className="cursor-pointer px-2 py-0.5 rounded text-[10px] text-gray-400 hover:text-white hover:bg-white/10 transition-colors"- >- Replace- </button>- <input- ref={i2iFileInputRef}- type="file" accept="image/*"- className="sr-only"- onChange={(e) => { const f = e.target.files?.[0]; if (f) handleI2iUpload(f); e.target.value = '' }}- />- <button- onClick={() => setI2iImage(null)}- className="p-0.5 rounded text-gray-500 hover:text-red-400 hover:bg-white/10 transition-colors"- title="Remove image"- >- <XIcon size={10} />- </button>- </div>- </div>- ) : (- <button- type="button"- onClick={() => i2iFileInputRef.current?.click()}- className="w-full flex flex-col items-center gap-1 px-3 py-3 cursor-pointer focus:outline-none"- >- {i2iUploading ? (- <Loader2 size={16} className="animate-spin text-gray-400" />- ) : (- <Upload size={16} className="text-gray-500" />- )}- <span className="text-[11px] text-gray-400">- {i2iUploading ? 'Uploading...' : 'Drop or click to upload source image'}- </span>- <span className="text-[9px] text-gray-600">- Image-to-Image: transforms your image guided by the prompt- </span>- <input- ref={i2iFileInputRef}- type="file" accept="image/*"- className="sr-only"- onChange={(e) => { const f = e.target.files?.[0]; if (f) handleI2iUpload(f); e.target.value = '' }}- />- </button>- )}- {i2iUploadError && (- <p className="px-3 pb-2 text-[10px] text-red-400 leading-snug break-words">{i2iUploadError}</p>- )}- </div>-- {/* Denoise Strength Slider */}- <div className="flex items-center gap-3 px-1">- <span className="text-[10px] text-gray-500 whitespace-nowrap">Denoise</span>- <input- type="range"- min={0} max={1} step={0.05}- value={denoise}- onChange={(e) => setDenoise(parseFloat(e.target.value))}- className="flex-1 h-1 accent-blue-500"- />- <span className="text-[10px] text-gray-400 font-mono w-8 text-right">{denoise.toFixed(2)}</span>- </div>- </div>- )}-- {/* Output area — slightly wider than the composer below it, both- centered like the chat column (David 2026-06-11) */}- {!showNoModelsEmptyState && (- <div className="flex-1 min-h-0 w-full max-w-[80%] mx-auto rounded-xl border border-gray-200 dark:border-white/5 bg-gray-100 dark:bg-white/[0.03] overflow-hidden flex flex-col">- <OutputDisplay />- <Gallery />- </div>- )}-- {/* Error */}- {!showNoModelsEmptyState && error && (- <div className="w-full max-w-[70%] mx-auto flex items-center gap-2 px-3 py-2 rounded-lg bg-red-500/5 border border-red-500/10 text-red-400 text-[11px]">- <AlertTriangle size={12} className="shrink-0" />- <span className="truncate">{error}</span>- </div>- )}-- {/* Prompt */}- {!showNoModelsEmptyState && (- <PromptInput onGenerate={generate} onCancel={cancel} disabled={!connected || !modelsLoaded} imageModels={imageModels} videoModels={videoModels} />- )}- </div>-- {/* Parameter sidebar — desktop. Gated on showParams so Create starts- with Advanced COLLAPSED (David: "Advanced bei Create immer- eingeklappt"); the toggle in the top controls opens it. */}- {!showNoModelsEmptyState && showParams && (- <div className="w-56 border-l border-gray-200 dark:border-white/5 bg-gray-50 dark:bg-white/[0.03] p-3 overflow-y-auto scrollbar-thin hidden lg:block">- <p className="text-[10px] font-medium text-gray-600 uppercase tracking-widest mb-3">Parameters</p>- <ParamPanel- imageModels={imageModels}- videoModels={videoModels}- samplerList={samplerList}- schedulerList={schedulerList}- modelsLoaded={modelsLoaded}- modelLoadError={modelLoadError}- onRetryModels={fetchModels}- />- </div>- )}-- {/* Parameter sidebar — mobile */}- {!showNoModelsEmptyState && showParams && (- <div className="fixed inset-0 z-40 lg:hidden" onClick={() => setShowParams(false)}>- <div className="absolute inset-0 bg-black/60" />- <div className="absolute right-0 top-0 h-full w-64 bg-white dark:bg-[#2d2d2d] border-l border-gray-200 dark:border-white/5 p-3 overflow-y-auto"- onClick={(e) => e.stopPropagation()}>- <div className="flex items-center justify-between mb-3">- <p className="text-[10px] font-medium text-gray-600 uppercase tracking-widest">Parameters</p>- <button onClick={() => setShowParams(false)} className="p-1 text-gray-500 hover:text-gray-300" aria-label="Close settings panel">- <XIcon size={12} />- </button>- </div>- <ParamPanel- imageModels={imageModels}- videoModels={videoModels}- samplerList={samplerList}- schedulerList={schedulerList}- modelsLoaded={modelsLoaded}- />- </div>- </div>- )}- </div>- )}- <VhsInstallModal />- </div>- )-}diff --git a/src/components/create/Gallery.tsx b/src/components/create/Gallery.tsxdeleted file mode 100644index 242df975..00000000--- a/src/components/create/Gallery.tsx+++ /dev/null@@ -1,152 +0,0 @@-import { useState } from 'react'-import { motion, AnimatePresence } from 'framer-motion'-import { Trash2, Download, ChevronDown, ChevronUp } from 'lucide-react'-import { getImageUrl } from '../../api/comfyui'-import { downloadComfyFile } from '../../api/backend'-import { useCreateStore, type GalleryItem } from '../../stores/createStore'-import { MediaViewer } from './MediaViewer'--const PAGE_SIZE = 20--export function Gallery() {- const { gallery, removeFromGallery, clearGallery } = useCreateStore()- const [expanded, setExpanded] = useState(true)- const [page, setPage] = useState(0)- const [viewerIndex, setViewerIndex] = useState<number | null>(null)-- if (gallery.length === 0) {- return (- <div className="border-t border-gray-200 dark:border-white/5 px-4 py-3">- <p className="text-xs text-gray-400 text-center">No images generated yet</p>- </div>- )- }-- const totalPages = Math.ceil(gallery.length / PAGE_SIZE)- const visible = gallery.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE)-- const handleDownload = (item: GalleryItem) => {- downloadComfyFile(item.filename, item.subfolder)- }-- return (- <>- <div className="border-t border-gray-200 dark:border-white/5">- {/* Header */}- <button- onClick={() => setExpanded(!expanded)}- className="flex items-center justify-between w-full px-4 py-2 text-xs font-medium text-gray-500 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-white/5 transition-colors"- aria-label="Toggle gallery"- >- <span>Gallery ({gallery.length})</span>- <div className="flex items-center gap-2">- {gallery.length > 0 && (- <span- onClick={(e) => { e.stopPropagation(); if (confirm('Clear all gallery items?')) clearGallery() }}- className="text-red-400 hover:text-red-500 transition-colors"- role="button"- aria-label="Clear gallery"- >- Clear- </span>- )}- {expanded ? <ChevronDown size={14} /> : <ChevronUp size={14} />}- </div>- </button>-- <AnimatePresence>- {expanded && (- <motion.div- initial={{ height: 0 }}- animate={{ height: 'auto' }}- exit={{ height: 0 }}- className="overflow-hidden"- >- <div className="flex gap-2 overflow-x-auto scrollbar-thin px-4 pb-3">- {visible.map((item, i) => {- // Stable URL (item's createdAt token) → no per-render refetch.- const url = getImageUrl(item.filename, item.subfolder, 'output', item.createdAt)- return (- <motion.div- key={item.id}- className="relative group shrink-0 cursor-pointer rounded-lg overflow-hidden border border-transparent hover:border-[rgba(160,148,248,0.6)] transition-colors"- initial={{ opacity: 0, scale: 0.9 }}- animate={{ opacity: 1, scale: 1 }}- transition={{ delay: i * 0.02 }}- onClick={() => setViewerIndex(page * PAGE_SIZE + i)}- title="Open"- >- {item.type === 'video' ? (- <video- src={url}- className="w-20 h-20 object-cover"- muted- playsInline- onMouseEnter={(e) => e.currentTarget.play()}- onMouseLeave={(e) => { e.currentTarget.pause(); e.currentTarget.currentTime = 0 }}- />- ) : (- <img src={url} alt="" className="w-20 h-20 object-cover" loading="lazy" />- )}- <div className="absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1">- <button- onClick={(e) => { e.stopPropagation(); handleDownload(item) }}- className="p-1.5 rounded bg-white/20 text-white hover:bg-white/30"- title="Download"- aria-label="Download image"- >- <Download size={12} />- </button>- <button- onClick={(e) => { e.stopPropagation(); removeFromGallery(item.id) }}- className="p-1.5 rounded bg-red-500/50 text-white hover:bg-red-500/70"- title="Delete"- aria-label="Delete image"- >- <Trash2 size={12} />- </button>- </div>- </motion.div>- )- })}- </div>-- {/* Pagination */}- {totalPages > 1 && (- <div className="flex items-center justify-center gap-2 px-4 pb-2 text-xs text-gray-400">- <button- onClick={() => setPage(Math.max(0, page - 1))}- disabled={page === 0}- className="disabled:opacity-30"- aria-label="Previous page"- >- Prev- </button>- <span>{page + 1} / {totalPages}</span>- <button- onClick={() => setPage(Math.min(totalPages - 1, page + 1))}- disabled={page >= totalPages - 1}- className="disabled:opacity-30"- aria-label="Next page"- >- Next- </button>- </div>- )}-- </motion.div>- )}- </AnimatePresence>- </div>-- {/* Media Viewer */}- {viewerIndex !== null && (- <MediaViewer- gallery={gallery}- initialIndex={viewerIndex}- onClose={() => setViewerIndex(null)}- />- )}- </>- )-}diff --git a/src/components/create/MediaViewer.tsx b/src/components/create/MediaViewer.tsxdeleted file mode 100644index edd521ec..00000000--- a/src/components/create/MediaViewer.tsx+++ /dev/null@@ -1,284 +0,0 @@-import { useState, useEffect, useRef, useCallback } from 'react'-import { createPortal } from 'react-dom'-import { motion, AnimatePresence } from 'framer-motion'-import { X, Download, ChevronLeft, ChevronRight, ZoomIn, ZoomOut, Info } from 'lucide-react'-import { getImageUrl } from '../../api/comfyui'-import { downloadComfyFile } from '../../api/backend'-import type { GalleryItem } from '../../stores/createStore'--interface Props {- gallery: GalleryItem[]- initialIndex: number- onClose: () => void-}--const MIN_ZOOM = 1-const MAX_ZOOM = 5--// Small round icon button used across the viewer chrome.-function IconBtn({- children, title, onClick, active = false,-}: { children: React.ReactNode; title: string; onClick: () => void; active?: boolean }) {- return (- <button- onClick={onClick}- title={title}- aria-label={title}- className={`p-2 rounded-full backdrop-blur transition-colors ${- active- ? 'bg-[rgba(160,148,248,0.28)] text-white ring-1 ring-[rgba(160,148,248,0.5)]'- : 'bg-white/10 text-white/90 hover:bg-white/20'- }`}- >- {children}- </button>- )-}--function NavBtn({ side, onClick }: { side: 'left' | 'right'; onClick: () => void }) {- return (- <button- onClick={(e) => { e.stopPropagation(); onClick() }}- aria-label={side === 'left' ? 'Previous' : 'Next'}- className={`absolute ${side === 'left' ? 'left-3' : 'right-3'} top-1/2 -translate-y-1/2 z-20 p-3 rounded-full bg-black/40 text-white/90 hover:bg-black/70 backdrop-blur transition-colors`}- >- {side === 'left' ? <ChevronLeft size={24} /> : <ChevronRight size={24} />}- </button>- )-}--function Meta({ k, v, wide = false }: { k: string; v: string; wide?: boolean }) {- return (- <span className={wide ? 'w-full sm:w-auto sm:max-w-[40ch] truncate' : ''}>- <b className="text-white/80 font-medium">{k}:</b> {v}- </span>- )-}--export function MediaViewer({ gallery, initialIndex, onClose }: Props) {- const [index, setIndex] = useState(initialIndex)- const [zoom, setZoom] = useState(1)- const [pan, setPan] = useState({ x: 0, y: 0 })- const [dragging, setDragging] = useState(false)- const [showInfo, setShowInfo] = useState(false)- const [closing, setClosing] = useState(false)- // The URL whose media has finished loading. `ready` compares it to the- // current url synchronously, so a freshly-navigated item is at opacity 0- // from its very first render until it decodes (no flash of an empty frame).- const [loadedUrl, setLoadedUrl] = useState('')- const dragStart = useRef({ x: 0, y: 0 })- const panStart = useRef({ x: 0, y: 0 })- const stageRef = useRef<HTMLDivElement>(null)-- // Clamp so a deleted item (gallery shrank under us) never indexes out of range.- const safeIndex = Math.max(0, Math.min(index, gallery.length - 1))- const item = gallery[safeIndex] as GalleryItem | undefined- const isVideo = item?.type === 'video'-- // Stable URL: keyed on the item's immutable createdAt, so the string is- // identical across every re-render (zoom/pan/mouse-move) → no refetch, no- // flicker. Empty when the gallery has emptied out.- const url = item ? getImageUrl(item.filename, item.subfolder, 'output', item.createdAt) : ''- const ready = !!url && loadedUrl === url-- const resetView = useCallback(() => { setZoom(1); setPan({ x: 0, y: 0 }) }, [])-- // Fade out first, then unmount via onClose (gives a smooth close without- // relying on a parent <AnimatePresence>, which the old code mis-used).- const requestClose = useCallback(() => setClosing(true), [])-- const navigate = useCallback((dir: 1 | -1) => {- setIndex((i) => {- const next = i + dir- if (next < 0 || next > gallery.length - 1) return i- return next- })- resetView()- }, [gallery.length, resetView])-- // If the gallery empties while open, close cleanly.- useEffect(() => { if (!item && !closing) requestClose() }, [item, closing, requestClose])-- // Keyboard navigation + zoom.- useEffect(() => {- const handler = (e: KeyboardEvent) => {- switch (e.key) {- case 'Escape': requestClose(); break- case 'ArrowLeft': navigate(-1); break- case 'ArrowRight': navigate(1); break- case '+': case '=': setZoom((z) => Math.min(z + 0.5, MAX_ZOOM)); break- case '-': case '_':- setZoom((z) => {- const n = Math.max(z - 0.5, MIN_ZOOM)- if (n <= 1) setPan({ x: 0, y: 0 })- return n- })- break- case '0': resetView(); break- }- }- window.addEventListener('keydown', handler)- return () => window.removeEventListener('keydown', handler)- }, [navigate, requestClose, resetView])-- // Wheel zoom via a non-passive native listener so preventDefault actually- // works (React's synthetic onWheel is passive → preventDefault is a no-op +- // console error). The overlay is fixed full-screen, so we suppress the- // underlying scroll entirely.- useEffect(() => {- const el = stageRef.current- if (!el) return- const onWheel = (e: WheelEvent) => {- e.preventDefault()- const delta = e.deltaY > 0 ? -0.25 : 0.25- setZoom((z) => {- const n = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, z + delta))- if (n <= 1) setPan({ x: 0, y: 0 })- return n- })- }- el.addEventListener('wheel', onWheel, { passive: false })- return () => el.removeEventListener('wheel', onWheel)- }, [])-- // Pan (only meaningful while zoomed in).- const onMouseDown = (e: React.MouseEvent) => {- if (zoom <= 1) return- e.preventDefault()- setDragging(true)- dragStart.current = { x: e.clientX, y: e.clientY }- panStart.current = { ...pan }- }- const onMouseMove = (e: React.MouseEvent) => {- if (!dragging) return- setPan({- x: panStart.current.x + (e.clientX - dragStart.current.x),- y: panStart.current.y + (e.clientY - dragStart.current.y),- })- }- const endDrag = () => setDragging(false)-- const content = (- <motion.div- initial={{ opacity: 0 }}- animate={{ opacity: closing ? 0 : 1 }}- transition={{ duration: 0.18, ease: 'easeOut' }}- onAnimationComplete={() => { if (closing) onClose() }}- className="fixed inset-0 z-[100] flex flex-col bg-[#0b0b0e]/95 backdrop-blur-md"- onMouseMove={onMouseMove}- onMouseUp={endDrag}- onMouseLeave={endDrag}- >- {/* Top scrim keeps the controls readable over bright images. */}- <div className="absolute inset-x-0 top-0 h-24 bg-gradient-to-b from-black/55 to-transparent pointer-events-none z-10" />-- {/* Top bar */}- <div className="relative flex items-center justify-between px-4 py-3 z-20">- <div className="flex items-center gap-2 text-white/70 text-xs">- <span className="tabular-nums">{safeIndex + 1} / {gallery.length}</span>- {isVideo && (- <span className="px-1.5 py-0.5 rounded bg-white/10 text-[10px] uppercase tracking-wider text-white/60">Video</span>- )}- </div>- <div className="flex items-center gap-1.5">- {!isVideo && (- <>- <IconBtn title="Zoom out (−)" onClick={() => setZoom((z) => {- const n = Math.max(MIN_ZOOM, z - 0.5)- if (n <= 1) setPan({ x: 0, y: 0 })- return n- })}>- <ZoomOut size={17} />- </IconBtn>- <span className="text-white/55 text-xs w-11 text-center tabular-nums">{Math.round(zoom * 100)}%</span>- <IconBtn title="Zoom in (+)" onClick={() => setZoom((z) => Math.min(MAX_ZOOM, z + 0.5))}>- <ZoomIn size={17} />- </IconBtn>- <div className="w-px h-5 bg-white/15 mx-1" />- </>- )}- <IconBtn title="Info" active={showInfo} onClick={() => setShowInfo((s) => !s)}>- <Info size={17} />- </IconBtn>- <IconBtn title="Download" onClick={() => item && downloadComfyFile(item.filename, item.subfolder)}>- <Download size={17} />- </IconBtn>- <IconBtn title="Close (Esc)" onClick={requestClose}>- <X size={17} />- </IconBtn>- </div>- </div>-- {/* Stage */}- <div- ref={stageRef}- className="flex-1 flex items-center justify-center overflow-hidden relative select-none"- onClick={(e) => { if (e.target === e.currentTarget) requestClose() }}- >- {safeIndex > 0 && <NavBtn side="left" onClick={() => navigate(-1)} />}- {safeIndex < gallery.length - 1 && <NavBtn side="right" onClick={() => navigate(1)} />}-- {item && (isVideo ? (- <video- key={item.id}- src={url}- controls- autoPlay- loop- playsInline- className="max-w-[92vw] max-h-[82vh] rounded-lg shadow-2xl bg-black"- onLoadedData={() => setLoadedUrl(url)}- onClick={(e) => e.stopPropagation()}- style={{ opacity: ready ? 1 : 0, transition: 'opacity 0.2s ease-out' }}- />- ) : (- <img- key={item.id}- src={url}- alt={item.prompt}- onLoad={() => setLoadedUrl(url)}- draggable={false}- onMouseDown={onMouseDown}- className="max-w-[92vw] max-h-[82vh] object-contain rounded-lg shadow-2xl"- style={{- transform: `scale(${zoom}) translate(${pan.x / zoom}px, ${pan.y / zoom}px)`,- transition: dragging ? 'none' : 'transform 0.16s ease-out, opacity 0.2s ease-out',- opacity: ready ? 1 : 0,- cursor: zoom > 1 ? (dragging ? 'grabbing' : 'grab') : 'default',- }}- />- ))}- </div>-- {/* Info panel */}- <AnimatePresence>- {showInfo && item && (- <motion.div- initial={{ height: 0, opacity: 0 }}- animate={{ height: 'auto', opacity: 1 }}- exit={{ height: 0, opacity: 0 }}- transition={{ duration: 0.18 }}- className="relative z-20 overflow-hidden border-t border-white/10 bg-black/40 backdrop-blur"- >- <div className="px-6 py-3 flex flex-wrap gap-x-6 gap-y-1.5 text-xs text-white/55">- <Meta k="Prompt" v={item.prompt} wide />- {item.negativePrompt && <Meta k="Negative" v={item.negativePrompt} wide />}- <Meta k="Model" v={item.model} />- <Meta k="Size" v={`${item.width}×${item.height}`} />- <Meta k="Steps" v={String(item.steps)} />- <Meta k="CFG" v={String(item.cfgScale)} />- <Meta k="Sampler" v={`${item.sampler}/${item.scheduler}`} />- <Meta k="Seed" v={String(item.seed)} />- {item.builderUsed && <Meta k="Builder" v={item.builderUsed} />}- </div>- </motion.div>- )}- </AnimatePresence>- </motion.div>- )-- // Render into <body> so no ancestor transform/zoom/overflow (e.g. the +25%- // sidebar zoom, or a framer-motion scale animation) can break the fixed- // overlay's sizing/position.- return createPortal(content, document.body)-}diff --git a/src/components/create/OutputDisplay.tsx b/src/components/create/OutputDisplay.tsxdeleted file mode 100644index f8b13212..00000000--- a/src/components/create/OutputDisplay.tsx+++ /dev/null@@ -1,220 +0,0 @@-import { useState } from 'react'-import { motion } from 'framer-motion'-import { Download, Maximize2, Copy, Check, RefreshCw, HardDrive, Brain, Cpu, Zap } from 'lucide-react'-import { getImageUrl } from '../../api/comfyui'-import { downloadComfyFile } from '../../api/backend'-import { useCreateStore, type GalleryItem } from '../../stores/createStore'-import { MediaViewer } from './MediaViewer'--export function OutputDisplay() {- const { isGenerating, progress, progressText, progressPhase, gallery } = useCreateStore()- const [viewerIndex, setViewerIndex] = useState<number | null>(null)- const [copiedSeed, setCopiedSeed] = useState(false)- // Gate the result media's fade-in on its own load so a freshly-finished- // generation never shows a half-painted frame. Keyed by item id so it- // auto-resets when a new result arrives.- const [loadedId, setLoadedId] = useState<string | null>(null)- const latest = gallery[0]-- const handleDownload = (item: GalleryItem) => {- downloadComfyFile(item.filename, item.subfolder)- }-- const copySeed = (seed: number) => {- navigator.clipboard.writeText(String(seed))- setCopiedSeed(true)- setTimeout(() => setCopiedSeed(false), 1500)- }-- // Phase-aware icon- const phaseIcon = () => {- switch (progressPhase) {- case 'loading-model': return <HardDrive size={20} className="text-amber-400" />- case 'loading-clip': return <Brain size={20} className="text-blue-400" />- case 'loading-vae': return <Cpu size={20} className="text-purple-400" />- case 'sampling': return <Zap size={20} className="text-green-400" />- case 'decoding': return <RefreshCw size={20} className="text-cyan-400" />- default: return null- }- }-- const isLoading = progressPhase === 'loading-model' || progressPhase === 'loading-clip' || progressPhase === 'loading-vae'-- // Generating state- if (isGenerating) {- return (- <div className="flex-1 flex flex-col items-center justify-center p-8">- <div className="space-y-6 flex flex-col items-center">- {/* Phase-aware animation */}- <div className="relative w-16 h-16">- {isLoading ? (- /* Slower breathing animation for model loading */- <>- <motion.div- className="absolute inset-0 rounded-full border border-amber-400/30"- animate={{ scale: [1, 1.6], opacity: [0.5, 0] }}- transition={{ duration: 3, repeat: Infinity, ease: 'easeOut' }}- />- <div className="absolute inset-0 rounded-full border border-amber-400/20 flex items-center justify-center">- <motion.div animate={{ rotate: 360 }} transition={{ duration: 3, repeat: Infinity, ease: 'linear' }}>- {phaseIcon()}- </motion.div>- </div>- </>- ) : progressPhase === 'sampling' ? (- /* Faster pulse for sampling */- <>- <motion.div- className="absolute inset-0 rounded-full border border-green-400/30"- animate={{ scale: [1, 1.8], opacity: [0.4, 0] }}- transition={{ duration: 1.2, repeat: Infinity, ease: 'easeOut' }}- />- <motion.div- className="absolute inset-0 rounded-full border border-green-400/20"- animate={{ scale: [1, 1.5], opacity: [0.3, 0] }}- transition={{ duration: 1.2, repeat: Infinity, ease: 'easeOut', delay: 0.3 }}- />- <div className="absolute inset-0 rounded-full border border-green-400/10 flex items-center justify-center">- {phaseIcon()}- </div>- </>- ) : (- /* Default pulse */- <>- <motion.div- className="absolute inset-0 rounded-full border border-gray-300 dark:border-white/20"- animate={{ scale: [1, 1.8], opacity: [0.4, 0] }}- transition={{ duration: 2, repeat: Infinity, ease: 'easeOut' }}- />- <motion.div- className="absolute inset-0 rounded-full border border-gray-300 dark:border-white/15"- animate={{ scale: [1, 1.5], opacity: [0.3, 0] }}- transition={{ duration: 2, repeat: Infinity, ease: 'easeOut', delay: 0.5 }}- />- <div className="absolute inset-0 rounded-full border border-gray-200 dark:border-white/10 flex items-center justify-center">- <motion.div- className="w-2 h-2 rounded-full bg-gray-400 dark:bg-white/40"- animate={{ opacity: [0.3, 0.8, 0.3] }}- transition={{ duration: 1.5, repeat: Infinity }}- />- </div>- </>- )}- </div>- <p className="text-gray-500 text-xs tracking-wide">{progressText || 'Generating...'}</p>- {/* Progress bar — shown for the whole run (loading → sampling →- decoding). Steps live in progressText above. No time estimates. */}- {progress > 0 && (- <div className="w-56 h-1 bg-gray-200 dark:bg-white/10 rounded-full overflow-hidden">- <motion.div- className="h-full rounded-full bg-[rgb(160,148,248)]"- initial={{ width: 0 }}- animate={{ width: `${Math.min(progress, 100)}%` }}- transition={{ duration: 0.3 }}- />- </div>- )}- </div>- </div>- )- }-- // Empty state- if (!latest) {- return (- <div className="flex-1 flex items-center justify-center p-8">- <div className="text-center space-y-3">- <div className="w-12 h-12 mx-auto rounded-full border border-gray-200 dark:border-white/10 flex items-center justify-center">- <div className="w-1.5 h-1.5 rounded-full bg-gray-300 dark:bg-white/20" />- </div>- <p className="text-gray-400 dark:text-gray-500 text-sm">Your creations will appear here</p>- <p className="text-gray-300 dark:text-gray-600 text-xs">Write a prompt and hit Generate</p>- </div>- </div>- )- }-- // Show latest result — stable URL (item's createdAt as cache token) so the- // element never refetches across re-renders.- const url = getImageUrl(latest.filename, latest.subfolder, 'output', latest.createdAt)- const ready = loadedId === latest.id-- return (- <>- <div className="flex-1 flex flex-col items-center justify-center p-4 relative group min-h-0 overflow-hidden">- <motion.div- initial={{ opacity: 0, scale: 0.95 }}- animate={{ opacity: 1, scale: 1 }}- className="relative flex flex-col items-center min-h-0 max-h-full max-w-full"- >- {latest.type === 'video' ? (- <video- key={latest.id}- src={url}- controls- autoPlay- loop- playsInline- onLoadedData={() => setLoadedId(latest.id)}- className="max-w-full max-h-full rounded-xl border border-gray-200 dark:border-white/10 object-contain cursor-pointer bg-black"- style={{ opacity: ready ? 1 : 0, transition: 'opacity 0.25s ease-out' }}- onClick={() => setViewerIndex(0)}- />- ) : (- <img- key={latest.id}- src={url}- alt={latest.prompt}- onLoad={() => setLoadedId(latest.id)}- className="max-w-full max-h-full rounded-xl border border-gray-200 dark:border-white/10 object-contain cursor-pointer"- style={{ opacity: ready ? 1 : 0, transition: 'opacity 0.25s ease-out' }}- onClick={() => setViewerIndex(0)}- />- )}-- {/* Hover controls */}- <div className="absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity z-10">- <button- onClick={() => setViewerIndex(0)}- className="p-2 rounded-lg bg-black/50 text-white hover:bg-black/70 transition-colors"- title="Fullscreen"- >- <Maximize2 size={14} />- </button>- <button- onClick={() => handleDownload(latest)}- className="p-2 rounded-lg bg-black/50 text-white hover:bg-black/70 transition-colors"- title="Download"- >- <Download size={14} />- </button>- </div>- </motion.div>-- {/* Info bar */}- <div className="flex items-center gap-3 mt-2 text-xs text-gray-400">- <span className="truncate max-w-xs">{latest.prompt}</span>- <span>·</span>- <button- onClick={() => copySeed(latest.seed)}- className="flex items-center gap-1 hover:text-gray-600 dark:hover:text-gray-300 transition-colors"- title="Copy seed"- >- Seed: {latest.seed} {copiedSeed ? <Check size={10} /> : <Copy size={10} />}- </button>- <span>·</span>- <span>{latest.width}x{latest.height}</span>- </div>- </div>-- {/* Media Viewer */}- {viewerIndex !== null && (- <MediaViewer- gallery={gallery}- initialIndex={viewerIndex}- onClose={() => setViewerIndex(null)}- />- )}- </>- )-}diff --git a/src/components/create/ParamPanel.tsx b/src/components/create/ParamPanel.tsxdeleted file mode 100644index d97627e4..00000000--- a/src/components/create/ParamPanel.tsx+++ /dev/null@@ -1,425 +0,0 @@-import { useState, useEffect } from 'react'-import { useCreateStore } from '../../stores/createStore'-import { SliderControl } from '../settings/SliderControl'-import { WorkflowFinder } from './WorkflowFinder'-import { Dice5, AlertTriangle, Film, ImageIcon, ImagePlus } from 'lucide-react'-import type { ClassifiedModel, ModelType } from '../../api/comfyui'-import { snapToVideoGrid, isI2VModel, getLoraModels, getVAEModels } from '../../api/comfyui'--interface Props {- imageModels: ClassifiedModel[]- videoModels: ClassifiedModel[]- samplerList: string[]- schedulerList: string[]- modelsLoaded: boolean- modelLoadError?: string | null- onRetryModels?: () => void-}--const IMG_SIZE_PRESETS_SD15 = [- { label: '512', w: 512, h: 512 },- { label: '512x768', w: 512, h: 768 },- { label: '768x512', w: 768, h: 512 },- { label: '768', w: 768, h: 768 },-]--const IMG_SIZE_PRESETS_XL = [- { label: '1024', w: 1024, h: 1024 },- { label: '768x1344', w: 768, h: 1344 },- { label: '1344x768', w: 1344, h: 768 },- { label: '896x1152', w: 896, h: 1152 },-]--function getImageSizePresets(modelType: ModelType) {- if (modelType === 'sd15') return IMG_SIZE_PRESETS_SD15- return IMG_SIZE_PRESETS_XL-}--const VID_SIZE_PRESETS = [- { label: '480p', w: 848, h: 480 },- { label: '640x480', w: 640, h: 480 },- { label: '512', w: 512, h: 512 },- { label: '480x848', w: 480, h: 848 },-]--const TYPE_BADGE: Record<ModelType, { label: string; color: string }> = {- flux: { label: 'FLUX', color: 'bg-purple-500/15 text-purple-300' },- flux2: { label: 'FLUX 2', color: 'bg-purple-500/15 text-purple-300' },- zimage: { label: 'Z-Image', color: 'bg-rose-500/15 text-rose-300' },- ernie_image: { label: 'ERNIE', color: 'bg-sky-500/15 text-sky-300' },- sdxl: { label: 'SDXL', color: 'bg-blue-500/15 text-blue-300' },- sd15: { label: 'SD 1.5', color: 'bg-green-500/15 text-green-300' },- wan: { label: 'Wan', color: 'bg-orange-500/15 text-orange-300' },- wan22: { label: 'Wan 2.2', color: 'bg-orange-500/15 text-orange-300' },- hunyuan: { label: 'Hunyuan', color: 'bg-red-500/15 text-red-300' },- ltx: { label: 'LTX', color: 'bg-cyan-500/15 text-cyan-300' },- mochi: { label: 'Mochi', color: 'bg-pink-500/15 text-pink-300' },- cosmos: { label: 'Cosmos', color: 'bg-emerald-500/15 text-emerald-300' },- cogvideo: { label: 'CogVideo', color: 'bg-amber-500/15 text-amber-300' },- svd: { label: 'SVD', color: 'bg-indigo-500/15 text-indigo-300' },- framepack: { label: 'FramePack', color: 'bg-teal-500/15 text-teal-300' },- pyramidflow: { label: 'PyramidFlow', color: 'bg-violet-500/15 text-violet-300' },- allegro: { label: 'Allegro', color: 'bg-rose-500/15 text-rose-300' },- unknown: { label: 'Model', color: 'bg-white/10 text-gray-400' },-}--export function ParamPanel({ imageModels, videoModels, samplerList, schedulerList, modelsLoaded, modelLoadError, onRetryModels }: Props) {- const store = useCreateStore()- const isVideo = store.mode === 'video'- const isI2I = store.mode === 'image' && store.imageSubMode === 'img2img'- // Sub-mode now lives in the store (shared with the main-screen T2V/I2V- // switch). CreateView owns the always-mounted effect that re-points- // store.videoModel to a valid entry when the sub-mode changes.- const videoSubMode = store.videoSubMode- const sizePresets = isVideo ? VID_SIZE_PRESETS : getImageSizePresets(store.imageModelType)-- // Filter video models by sub-mode- const filteredVideoModels = isVideo- ? videoModels.filter(m => videoSubMode === 'i2v' ? isI2VModel(m.name) : !isI2VModel(m.name))- : videoModels- const models = isVideo ? filteredVideoModels : imageModels // i2i also uses imageModels-- const sel = 'w-full px-2.5 py-1.5 rounded-lg bg-gray-100 dark:bg-[#1a1a1a] border border-gray-200 dark:border-white/8 text-gray-900 dark:text-white text-[11px] focus:outline-none focus:border-gray-400 dark:focus:border-white/20 cursor-pointer'- const lbl = 'text-[10px] font-medium text-gray-500 dark:text-gray-600 uppercase tracking-widest mb-1 block'-- const handleModelChange = (name: string) => {- if (isVideo) {- store.setVideoModel(name)- } else {- const model = imageModels.find(m => m.name === name)- store.setImageModel(name, model?.type ?? 'unknown')- }- }-- const activeModel = isVideo ? store.videoModel : store.imageModel-- return (- <div className="space-y-3">- {/* Video Sub-Tabs: Text to Video / Image to Video */}- {isVideo && (- <div className="flex rounded-lg bg-gray-100 dark:bg-white/5 p-0.5 gap-0.5">- <button- onClick={() => store.setVideoSubMode('t2v')}- className={`flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 rounded-md text-[10px] font-medium transition-all ${- videoSubMode === 't2v'- ? 'bg-white dark:bg-white/15 text-gray-900 dark:text-white shadow-sm'- : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'- }`}- >- <Film size={11} />- Text to Video- </button>- <button- onClick={() => store.setVideoSubMode('i2v')}- className={`flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 rounded-md text-[10px] font-medium transition-all ${- videoSubMode === 'i2v'- ? 'bg-white dark:bg-white/15 text-gray-900 dark:text-white shadow-sm'- : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'- }`}- >- <ImageIcon size={11} />- Image to Video- </button>- </div>- )}-- {/* Image Sub-Tabs: Text to Image / Image to Image */}- {!isVideo && (- <div className="flex rounded-lg bg-gray-100 dark:bg-white/5 p-0.5 gap-0.5">- <button- onClick={() => store.setImageSubMode('text2img')}- className={`flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 rounded-md text-[10px] font-medium transition-all ${- store.imageSubMode === 'text2img'- ? 'bg-white dark:bg-white/15 text-gray-900 dark:text-white shadow-sm'- : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'- }`}- >- <ImageIcon size={11} />- Text to Image- </button>- <button- onClick={() => store.setImageSubMode('img2img')}- className={`flex-1 flex items-center justify-center gap-1.5 px-2 py-1.5 rounded-md text-[10px] font-medium transition-all ${- store.imageSubMode === 'img2img'- ? 'bg-white dark:bg-white/15 text-gray-900 dark:text-white shadow-sm'- : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300'- }`}- >- <ImagePlus size={11} />- Image to Image- </button>- </div>- )}-- {/* Model */}- <div>- <label className={lbl}>{isVideo ? (videoSubMode === 'i2v' ? 'I2V Model' : 'Video Model') : 'Image Model'}</label>- {modelLoadError ? (- <div className="space-y-1">- <div className="px-2.5 py-1.5 rounded-lg bg-red-500/10 border border-red-500/20 text-red-400 text-[10px]">- {modelLoadError}- </div>- {onRetryModels && (- <button onClick={onRetryModels} className="text-[9px] text-gray-500 hover:text-gray-300 transition-colors">- Retry- </button>- )}- </div>- ) : !modelsLoaded ? (- <div className="px-2.5 py-1.5 rounded-lg bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/8 text-gray-400 dark:text-gray-600 text-[10px] animate-pulse">- Loading models from ComfyUI...- </div>- ) : models.length === 0 ? (- <div className="px-2.5 py-1.5 rounded-lg bg-yellow-500/5 border border-yellow-500/10 text-yellow-400 text-[10px]">- No models found. Download models in the Model Manager.- </div>- ) : (- <>- <select value={activeModel} onChange={(e) => handleModelChange(e.target.value)} className={sel}>- {models.map((m) => {- const badge = TYPE_BADGE[m.type]- const shortName = m.name.replace(/\.[^.]+$/, '')- return <option key={m.name} value={m.name}>{shortName} ({badge.label})</option>- })}- </select>- {activeModel && (() => {- const model = models.find(m => m.name === activeModel)- if (!model) return null- const badge = TYPE_BADGE[model.type]- return (- <span className={`mt-1 inline-block px-1.5 py-0.5 rounded text-[9px] font-medium ${badge.color}`}>- {badge.label}- </span>- )- })()}- </>- )}- </div>-- {/* Sampler + Scheduler side by side */}- <div className="grid grid-cols-2 gap-2">- <div>- <label className={lbl}>Sampler</label>- <select value={store.sampler} onChange={(e) => store.setSampler(e.target.value)} className={sel}>- {samplerList.map((s) => <option key={s} value={s}>{s}</option>)}- </select>- </div>- <div>- <label className={lbl}>Scheduler</label>- <select value={store.scheduler} onChange={(e) => store.setScheduler(e.target.value)} className={sel}>- {schedulerList.map((s) => <option key={s} value={s}>{s}</option>)}- </select>- </div>- </div>-- {/* Steps + CFG side by side */}- <div className="grid grid-cols-2 gap-2">- <SliderControl label="Steps" value={store.steps} min={1} max={50} step={1} onChange={store.setSteps} />- <SliderControl label="CFG" value={store.cfgScale} min={0} max={30} step={0.5} onChange={store.setCfgScale} />- </div>-- {/* Batch Size (not for I2I) */}- {!isVideo && !isI2I && (- <SliderControl label="Batch" value={store.batchSize} min={1} max={4} step={1} onChange={store.setBatchSize} />- )}-- {/* Denoise Strength (I2I only) */}- {isI2I && (- <SliderControl label="Denoise" value={store.denoise} min={0.05} max={1.0} step={0.05} onChange={store.setDenoise} />- )}-- {/* F2 (cinemazverev GH#4) + F3 (vanja-san GH#4) — extended params.- LoRA / VAE / Skip CLIP only matter for image generation; we- hide them for video to keep the panel terse. The LoRA list is- fetched lazily from ComfyUI's LoraLoader node enum the first- time the panel mounts. */}- {!isVideo && (- <ExtendedComfyParams />- )}-- {/* Size */}- <div>- <label className={lbl}>Size ({store.width}x{store.height})</label>- <div className="flex flex-wrap gap-1">- {sizePresets.map((preset) => (- <button- key={preset.label}- onClick={() => store.setSize(preset.w, preset.h)}- className={`px-1.5 py-0.5 rounded text-[10px] transition-all ${- store.width === preset.w && store.height === preset.h- ? 'bg-gray-800 dark:bg-white/15 text-white'- : 'bg-gray-100 dark:bg-white/5 text-gray-500 hover:bg-gray-200 dark:hover:bg-white/10 hover:text-gray-700 dark:hover:text-gray-300'- }`}- >- {preset.label}- </button>- ))}- </div>- </div>-- {/* Seed */}- <div>- <label className={lbl}>Seed</label>- <div className="flex gap-1.5">- <input- type="number"- value={store.seed}- onChange={(e) => store.setSeed(parseInt(e.target.value) || -1)}- className="flex-1 px-2.5 py-1.5 rounded-lg bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/8 text-gray-900 dark:text-white text-[11px] focus:outline-none font-mono"- placeholder="-1"- />- <button- onClick={() => store.setSeed(-1)}- className="p-1.5 rounded-lg bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/8 text-gray-500 hover:text-gray-900 dark:hover:text-white transition-colors"- title="Random"- aria-label="Random seed"- >- <Dice5 size={12} />- </button>- </div>- </div>-- {/* Video params */}- {isVideo && (- <>- <div className="grid grid-cols-2 gap-2">- <SliderControl label="Frames" value={store.frames} min={1} max={81} step={4} onChange={store.setFrames} />- <SliderControl label="FPS" value={store.fps} min={4} max={30} step={1} onChange={store.setFps} />- </div>- {(store.width % 16 !== 0 || store.height % 16 !== 0) && (- <button- onClick={() => { const s = snapToVideoGrid(store.width, store.height); store.setSize(s.width, s.height) }}- className="flex items-center gap-1 text-[10px] text-yellow-400 hover:underline"- aria-label="Fix video dimensions"- >- <AlertTriangle size={10} /> Fix to {snapToVideoGrid(store.width, store.height).width}x{snapToVideoGrid(store.width, store.height).height}- </button>- )}- {store.frames > 40 && (- <div className="flex items-center gap-1 text-[10px] text-orange-400">- <AlertTriangle size={10} /> High VRAM usage- </div>- )}- </>- )}-- {/* Workflow (bottom) */}- <div className="pt-2 border-t border-gray-200 dark:border-white/5">- <WorkflowFinder- modelName={activeModel}- modelType={isVideo ? (models.find(m => m.name === activeModel)?.type ?? 'unknown') : store.imageModelType}- />- </div>- </div>- )-}--// ── F2 + F3 extended params (image generation only) ──────────────-//-// Lazy-loads the LoRA + VAE enum from ComfyUI's `/object_info/...` once-// per mount. Both lists silently fall back to empty when the node isn't-// registered — F2/F3 then degrade to "no LoRA" / "VAE: auto".--function ExtendedComfyParams() {- const store = useCreateStore()- const [loras, setLoras] = useState<string[]>([])- const [vaes, setVaes] = useState<string[]>([])- const [loaded, setLoaded] = useState(false)-- useEffect(() => {- let cancelled = false- void Promise.all([getLoraModels(), getVAEModels()]).then(([l, v]) => {- if (cancelled) return- setLoras(l)- setVaes(v)- setLoaded(true)- })- return () => {- cancelled = true- }- }, [])-- const sel = 'w-full px-2 py-1 rounded bg-gray-50 dark:bg-white/[0.04] border border-gray-200 dark:border-white/10 text-[0.7rem] text-gray-800 dark:text-gray-200 focus:outline-none focus:border-blue-400/40'- const lbl = 'text-[0.55rem] text-gray-500 mb-1 block'-- return (- <div className="space-y-2 pt-1 border-t border-gray-200 dark:border-white/5">- <div className="text-[0.55rem] uppercase tracking-widest text-gray-500">Extended</div>-- {/* LoRA stack (F2 + multi-LoRA, konata 2026-06-09) — click to stack;- applied in click order via chained LoraLoader nodes, each with its- own strength slider. */}- <div>- <label className={lbl}>- LoRAs {!loaded && <span className="text-gray-400">(loading…)</span>}- {store.selectedLoras.length > 1 && (- <span className="ml-1 text-gray-400">— {store.selectedLoras.length} stacked, applied in order</span>- )}- </label>- {loaded && loras.length === 0 && (- <div className="text-[0.6rem] text-gray-500">No LoRAs installed (ComfyUI/models/loras)</div>- )}- <div className="space-y-1 max-h-44 overflow-y-auto scrollbar-thin pr-0.5">- {loras.map((l) => {- const active = store.selectedLoras.find((x) => x.name === l)- return (- <div key={l}>- <button- type="button"- onClick={() => store.toggleLora(l)}- disabled={!loaded}- className={`w-full text-left px-2 py-1 rounded border text-[0.65rem] transition-colors truncate ${- active- ? 'border-blue-400/40 bg-blue-500/10 text-gray-900 dark:text-gray-100'- : 'border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-white/[0.04] text-gray-600 dark:text-gray-400 hover:border-gray-300 dark:hover:border-white/20'- }`}- title={l}- >- {active ? '✓ ' : ''}{l}- </button>- {active && (- <SliderControl- label="strength"- value={active.strength}- min={0}- max={2}- step={0.05}- onChange={(v) => store.setLoraStrengthFor(l, v)}- />- )}- </div>- )- })}- </div>- </div>-- {/* VAE override (F3) */}- <div>- <label className={lbl}>VAE</label>- <select- value={store.selectedVae}- onChange={(e) => store.setSelectedVae(e.target.value)}- className={sel}- disabled={!loaded}- >- <option value="auto">auto (use checkpoint VAE)</option>- {vaes.map((v) => (- <option key={v} value={v}>{v}</option>- ))}- </select>- </div>-- {/* Skip CLIP (F3) — 0 = none. 1-2 is the SD1.5 / SDXL sweet spot- for some abliterated finetunes. >2 only makes sense for very- specialised use. */}- <SliderControl- label="Skip CLIP layers"- value={store.clipSkip}- min={0}- max={12}- step={1}- onChange={store.setClipSkip}- />- </div>- )-}diff --git a/src/components/create/PromptInput.tsx b/src/components/create/PromptInput.tsxdeleted file mode 100644index 8eb6056c..00000000--- a/src/components/create/PromptInput.tsx+++ /dev/null@@ -1,243 +0,0 @@-import { useState, useRef, useEffect } from 'react'-import { motion, AnimatePresence } from 'framer-motion'-import { Sparkles, Square, History, X, Minus, Trash2 } from 'lucide-react'-import { useCreateStore } from '../../stores/createStore'-import { classifyModel, isI2VModel } from '../../api/comfyui'-import type { ClassifiedModel } from '../../api/comfyui'--interface Props {- onGenerate: () => void- onCancel: () => void- disabled?: boolean- imageModels: ClassifiedModel[]- videoModels: ClassifiedModel[]-}--/**- * Create-tab composer, rebuilt on the chat composer's DNA (David 2026-06-11:- * "prompt fenster kleiner ... etwas wie bei chat, button elemente wie bei- * chat/agent/code"): one centered max-w-[70%] box, a single auto-growing- * input row with all controls inline, compact p-1.5 icon buttons.- */-export function PromptInput({ onGenerate, onCancel, disabled, imageModels, videoModels }: Props) {- const {- prompt, negativePrompt, isGenerating, promptHistory, mode, imageSubMode, videoSubMode,- imageModel, videoModel, setPrompt, setNegativePrompt, setImageSubMode, setVideoSubMode,- setImageModel, setVideoModel, clearPromptHistory,- } = useCreateStore()-- // Model picker (lives right next to Generate). Video models are filtered by- // the T2V/I2V sub-mode so the list only shows compatible checkpoints.- const modelOptions = mode === 'video'- ? videoModels.filter((m) => (videoSubMode === 'i2v' ? isI2VModel(m.name) : !isI2VModel(m.name)))- : imageModels- const activeModelValue = mode === 'video' ? videoModel : imageModel- const onModelChange = (name: string) => {- if (mode === 'video') setVideoModel(name)- else setImageModel(name, classifyModel(name))- }- const [showNegative, setShowNegative] = useState(false)- const [showHistory, setShowHistory] = useState(false)- const textareaRef = useRef<HTMLTextAreaElement>(null)- const isMac = navigator.platform.toUpperCase().includes('MAC')-- // Auto-grow like the chat composer: single line at rest, expands with- // content up to a cap instead of a fixed 3-row block.- useEffect(() => {- if (textareaRef.current) {- textareaRef.current.style.height = 'auto'- textareaRef.current.style.height = Math.min(textareaRef.current.scrollHeight, 160) + 'px'- }- }, [prompt])-- const handleKeyDown = (e: React.KeyboardEvent) => {- if (e.key === 'Enter' && (isMac ? e.metaKey : e.ctrlKey)) {- e.preventDefault()- if (!isGenerating && prompt.trim()) onGenerate()- }- }-- const selectFromHistory = (p: string) => {- setPrompt(p)- setShowHistory(false)- textareaRef.current?.focus()- }-- const subModeBtn = (active: boolean) =>- `px-2 h-full text-[0.6rem] font-medium transition-colors ${- active- ? 'bg-gray-200 dark:bg-white/10 text-gray-900 dark:text-white'- : 'text-gray-500 hover:text-gray-800 dark:hover:text-gray-200'- }`-- return (- <div className="w-full max-w-[70%] mx-auto">- <div className="flex flex-col rounded-lg border bg-gray-50 dark:bg-white/[0.03] border-gray-200 dark:border-white/[0.06] px-2.5 py-1 transition-colors">- {/* Input row — everything inline, chat style. items-center + a single- 28px control height keeps every element on the same line/height. */}- <div className="flex items-center gap-2">- {/* T2I/I2I resp. T2V/I2V sub-mode switch */}- {mode === 'image' ? (- <div className="flex items-center rounded-md border border-gray-200 dark:border-white/10 overflow-hidden shrink-0 h-[28px]">- <button onClick={() => setImageSubMode('text2img')} className={subModeBtn(imageSubMode === 'text2img')} title="Text to Image">T2I</button>- <button onClick={() => setImageSubMode('img2img')} className={subModeBtn(imageSubMode === 'img2img')} title="Image to Image">I2I</button>- </div>- ) : (- <div className="flex items-center rounded-md border border-gray-200 dark:border-white/10 overflow-hidden shrink-0 h-[28px]">- <button onClick={() => setVideoSubMode('t2v')} className={subModeBtn(videoSubMode === 't2v')} title="Text to Video">T2V</button>- <button onClick={() => setVideoSubMode('i2v')} className={subModeBtn(videoSubMode === 'i2v')} title="Image to Video">I2V</button>- </div>- )}-- <textarea- ref={textareaRef}- value={prompt}- onChange={(e) => setPrompt(e.target.value)}- onKeyDown={handleKeyDown}- placeholder="Describe what you want to create..."- rows={1}- className="flex-1 bg-transparent resize-none text-gray-800 dark:text-gray-200 placeholder-gray-400 dark:placeholder-gray-600 focus:outline-none text-[0.75rem] leading-relaxed max-h-[160px] py-1 disabled:opacity-50 scrollbar-thin"- disabled={isGenerating || disabled}- aria-label="Image or video generation prompt"- />-- {/* Negative-prompt toggle — pill like the chat Think toggle */}- <button- onClick={() => setShowNegative(!showNegative)}- className={`flex items-center gap-1 px-2 h-[28px] rounded-md transition-all shrink-0 text-[0.6rem] font-medium ${- showNegative || negativePrompt.trim()- ? 'bg-white/10 text-gray-800 dark:text-gray-200 border border-gray-300 dark:border-white/15'- : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-white/5'- }`}- title="Negative prompt — what to avoid"- aria-expanded={showNegative}- >- <Minus size={11} />- <span>Neg</span>- </button>-- {/* Prompt history */}- {promptHistory.length > 0 && (- <button- onClick={() => setShowHistory(!showHistory)}- className={`h-[28px] w-[28px] flex items-center justify-center rounded-md transition-all shrink-0 ${showHistory ? 'bg-white/10 text-gray-700 dark:text-gray-200' : 'text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-white/5'}`}- title="Prompt history"- aria-label="Prompt history"- >- <History size={13} />- </button>- )}-- {/* Clear */}- {prompt.trim() && !isGenerating && (- <button- onClick={() => setPrompt('')}- className="h-[28px] w-[28px] flex items-center justify-center rounded-md text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-white/5 transition-all shrink-0"- aria-label="Clear prompt"- >- <X size={13} />- </button>- )}-- {/* Model picker — always visible + switchable without opening Advanced */}- {modelOptions.length > 0 && (- <select- value={activeModelValue}- onChange={(e) => onModelChange(e.target.value)}- disabled={isGenerating || disabled}- title={activeModelValue || `Select ${mode} model`}- aria-label={`${mode} model`}- className="max-w-[140px] h-[28px] px-1.5 rounded-md bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/10 text-gray-700 dark:text-gray-200 text-[0.65rem] focus:outline-none focus:border-gray-400 dark:focus:border-white/20 cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed shrink-0"- >- {modelOptions.map((m) => (- <option key={m.name} value={m.name}>{m.name.replace(/\.[^.]+$/, '')}</option>- ))}- </select>- )}-- {isGenerating ? (- <motion.button- onClick={onCancel}- className="flex items-center gap-1.5 px-2.5 h-[28px] rounded-md bg-red-500/15 text-red-500 dark:text-red-400 hover:bg-red-500/25 text-[0.65rem] font-medium transition-all shrink-0"- whileTap={{ scale: 0.95 }}- aria-label="Cancel generation"- >- <Square size={11} /> Cancel- </motion.button>- ) : (- <motion.button- onClick={onGenerate}- disabled={!prompt.trim() || disabled}- className="flex items-center gap-1.5 px-2.5 h-[28px] rounded-md bg-gray-900 text-white dark:bg-white/10 dark:text-white hover:bg-gray-700 dark:hover:bg-white/15 disabled:opacity-30 disabled:cursor-not-allowed text-[0.65rem] font-medium transition-all shrink-0"- whileTap={{ scale: 0.95 }}- title={`${isMac ? 'Cmd' : 'Ctrl'}+Enter`}- aria-label="Generate"- >- <Sparkles size={11} /> Generate- </motion.button>- )}- </div>-- {/* Negative prompt — slim row inside the same box, not a second panel */}- <AnimatePresence>- {showNegative && (- <motion.div- initial={{ opacity: 0, height: 0 }}- animate={{ opacity: 1, height: 'auto' }}- exit={{ opacity: 0, height: 0 }}- className="overflow-hidden"- >- <div className="border-t border-gray-100 dark:border-white/5 mt-1 pt-1.5 pb-0.5">- <textarea- value={negativePrompt}- onChange={(e) => setNegativePrompt(e.target.value)}- placeholder="What to avoid (e.g. blurry, low quality, watermark)..."- rows={1}- className="w-full bg-transparent resize-none text-gray-700 dark:text-gray-300 placeholder-gray-400 dark:placeholder-gray-600 focus:outline-none text-[0.7rem] leading-relaxed scrollbar-thin"- disabled={isGenerating}- aria-label="Negative prompt"- />- </div>- </motion.div>- )}- </AnimatePresence>-- {/* Prompt history dropdown */}- <AnimatePresence>- {showHistory && promptHistory.length > 0 && (- <motion.div- initial={{ opacity: 0, height: 0 }}- animate={{ opacity: 1, height: 'auto' }}- exit={{ opacity: 0, height: 0 }}- className="border-t border-gray-100 dark:border-white/5 mt-1"- >- {/* GitHub #66 (rubacc80-png) — let users wipe the prompt history. */}- <div className="flex items-center justify-between px-1.5 pt-1 pb-0.5">- <span className="text-[0.55rem] uppercase tracking-wide text-gray-400 dark:text-gray-600">Recent prompts</span>- <button- onClick={() => clearPromptHistory()}- className="flex items-center gap-0.5 text-[0.55rem] text-gray-500 hover:text-red-500 dark:hover:text-red-400 transition-colors"- title="Clear prompt history"- aria-label="Clear prompt history"- >- <Trash2 size={9} /> Clear- </button>- </div>- <div className="max-h-24 overflow-y-auto scrollbar-thin">- {promptHistory.map((p, i) => (- <button- key={i}- onClick={() => selectFromHistory(p)}- className="w-full text-left px-1.5 py-1 text-[0.65rem] text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-white/5 rounded truncate transition-colors"- >- {p}- </button>- ))}- </div>- </motion.div>- )}- </AnimatePresence>- </div>- </div>- )-}diff --git a/src/components/create/WorkflowCard.tsx b/src/components/create/WorkflowCard.tsxdeleted file mode 100644index e161015c..00000000--- a/src/components/create/WorkflowCard.tsx+++ /dev/null@@ -1,110 +0,0 @@-import { Download, Check, ExternalLink, RotateCcw, Star } from 'lucide-react'-import type { WorkflowSearchResult } from '../../types/workflows'-import type { ModelType } from '../../api/comfyui'-import { proxyImageUrl } from '../../lib/privacy'-import { openExternal } from '../../api/backend'--interface Props {- result: WorkflowSearchResult- isInstalled: boolean- isActive: boolean- currentModelType?: ModelType- onInstall: (result: WorkflowSearchResult) => void-}--const SOURCE_BADGE: Record<string, { label: string; color: string }> = {- civitai: { label: 'CivitAI', color: 'bg-blue-500/20 text-blue-300' },- manual: { label: 'Template', color: 'bg-emerald-500/20 text-emerald-300' },-}--export function WorkflowCard({ result, isInstalled, isActive, currentModelType, onInstall }: Props) {- const badge = SOURCE_BADGE[result.source] ?? SOURCE_BADGE.manual- const displayName = result.name || result.sourceUrl?.split('/').pop() || 'Unnamed Workflow'- const isCompatible = currentModelType && result.modelTypes.includes(currentModelType)-- return (- <div className={`flex gap-3 p-3 rounded-xl border transition-colors ${- isActive- ? 'bg-white/8 border-emerald-500/30'- : 'bg-white/5 border-white/10 hover:border-white/20'- }`}>- {/* Thumbnail */}- {result.thumbnailUrl ? (- <img- src={proxyImageUrl(result.thumbnailUrl)}- alt={displayName}- className="w-16 h-16 rounded-lg object-cover flex-shrink-0 bg-white/5"- loading="lazy"- />- ) : (- <div className="w-16 h-16 rounded-lg bg-white/5 flex items-center justify-center flex-shrink-0">- <Download size={20} className="text-gray-500" />- </div>- )}-- {/* Info */}- <div className="flex-1 min-w-0">- <div className="flex items-center gap-2 mb-0.5">- <span className="text-sm font-semibold text-white truncate" title={displayName}>- {displayName}- </span>- <span className={`px-1.5 py-0.5 rounded text-[10px] font-medium flex-shrink-0 ${badge.color}`}>- {badge.label}- </span>- {isCompatible && (- <span className="flex items-center gap-0.5 px-1.5 py-0.5 rounded text-[10px] font-medium bg-emerald-500/20 text-emerald-300 flex-shrink-0">- <Star size={8} /> Match- </span>- )}- </div>-- {result.description && (- <p className="text-xs text-gray-400 line-clamp-2 mb-1.5" title={result.description}>- {result.description}- </p>- )}-- {result.modelTypes.length > 0 && result.modelTypes[0] !== 'unknown' && (- <div className="flex gap-1 mb-1.5">- {result.modelTypes.map((mt) => (- <span key={mt} className="px-1 py-0.5 rounded text-[9px] font-medium bg-white/10 text-gray-300">- {mt.toUpperCase()}- </span>- ))}- </div>- )}-- {/* Actions */}- <div className="flex items-center gap-2">- {isActive ? (- <span className="flex items-center gap-1 px-2 py-1 rounded-lg bg-emerald-500/20 text-emerald-300 text-xs">- <Check size={12} /> Active- </span>- ) : isInstalled ? (- <button- onClick={() => onInstall(result)}- className="flex items-center gap-1 px-2 py-1 rounded-lg bg-white/10 hover:bg-white/20 text-white text-xs transition-colors"- >- <RotateCcw size={12} /> Use- </button>- ) : (- <button- onClick={() => onInstall(result)}- className="flex items-center gap-1 px-2 py-1 rounded-lg bg-white/10 hover:bg-white/20 text-white text-xs transition-colors"- >- <Download size={12} /> Install- </button>- )}- {result.sourceUrl && (- <button- onClick={() => openExternal(result.sourceUrl!)}- className="flex items-center gap-1 px-2 py-1 rounded-lg bg-white/5 hover:bg-white/10 text-gray-400 hover:text-white text-xs transition-colors"- >- <ExternalLink size={12} /> Source- </button>- )}- </div>- </div>- </div>- )-}diff --git a/src/components/create/WorkflowFinder.tsx b/src/components/create/WorkflowFinder.tsxdeleted file mode 100644index d5e4d09a..00000000--- a/src/components/create/WorkflowFinder.tsx+++ /dev/null@@ -1,71 +0,0 @@-import { useState } from 'react'-import { X, Workflow } from 'lucide-react'-import { useWorkflowStore } from '../../stores/workflowStore'-import { WorkflowSearchModal } from './WorkflowSearchModal'-import type { ModelType } from '../../api/comfyui'--interface Props {- modelName: string- modelType: ModelType-}--export function WorkflowFinder({ modelName, modelType }: Props) {- const [modalOpen, setModalOpen] = useState(false)- const {- getWorkflowForModel,- assignToModelName,- unassignModelName,- unassignModelType,- } = useWorkflowStore()-- const activeWorkflow = getWorkflowForModel(modelName, modelType)-- return (- <>- <div>- <label className="text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider mb-1.5 flex items-center gap-1.5">- <Workflow size={12} />- Workflow- </label>-- {/* Load Workflow button - opens the finder modal */}- <button- onClick={() => setModalOpen(true)}- className="w-full px-3 py-2 rounded-lg bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/10 text-gray-900 dark:text-white text-sm hover:bg-gray-200 dark:hover:bg-white/10 transition-colors text-left"- >- {activeWorkflow ? activeWorkflow.name : 'Auto'}- </button>-- {/* Active workflow info badge + clear */}- {activeWorkflow && (- <div className="mt-1 flex items-center gap-1.5">- <span className="inline-block px-1.5 py-0.5 rounded text-[10px] font-medium bg-emerald-500/20 text-emerald-300">- {activeWorkflow.source}- </span>- <span className="text-[10px] text-gray-500 truncate">- {activeWorkflow.mode === 'video' ? 'Video' : activeWorkflow.mode === 'both' ? 'Image+Video' : 'Image'}- </span>- <button- onClick={(e) => {- e.stopPropagation()- unassignModelName(modelName)- unassignModelType(modelType)- }}- className="ml-auto text-gray-500 hover:text-red-400 transition-colors"- title="Reset to Auto"- >- <X size={12} />- </button>- </div>- )}- </div>-- <WorkflowSearchModal- open={modalOpen}- onClose={() => setModalOpen(false)}- modelName={modelName}- modelType={modelType}- />- </>- )-}diff --git a/src/components/create/WorkflowSearchModal.tsx b/src/components/create/WorkflowSearchModal.tsxdeleted file mode 100644index 5f907205..00000000--- a/src/components/create/WorkflowSearchModal.tsx+++ /dev/null@@ -1,500 +0,0 @@-import { useState, useEffect, useRef } from 'react'-import { Search, Upload, Loader2, AlertCircle, Key, Eye, EyeOff } from 'lucide-react'-import { v4 as uuid } from 'uuid'-import { Modal } from '../ui/Modal'-import { openExternal } from '../../api/backend'-import { WorkflowCard } from './WorkflowCard'-import { useWorkflowStore } from '../../stores/workflowStore'-import {- searchWorkflows,- fetchWorkflowFromUrl,- validateWorkflowJson,- parseImportedWorkflow,- extractSearchTerms,-} from '../../api/workflows'-import type { WorkflowSearchResult, WorkflowTemplate } from '../../types/workflows'-import type { ModelType } from '../../api/comfyui'--interface Props {- open: boolean- onClose: () => void- modelName: string- modelType: ModelType-}--type TabId = 'discover' | 'templates' | 'import'--const TABS: { id: TabId; label: string }[] = [- { id: 'templates', label: 'Templates' },- { id: 'discover', label: 'Discover' },- { id: 'import', label: 'Import' },-]--export function WorkflowSearchModal({ open, onClose, modelName, modelType }: Props) {- const [activeTab, setActiveTab] = useState<TabId>('discover')- const [query, setQuery] = useState('')- const [results, setResults] = useState<WorkflowSearchResult[]>([])- const [loading, setLoading] = useState(false)- const [error, setError] = useState<string | null>(null)- const [importUrl, setImportUrl] = useState('')- const [importJson, setImportJson] = useState('')- const [importName, setImportName] = useState('')- const [importLoading, setImportLoading] = useState(false)- // Visible success confirmation after a manual Import action. Without this the- // Import button silently clears its inputs on success and the user sees no- // feedback at all (diimmortalis' report: "doesn't seem to persist manually- // entered json … no feedback or console output when clicking the Import- // button"). The toast auto-clears after a few seconds.- const [importSuccess, setImportSuccess] = useState<string | null>(null)- const initialSearchDone = useRef(false)- const templatesCached = useRef<WorkflowSearchResult[] | null>(null)-- const { installedWorkflows, installWorkflow, assignToModelName, civitaiApiKey, setCivitaiApiKey, civitaiHost } = useWorkflowStore()- const [showApiKey, setShowApiKey] = useState(false)- const [showApiKeyInput, setShowApiKeyInput] = useState(false)- const [showApiKeyWarning, setShowApiKeyWarning] = useState(false)- const [installStatus, setInstallStatus] = useState<string | null>(null)-- // Reset state and load templates when modal opens- useEffect(() => {- if (open) {- const terms = extractSearchTerms(modelName, modelType)- setQuery(terms)- setError(null)- setActiveTab('templates')- initialSearchDone.current = false- // Load templates immediately, sorted by compatibility (matching first)- searchWorkflows('', 'templates' as any).then(r => {- const sorted = [...r].sort((a, b) => {- const aMatch = a.modelTypes.includes(modelType) ? -1 : 1- const bMatch = b.modelTypes.includes(modelType) ? -1 : 1- return aMatch - bMatch- })- templatesCached.current = sorted- setResults(sorted)- })- }- }, [open, modelName, modelType])-- const performSearch = async (source: TabId, searchQuery: string) => {- if (source === 'import') return- setLoading(true)- setError(null)- try {- const searchSource = source === 'discover' ? 'civitai' : 'templates'- const r = await searchWorkflows(searchQuery, searchSource as any, civitaiHost)- setResults(r)- if (r.length === 0) setError('No workflows found. Try different search terms.')- } catch (err) {- setError(`Search failed: ${err instanceof Error ? err.message : String(err)}`)- } finally {- setLoading(false)- }- }-- const handleSearch = () => {- if (activeTab !== 'import') {- performSearch(activeTab, activeTab === 'templates' ? '' : query)- }- }-- const handleTabChange = (tab: TabId) => {- setActiveTab(tab)- setError(null)-- if (tab === 'templates') {- // Load templates synchronously — they're local data- if (templatesCached.current) {- setResults(templatesCached.current)- } else {- const templates = searchWorkflows('', 'templates' as any)- // searchWorkflows returns a Promise, but templates are sync- templates.then(r => {- templatesCached.current = r- setResults(r)- })- }- } else if (tab === 'discover') {- // Restore discover results or clear- setResults([])- if (query) {- performSearch('discover', query)- }- } else {- setResults([])- }- }-- const handleInstallResult = async (result: WorkflowSearchResult) => {- if (!result.downloadUrl && !result.rawWorkflow) {- setError('No download link available. Try the Import tab with the workflow page URL.')- return- }-- if (!result.rawWorkflow && result.source === 'civitai' && !civitaiApiKey) {- setShowApiKeyWarning(true)- return- }-- setLoading(true)- setError(null)- setInstallStatus('Downloading workflow...')- try {- let workflow: Record<string, any>- if (result.rawWorkflow) {- workflow = result.rawWorkflow- } else {- workflow = await fetchWorkflowFromUrl(result.downloadUrl!, civitaiApiKey || undefined)- }-- setInstallStatus('Processing...')- const parsed = parseImportedWorkflow(- result.name,- workflow,- result.source,- result.sourceUrl,- result.description,- )-- const template: WorkflowTemplate = {- ...parsed,- id: uuid(),- installedAt: Date.now(),- thumbnailUrl: result.thumbnailUrl,- }-- installWorkflow(template)- assignToModelName(modelName, template.id)- setInstallStatus(null)- } catch (err) {- setError(`Install failed: ${err instanceof Error ? err.message : String(err)}`)- setInstallStatus(null)- } finally {- setLoading(false)- }- }-- const handleImportUrl = async () => {- if (!importUrl.trim()) return- setImportLoading(true)- setError(null)- setImportSuccess(null)- try {- const workflow = await fetchWorkflowFromUrl(importUrl.trim())- const name = importName.trim() || new URL(importUrl).pathname.split('/').pop()?.replace('.json', '') || 'Imported Workflow'- const parsed = parseImportedWorkflow(name, workflow, 'manual', importUrl)- const template: WorkflowTemplate = {- ...parsed,- id: uuid(),- installedAt: Date.now(),- }- installWorkflow(template)- assignToModelName(modelName, template.id)- setImportUrl('')- setImportName('')- setImportSuccess(`Imported "${name}" and assigned to ${modelName}.`)- setTimeout(() => setImportSuccess(null), 4000)- } catch (err) {- setError(`Import failed: ${err instanceof Error ? err.message : String(err)}`)- } finally {- setImportLoading(false)- }- }-- const handleImportJson = () => {- if (!importJson.trim()) return- setError(null)- setImportSuccess(null)- try {- const json = JSON.parse(importJson.trim())- if (!validateWorkflowJson(json)) {- setError('Invalid workflow format. Expected ComfyUI API format with nodes (class_type).')- return- }- const name = importName.trim() || 'Imported Workflow'- const parsed = parseImportedWorkflow(name, json, 'manual')- const template: WorkflowTemplate = {- ...parsed,- id: uuid(),- installedAt: Date.now(),- }- installWorkflow(template)- assignToModelName(modelName, template.id)- setImportJson('')- setImportName('')- setImportSuccess(`Imported "${name}" and assigned to ${modelName}.`)- setTimeout(() => setImportSuccess(null), 4000)- } catch (err) {- if (err instanceof SyntaxError) {- setError('Invalid JSON. Please paste valid JSON.')- } else {- setError(`Import failed: ${err instanceof Error ? err.message : String(err)}`)- }- }- }-- const findInstalledWorkflow = (result: WorkflowSearchResult) =>- installedWorkflows.find(w => w.name === result.name && w.source === result.source)-- const isInstalledResult = (result: WorkflowSearchResult) => !!findInstalledWorkflow(result)-- const isActiveResult = (result: WorkflowSearchResult) => {- const installed = findInstalledWorkflow(result)- if (!installed) return false- const activeWf = useWorkflowStore.getState().getWorkflowForModel(modelName, modelType)- return activeWf?.id === installed.id- }-- const handleInstallOrUse = async (result: WorkflowSearchResult) => {- const existing = findInstalledWorkflow(result)- if (existing) {- // Already installed — just assign to current model- assignToModelName(modelName, existing.id)- return- }- // Not installed — download and install- handleInstallResult(result)- }-- const inputClass = 'w-full px-3 py-2 rounded-lg bg-white/5 border border-white/10 text-white text-sm focus:outline-none focus:border-white/20 placeholder-gray-500'-- return (- <Modal open={open} onClose={onClose} title="Workflow Finder">- <div className="relative">- <div className={`space-y-4 max-h-[70vh] flex flex-col transition-all duration-200 ${showApiKeyWarning ? 'blur-sm opacity-40 pointer-events-none' : ''}`}>- {/* Tab Bar */}- <div className="flex gap-1 p-1 rounded-lg bg-white/5">- {TABS.map((tab) => (- <button- key={tab.id}- onClick={() => handleTabChange(tab.id)}- className={`flex-1 px-3 py-1.5 rounded-md text-xs font-medium transition-colors ${- activeTab === tab.id- ? 'bg-white/15 text-white'- : 'text-gray-400 hover:text-white hover:bg-white/5'- }`}- >- {tab.label}- </button>- ))}- </div>-- {/* Search bar (Discover tab) */}- {activeTab === 'discover' && (- <>- <div className="flex gap-2">- <input- type="text"- value={query}- onChange={(e) => setQuery(e.target.value)}- onKeyDown={(e) => e.key === 'Enter' && handleSearch()}- placeholder="e.g. flux workflow, sdxl inpainting..."- className={`${inputClass} flex-1`}- />- <button- onClick={handleSearch}- disabled={loading}- className="px-3 py-2 rounded-lg bg-white/10 hover:bg-white/20 text-white transition-colors disabled:opacity-50"- >- {loading ? <Loader2 size={16} className="animate-spin" /> : <Search size={16} />}- </button>- <button- onClick={() => setShowApiKeyInput(!showApiKeyInput)}- className={`p-2 rounded-lg border transition-colors ${- civitaiApiKey- ? 'bg-emerald-500/10 border-emerald-500/30 text-emerald-400'- : 'bg-white/5 border-white/10 text-gray-500 hover:text-white'- }`}- title={civitaiApiKey ? 'API key set' : 'Add CivitAI API key (required for downloads)'}- aria-label="CivitAI API key"- >- <Key size={16} />- </button>- </div>-- {/* API Key Input */}- {showApiKeyInput && (- <div className="flex gap-2 items-center">- <div className="relative flex-1">- <input- type={showApiKey ? 'text' : 'password'}- value={civitaiApiKey}- onChange={(e) => setCivitaiApiKey(e.target.value)}- placeholder="CivitAI API key (civitai.com/user/account)"- className={`${inputClass} pr-8`}- />- <button- onClick={() => setShowApiKey(!showApiKey)}- className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-white"- aria-label="Toggle API key visibility"- >- {showApiKey ? <EyeOff size={14} /> : <Eye size={14} />}- </button>- </div>- {civitaiApiKey && (- <span className="text-[10px] text-emerald-400 flex-shrink-0">Saved</span>- )}- </div>- )}- </>- )}-- {/* Error */}- {error && (- <div className="flex items-start gap-2 p-2 rounded-lg bg-red-500/10 border border-red-500/20 text-red-300 text-xs">- <AlertCircle size={14} className="mt-0.5 flex-shrink-0" />- <span>{error}</span>- </div>- )}-- {/* Success — visible confirmation that the manual Import landed */}- {importSuccess && (- <div className="flex items-start gap-2 p-2 rounded-lg bg-emerald-500/10 border border-emerald-500/25 text-emerald-300 text-xs">- <span aria-hidden className="mt-0.5">✓</span>- <span>{importSuccess}</span>- </div>- )}-- {/* Content */}- {activeTab === 'import' ? (- <div className="space-y-3 overflow-y-auto flex-1">- <div>- <label className="text-xs font-medium text-gray-400 uppercase tracking-wider mb-1 block">Name</label>- <input- type="text"- value={importName}- onChange={(e) => setImportName(e.target.value)}- placeholder="Workflow name (optional)"- className={inputClass}- />- </div>-- <div>- <label className="text-xs font-medium text-gray-400 uppercase tracking-wider mb-1 block">URL Import</label>- <div className="flex gap-2">- <input- type="text"- value={importUrl}- onChange={(e) => setImportUrl(e.target.value)}- placeholder="https://example.com/workflow.json"- className={`${inputClass} flex-1`}- />- <button- onClick={handleImportUrl}- disabled={importLoading || !importUrl.trim()}- className="px-3 py-2 rounded-lg bg-white/10 hover:bg-white/20 text-white transition-colors disabled:opacity-50"- >- {importLoading ? <Loader2 size={16} className="animate-spin" /> : <Upload size={16} />}- </button>- </div>- </div>-- <div>- <label className="text-xs font-medium text-gray-400 uppercase tracking-wider mb-1 block">Paste JSON</label>- <textarea- value={importJson}- onChange={(e) => setImportJson(e.target.value)}- placeholder='{"1": {"class_type": "CheckpointLoaderSimple", ...}}'- className={`${inputClass} h-32 resize-none font-mono text-xs`}- />- <button- onClick={handleImportJson}- disabled={!importJson.trim()}- className="mt-2 w-full px-3 py-2 rounded-lg bg-white/10 hover:bg-white/20 text-white text-sm transition-colors disabled:opacity-50"- >- Import- </button>- </div>- </div>- ) : (- <div className="space-y-2 overflow-y-auto flex-1 min-h-0">- {loading && (- <div className="flex items-center justify-center py-4 text-gray-400 text-sm">- <Loader2 size={16} className="animate-spin mr-2" />- {installStatus || 'Searching...'}- </div>- )}- {!loading && results.length === 0 && !error && activeTab === 'discover' && (- <div className="text-center py-8 text-gray-500 text-sm">- Search for ComfyUI workflows- </div>- )}- {results.map((r, i) => (- <WorkflowCard- key={`${r.source}-${r.sourceUrl}-${i}`}- result={r}- isInstalled={isInstalledResult(r)}- isActive={isActiveResult(r)}- currentModelType={modelType}- onInstall={handleInstallOrUse}- />- ))}- </div>- )}- </div>-- {/* API Key Warning Overlay */}- {showApiKeyWarning && (- <div className="absolute inset-0 z-20 flex items-center justify-center p-6">- <div className="absolute inset-0 bg-black/60 rounded-2xl" onClick={() => setShowApiKeyWarning(false)} />- <div className="relative z-10 bg-neutral-900 border border-white/15 rounded-xl p-5 max-w-sm w-full space-y-4 shadow-2xl">- <div className="flex items-center gap-2">- <Key size={18} className="text-amber-400" />- <h3 className="text-sm font-semibold text-white">CivitAI API Key Required</h3>- </div>- <p className="text-xs text-gray-300 leading-relaxed">- CivitAI requires an API key to download workflows. You can create one for free in about a minute:- </p>- <button- onClick={() => openExternal('https://civitai.com/user/account')}- className="block w-full px-3 py-2 rounded-lg bg-white/10 hover:bg-white/15 border border-white/20 text-white text-sm font-medium text-center transition-colors"- >- Get Free API Key on CivitAI- </button>- <div>- <label className="text-[10px] font-medium text-gray-500 uppercase tracking-wider mb-1 block">Paste your key here</label>- <div className="relative">- <input- type={showApiKey ? 'text' : 'password'}- value={civitaiApiKey}- onChange={(e) => setCivitaiApiKey(e.target.value)}- placeholder="Your CivitAI API key"- className={`${inputClass} pr-8`}- autoFocus- />- <button- onClick={() => setShowApiKey(!showApiKey)}- className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-500 hover:text-white"- aria-label="Toggle API key visibility"- >- {showApiKey ? <EyeOff size={14} /> : <Eye size={14} />}- </button>- </div>- </div>- <div className="flex gap-2">- <button- onClick={() => setShowApiKeyWarning(false)}- className="flex-1 px-3 py-2 rounded-lg bg-white/10 hover:bg-white/15 text-gray-300 text-xs transition-colors"- >- Cancel- </button>- <button- onClick={() => {- if (civitaiApiKey) {- setShowApiKeyWarning(false)- setShowApiKeyInput(false)- }- }}- disabled={!civitaiApiKey}- className="flex-1 px-3 py-2 rounded-lg bg-white hover:bg-gray-200 disabled:opacity-40 text-gray-900 text-xs font-medium transition-colors"- >- Save & Continue- </button>- </div>- </div>- </div>- )}- </div>- </Modal>- )-}diff --git a/src/components/create/canvas/MaskCanvasEngine.ts b/src/components/create/canvas/MaskCanvasEngine.tsnew file mode 100644index 00000000..708ada1f--- /dev/null+++ b/src/components/create/canvas/MaskCanvasEngine.ts@@ -0,0 +1,155 @@+// ─────────────────────────────────────────────────────────────────────+// Framework-agnostic mask painting engine. Owns a mask buffer at SOURCE+// resolution (hard invariant — never display resolution, or ComfyUI's+// LoadImageMask misaligns). Exports white-where-painted on black (ComfyUI+// mask convention). Pure TS — ports back to src/components/create unchanged.+// ─────────────────────────────────────────────────────────────────────+export type Tool = 'brush' | 'eraser'++const UNDO_CAP = 20++export class MaskCanvasEngine {+ readonly width: number+ readonly height: number+ private mask: HTMLCanvasElement+ private ctx: CanvasRenderingContext2D+ private undoStack: ImageData[] = []+ private redoStack: ImageData[] = []+ private painting = false+ private lastX = 0+ private lastY = 0++ tool: Tool = 'brush'+ brushSize: number++ constructor(width: number, height: number) {+ this.width = Math.max(1, Math.round(width))+ this.height = Math.max(1, Math.round(height))+ this.mask = document.createElement('canvas')+ this.mask.width = this.width+ this.mask.height = this.height+ // willReadFrequently: undo snapshots + hasPaint do frequent getImageData.+ this.ctx = this.mask.getContext('2d', { willReadFrequently: true })!+ this.brushSize = Math.round(Math.max(this.width, this.height) * 0.06)+ }++ // ── stroke lifecycle (coords are in SOURCE pixels) ──+ beginStroke(x: number, y: number) {+ this.pushUndo()+ this.redoStack = []+ this.painting = true+ this.lastX = x+ this.lastY = y+ this.dab(x, y)+ }++ strokeTo(x: number, y: number) {+ if (!this.painting) return+ this.applyStyle()+ this.ctx.lineWidth = this.brushSize+ this.ctx.beginPath()+ this.ctx.moveTo(this.lastX, this.lastY)+ this.ctx.lineTo(x, y)+ this.ctx.stroke()+ this.lastX = x+ this.lastY = y+ }++ endStroke() { this.painting = false }++ private dab(x: number, y: number) {+ this.applyStyle()+ this.ctx.beginPath()+ this.ctx.arc(x, y, this.brushSize / 2, 0, Math.PI * 2)+ this.ctx.fill()+ }++ private applyStyle() {+ this.ctx.lineCap = 'round'+ this.ctx.lineJoin = 'round'+ if (this.tool === 'eraser') {+ this.ctx.globalCompositeOperation = 'destination-out'+ this.ctx.fillStyle = 'rgba(0,0,0,1)'+ this.ctx.strokeStyle = 'rgba(0,0,0,1)'+ } else {+ this.ctx.globalCompositeOperation = 'source-over'+ this.ctx.fillStyle = '#ffffff'+ this.ctx.strokeStyle = '#ffffff'+ }+ }++ // ── operations ──+ clear() {+ this.pushUndo()+ this.redoStack = []+ this.ctx.clearRect(0, 0, this.width, this.height)+ }++ invert() {+ this.pushUndo()+ this.redoStack = []+ const tmp = document.createElement('canvas')+ tmp.width = this.width; tmp.height = this.height+ const tctx = tmp.getContext('2d')!+ tctx.fillStyle = '#ffffff'+ tctx.fillRect(0, 0, this.width, this.height)+ tctx.globalCompositeOperation = 'destination-out'+ tctx.drawImage(this.mask, 0, 0)+ this.ctx.globalCompositeOperation = 'source-over'+ this.ctx.clearRect(0, 0, this.width, this.height)+ this.ctx.drawImage(tmp, 0, 0)+ }++ hasPaint(): boolean {+ const { data } = this.ctx.getImageData(0, 0, this.width, this.height)+ for (let i = 3; i < data.length; i += 4) if (data[i] !== 0) return true+ return false+ }++ // ── undo / redo (capped ring) ──+ private snapshot(): ImageData { return this.ctx.getImageData(0, 0, this.width, this.height) }+ private pushUndo() {+ this.undoStack.push(this.snapshot())+ if (this.undoStack.length > UNDO_CAP) this.undoStack.shift()+ }+ canUndo() { return this.undoStack.length > 0 }+ canRedo() { return this.redoStack.length > 0 }+ undo() {+ const prev = this.undoStack.pop()+ if (!prev) return+ this.redoStack.push(this.snapshot())+ this.ctx.globalCompositeOperation = 'source-over'+ this.ctx.putImageData(prev, 0, 0)+ }+ redo() {+ const next = this.redoStack.pop()+ if (!next) return+ this.undoStack.push(this.snapshot())+ this.ctx.globalCompositeOperation = 'source-over'+ this.ctx.putImageData(next, 0, 0)+ }++ // ── rendering / export ──+ /** Paint the mask, tinted red, onto a source-res overlay context. */+ renderOverlay(octx: CanvasRenderingContext2D) {+ octx.clearRect(0, 0, this.width, this.height)+ octx.globalCompositeOperation = 'source-over'+ octx.drawImage(this.mask, 0, 0)+ octx.globalCompositeOperation = 'source-in'+ octx.fillStyle = 'rgba(239,68,68,0.5)'+ octx.fillRect(0, 0, this.width, this.height)+ octx.globalCompositeOperation = 'source-over'+ }++ /** White-where-painted on black — the ComfyUI LoadImageMask convention. */+ exportMaskBlob(): Promise<Blob> {+ const out = document.createElement('canvas')+ out.width = this.width; out.height = this.height+ const octx = out.getContext('2d')!+ octx.fillStyle = '#000000'+ octx.fillRect(0, 0, this.width, this.height)+ octx.globalCompositeOperation = 'source-over'+ octx.drawImage(this.mask, 0, 0)+ return new Promise((resolve) => out.toBlob((b) => resolve(b!), 'image/png'))+ }+}diff --git a/src/components/create/experimental/AdvancedDrawer.tsx b/src/components/create/experimental/AdvancedDrawer.tsxnew file mode 100644index 00000000..25891ab5--- /dev/null+++ b/src/components/create/experimental/AdvancedDrawer.tsx@@ -0,0 +1,10 @@+import { Drawer } from '../ui/Drawer'+import { ParamGroups } from './ParamGroups'++export function AdvancedDrawer({ open, onClose }: { open: boolean; onClose: () => void }) {+ return (+ <Drawer open={open} onClose={onClose} title="Advanced settings" width={320}>+ <ParamGroups />+ </Drawer>+ )+}diff --git a/src/components/create/experimental/Composer.tsx b/src/components/create/experimental/Composer.tsxnew file mode 100644index 00000000..d6b8a147--- /dev/null+++ b/src/components/create/experimental/Composer.tsx@@ -0,0 +1,274 @@+import { useCallback, useRef, useState } from 'react'+import { motion, AnimatePresence } from 'framer-motion'+import { Sparkles, X, History, SlidersHorizontal, Square } from 'lucide-react'+import { useCreateStore, MODEL_TYPE_DEFAULTS } from '../../../stores/createStore'+import { useCreateExp } from './CreateContext'+import { intentToJob } from '../../../lib/render/cloud-jobs'+import { INTENT_MAP } from './intents'+import { ModelChip } from './ModelChip'+import { CreditsMeter } from './CreditsMeter'+import { Button } from '../ui/Button'+import { PromptField } from '../ui/PromptField'+import { Segmented } from '../ui/Segmented'+import { Slider } from '../ui/Slider'+import { Tooltip } from '../ui/Tooltip'+import { cn } from '../ui/cn'+import { useClickAway } from '../ui/useClickAway'++interface Props {+ onOpenAdvanced: () => void+}++export function Composer({ onOpenAdvanced }: Props) {+ const intent = useCreateStore((s) => s.intent())+ const meta = INTENT_MAP[intent]+ const prompt = useCreateStore((s) => s.prompt)+ const setPrompt = useCreateStore((s) => s.setPrompt)+ const negativePrompt = useCreateStore((s) => s.negativePrompt)+ const setNegativePrompt = useCreateStore((s) => s.setNegativePrompt)+ const showNegative = useCreateStore((s) => s.showNegative)+ const toggleNegative = useCreateStore((s) => s.toggleNegative)+ const source = useCreateStore((s) => s.source)+ const isGenerating = useCreateStore((s) => s.isGenerating)+ const backend = useCreateStore((s) => s.backend)+ const setBackend = useCreateStore((s) => s.setBackend)+ const { generate, cancel, cloudAvailable, quota } = useCreateExp()++ // The Create button turns into Cancel in place — a double-click's second+ // press would instantly cancel the run it just started. Ignore cancel+ // presses in the first 400ms after starting.+ const startedAt = useRef(0)+ const guardedGenerate = useCallback(() => {+ startedAt.current = Date.now()+ generate()+ }, [generate])+ const guardedCancel = useCallback(() => {+ if (Date.now() - startedAt.current < 400) return+ cancel()+ }, [cancel])++ const needPrompt = meta.needsPrompt+ const creditsOk =+ backend !== 'cloud' ||+ (quota != null && quota.remaining.credits >= quota.costs[intentToJob(intent).kind])+ const canGenerate =+ (!needPrompt || prompt.trim().length > 0) &&+ (!meta.needsSource || !!source) &&+ creditsOk++ return (+ <div className="shrink-0 px-4 pb-4 pt-2">+ <div className="mx-auto w-full max-w-[760px] space-y-2.5">+ {meta.id !== 'removebg' && <QuickControls />}++ <div className="rounded-[var(--radius-panel)] bg-white/[0.03] border border-white/[0.06] focus-within:border-white/15 transition-colors">+ {meta.needsPrompt && (+ <div className="px-3.5 pt-3">+ <PromptField+ value={prompt}+ onChange={setPrompt}+ placeholder={meta.placeholder}+ onSubmit={() => canGenerate && !isGenerating && guardedGenerate()}+ />+ </div>+ )}++ <AnimatePresence>+ {showNegative && meta.needsPrompt && (+ <motion.div+ initial={{ height: 0, opacity: 0 }}+ animate={{ height: 'auto', opacity: 1 }}+ exit={{ height: 0, opacity: 0 }}+ className="overflow-hidden"+ >+ <div className="mx-3.5 mt-2 pt-2 border-t border-white/[0.06]">+ <PromptField+ value={negativePrompt}+ onChange={setNegativePrompt}+ placeholder="Negative — what to avoid…"+ className="text-gray-400"+ />+ </div>+ </motion.div>+ )}+ </AnimatePresence>++ {!meta.needsPrompt && (+ <div className="px-3.5 py-3 t-body text-gray-500">+ No prompt needed — just hit Create to remove the background.+ </div>+ )}++ {/* Action bar */}+ <div className="flex items-center gap-1.5 px-2.5 py-2 border-t border-white/[0.05]">+ {meta.needsPrompt && (+ <button+ onClick={toggleNegative}+ className={cn('t-control px-2 h-[var(--control-h-sm)] rounded-md transition-colors', showNegative ? 'bg-white/10 text-gray-200' : 'text-gray-500 hover:text-gray-300 hover:bg-white/[0.05]')}+ title="Negative prompt"+ >+ Neg+ </button>+ )}+ {meta.needsPrompt && <PromptHistory onPick={setPrompt} />}+ <div className="flex-1" />+ {cloudAvailable && (+ <Tooltip content="Render on your own machine or on LU's confidential cloud GPUs.">+ <div>+ <Segmented+ size="sm"+ layoutId="backend-axis"+ value={backend}+ onChange={(v) => setBackend(v as 'local' | 'cloud')}+ options={[{ value: 'local', label: 'Local' }, { value: 'cloud', label: 'Cloud' }]}+ />+ </div>+ </Tooltip>+ )}+ {backend === 'cloud' && <CreditsMeter />}+ {meta.id !== 'removebg' && (+ <>+ <ModelChip />+ <Tooltip content="All advanced settings — sampler, seed, LoRA, VAE and more.">+ <Button variant="ghost" size="sm" icon={SlidersHorizontal} iconOnly onClick={onOpenAdvanced} title="Advanced settings" />+ </Tooltip>+ </>+ )}+ {isGenerating ? (+ <Button variant="danger" size="md" icon={X} onClick={guardedCancel}>Cancel</Button>+ ) : (+ <Button variant="primary" size="lg" icon={Sparkles} disabled={!canGenerate} onClick={guardedGenerate}>Create</Button>+ )}+ </div>+ </div>+ </div>+ </div>+ )+}++// Quality (proxy over steps) + Aspect (image) + Edit strength (edit).+function QuickControls() {+ const intent = useCreateStore((s) => s.intent())+ const meta = INTENT_MAP[intent]+ const steps = useCreateStore((s) => s.steps)+ const setSteps = useCreateStore((s) => s.setSteps)+ const denoise = useCreateStore((s) => s.denoise)+ const setDenoise = useCreateStore((s) => s.setDenoise)+ const imageModelType = useCreateStore((s) => s.imageModelType)+ const width = useCreateStore((s) => s.width)+ const height = useCreateStore((s) => s.height)+ const setSize = useCreateStore((s) => s.setSize)++ const base = MODEL_TYPE_DEFAULTS[imageModelType]?.steps ?? 25+ const qSteps = { Draft: Math.round(base * 0.6), Standard: base, High: Math.round(base * 1.5) }+ const activeQ = nearestKey(qSteps, steps)++ return (+ <div className="flex items-center justify-center gap-3 flex-wrap">+ <div className="flex items-center gap-2" style={{ transform: 'scale(0.7)', transformOrigin: 'center' }}>+ <LabeledControl label="Quality">+ <Segmented+ size="sm"+ layoutId="quality"+ value={activeQ}+ onChange={(k) => setSteps(qSteps[k as keyof typeof qSteps])}+ options={[{ value: 'Draft', label: 'Draft' }, { value: 'Standard', label: 'Standard' }, { value: 'High', label: 'High' }]}+ />+ </LabeledControl>++ {!meta.isVideo && (+ <LabeledControl label="Aspect">+ <Segmented+ size="sm"+ layoutId="aspect"+ value={aspectKey(width, height)}+ onChange={(k) => { const p = aspectPresets(imageModelType)[k as AspectKey]; setSize(p.w, p.h) }}+ options={[+ { value: '1:1', label: '1:1', icon: Square },+ { value: '3:4', label: '3:4' },+ { value: '4:3', label: '4:3' },+ { value: '16:9', label: '16:9' },+ ]}+ />+ </LabeledControl>+ )}+ </div>++ {meta.id === 'edit' && (+ <div className="w-44">+ <Slider label="Edit strength" min={0.05} max={1} step={0.05} value={denoise} onChange={setDenoise} format={(v) => v.toFixed(2)} />+ </div>+ )}+ </div>+ )+}++function LabeledControl({ label, children }: { label: string; children: React.ReactNode }) {+ return (+ <div className="flex items-center gap-1.5">+ <span className="t-label text-gray-600">{label}</span>+ {children}+ </div>+ )+}++function PromptHistory({ onPick }: { onPick: (p: string) => void }) {+ const history = useCreateStore((s) => s.promptHistory)+ const [open, setOpen] = useState(false)+ const ref = useRef<HTMLDivElement>(null)+ useClickAway(ref, () => setOpen(false), open)+ if (history.length === 0) return null+ return (+ <div ref={ref} className="relative">+ <Button variant="ghost" size="sm" icon={History} iconOnly title="Prompt history" onClick={() => setOpen((o) => !o)} />+ <AnimatePresence>+ {open && (+ <motion.div+ initial={{ opacity: 0, y: 4 }}+ animate={{ opacity: 1, y: 0 }}+ exit={{ opacity: 0, y: 4 }}+ transition={{ duration: 0.12 }}+ className="lu-elevated absolute bottom-full mb-1.5 left-0 z-50 w-72 rounded-lg p-1 max-h-64 overflow-y-auto scrollbar-thin"+ >+ {history.map((h, i) => (+ <button key={i} onClick={() => { onPick(h); setOpen(false) }} className="w-full text-left t-control text-gray-300 px-2.5 py-1.5 rounded-md hover:bg-white/[0.06] truncate">{h}</button>+ ))}+ </motion.div>+ )}+ </AnimatePresence>+ </div>+ )+}++// ── aspect helpers ──+type AspectKey = '1:1' | '3:4' | '4:3' | '16:9'+const RATIO: Record<AspectKey, number> = { '1:1': 1, '3:4': 3 / 4, '4:3': 4 / 3, '16:9': 16 / 9 }++function snap64(n: number): number { return Math.max(64, Math.round(n / 64) * 64) }++function aspectPresets(modelType: string): Record<AspectKey, { w: number; h: number }> {+ const def = MODEL_TYPE_DEFAULTS[modelType as keyof typeof MODEL_TYPE_DEFAULTS] ?? MODEL_TYPE_DEFAULTS.sdxl+ const baseLong = Math.max(def.width, def.height)+ const out = {} as Record<AspectKey, { w: number; h: number }>+ for (const k of Object.keys(RATIO) as AspectKey[]) {+ const r = RATIO[k]+ out[k] = r >= 1 ? { w: baseLong, h: snap64(baseLong / r) } : { w: snap64(baseLong * r), h: baseLong }+ }+ return out+}++function aspectKey(w: number, h: number): AspectKey {+ const r = w / h+ let best: AspectKey = '1:1'; let bestD = Infinity+ for (const k of Object.keys(RATIO) as AspectKey[]) {+ const d = Math.abs(RATIO[k] - r)+ if (d < bestD) { bestD = d; best = k }+ }+ return best+}++function nearestKey(map: Record<string, number>, val: number): string {+ let best = Object.keys(map)[0]; let bestD = Infinity+ for (const [k, v] of Object.entries(map)) { const d = Math.abs(v - val); if (d < bestD) { bestD = d; best = k } }+ return best+}diff --git a/src/components/create/experimental/CreateContext.tsx b/src/components/create/experimental/CreateContext.tsxnew file mode 100644index 00000000..123511ce--- /dev/null+++ b/src/components/create/experimental/CreateContext.tsx@@ -0,0 +1,125 @@+import { createContext, useContext, useEffect, useState, useCallback, type ReactNode } from 'react'+import { useCreate } from '../../../hooks/useCreate'+import { useCreateStore } from '../../../stores/createStore'+import { useUIStore } from '../../../stores/uiStore'+import { getLoraModels, getVAEModels } from '../../../api/comfyui'+import { getAllNodeInfo } from '../../../api/comfyui-nodes'+import { ensureLocalFilename } from './loadImage'+import type { CloudQuota } from '../../../lib/render/cloud-jobs'++/**+ * The seam between the redesigned Create surface and the live backend. Replaces+ * the sandbox mockStore's non-persisted actions (generate/cancel) and mockComfy+ * (uploadImage/installCapability/capability lists). Everything else the ported+ * components need is read straight from useCreateStore.+ */+interface CreateExpValue {+ generate: () => void | Promise<void>+ cancel: () => void | Promise<void>+ /** ComfyUI /object_info sampler + scheduler names (fallback lists until loaded). */+ samplerList: string[]+ schedulerList: string[]+ /** Installed LoRA + VAE filenames for the Advanced drawer. */+ loraList: string[]+ vaeList: string[]+ connected: boolean | null+ modelsLoaded: boolean+ modelLoadError: string | null+ /** Route a missing capability (e.g. background-removal nodes) to the Model Manager. */+ installCapability: (cap: 'rmbg') => void+ /** Runtime backend axis: hosted rendering offered for this session? */+ cloudAvailable: boolean+ quota: CloudQuota | null+ refreshQuota: () => Promise<void>+}++const Ctx = createContext<CreateExpValue | null>(null)++export function useCreateExp(): CreateExpValue {+ const v = useContext(Ctx)+ if (!v) throw new Error('useCreateExp must be used within <CreateExpProvider>')+ return v+}++export function CreateExpProvider({ children }: { children: ReactNode }) {+ const {+ generate, cancel, samplerList, schedulerList,+ connected, modelsLoaded, modelLoadError, checkConnection, fetchModels,+ } = useCreate()+ // Desktop build: no hosted rendering — the cloud axis is permanently off.+ const cloudAvailable = false+ const quota: CloudQuota | null = null+ const refreshQuota = useCallback(async () => {}, [])+ const backend = useCreateStore((s) => s.backend)+ const setBackend = useCreateStore((s) => s.setBackend)+ const setView = useUIStore((s) => s.setView)+ const setCaps = useCreateStore((s) => s.setCaps)+ const [loraList, setLoraList] = useState<string[]>([])+ const [vaeList, setVaeList] = useState<string[]>(['auto'])++ // Never strand the session on a dead axis: losing the license/logging out+ // while 'cloud' is selected falls back to local rendering.+ useEffect(() => {+ if (!cloudAvailable && backend === 'cloud') setBackend('local')+ }, [cloudAvailable, backend, setBackend])++ // Inputs picked while on cloud skip the ComfyUI staging (filename '') —+ // backfill it when the user switches to local so edit/animate keep working.+ useEffect(() => {+ if (backend !== 'local' || connected !== true) return+ const s = useCreateStore.getState()+ if (s.source && !s.source.filename) {+ ensureLocalFilename(s.source, 'source.png')+ .then((ref) => useCreateStore.getState().setSource(ref))+ .catch(() => { /* next generate surfaces the error */ })+ }+ if (s.mask && !s.mask.filename) {+ ensureLocalFilename(s.mask, 'mask.png')+ .then((ref) => useCreateStore.getState().setMask(ref))+ .catch(() => { /* next generate surfaces the error */ })+ }+ }, [backend, connected])++ // Bootstrap the backend exactly like the old CreateView mount did.+ useEffect(() => {+ checkConnection()+ fetchModels()+ }, [checkConnection, fetchModels])++ // Once ComfyUI is reachable, fetch LoRA/VAE lists and probe installed+ // capabilities (RMBG for cutout, inpaint nodes) so the UI gates correctly.+ useEffect(() => {+ if (connected !== true) return+ let cancelled = false+ ;(async () => {+ const [loras, vaes] = await Promise.all([+ getLoraModels().catch(() => [] as string[]),+ getVAEModels().catch(() => [] as string[]),+ ])+ if (cancelled) return+ setLoraList(loras)+ setVaeList(['auto', ...vaes])+ try {+ const nodes = await getAllNodeInfo()+ if (cancelled) return+ const names = new Set(Object.keys(nodes))+ setCaps({+ rmbg: names.has('RMBG'),+ 'inpaint-nodes': names.has('VAEEncodeForInpaint') || names.has('InpaintModelConditioning'),+ })+ } catch { /* node probe is best-effort */ }+ })()+ return () => { cancelled = true }+ }, [connected, setCaps])++ const installCapability = useCallback((_cap: 'rmbg') => { setView('models') }, [setView])++ const value: CreateExpValue = {+ generate,+ cancel,+ samplerList, schedulerList, loraList, vaeList,+ connected, modelsLoaded, modelLoadError, installCapability,+ cloudAvailable, quota, refreshQuota,+ }+ return <Ctx.Provider value={value}>{children}</Ctx.Provider>+}diff --git a/src/components/create/experimental/CreateExperimental.tsx b/src/components/create/experimental/CreateExperimental.tsxnew file mode 100644index 00000000..ca40c003--- /dev/null+++ b/src/components/create/experimental/CreateExperimental.tsx@@ -0,0 +1,87 @@+import { useEffect, useRef, useState } from 'react'+import { AnimatePresence, motion } from 'framer-motion'+import { AlertTriangle, X } from 'lucide-react'+import { useCreateStore, type GalleryItem } from '../../../stores/createStore'+import { CreateExpProvider, useCreateExp } from './CreateContext'+import { IntentBar } from './IntentBar'+import { Stage } from './Stage'+import { Composer } from './Composer'+import { GalleryStrip } from './GalleryStrip'+import { Lightbox } from './Lightbox'+import { AdvancedDrawer } from './AdvancedDrawer'+import { MaskEditor } from './MaskEditor'++/** The redesigned Create surface. Mounted by AppShell for currentView==='create'. */+export function CreateExperimental() {+ return (+ <CreateExpProvider>+ <CreateExperimentalInner />+ </CreateExpProvider>+ )+}++function CreateExperimentalInner() {+ const gallery = useCreateStore((s) => s.gallery)+ const error = useCreateStore((s) => s.error)+ const setError = useCreateStore((s) => s.setError)+ const { modelLoadError } = useCreateExp()++ const [pinnedId, setPinnedId] = useState<string | null>(null)+ const [advancedOpen, setAdvancedOpen] = useState(false)+ const [maskOpen, setMaskOpen] = useState(false)+ const [lightbox, setLightbox] = useState<GalleryItem | null>(null)++ // When a fresh generation lands on top, drop any pinned selection so the+ // newest result shows.+ const prevTop = useRef<string | undefined>(undefined)+ useEffect(() => {+ const top = gallery[0]?.id+ if (top && top !== prevTop.current) { setPinnedId(null); prevTop.current = top }+ }, [gallery])++ const displayed = (pinnedId ? gallery.find((g) => g.id === pinnedId) : undefined) ?? gallery[0]+ const banner = error ?? modelLoadError++ return (+ <div className="h-full w-full flex flex-col bg-[#141414] text-gray-200 overflow-hidden">+ <IntentBar />++ <AnimatePresence>+ {banner && (+ <motion.div+ initial={{ height: 0, opacity: 0 }}+ animate={{ height: 'auto', opacity: 1 }}+ exit={{ height: 0, opacity: 0 }}+ className="overflow-hidden shrink-0"+ >+ <div className="flex items-center gap-2 px-4 py-2 bg-red-500/10 border-b border-red-500/20 text-red-200 t-body">+ <AlertTriangle size={14} className="shrink-0" />+ <span className="flex-1 min-w-0 truncate">{banner}</span>+ {error && (+ <button onClick={() => setError(null)} className="shrink-0 text-red-300/70 hover:text-red-100" title="Dismiss">+ <X size={14} />+ </button>+ )}+ </div>+ </motion.div>+ )}+ </AnimatePresence>++ {/* Stage + Composer + right Advanced drawer share one relative container */}+ <div className="flex-1 min-h-0 relative flex flex-col">+ <Stage+ displayed={displayed}+ onOpenMaskEditor={() => setMaskOpen(true)}+ onFullscreen={(it) => setLightbox(it)}+ />+ <GalleryStrip activeId={pinnedId} onSelect={setPinnedId} />+ <Composer onOpenAdvanced={() => setAdvancedOpen(true)} />++ <AdvancedDrawer open={advancedOpen} onClose={() => setAdvancedOpen(false)} />+ <MaskEditor open={maskOpen} onClose={() => setMaskOpen(false)} />+ </div>++ <Lightbox item={lightbox} onClose={() => setLightbox(null)} />+ </div>+ )+}diff --git a/src/components/create/experimental/CreditsMeter.tsx b/src/components/create/experimental/CreditsMeter.tsxnew file mode 100644index 00000000..fce4a207--- /dev/null+++ b/src/components/create/experimental/CreditsMeter.tsx@@ -0,0 +1,49 @@+import { useCreateStore } from '../../../stores/createStore'+import { useCreateExp } from './CreateContext'+import { intentToJob } from '../../../lib/render/cloud-jobs'+import { Tooltip } from '../ui/Tooltip'+import { cn } from '../ui/cn'++// Compact credits meter for the cloud backend: remaining vs monthly budget,+// plus the cost of the run the user is about to start. One shared pool —+// images and clips draw from the same number. At 0 (or not enough for this+// run) it becomes the upsell chip and the Create button is gated off.+export function CreditsMeter() {+ const { quota } = useCreateExp()+ const intent = useCreateStore((s) => s.intent())+ if (!quota) return null++ const { kind } = intentToJob(intent)+ const cost = quota.costs[kind]+ const remaining = quota.remaining.credits+ const limit = quota.limits.credits+ const enough = remaining >= cost+ const pct = limit > 0 ? Math.max(0, Math.min(1, remaining / limit)) : 0++ if (!enough) {+ return (+ <a+ href="/pricing"+ className="t-control px-2 h-[var(--control-h-sm)] inline-flex items-center rounded-md bg-amber-500/15 text-amber-300 hover:bg-amber-500/25 transition-colors"+ >+ {remaining <= 0 ? 'Out of credits — upgrade' : `Needs ${cost} credits (${remaining} left)`}+ </a>+ )+ }++ return (+ <Tooltip+ content={`${remaining} of ${limit} credits left this month — this ${kind === 'video' ? 'clip' : 'image'} uses ${cost}.`}+ >+ <div className="flex items-center gap-1.5 px-2 h-[var(--control-h-sm)] rounded-md bg-white/[0.04] text-gray-400 t-control">+ <div className="w-12 h-1 rounded-full bg-white/10 overflow-hidden">+ <div+ className={cn('h-full rounded-full', pct > 0.25 ? 'bg-emerald-400/80' : 'bg-amber-400/80')}+ style={{ width: `${pct * 100}%` }}+ />+ </div>+ <span className="tabular-nums">{remaining}</span>+ </div>+ </Tooltip>+ )+}diff --git a/src/components/create/experimental/GalleryStrip.tsx b/src/components/create/experimental/GalleryStrip.tsxnew file mode 100644index 00000000..a9dd48ae--- /dev/null+++ b/src/components/create/experimental/GalleryStrip.tsx@@ -0,0 +1,60 @@+import { motion } from 'framer-motion'+import { Trash2, Play } from 'lucide-react'+import { useCreateStore } from '../../../stores/createStore'+import { galleryItemUrl } from './galleryUrl'+import { cn } from '../ui/cn'++interface Props {+ activeId: string | null+ onSelect: (id: string) => void+}++export function GalleryStrip({ activeId, onSelect }: Props) {+ const gallery = useCreateStore((s) => s.gallery)+ const removeFromGallery = useCreateStore((s) => s.removeFromGallery)+ if (gallery.length === 0) return null++ return (+ <div className="shrink-0 border-t border-white/[0.05] px-4 py-2.5">+ <div className="flex items-center gap-2 mb-1.5">+ <span className="t-label text-gray-600">Gallery</span>+ <span className="t-mono text-gray-700">{gallery.length}</span>+ </div>+ <div className="flex gap-2 overflow-x-auto scrollbar-thin pb-1">+ {gallery.map((g) => (+ <motion.div+ key={g.id}+ initial={{ opacity: 0, scale: 0.9 }}+ animate={{ opacity: 1, scale: 1 }}+ className="relative group shrink-0"+ >+ <button+ onClick={() => onSelect(g.id)}+ className={cn(+ 'w-14 h-14 rounded-lg overflow-hidden border-2 transition-colors relative',+ (activeId ?? gallery[0]?.id) === g.id ? 'border-white/60' : 'border-transparent hover:border-white/20',+ g.intent === 'removebg' && 'lu-checker',+ )}+ >+ {g.type === 'video' ? (+ <>+ <video src={galleryItemUrl(g)} muted playsInline className="w-full h-full object-cover" />+ <span className="absolute inset-0 flex items-center justify-center bg-black/20"><Play size={14} className="text-white/90" /></span>+ </>+ ) : (+ <img src={galleryItemUrl(g)} alt="" className="w-full h-full object-cover" />+ )}+ </button>+ <button+ onClick={() => removeFromGallery(g.id)}+ className="absolute -top-1 -right-1 w-4 h-4 rounded-full bg-black/70 text-gray-300 hover:text-white opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center"+ title="Delete"+ >+ <Trash2 size={9} />+ </button>+ </motion.div>+ ))}+ </div>+ </div>+ )+}diff --git a/src/components/create/experimental/IntentBar.tsx b/src/components/create/experimental/IntentBar.tsxnew file mode 100644index 00000000..2dbc5b3c--- /dev/null+++ b/src/components/create/experimental/IntentBar.tsx@@ -0,0 +1,61 @@+import { useCreateStore } from '../../../stores/createStore'+import { INTENTS } from './intents'+import { cn } from '../ui/cn'++// Pure-CSS expand: no Framer layout projection anywhere, so nothing can snap or+// jitter on settle. The label opens via a `max-width` transition (collapses+// reliably to 0 — unlike grid `0fr`, which keeps its min-content floor — and+// interpolates as a plain length, so it's always smooth). The active pill+// cross-fades via colour/shadow; neighbours slide on natural flex reflow.+const EASE = 'ease-[cubic-bezier(0.22,1,0.36,1)]'++export function IntentBar() {+ const intent = useCreateStore((s) => s.intent())+ const setIntent = useCreateStore((s) => s.setIntent)++ return (+ <div+ role="radiogroup"+ aria-label="Create mode"+ className="flex items-center justify-center gap-1 px-4 py-0.5"+ // Sized to sit just 9% larger than the QuickControls ratio bar below+ // (which runs at scale 0.7): 0.7 × 1.09 ≈ 0.763.+ style={{ transform: 'scale(0.763)', transformOrigin: 'center' }}+ >+ {INTENTS.map((meta) => {+ const selected = intent === meta.id+ const Icon = meta.icon+ return (+ <button+ key={meta.id}+ role="radio"+ aria-checked={selected}+ aria-label={meta.label}+ title={meta.label}+ onClick={() => setIntent(meta.id)}+ className={cn(+ 'flex items-center h-9 rounded-full border lu-focus-ring transition-[background-color,border-color,box-shadow,color] duration-200',+ EASE,+ selected+ ? 'bg-white/[0.11] border-white/20 shadow-sm text-white'+ : 'border-transparent text-gray-500 hover:text-gray-200 hover:bg-white/[0.05]',+ )}+ >+ <span className="grid place-items-center w-9 h-9 shrink-0">+ <Icon size={16} strokeWidth={selected ? 2 : 1.75} />+ </span>+ <span+ className={cn(+ 'overflow-hidden whitespace-nowrap min-w-0 t-control transition-[max-width,opacity,padding] duration-200',+ EASE,+ selected ? 'max-w-[150px] opacity-100 pl-1 pr-3.5' : 'max-w-0 opacity-0 px-0',+ )}+ >+ {meta.label}+ </span>+ </button>+ )+ })}+ </div>+ )+}diff --git a/src/components/create/experimental/Lightbox.tsx b/src/components/create/experimental/Lightbox.tsxnew file mode 100644index 00000000..7a83e0e7--- /dev/null+++ b/src/components/create/experimental/Lightbox.tsx@@ -0,0 +1,56 @@+import { useEffect } from 'react'+import { motion, AnimatePresence } from 'framer-motion'+import { X } from 'lucide-react'+import type { GalleryItem } from '../../../stores/createStore'+import { galleryItemUrl } from './galleryUrl'+import { cn } from '../ui/cn'++export function Lightbox({ item, onClose }: { item: GalleryItem | null; onClose: () => void }) {+ useEffect(() => {+ if (!item) return+ const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose() }+ window.addEventListener('keydown', onKey)+ return () => window.removeEventListener('keydown', onKey)+ }, [item, onClose])++ return (+ <AnimatePresence>+ {item && (+ <motion.div+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ exit={{ opacity: 0 }}+ onClick={onClose}+ className="fixed inset-0 z-[80] bg-black/85 flex items-center justify-center p-8"+ >+ <button onClick={onClose} className="absolute top-4 right-4 w-9 h-9 flex items-center justify-center rounded-lg bg-white/10 text-gray-200 hover:bg-white/20">+ <X size={18} />+ </button>+ {item.type === 'video' ? (+ <motion.video+ initial={{ scale: 0.95 }}+ animate={{ scale: 1 }}+ exit={{ scale: 0.95 }}+ src={galleryItemUrl(item)}+ controls+ autoPlay+ loop+ onClick={(e) => e.stopPropagation()}+ className="max-w-full max-h-full object-contain rounded-lg"+ />+ ) : (+ <motion.img+ initial={{ scale: 0.95 }}+ animate={{ scale: 1 }}+ exit={{ scale: 0.95 }}+ src={galleryItemUrl(item)}+ alt={item.prompt}+ onClick={(e) => e.stopPropagation()}+ className={cn('max-w-full max-h-full object-contain rounded-lg', item.intent === 'removebg' && 'lu-checker')}+ />+ )}+ </motion.div>+ )}+ </AnimatePresence>+ )+}diff --git a/src/components/create/experimental/MaskEditor.tsx b/src/components/create/experimental/MaskEditor.tsxnew file mode 100644index 00000000..40ee51d1--- /dev/null+++ b/src/components/create/experimental/MaskEditor.tsx@@ -0,0 +1,281 @@+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'+import { motion, AnimatePresence } from 'framer-motion'+import {+ Brush, Eraser, Undo2, Redo2, FlipHorizontal2, Trash2, ZoomIn, ZoomOut, Maximize,+ X, Check, Hand,+} from 'lucide-react'+import { useCreateStore, type ImageRef } from '../../../stores/createStore'+import { uploadImage } from '../../../api/comfyui'+import { MaskCanvasEngine, type Tool } from '../canvas/MaskCanvasEngine'+import { Slider } from '../ui/Slider'+import { Button } from '../ui/Button'+import { cn } from '../ui/cn'++export function MaskEditor({ open, onClose }: { open: boolean; onClose: () => void }) {+ const source = useCreateStore((s) => s.source)+ return (+ <AnimatePresence>+ {open && source && <MaskEditorInner key={source.filename} onClose={onClose} />}+ </AnimatePresence>+ )+}++function MaskEditorInner({ onClose }: { onClose: () => void }) {+ const source = useCreateStore((s) => s.source)!+ const setMask = useCreateStore((s) => s.setMask)++ const viewportRef = useRef<HTMLDivElement>(null)+ const stackRef = useRef<HTMLDivElement>(null)+ const imageRef = useRef<HTMLCanvasElement>(null)+ const overlayRef = useRef<HTMLCanvasElement>(null)+ const cursorRef = useRef<HTMLCanvasElement>(null)+ const engineRef = useRef<MaskCanvasEngine | null>(null)++ const [tool, setTool] = useState<Tool>('brush')+ const [brushSize, setBrushSize] = useState(0)+ const [view, setView] = useState({ scale: 1, x: 0, y: 0 })+ const [, force] = useState(0)+ const rerender = useCallback(() => force((n) => n + 1), [])++ const painting = useRef(false)+ const spaceDown = useRef(false)+ const panning = useRef(false)+ const panStart = useRef({ x: 0, y: 0, vx: 0, vy: 0 })+ const touched = useRef(false)++ const maxBrush = Math.round(Math.max(source.width, source.height) * 0.4)++ const renderOverlay = useCallback(() => {+ const e = engineRef.current, octx = overlayRef.current?.getContext('2d')+ if (e && octx) e.renderOverlay(octx)+ }, [])++ // ── init engine + draw source ──+ useEffect(() => {+ const e = new MaskCanvasEngine(source.width, source.height)+ engineRef.current = e+ setBrushSize(e.brushSize)++ const img = new Image()+ img.onload = () => {+ const ictx = imageRef.current?.getContext('2d')+ if (ictx) ictx.drawImage(img, 0, 0, source.width, source.height)+ }+ img.src = source.url+ renderOverlay()+ rerender()+ return () => { engineRef.current = null }+ }, [source, renderOverlay, rerender])++ // ── fit view to viewport ──+ useLayoutEffect(() => {+ const vp = viewportRef.current+ if (!vp) return+ const fit = Math.min((vp.clientWidth - 48) / source.width, (vp.clientHeight - 48) / source.height)+ setView({ scale: Math.max(0.05, fit), x: 0, y: 0 })+ }, [source])++ // ── pointer → source coords ──+ const toSource = useCallback((clientX: number, clientY: number) => {+ const rect = overlayRef.current!.getBoundingClientRect()+ return {+ x: ((clientX - rect.left) / rect.width) * source.width,+ y: ((clientY - rect.top) / rect.height) * source.height,+ }+ }, [source])++ const drawCursor = useCallback((sx: number, sy: number) => {+ const cctx = cursorRef.current?.getContext('2d')+ const e = engineRef.current+ if (!cctx || !e) return+ cctx.clearRect(0, 0, source.width, source.height)+ cctx.beginPath()+ cctx.arc(sx, sy, e.brushSize / 2, 0, Math.PI * 2)+ cctx.strokeStyle = tool === 'eraser' ? 'rgba(255,120,120,0.9)' : 'rgba(255,255,255,0.9)'+ cctx.lineWidth = Math.max(1, 2 / view.scale)+ cctx.stroke()+ }, [source, tool, view.scale])++ // Show the brush ring at canvas center on open so the tool reads as ready+ // immediately (until the user first moves the pointer).+ useEffect(() => {+ if (!touched.current) drawCursor(source.width / 2, source.height / 2)+ }, [source, drawCursor])++ const onPointerDown = (e: React.PointerEvent) => {+ const eng = engineRef.current!+ if (spaceDown.current || e.button === 1) {+ panning.current = true+ panStart.current = { x: e.clientX, y: e.clientY, vx: view.x, vy: view.y }+ try { (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId) } catch { /* synthetic / unsupported */ }+ return+ }+ if (e.button !== 0) return+ const { x, y } = toSource(e.clientX, e.clientY)+ eng.beginStroke(x, y)+ painting.current = true+ try { (e.currentTarget as HTMLElement).setPointerCapture(e.pointerId) } catch { /* synthetic / unsupported */ }+ renderOverlay()+ }++ const onPointerMove = (e: React.PointerEvent) => {+ if (panning.current) {+ setView((v) => ({ ...v, x: panStart.current.vx + (e.clientX - panStart.current.x), y: panStart.current.vy + (e.clientY - panStart.current.y) }))+ return+ }+ touched.current = true+ const { x, y } = toSource(e.clientX, e.clientY)+ drawCursor(x, y)+ if (painting.current) {+ engineRef.current!.strokeTo(x, y)+ renderOverlay()+ }+ }++ const endInteraction = () => {+ if (painting.current) { engineRef.current!.endStroke(); painting.current = false; rerender() }+ panning.current = false+ }++ const onWheel = (e: React.WheelEvent) => {+ const factor = e.deltaY < 0 ? 1.12 : 1 / 1.12+ setView((v) => ({ ...v, scale: Math.min(8, Math.max(0.05, v.scale * factor)) }))+ }++ const fitView = useCallback(() => {+ const vp = viewportRef.current+ if (!vp) return+ const fit = Math.min((vp.clientWidth - 48) / source.width, (vp.clientHeight - 48) / source.height)+ setView({ scale: Math.max(0.05, fit), x: 0, y: 0 })+ }, [source])++ // ── keyboard shortcuts ──+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (e.key === 'Escape') { onClose(); return }+ if (e.key === ' ') { spaceDown.current = true; return }+ const eng = engineRef.current+ if (!eng) return+ const mod = e.metaKey || e.ctrlKey+ if (mod && e.key.toLowerCase() === 'z') { e.preventDefault(); if (e.shiftKey) eng.redo(); else eng.undo(); renderOverlay(); rerender(); return }+ if (e.key === 'y') { eng.redo(); renderOverlay(); rerender(); return }+ if (e.key === '[') { setBrush(eng, Math.max(4, eng.brushSize - 8)) }+ if (e.key === ']') { setBrush(eng, Math.min(maxBrush, eng.brushSize + 8)) }+ if (e.key.toLowerCase() === 'b') { eng.tool = 'brush'; setTool('brush') }+ if (e.key.toLowerCase() === 'e') { eng.tool = 'eraser'; setTool('eraser') }+ if (e.key.toLowerCase() === 'i') { eng.invert(); renderOverlay(); rerender() }+ }+ const onUp = (e: KeyboardEvent) => { if (e.key === ' ') spaceDown.current = false }+ const setBrush = (eng: MaskCanvasEngine, n: number) => { eng.brushSize = n; setBrushSize(n) }+ window.addEventListener('keydown', onKey)+ window.addEventListener('keyup', onUp)+ return () => { window.removeEventListener('keydown', onKey); window.removeEventListener('keyup', onUp) }+ }, [onClose, renderOverlay, rerender, maxBrush])++ const apply = async () => {+ const eng = engineRef.current!+ if (!eng.hasPaint()) { setMask(null); onClose(); return }+ const blob = await eng.exportMaskBlob()+ // Cloud sessions may have no ComfyUI to stage into — the cloud path+ // re-uploads from the blob URL at submit time (filename stays '').+ const filename =+ useCreateStore.getState().backend === 'cloud'+ ? ''+ : await uploadImage(new File([blob], 'mask.png', { type: 'image/png' }))+ const ref: ImageRef = { filename, url: URL.createObjectURL(blob), width: source.width, height: source.height }+ setMask(ref)+ onClose()+ }++ const eng = engineRef.current+ return (+ <motion.div+ initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}+ role="dialog" aria-modal="true" aria-labelledby="mask-editor-title"+ className="fixed inset-0 z-[90] bg-[#141414] flex flex-col"+ >+ {/* top bar */}+ <div className="flex items-center justify-between px-4 h-12 border-b border-white/[0.06] shrink-0">+ <div className="flex items-center gap-2">+ <Brush size={15} className="text-gray-300" />+ <span id="mask-editor-title" className="t-title text-gray-200">Mask editor</span>+ <span className="t-mono text-gray-600 ml-2">{source.width}×{source.height}</span>+ </div>+ <div className="flex items-center gap-2">+ <Button variant="ghost" icon={X} onClick={onClose}>Cancel</Button>+ <Button variant="primary" icon={Check} onClick={apply}>Apply mask</Button>+ </div>+ </div>++ {/* toolbar */}+ <div className="flex items-center gap-2 px-4 py-2 border-b border-white/[0.05] shrink-0 flex-wrap">+ <div className="inline-flex gap-0.5 p-0.5 rounded-[var(--radius-control)] bg-white/[0.04] border border-white/[0.06]">+ <ToolBtn active={tool === 'brush'} icon={Brush} label="Brush (B)" onClick={() => { eng && (eng.tool = 'brush'); setTool('brush') }} />+ <ToolBtn active={tool === 'eraser'} icon={Eraser} label="Eraser (E)" onClick={() => { eng && (eng.tool = 'eraser'); setTool('eraser') }} />+ </div>+ <div className="w-40"><Slider label="Size" min={4} max={maxBrush} step={1} value={brushSize} onChange={(v) => { if (eng) eng.brushSize = v; setBrushSize(v) }} unit="px" /></div>+ <Divider />+ <Button variant="ghost" size="sm" icon={Undo2} iconOnly title="Undo (⌘Z)" disabled={!eng?.canUndo()} onClick={() => { eng?.undo(); renderOverlay(); rerender() }} />+ <Button variant="ghost" size="sm" icon={Redo2} iconOnly title="Redo (⇧⌘Z)" disabled={!eng?.canRedo()} onClick={() => { eng?.redo(); renderOverlay(); rerender() }} />+ <Button variant="ghost" size="sm" icon={FlipHorizontal2} iconOnly title="Invert (I)" onClick={() => { eng?.invert(); renderOverlay(); rerender() }} />+ <Button variant="ghost" size="sm" icon={Trash2} iconOnly title="Clear" onClick={() => { eng?.clear(); renderOverlay(); rerender() }} />+ <Divider />+ <Button variant="ghost" size="sm" icon={ZoomOut} iconOnly title="Zoom out" onClick={() => setView((v) => ({ ...v, scale: Math.max(0.05, v.scale / 1.2) }))} />+ <Button variant="ghost" size="sm" icon={ZoomIn} iconOnly title="Zoom in" onClick={() => setView((v) => ({ ...v, scale: Math.min(8, v.scale * 1.2) }))} />+ <Button variant="ghost" size="sm" icon={Maximize} iconOnly title="Fit" onClick={fitView} />+ <span className="t-mono text-gray-600">{Math.round(view.scale * 100)}%</span>+ <div className="flex-1" />+ <span className="inline-flex items-center gap-1.5 t-control text-gray-500"><Hand size={13} /> hold Space to pan · scroll to zoom</span>+ </div>++ {/* canvas viewport */}+ <div+ ref={viewportRef}+ onWheel={onWheel}+ className="flex-1 min-h-0 min-w-0 overflow-hidden relative flex items-center justify-center"+ style={{ cursor: panning.current || spaceDown.current ? 'grab' : 'none' }}+ >+ <div+ ref={stackRef}+ onPointerDown={onPointerDown}+ onPointerMove={onPointerMove}+ onPointerUp={endInteraction}+ onPointerLeave={() => { const cctx = cursorRef.current?.getContext('2d'); cctx?.clearRect(0, 0, source.width, source.height); endInteraction() }}+ style={{+ width: source.width,+ height: source.height,+ transform: `translate(${view.x}px, ${view.y}px) scale(${view.scale})`,+ touchAction: 'none',+ }}+ className="relative shrink-0"+ >+ <canvas ref={imageRef} width={source.width} height={source.height} className="absolute inset-0 rounded-sm" style={{ width: source.width, height: source.height }} />+ <canvas ref={overlayRef} width={source.width} height={source.height} className="absolute inset-0 pointer-events-none" style={{ width: source.width, height: source.height }} />+ <canvas ref={cursorRef} width={source.width} height={source.height} className="absolute inset-0 pointer-events-none" style={{ width: source.width, height: source.height }} />+ </div>+ </div>++ {/* polarity caption */}+ <div className="flex items-center justify-center gap-2 py-2.5 border-t border-white/[0.06] shrink-0">+ <span className="w-3 h-3 rounded-sm" style={{ background: 'rgba(239,68,68,0.6)' }} />+ <span className="t-body text-gray-400">Red = will be regenerated. Paint over what you want the AI to change.</span>+ </div>+ </motion.div>+ )+}++function ToolBtn({ active, icon: Icon, label, onClick }: { active: boolean; icon: typeof Brush; label: string; onClick: () => void }) {+ return (+ <button+ onClick={onClick}+ title={label}+ aria-label={label}+ aria-pressed={active}+ className={cn('h-[var(--control-h-md)] aspect-square inline-flex items-center justify-center rounded-[6px] transition-colors lu-focus-ring', active ? 'bg-white/[0.16] text-white border border-white/30 shadow-sm' : 'text-gray-500 hover:text-gray-200 hover:bg-white/[0.04]')}+ >+ <Icon size={15} />+ </button>+ )+}++function Divider() { return <span className="w-px h-5 bg-white/[0.08] mx-0.5" /> }diff --git a/src/components/create/experimental/ModelChip.tsx b/src/components/create/experimental/ModelChip.tsxnew file mode 100644index 00000000..4dc7315b--- /dev/null+++ b/src/components/create/experimental/ModelChip.tsx@@ -0,0 +1,49 @@+import { useCreateStore } from '../../../stores/createStore'+import { Select, type SelectOption } from '../ui/Select'+import { TYPE_BADGE } from './badges'++// Badge-aware model picker (replaces the raw <select>). Desktop build: only+// the locally installed checkpoints — the web app's hosted-catalog branch+// (backend === 'cloud') does not exist here.+export function ModelChip() {+ const mode = useCreateStore((s) => s.mode)+ const imageModel = useCreateStore((s) => s.imageModel)+ const videoModel = useCreateStore((s) => s.videoModel)+ const imageModelList = useCreateStore((s) => s.imageModelList)+ const videoModelList = useCreateStore((s) => s.videoModelList)+ const setImageModel = useCreateStore((s) => s.setImageModel)+ const setVideoModel = useCreateStore((s) => s.setVideoModel)++ const isVideo = mode === 'video'++ const list = isVideo ? videoModelList : imageModelList+ const value = isVideo ? videoModel : imageModel++ const options: SelectOption[] = list.map((m) => ({+ value: m.name,+ label: prettyName(m.name),+ badge: TYPE_BADGE[m.type],+ }))++ return (+ <Select+ size="sm"+ searchable+ align="right"+ className="min-w-[150px] max-w-[230px]"+ options={options}+ value={value}+ onChange={(v) => {+ if (isVideo) setVideoModel(v)+ else {+ const m = list.find((x) => x.name === v)+ setImageModel(v, m?.type ?? 'unknown')+ }+ }}+ />+ )+}++function prettyName(filename: string): string {+ return filename.replace(/\.(safetensors|ckpt|pt|gguf)$/i, '').replace(/[_]+/g, ' ')+}diff --git a/src/components/create/experimental/OutputView.tsx b/src/components/create/experimental/OutputView.tsxnew file mode 100644index 00000000..a33edfcb--- /dev/null+++ b/src/components/create/experimental/OutputView.tsx@@ -0,0 +1,117 @@+import { motion } from 'framer-motion'+import { Cpu, Sparkles, ImageDown, Maximize2, Download, Wand2 } from 'lucide-react'+import { useCreateStore, type GalleryItem, type ProgressPhase } from '../../../stores/createStore'+import { downloadComfyFile } from '../../../api/backend'+import { galleryItemUrl } from './galleryUrl'+import { cn } from '../ui/cn'++function phaseIcon(phase: ProgressPhase) {+ if (phase === 'loading-model' || phase === 'loading-clip' || phase === 'loading-vae') return <Cpu size={20} className="text-amber-300" />+ if (phase === 'sampling') return <Sparkles size={20} className="text-green-300" />+ if (phase === 'decoding') return <ImageDown size={20} className="text-lu-accent" />+ return <Sparkles size={20} className="text-gray-400" />+}++// Generation progress — phase-aware animation.+export function GeneratingView() {+ const progressPhase = useCreateStore((s) => s.progressPhase)+ const progressText = useCreateStore((s) => s.progressText)+ const progress = useCreateStore((s) => s.progress)+ const isLoading = progressPhase === 'loading-model' || progressPhase === 'loading-clip' || progressPhase === 'loading-vae'++ return (+ <div className="flex-1 flex flex-col items-center justify-center p-8">+ <div className="space-y-6 flex flex-col items-center">+ <div className="relative w-16 h-16">+ {isLoading ? (+ <>+ <motion.div className="absolute inset-0 rounded-full border border-amber-400/30" animate={{ scale: [1, 1.6], opacity: [0.5, 0] }} transition={{ duration: 3, repeat: Infinity, ease: 'easeOut' }} />+ <div className="absolute inset-0 rounded-full border border-amber-400/20 flex items-center justify-center">+ <motion.div animate={{ rotate: 360 }} transition={{ duration: 3, repeat: Infinity, ease: 'linear' }}>{phaseIcon(progressPhase)}</motion.div>+ </div>+ </>+ ) : progressPhase === 'sampling' ? (+ <>+ <motion.div className="absolute inset-0 rounded-full border border-green-400/30" animate={{ scale: [1, 1.8], opacity: [0.4, 0] }} transition={{ duration: 1.2, repeat: Infinity, ease: 'easeOut' }} />+ <motion.div className="absolute inset-0 rounded-full border border-green-400/20" animate={{ scale: [1, 1.5], opacity: [0.3, 0] }} transition={{ duration: 1.2, repeat: Infinity, ease: 'easeOut', delay: 0.3 }} />+ <div className="absolute inset-0 rounded-full border border-green-400/10 flex items-center justify-center">{phaseIcon(progressPhase)}</div>+ </>+ ) : (+ <>+ <motion.div className="absolute inset-0 rounded-full border border-white/20" animate={{ scale: [1, 1.8], opacity: [0.4, 0] }} transition={{ duration: 2, repeat: Infinity, ease: 'easeOut' }} />+ <motion.div className="absolute inset-0 rounded-full border border-white/15" animate={{ scale: [1, 1.5], opacity: [0.3, 0] }} transition={{ duration: 2, repeat: Infinity, ease: 'easeOut', delay: 0.5 }} />+ <div className="absolute inset-0 rounded-full border border-white/10 flex items-center justify-center">{phaseIcon(progressPhase)}</div>+ </>+ )}+ </div>+ <p className="t-body text-gray-400 tracking-wide">{progressText || 'Generating…'}</p>+ {progress > 0 && (+ <div className="w-56 h-1 bg-white/10 rounded-full overflow-hidden">+ <motion.div className="h-full rounded-full bg-lu-accent" initial={{ width: 0 }} animate={{ width: `${Math.min(progress, 100)}%` }} transition={{ duration: 0.3 }} />+ </div>+ )}+ </div>+ </div>+ )+}++interface ResultProps {+ item: GalleryItem+ onFullscreen: () => void+ onSendToEditor?: () => void+}++export function ResultView({ item, onFullscreen, onSendToEditor }: ResultProps) {+ const url = galleryItemUrl(item)+ // Desktop build: every gallery item is a ComfyUI output (dataUrl was the+ // MLX path, remoteUrl the cloud path — both web-only). downloadComfyFile+ // goes through the native Save-As dialog, which WebView2 blob-anchors can't.+ const download = () => downloadComfyFile(item.filename, item.subfolder)+ const isVideo = item.type === 'video'+ return (+ <div className="flex-1 flex flex-col items-center justify-center p-6 min-h-0">+ <div className="relative group max-w-full max-h-full">+ {isVideo ? (+ <video+ src={url}+ controls+ loop+ autoPlay+ muted+ className="max-w-full max-h-[62vh] object-contain rounded-[var(--radius-panel)] border border-white/[0.06]"+ />+ ) : (+ <img+ src={url}+ alt={item.prompt}+ className={cn('max-w-full max-h-[62vh] object-contain rounded-[var(--radius-panel)] border border-white/[0.06]', item.intent === 'removebg' && 'lu-checker')}+ />+ )}+ <div className="absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">+ {onSendToEditor && !isVideo && (+ <IconBtn title="Edit with mask" onClick={onSendToEditor}><Wand2 size={14} /></IconBtn>+ )}+ <IconBtn title="Download" onClick={download}><Download size={14} /></IconBtn>+ <IconBtn title="Fullscreen" onClick={onFullscreen}><Maximize2 size={14} /></IconBtn>+ </div>+ </div>+ <div className="flex items-center gap-3 mt-3 t-mono text-gray-600">+ <span>{item.width}×{item.height}</span>+ <span>·</span>+ <span>seed {item.seed}</span>+ <span>·</span>+ <span className="truncate max-w-[280px]">{prettyModel(item.model)}</span>+ </div>+ </div>+ )+}++function IconBtn({ children, title, onClick }: { children: React.ReactNode; title: string; onClick: () => void }) {+ return (+ <button onClick={onClick} title={title} className="w-7 h-7 flex items-center justify-center rounded-lg bg-black/50 backdrop-blur text-gray-200 hover:text-white hover:bg-black/70 transition-colors">+ {children}+ </button>+ )+}++function prettyModel(f: string): string { return f.replace(/\.(safetensors|ckpt|pt)$/i, '').replace(/[_]+/g, ' ') }diff --git a/src/components/create/experimental/ParamGroups.tsx b/src/components/create/experimental/ParamGroups.tsxnew file mode 100644index 00000000..bc536620--- /dev/null+++ b/src/components/create/experimental/ParamGroups.tsx@@ -0,0 +1,125 @@+import { Gauge, Boxes, FlaskConical, RotateCcw, HelpCircle } from 'lucide-react'+import { useCreateStore } from '../../../stores/createStore'+import { useCreateExp } from './CreateContext'+import { INTENT_MAP } from './intents'+import { SAMPLERS as SAMPLERS_FALLBACK, SCHEDULERS as SCHEDULERS_FALLBACK } from './badges'+import { Section } from '../ui/Section'+import { Slider } from '../ui/Slider'+import { Select } from '../ui/Select'+import { NumberField } from '../ui/NumberField'+import { Button } from '../ui/Button'+import { Tooltip } from '../ui/Tooltip'+import { cn } from '../ui/cn'++// The full param surface, reorganized into 3 frequency-ranked Sections.+// Sampler/scheduler/LoRA/VAE lists come live from ComfyUI via CreateContext,+// falling back to the standard node names until they load.+export function ParamGroups() {+ const s = useCreateStore()+ const { samplerList, schedulerList, loraList, vaeList } = useCreateExp()+ const meta = INTENT_MAP[s.intent()]+ const isVideo = meta.isVideo+ const isEdit = meta.id === 'edit'++ const samplers = samplerList.length ? samplerList : SAMPLERS_FALLBACK+ const schedulers = schedulerList.length ? schedulerList : SCHEDULERS_FALLBACK+ const vaes = vaeList.length ? vaeList : ['auto']++ return (+ <div className="py-1">+ {/* QUALITY */}+ <Section title="Quality" icon={Gauge} defaultOpen+ right={<Button variant="ghost" size="sm" icon={RotateCcw} iconOnly title="Reset to model defaults" onClick={s.resetParamsToModelDefaults} />}+ >+ <Slider label="Steps" min={1} max={60} step={1} value={s.steps} onChange={s.setSteps} />+ <Slider label={isVideo ? 'Guidance' : 'CFG scale'} min={0} max={30} step={0.5} value={s.cfgScale} onChange={s.setCfgScale} format={(v) => v.toFixed(1)} />+ <div className="grid grid-cols-2 gap-2">+ <NumberField label="Width" value={s.width} min={64} max={4096} step={64} mono onChange={(v) => s.setSize(v, s.height)} suffix="px" />+ <NumberField label="Height" value={s.height} min={64} max={4096} step={64} mono onChange={(v) => s.setSize(s.width, v)} suffix="px" />+ </div>+ </Section>++ {/* OUTPUT */}+ <Section title="Output" icon={Boxes} defaultOpen>+ <NumberField label="Seed (−1 = random)" value={s.seed} step={1} mono onRandomize={() => s.setSeed(-1)} onChange={s.setSeed} />+ {!isVideo && <Slider label="Batch size" min={1} max={8} step={1} value={s.batchSize} onChange={s.setBatchSize} />}+ {isVideo && (+ <div className="grid grid-cols-2 gap-2">+ <Slider label="Frames" min={1} max={120} step={1} value={s.frames} onChange={s.setFrames} />+ <Slider label="FPS" min={1} max={60} step={1} value={s.fps} onChange={s.setFps} />+ </div>+ )}+ </Section>++ {/* EXPERT */}+ <Section title="Expert" icon={FlaskConical} defaultOpen={false}>+ <Field label="Sampler" help="The algorithm that turns noise into your image. dpmpp_2m / euler are safe all-rounders.">+ <Select size="sm" options={samplers.map((x) => ({ value: x, label: x }))} value={s.sampler} onChange={s.setSampler} />+ </Field>+ <Field label="Scheduler" help="How the denoise steps are spaced. karras is a good default for SDXL; simple for FLUX.">+ <Select size="sm" options={schedulers.map((x) => ({ value: x, label: x }))} value={s.scheduler} onChange={s.setScheduler} />+ </Field>++ {isEdit && (+ <Slider label="Denoise (raw)" min={0.05} max={1} step={0.05} value={s.denoise} onChange={s.setDenoise} format={(v) => v.toFixed(2)} />+ )}+ {meta.allowsMask && (+ <Slider label="Mask edge feather" min={0} max={64} step={1} value={s.growMaskBy} onChange={s.setGrowMaskBy} unit="px" />+ )}++ {!isVideo && loraList.length > 0 && (+ <div className="space-y-1.5">+ <div className="t-control text-gray-400">LoRA stack {s.selectedLoras.length > 0 && <span className="t-mono text-gray-600">· {s.selectedLoras.length} active</span>}</div>+ <div className="space-y-1 max-h-44 overflow-y-auto scrollbar-thin">+ {loraList.map((name) => {+ const active = s.selectedLoras.find((l) => l.name === name)+ return (+ <div key={name} className={cn('rounded-md border transition-colors', active ? 'border-white/15 bg-white/[0.06]' : 'border-white/[0.06]')}>+ <button onClick={() => s.toggleLora(name)} className="w-full flex items-center justify-between px-2.5 py-1.5 t-control text-left text-gray-300">+ <span className="truncate">{name.replace(/\.safetensors$/, '')}</span>+ <span className={cn('t-mono', active ? 'text-emerald-400' : 'text-gray-600')}>{active ? 'on' : 'off'}</span>+ </button>+ {active && (+ <div className="px-2.5 pb-2">+ <Slider min={0} max={2} step={0.05} value={active.strength} onChange={(v) => s.setLoraStrengthFor(name, v)} format={(v) => v.toFixed(2)} />+ </div>+ )}+ </div>+ )+ })}+ </div>+ </div>+ )}++ {!isVideo && (+ <Field label="VAE" help="Override the checkpoint's built-in VAE. 'auto' lets the checkpoint decide.">+ <Select size="sm" options={vaes.map((v) => ({ value: v, label: v }))} value={s.selectedVae} onChange={s.setSelectedVae} />+ </Field>+ )}+ {!isVideo && (+ <Slider label="Skip CLIP layers" min={0} max={12} step={1} value={s.clipSkip} onChange={s.setClipSkip} />+ )}+ </Section>+ </div>+ )+}++function Field({ label, help, children }: { label: string; help?: string; children: React.ReactNode }) {+ return (+ <div className="space-y-1.5">+ <div className="flex items-center gap-1.5">+ <span className="t-control text-gray-400">{label}</span>+ {help && <HelpDot help={help} />}+ </div>+ {children}+ </div>+ )+}++function HelpDot({ help }: { help: string }) {+ return (+ <Tooltip content={help} side="bottom">+ <HelpCircle size={12} className="text-gray-600 hover:text-gray-400" />+ </Tooltip>+ )+}diff --git a/src/components/create/experimental/Stage.tsx b/src/components/create/experimental/Stage.tsxnew file mode 100644index 00000000..846bc964--- /dev/null+++ b/src/components/create/experimental/Stage.tsx@@ -0,0 +1,215 @@+import { useRef, useState } from 'react'+import { motion, AnimatePresence } from 'framer-motion'+import { UploadCloud, ImagePlus, Scissors, Wand2, Sparkles, X, Loader2 } from 'lucide-react'+import { useCreateStore, type GalleryItem } from '../../../stores/createStore'+import { useCreateExp } from './CreateContext'+import { INTENT_MAP } from './intents'+import { GeneratingView, ResultView } from './OutputView'+import { EmptyState } from '../ui/EmptyState'+import { Button } from '../ui/Button'+import { cn } from '../ui/cn'+import { loadImageRef } from './loadImage'++interface Props {+ displayed?: GalleryItem+ onOpenMaskEditor: () => void+ onFullscreen: (item: GalleryItem) => void+}++export function Stage({ displayed, onOpenMaskEditor, onFullscreen }: Props) {+ const intent = useCreateStore((s) => s.intent())+ const meta = INTENT_MAP[intent]+ const isGenerating = useCreateStore((s) => s.isGenerating)+ const source = useCreateStore((s) => s.source)+ const sourceSetAt = useCreateStore((s) => s.sourceSetAt)+ const setPrompt = useCreateStore((s) => s.setPrompt)+ const caps = useCreateStore((s) => s.caps)+ const capReady = meta.capability ? caps[meta.capability] : true++ // A result counts for the current source only if it was generated after the+ // source was loaded — otherwise an older gallery item would hijack the stage.+ const freshResult = displayed && displayed.createdAt >= sourceSetAt++ let body: React.ReactNode+ if (isGenerating) {+ body = <GeneratingView />+ } else if (meta.capability && !capReady) {+ body = <CapabilityCard cap={meta.capability} />+ } else if (meta.needsSource && !source) {+ body = <InputSlot />+ } else if (meta.needsSource && source && !freshResult) {+ body = <SourcePreview onOpenMaskEditor={onOpenMaskEditor} />+ } else if (displayed) {+ body = (+ <ResultView+ item={displayed}+ onFullscreen={() => onFullscreen(displayed)}+ onSendToEditor={!meta.isVideo ? onOpenMaskEditor : undefined}+ />+ )+ } else {+ body = (+ <EmptyState icon={Sparkles} logoSrc="/LU-monogram-white.png" title={teachTitle(intent)}>+ {meta.examples.length > 0 && (+ <div className="flex flex-wrap justify-center gap-1.5 pt-1">+ {meta.examples.map((ex) => (+ <button+ key={ex}+ onClick={() => setPrompt(ex)}+ className="t-control text-gray-400 px-2.5 py-1.5 rounded-full bg-white/[0.04] border border-white/[0.06] hover:border-white/15 hover:text-gray-200 transition-colors"+ >+ {ex}+ </button>+ ))}+ </div>+ )}+ </EmptyState>+ )+ }++ return (+ <div className="flex-1 min-h-0 flex flex-col overflow-hidden">+ <AnimatePresence mode="wait">+ <motion.div+ key={intent + (isGenerating ? ':gen' : '')}+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ exit={{ opacity: 0 }}+ transition={{ duration: 0.12 }}+ className="flex-1 min-h-0 flex flex-col"+ >+ {body}+ </motion.div>+ </AnimatePresence>+ </div>+ )+}++function teachTitle(intent: string): string {+ switch (intent) {+ case 'image': return 'What do you want to create?'+ case 'video': return 'Describe a scene to animate'+ default: return 'Get started'+ }+}++// ── Source upload dropzone ──+function InputSlot() {+ const setSource = useCreateStore((s) => s.setSource)+ const setError = useCreateStore((s) => s.setError)+ const intent = useCreateStore((s) => s.intent())+ const meta = INTENT_MAP[intent]+ const inputRef = useRef<HTMLInputElement>(null)+ const [drag, setDrag] = useState(false)+ const [loading, setLoading] = useState(false)++ const handleFile = async (file: File) => {+ // Drag&drop bypasses the input's accept filter — validate here so a+ // stray .txt/.pdf gets a message instead of a silent no-op.+ if (!/^image\/(png|jpe?g|webp)$/i.test(file.type)) {+ setError('That file type is not supported — use PNG, JPG or WebP.')+ return+ }+ setLoading(true)+ setError(null)+ try {+ setSource(await loadImageRef(file))+ } catch (err) {+ setError(`Could not load the image: ${err instanceof Error ? err.message : String(err)}`)+ } finally {+ setLoading(false)+ }+ }++ return (+ <div className="flex-1 flex flex-col items-center justify-center p-6">+ <div+ onClick={() => inputRef.current?.click()}+ onDragOver={(e) => { e.preventDefault(); setDrag(true) }}+ onDragLeave={() => setDrag(false)}+ onDrop={(e) => { e.preventDefault(); setDrag(false); const f = e.dataTransfer.files[0]; if (f) handleFile(f) }}+ className={cn(+ 'w-full max-w-sm aspect-[5/4] min-h-[220px] max-h-[44vh] rounded-[var(--radius-panel)] border-2 border-dashed flex flex-col items-center justify-center gap-3 cursor-pointer transition-colors',+ drag ? 'border-blue-400 bg-blue-500/10' : 'border-white/10 bg-white/[0.02] hover:border-white/20',+ )}+ >+ {loading ? <Loader2 className="animate-spin text-gray-400" size={28} /> : (+ meta.id === 'removebg' ? <Scissors className="text-gray-500" size={28} strokeWidth={1.5} /> : <UploadCloud className="text-gray-500" size={28} strokeWidth={1.5} />+ )}+ <div className="text-center">+ <div className="t-title text-gray-300">{meta.id === 'removebg' ? 'Drop an image to cut out' : meta.id === 'animate' ? 'Drop an image to animate' : 'Drop an image to edit'}</div>+ <div className="t-body text-gray-600">or click to browse · PNG, JPG, WebP</div>+ </div>+ <input ref={inputRef} type="file" accept="image/*" className="hidden" onChange={(e) => { const f = e.target.files?.[0]; if (f) handleFile(f) }} />+ </div>+ </div>+ )+}++// ── Source loaded, awaiting generation ──+function SourcePreview({ onOpenMaskEditor }: { onOpenMaskEditor: () => void }) {+ const source = useCreateStore((s) => s.source)+ const mask = useCreateStore((s) => s.mask)+ const setSource = useCreateStore((s) => s.setSource)+ const setMask = useCreateStore((s) => s.setMask)+ const intent = useCreateStore((s) => s.intent())+ const meta = INTENT_MAP[intent]++ // Zombie render: an intent switch drops the source in the same store update+ // that swaps this component out, but the child subscription can fire first.+ if (!source) return null++ return (+ <div className="flex-1 flex flex-col items-center justify-center p-6">+ <div className="relative">+ <img src={source.url} alt="source" className={cn('max-h-[52vh] max-w-full object-contain rounded-[var(--radius-panel)] border border-white/[0.06]', intent === 'removebg' && 'lu-checker')} />+ {mask && (+ <div className="absolute top-2 left-2 t-label text-gray-300 bg-black/50 px-2 py-1 rounded-md">mask painted</div>+ )}+ <button+ onClick={() => { setSource(null); setMask(null) }}+ className="absolute top-2 right-2 w-7 h-7 flex items-center justify-center rounded-lg bg-black/50 text-gray-300 hover:text-white"+ title="Remove image"+ >+ <X size={14} />+ </button>+ </div>+ <div className="flex items-center gap-2 mt-4">+ {meta.allowsMask && (+ <Button variant="secondary" icon={Wand2} onClick={onOpenMaskEditor}>{mask ? 'Edit mask' : 'Paint mask'}</Button>+ )}+ <ChangeImageButton onChange={(r) => setSource(r)} />+ </div>+ <p className="t-body text-gray-600 mt-3 text-center max-w-sm">+ {meta.id === 'removebg' ? 'Hit Create to cut out the subject and export a transparent PNG.'+ : meta.allowsMask ? 'Paint a mask over what should change, write the edit prompt below, then Create. Or skip the mask for a full image-to-image pass.'+ : 'Describe the motion below, then Create.'}+ </p>+ </div>+ )+}++function ChangeImageButton({ onChange }: { onChange: (r: Awaited<ReturnType<typeof loadImageRef>>) => void }) {+ const inputRef = useRef<HTMLInputElement>(null)+ return (+ <>+ <Button variant="ghost" icon={ImagePlus} onClick={() => inputRef.current?.click()}>Change image</Button>+ <input ref={inputRef} type="file" accept="image/*" className="hidden" onChange={async (e) => { const f = e.target.files?.[0]; if (f) onChange(await loadImageRef(f)) }} />+ </>+ )+}++// ── Capability missing → route to Model Manager ──+function CapabilityCard({ cap }: { cap: 'rmbg' }) {+ const { installCapability } = useCreateExp()+ return (+ <EmptyState+ icon={Scissors}+ tone="accent"+ title="Background Removal needs a quick one-time download"+ description="The AI cutout model (ComfyUI-RMBG / BiRefNet) runs fully locally. Get it from the Model Manager — about 300 MB — and this becomes a one-click action."+ action={{ label: 'Get this feature', icon: UploadCloud, onClick: () => installCapability(cap) }}+ secondaryAction={{ label: 'Open Model Manager', onClick: () => installCapability(cap) }}+ />+ )+}diff --git a/src/components/create/experimental/badges.ts b/src/components/create/experimental/badges.tsnew file mode 100644index 00000000..14c35b68--- /dev/null+++ b/src/components/create/experimental/badges.ts@@ -0,0 +1,29 @@+import type { ModelType } from '../../../api/comfyui'++/** Model-type badge map — single source for the redesign's ModelChip + Badge.+ * Mirrors ParamPanel.tsx's private TYPE_BADGE (uselu's ModelType set). */+export const TYPE_BADGE: Record<ModelType, { label: string; color: string }> = {+ flux: { label: 'FLUX', color: 'bg-purple-500/15 text-purple-300' },+ flux2: { label: 'FLUX 2', color: 'bg-purple-500/15 text-purple-300' },+ zimage: { label: 'Z-Image', color: 'bg-rose-500/15 text-rose-300' },+ ernie_image: { label: 'Ernie', color: 'bg-yellow-500/15 text-yellow-300' },+ sdxl: { label: 'SDXL', color: 'bg-blue-500/15 text-blue-300' },+ sd15: { label: 'SD 1.5', color: 'bg-green-500/15 text-green-300' },+ wan: { label: 'Wan', color: 'bg-orange-500/15 text-orange-300' },+ wan22: { label: 'Wan 2.2', color: 'bg-orange-500/15 text-orange-300' },+ hunyuan: { label: 'Hunyuan', color: 'bg-red-500/15 text-red-300' },+ ltx: { label: 'LTX', color: 'bg-cyan-500/15 text-cyan-300' },+ mochi: { label: 'Mochi', color: 'bg-pink-500/15 text-pink-300' },+ cosmos: { label: 'Cosmos', color: 'bg-emerald-500/15 text-emerald-300' },+ cogvideo: { label: 'CogVideo', color: 'bg-amber-500/15 text-amber-300' },+ svd: { label: 'SVD', color: 'bg-indigo-500/15 text-indigo-300' },+ framepack: { label: 'FramePack', color: 'bg-teal-500/15 text-teal-300' },+ pyramidflow: { label: 'PyramidFlow', color: 'bg-violet-500/15 text-violet-300' },+ allegro: { label: 'Allegro', color: 'bg-rose-500/15 text-rose-300' },+ unknown: { label: 'Model', color: 'bg-white/10 text-gray-400' },+}++/** Fallback sampler/scheduler lists — used until ComfyUI's /object_info lists+ * arrive via useCreate (threaded through CreateContext). Standard ComfyUI names. */+export const SAMPLERS = ['euler', 'euler_ancestral', 'dpmpp_2m', 'dpmpp_2m_sde', 'dpmpp_3m_sde', 'heun', 'dpm_2', 'lms', 'ddim', 'uni_pc']+export const SCHEDULERS = ['normal', 'karras', 'simple', 'sgm_uniform', 'exponential', 'beta', 'ddim_uniform']diff --git a/src/components/create/experimental/galleryUrl.ts b/src/components/create/experimental/galleryUrl.tsnew file mode 100644index 00000000..2e09c7e0--- /dev/null+++ b/src/components/create/experimental/galleryUrl.ts@@ -0,0 +1,9 @@+import { getImageUrl } from '../../../api/comfyui'+import type { GalleryItem } from '../../../stores/createStore'++/** Resolve a gallery item's display URL. Priority mirrors MediaViewer/Gallery:+ * remoteUrl (cloud signed URL) → dataUrl (MLX self-contained PNG) → ComfyUI+ * /view path (filename/subfolder). */+export function galleryItemUrl(item: GalleryItem): string {+ return item.remoteUrl ?? item.dataUrl ?? getImageUrl(item.filename, item.subfolder)+}diff --git a/src/components/create/experimental/intents.ts b/src/components/create/experimental/intents.tsnew file mode 100644index 00000000..9da3a4bc--- /dev/null+++ b/src/components/create/experimental/intents.ts@@ -0,0 +1,59 @@+import { Image as ImageIcon, Wand2, Scissors, Video, Film } from 'lucide-react'+import type { LucideIcon } from 'lucide-react'+import type { CreateIntent } from '../../../stores/createStore'++export interface IntentMeta {+ id: CreateIntent+ label: string+ short: string+ icon: LucideIcon+ placeholder: string+ needsSource: boolean+ needsPrompt: boolean+ allowsMask: boolean+ isVideo: boolean+ /** Capability id (custom-node bundle) this intent depends on, if any. */+ capability?: 'rmbg'+ examples: string[]+}++export const INTENTS: IntentMeta[] = [+ {+ id: 'image', label: 'Image', short: 'Image', icon: ImageIcon,+ placeholder: 'Describe your image…',+ needsSource: false, needsPrompt: true, allowsMask: false, isVideo: false,+ examples: [+ 'a lighthouse at dusk, dramatic storm clouds, cinematic',+ 'a neon-lit alley in the rain, reflections, moody',+ 'a cozy reading nook by a window, warm morning light',+ ],+ },+ {+ id: 'edit', label: 'Edit Image', short: 'Edit', icon: Wand2,+ placeholder: 'Describe the edit — what should change in the painted area…',+ needsSource: true, needsPrompt: true, allowsMask: true, isVideo: false,+ examples: ['replace the sky with a starry night', 'add a leather jacket', 'remove the person on the left'],+ },+ {+ id: 'removebg', label: 'Remove Background', short: 'Cutout', icon: Scissors,+ placeholder: '',+ needsSource: true, needsPrompt: false, allowsMask: false, isVideo: false,+ capability: 'rmbg',+ examples: [],+ },+ {+ id: 'video', label: 'Video', short: 'Video', icon: Video,+ placeholder: 'Describe the motion and the scene…',+ needsSource: false, needsPrompt: true, allowsMask: false, isVideo: true,+ examples: ['a slow-motion wave breaking on rocks, cinematic', 'timelapse of clouds over a mountain range'],+ },+ {+ id: 'animate', label: 'Animate Image', short: 'Animate', icon: Film,+ placeholder: 'Describe how the image should move…',+ needsSource: true, needsPrompt: true, allowsMask: false, isVideo: true,+ examples: ['slow zoom in, subtle parallax', 'hair and clothes moving in the wind'],+ },+]++export const INTENT_MAP: Record<CreateIntent, IntentMeta> =+ Object.fromEntries(INTENTS.map((i) => [i.id, i])) as Record<CreateIntent, IntentMeta>diff --git a/src/components/create/experimental/loadImage.ts b/src/components/create/experimental/loadImage.tsnew file mode 100644index 00000000..02e64733--- /dev/null+++ b/src/components/create/experimental/loadImage.ts@@ -0,0 +1,43 @@+import { uploadImage } from '../../../api/comfyui'+import { useCreateStore } from '../../../stores/createStore'+import type { ImageRef } from '../../../stores/createStore'++function readDataUrl(file: Blob): Promise<string> {+ return new Promise((resolve, reject) => {+ const r = new FileReader()+ r.onload = () => resolve(r.result as string)+ r.onerror = reject+ r.readAsDataURL(file)+ })+}++function imageSize(url: string): Promise<{ width: number; height: number }> {+ return new Promise((resolve) => {+ const img = new Image()+ img.onload = () => resolve({ width: img.naturalWidth || 1024, height: img.naturalHeight || 1024 })+ img.onerror = () => resolve({ width: 1024, height: 1024 })+ img.src = url+ })+}++/** File → ImageRef. Always reads a data URL for preview (and for the cloud+ * path, which re-uploads from it at submit time). On the local backend the+ * file is additionally uploaded to ComfyUI (/upload/image) to obtain the+ * input/ filename the local workflow uses — on cloud there may be no+ * ComfyUI at all, so that step is skipped and filename stays ''. */+export async function loadImageRef(file: File): Promise<ImageRef> {+ const url = await readDataUrl(file)+ const { width, height } = await imageSize(url)+ const backend = useCreateStore.getState().backend+ const filename = backend === 'cloud' ? '' : await uploadImage(file)+ return { filename, url, width, height }+}++/** Backfill the ComfyUI filename for a ref picked while on the cloud backend+ * (filename '') so switching cloud → local keeps edit/animate working. */+export async function ensureLocalFilename(ref: ImageRef, name: string): Promise<ImageRef> {+ if (ref.filename) return ref+ const blob = await (await fetch(ref.url)).blob()+ const filename = await uploadImage(new File([blob], name, { type: blob.type || 'image/png' }))+ return { ...ref, filename }+}diff --git a/src/components/create/ui/Button.tsx b/src/components/create/ui/Button.tsxnew file mode 100644index 00000000..1ca558b2--- /dev/null+++ b/src/components/create/ui/Button.tsx@@ -0,0 +1,78 @@++import { motion } from 'framer-motion'+import { Loader2 } from 'lucide-react'+import type { LucideIcon } from 'lucide-react'+import { cn } from './cn'++type Variant = 'primary' | 'secondary' | 'ghost' | 'danger'+type Size = 'sm' | 'md' | 'lg'++interface Props {+ children?: React.ReactNode+ onClick?: () => void+ variant?: Variant+ size?: Size+ icon?: LucideIcon+ iconOnly?: boolean+ loading?: boolean+ disabled?: boolean+ fullWidth?: boolean+ title?: string+ ariaLabel?: string+ type?: 'button' | 'submit'+ active?: boolean+}++const SIZE_H: Record<Size, string> = {+ sm: 'h-[var(--control-h-sm)]',+ md: 'h-[var(--control-h-md)]',+ lg: 'h-[var(--control-h-lg)]',+}+const SIZE_PX: Record<Size, string> = {+ sm: 'px-2 gap-1.5',+ md: 'px-3 gap-2',+ lg: 'px-4 gap-2',+}+const ICON_SIZE: Record<Size, number> = { sm: 13, md: 14, lg: 16 }++// Matches the live app exactly: the primary action (Generate) is a neutral+// white-translucent button — the app uses NO loud accent fill. Emphasis comes+// from the icon + size, not colour.+const VARIANT: Record<Variant, string> = {+ primary: 'bg-gray-900 text-white dark:bg-white/10 dark:text-white hover:bg-gray-700 dark:hover:bg-white/15 font-medium',+ secondary: 'bg-white/10 text-gray-100 hover:bg-white/15',+ ghost: 'bg-transparent text-gray-400 hover:text-white hover:bg-white/8',+ danger: 'bg-red-500/15 text-red-500 dark:text-red-400 hover:bg-red-500/25',+}++export function Button({+ children, onClick, variant = 'secondary', size = 'md', icon: Icon,+ iconOnly = false, loading = false, disabled = false, fullWidth = false,+ title, ariaLabel, type = 'button', active = false,+}: Props) {+ const isDisabled = disabled || loading+ return (+ <motion.button+ type={type}+ title={title}+ aria-label={ariaLabel ?? title}+ aria-busy={loading || undefined}+ onClick={onClick}+ disabled={isDisabled}+ whileTap={isDisabled ? undefined : { scale: 0.96 }}+ className={cn(+ 't-control inline-flex items-center justify-center select-none transition-colors lu-focus-ring rounded-[var(--radius-control)]',+ SIZE_H[size],+ iconOnly ? 'aspect-square' : SIZE_PX[size],+ VARIANT[variant],+ active && variant === 'ghost' && 'bg-white/10 text-white',+ fullWidth && 'w-full',+ isDisabled && 'opacity-40 pointer-events-none',+ )}+ >+ {loading ? <Loader2 size={ICON_SIZE[size]} className="animate-spin" />+ : Icon ? <Icon size={ICON_SIZE[size]} /> : null}+ {!iconOnly && children}+ </motion.button>+ )+}\ No newline at end of filediff --git a/src/components/create/ui/Drawer.tsx b/src/components/create/ui/Drawer.tsxnew file mode 100644index 00000000..b93d0a1a--- /dev/null+++ b/src/components/create/ui/Drawer.tsx@@ -0,0 +1,79 @@++import { useEffect, useRef } from 'react'+import { motion, AnimatePresence } from 'framer-motion'+import { X } from 'lucide-react'+import { cn } from './cn'++interface Props {+ open: boolean+ onClose: () => void+ title?: string+ width?: number+ children: React.ReactNode+ footer?: React.ReactNode+}++// Right slide-over. Soft scrim (no hard backdrop) so params stay in context of+// the result; full-height on the right edge of the stage.+export function Drawer({ open, onClose, title, width = 320, children, footer }: Props) {+ const closeRef = useRef<HTMLButtonElement>(null)+ const prevFocus = useRef<HTMLElement | null>(null)+ const wasOpen = useRef(false)++ // Move focus into the drawer on open, restore it on close — but ONLY on the+ // actual open↔close transition, never on unrelated parent re-renders (which+ // would otherwise steal focus while the drawer is closed).+ useEffect(() => {+ if (open && !wasOpen.current) {+ prevFocus.current = document.activeElement as HTMLElement+ closeRef.current?.focus()+ } else if (!open && wasOpen.current) {+ prevFocus.current?.focus?.()+ }+ wasOpen.current = open+ }, [open])++ useEffect(() => {+ if (!open) return+ const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose() }+ window.addEventListener('keydown', onKey)+ return () => window.removeEventListener('keydown', onKey)+ }, [open, onClose])++ return (+ <AnimatePresence>+ {open && (+ <>+ <motion.div+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ exit={{ opacity: 0 }}+ transition={{ duration: 0.15 }}+ onClick={onClose}+ className="absolute inset-0 z-40 bg-black/20"+ />+ <motion.aside+ initial={{ x: '100%' }}+ animate={{ x: 0 }}+ exit={{ x: '100%' }}+ transition={{ type: 'spring', stiffness: 420, damping: 40 }}+ style={{ width }}+ className={cn(+ 'absolute top-0 right-0 bottom-0 z-50 flex flex-col',+ 'bg-[#1e1e1e] border-l border-white/[0.08] shadow-[var(--shadow-xl)]',+ )}+ >+ <div className="flex items-center justify-between px-4 h-12 border-b border-white/[0.06] shrink-0">+ <span className="t-title text-gray-200">{title}</span>+ <button ref={closeRef} onClick={onClose} aria-label="Close" className="text-gray-500 hover:text-white p-1 rounded-md hover:bg-white/8 transition-colors lu-focus-ring">+ <X size={16} />+ </button>+ </div>+ <div className="flex-1 overflow-y-auto scrollbar-thin px-4">{children}</div>+ {footer && <div className="px-4 py-3 border-t border-white/[0.06] shrink-0">{footer}</div>}+ </motion.aside>+ </>+ )}+ </AnimatePresence>+ )+}\ No newline at end of filediff --git a/src/components/create/ui/EmptyState.tsx b/src/components/create/ui/EmptyState.tsxnew file mode 100644index 00000000..c596d539--- /dev/null+++ b/src/components/create/ui/EmptyState.tsx@@ -0,0 +1,59 @@++import { motion } from 'framer-motion'+import type { LucideIcon } from 'lucide-react'+import { cn } from './cn'+import { Button } from './Button'++interface Action {+ label: string+ onClick: () => void+ icon?: LucideIcon+ variant?: 'primary' | 'secondary' | 'ghost'+}++interface Props {+ icon: LucideIcon+ /** When set, renders this image (e.g. the LU monogram) instead of the icon. */+ logoSrc?: string+ title: string+ description?: string+ action?: Action+ secondaryAction?: Action+ children?: React.ReactNode+ tone?: 'neutral' | 'accent'+}++export function EmptyState({ icon: Icon, logoSrc, title, description, action, secondaryAction, children, tone = 'neutral' }: Props) {+ return (+ <div className="h-full flex flex-col items-center justify-center text-center px-6">+ <motion.div+ initial={{ opacity: 0, y: 8 }}+ animate={{ opacity: 1, y: 0 }}+ transition={{ duration: 0.3 }}+ className="max-w-sm space-y-4"+ >+ {logoSrc ? (+ <img src={logoSrc} alt="" className="mx-auto h-14 w-14 object-contain opacity-90 select-none" draggable={false} />+ ) : (+ <div className={cn(+ 'mx-auto w-14 h-14 rounded-2xl flex items-center justify-center',+ tone === 'accent' ? 'bg-white/[0.06] text-gray-300' : 'bg-white/[0.04] text-gray-500',+ )}>+ <Icon size={24} strokeWidth={1.5} />+ </div>+ )}+ <div className="space-y-1.5">+ <div className="t-title text-gray-200">{title}</div>+ {description && <div className="t-body text-gray-500">{description}</div>}+ </div>+ {children}+ {(action || secondaryAction) && (+ <div className="flex items-center justify-center gap-2 pt-1">+ {action && <Button variant={action.variant ?? 'primary'} icon={action.icon} onClick={action.onClick}>{action.label}</Button>}+ {secondaryAction && <Button variant={secondaryAction.variant ?? 'ghost'} icon={secondaryAction.icon} onClick={secondaryAction.onClick}>{secondaryAction.label}</Button>}+ </div>+ )}+ </motion.div>+ </div>+ )+}\ No newline at end of filediff --git a/src/components/create/ui/NumberField.tsx b/src/components/create/ui/NumberField.tsxnew file mode 100644index 00000000..38a40aa0--- /dev/null+++ b/src/components/create/ui/NumberField.tsx@@ -0,0 +1,46 @@+import { Dices } from 'lucide-react'+import { cn } from './cn'++interface Props {+ label?: string+ value: number+ min?: number+ max?: number+ step?: number+ onChange: (v: number) => void+ onRandomize?: () => void+ mono?: boolean+ suffix?: string+ className?: string+}++export function NumberField({ label, value, min, max, step = 1, onChange, onRandomize, mono = true, suffix, className }: Props) {+ return (+ <div className={cn('space-y-1.5', className)}>+ {label !== undefined && <div className="t-control text-gray-400">{label}</div>}+ <div className="flex items-center gap-1.5">+ <div className="flex items-center flex-1 h-[var(--control-h-md)] px-2.5 rounded-[var(--radius-control)] bg-white/[0.04] border border-white/[0.08] focus-within:border-white/20">+ <input+ type="number"+ value={value}+ min={min}+ max={max}+ step={step}+ onChange={(e) => { const v = parseFloat(e.target.value); if (!Number.isNaN(v)) onChange(v) }}+ className={cn('bg-transparent outline-none w-full t-control text-gray-200', mono && 'lu-hud-num')}+ />+ {suffix && <span className="t-mono text-gray-600 shrink-0 pl-1">{suffix}</span>}+ </div>+ {onRandomize && (+ <button+ onClick={onRandomize}+ title="Randomize"+ className="h-[var(--control-h-md)] aspect-square inline-flex items-center justify-center rounded-[var(--radius-control)] bg-white/[0.06] text-gray-400 hover:text-white hover:bg-white/10 transition-colors lu-focus-ring"+ >+ <Dices size={14} />+ </button>+ )}+ </div>+ </div>+ )+}diff --git a/src/components/create/ui/PromptField.tsx b/src/components/create/ui/PromptField.tsxnew file mode 100644index 00000000..26782da6--- /dev/null+++ b/src/components/create/ui/PromptField.tsx@@ -0,0 +1,44 @@++import { useEffect, useRef } from 'react'+import { cn } from './cn'++interface Props {+ value: string+ onChange: (v: string) => void+ placeholder?: string+ onSubmit?: () => void+ maxHeight?: number+ autoFocus?: boolean+ className?: string+}++// Auto-grow textarea — grow logic ported from PromptInput.tsx:46-51.+export function PromptField({ value, onChange, placeholder, onSubmit, maxHeight = 220, autoFocus, className }: Props) {+ const ref = useRef<HTMLTextAreaElement>(null)++ useEffect(() => {+ const el = ref.current+ if (!el) return+ el.style.height = 'auto'+ el.style.height = Math.min(el.scrollHeight, maxHeight) + 'px'+ }, [value, maxHeight])++ return (+ <textarea+ ref={ref}+ value={value}+ autoFocus={autoFocus}+ onChange={(e) => onChange(e.target.value)}+ onKeyDown={(e) => {+ if (onSubmit && (e.metaKey || e.ctrlKey) && e.key === 'Enter') { e.preventDefault(); onSubmit() }+ }}+ placeholder={placeholder}+ rows={1}+ className={cn(+ 't-body w-full resize-none bg-transparent outline-none text-gray-100 placeholder-gray-600 scrollbar-thin leading-relaxed',+ className,+ )}+ style={{ maxHeight }}+ />+ )+}\ No newline at end of filediff --git a/src/components/create/ui/Section.tsx b/src/components/create/ui/Section.tsxnew file mode 100644index 00000000..34f5a6fa--- /dev/null+++ b/src/components/create/ui/Section.tsx@@ -0,0 +1,55 @@++import { useState } from 'react'+import { motion, AnimatePresence } from 'framer-motion'+import { ChevronRight, HelpCircle } from 'lucide-react'+import type { LucideIcon } from 'lucide-react'+import { cn } from './cn'+import { Tooltip } from './Tooltip'++interface Props {+ title: string+ icon?: LucideIcon+ help?: string+ collapsible?: boolean+ defaultOpen?: boolean+ right?: React.ReactNode+ children: React.ReactNode+}++export function Section({ title, icon: Icon, help, collapsible = true, defaultOpen = true, right, children }: Props) {+ const [open, setOpen] = useState(defaultOpen)+ const toggle = () => collapsible && setOpen((o) => !o)++ return (+ <div className="border-b border-white/[0.05] last:border-b-0">+ <div className="flex items-center justify-between py-2.5">+ <button onClick={toggle} className={cn('flex items-center gap-1.5 group', !collapsible && 'cursor-default')}>+ {collapsible && (+ <ChevronRight size={13} className={cn('text-gray-600 transition-transform', open && 'rotate-90')} />+ )}+ {Icon && <Icon size={13} className="text-gray-500" />}+ <span className="t-label text-gray-400 group-hover:text-gray-300">{title}</span>+ {help && (+ <Tooltip content={help}>+ <HelpCircle size={12} className="text-gray-600 hover:text-gray-400" />+ </Tooltip>+ )}+ </button>+ {right}+ </div>+ <AnimatePresence initial={false}>+ {open && (+ <motion.div+ initial={{ height: 0, opacity: 0 }}+ animate={{ height: 'auto', opacity: 1 }}+ exit={{ height: 0, opacity: 0 }}+ transition={{ duration: 0.18 }}+ className="overflow-hidden"+ >+ <div className="pb-3 space-y-3">{children}</div>+ </motion.div>+ )}+ </AnimatePresence>+ </div>+ )+}\ No newline at end of filediff --git a/src/components/create/ui/Segmented.tsx b/src/components/create/ui/Segmented.tsxnew file mode 100644index 00000000..6c442780--- /dev/null+++ b/src/components/create/ui/Segmented.tsx@@ -0,0 +1,70 @@++import { motion } from 'framer-motion'+import type { LucideIcon } from 'lucide-react'+import { cn } from './cn'++export interface SegOption<T extends string> {+ value: T+ label?: string+ icon?: LucideIcon+ title?: string+}++interface Props<T extends string> {+ options: SegOption<T>[]+ value: T+ onChange: (v: T) => void+ size?: 'sm' | 'md'+ layoutId?: string+ className?: string+ ariaLabel?: string+}++export function Segmented<T extends string>({ options, value, onChange, size = 'md', layoutId = 'seg', className, ariaLabel }: Props<T>) {+ const h = size === 'sm' ? 'h-[var(--control-h-sm)]' : 'h-[var(--control-h-md)]'+ const iconSize = size === 'sm' ? 13 : 15++ const move = (dir: -1 | 1) => {+ const i = options.findIndex((o) => o.value === value)+ const next = options[i + dir]+ if (next) onChange(next.value)+ }++ return (+ <div role="radiogroup" aria-label={ariaLabel} className={cn('inline-flex items-center gap-0.5 p-0.5 rounded-[var(--radius-control)] bg-white/[0.04] border border-white/[0.06]', className)}>+ {options.map((o) => {+ const selected = o.value === value+ const Icon = o.icon+ return (+ <button+ key={o.value}+ role="radio"+ aria-checked={selected}+ aria-label={o.label || o.title}+ title={o.title || o.label}+ onClick={() => onChange(o.value)}+ onKeyDown={(e) => {+ if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') { e.preventDefault(); move(-1) }+ if (e.key === 'ArrowRight' || e.key === 'ArrowDown') { e.preventDefault(); move(1) }+ }}+ className={cn(+ 'relative t-control inline-flex items-center justify-center gap-1.5 px-2.5 rounded-[6px] transition-colors lu-focus-ring',+ h,+ selected ? 'text-white' : 'text-gray-500 hover:text-gray-300',+ )}+ >+ {selected && (+ <motion.div+ layoutId={layoutId}+ className="absolute inset-0 rounded-[6px] bg-white/[0.12] border border-white/20"+ transition={{ type: 'spring', stiffness: 500, damping: 38 }}+ />+ )}+ {Icon && <Icon size={iconSize} className="relative z-10" />}+ {o.label && <span className="relative z-10 whitespace-nowrap">{o.label}</span>}+ </button>+ )+ })}+ </div>+ )+}\ No newline at end of filediff --git a/src/components/create/ui/Select.tsx b/src/components/create/ui/Select.tsxnew file mode 100644index 00000000..2b09505c--- /dev/null+++ b/src/components/create/ui/Select.tsx@@ -0,0 +1,129 @@++import { useRef, useState, useMemo } from 'react'+import { motion, AnimatePresence } from 'framer-motion'+import { ChevronDown, Check, Search } from 'lucide-react'+import { cn } from './cn'+import { useClickAway } from './useClickAway'++export interface SelectOption {+ value: string+ label: string+ sublabel?: string+ badge?: { label: string; color: string }+}++interface Props {+ options: SelectOption[]+ value: string+ onChange: (v: string) => void+ searchable?: boolean+ placeholder?: string+ size?: 'sm' | 'md'+ align?: 'left' | 'right'+ className?: string+ maxHeight?: number+}++export function Select({ options, value, onChange, searchable = false, placeholder = 'Select…', size = 'md', align = 'left', className, maxHeight = 280 }: Props) {+ const [open, setOpen] = useState(false)+ const [dropUp, setDropUp] = useState(false)+ const [query, setQuery] = useState('')+ const ref = useRef<HTMLDivElement>(null)+ useClickAway(ref, () => setOpen(false), open)++ // Open upward when there isn't room below (e.g. the model chip in the+ // bottom composer bar) so the list never clips off the viewport.+ const toggle = () => {+ if (!open && ref.current) {+ const rect = ref.current.getBoundingClientRect()+ setDropUp(window.innerHeight - rect.bottom < maxHeight + 64)+ }+ setOpen((o) => !o)+ }++ const current = options.find((o) => o.value === value)+ const filtered = useMemo(() => {+ if (!query.trim()) return options+ const q = query.toLowerCase()+ return options.filter((o) => o.label.toLowerCase().includes(q) || o.sublabel?.toLowerCase().includes(q))+ }, [options, query])++ const h = size === 'sm' ? 'h-[var(--control-h-sm)]' : 'h-[var(--control-h-md)]'++ return (+ <div ref={ref} className={cn('relative', className)}>+ <button+ onClick={toggle}+ aria-haspopup="listbox"+ aria-expanded={open}+ className={cn(+ 't-control inline-flex items-center justify-between gap-2 w-full px-2.5 rounded-[var(--radius-control)] transition-colors lu-focus-ring',+ 'bg-white/[0.04] border border-white/[0.08] hover:border-white/15 text-gray-200',+ h,+ )}+ >+ <span className="flex items-center gap-1.5 min-w-0">+ {current?.badge && <Badge color={current.badge.color} label={current.badge.label} />}+ <span className="truncate">{current?.label ?? placeholder}</span>+ </span>+ <ChevronDown size={13} className={cn('shrink-0 text-gray-500 transition-transform', open && 'rotate-180')} />+ </button>++ <AnimatePresence>+ {open && (+ <motion.div+ initial={{ opacity: 0, y: -4, scale: 0.98 }}+ animate={{ opacity: 1, y: 0, scale: 1 }}+ exit={{ opacity: 0, y: -4, scale: 0.98 }}+ transition={{ duration: 0.12 }}+ className={cn(+ 'lu-elevated absolute z-50 min-w-full rounded-[var(--radius-panel)] p-1 overflow-hidden',+ dropUp ? 'bottom-full mb-1' : 'top-full mt-1',+ align === 'right' ? 'right-0' : 'left-0',+ )}+ >+ {searchable && (+ <div className="flex items-center gap-1.5 px-2 py-1.5 mb-1 border-b border-white/[0.06]">+ <Search size={13} className="text-gray-500" />+ <input+ autoFocus+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder="Search…"+ className="t-control bg-transparent outline-none w-full text-gray-200 placeholder-gray-600"+ />+ </div>+ )}+ <div className="overflow-y-auto scrollbar-thin" style={{ maxHeight }}>+ {filtered.length === 0 && <div className="t-control text-gray-600 px-2.5 py-2">No matches</div>}+ {filtered.map((o) => {+ const selected = o.value === value+ return (+ <button+ key={o.value}+ onClick={() => { onChange(o.value); setOpen(false); setQuery('') }}+ className={cn(+ 't-control w-full flex items-center justify-between gap-2 px-2.5 py-1.5 rounded-[6px] text-left transition-colors',+ selected ? 'bg-white/10 text-white' : 'text-gray-300 hover:bg-white/[0.06]',+ )}+ >+ <span className="flex items-center gap-1.5 min-w-0">+ {o.badge && <Badge color={o.badge.color} label={o.badge.label} />}+ <span className="truncate">{o.label}</span>+ {o.sublabel && <span className="t-mono text-gray-600 truncate">{o.sublabel}</span>}+ </span>+ {selected && <Check size={13} className="shrink-0 text-gray-300" />}+ </button>+ )+ })}+ </div>+ </motion.div>+ )}+ </AnimatePresence>+ </div>+ )+}++function Badge({ color, label }: { color: string; label: string }) {+ return <span className={cn('px-1.5 py-0.5 rounded text-[0.55rem] font-semibold shrink-0', color)}>{label}</span>+}\ No newline at end of filediff --git a/src/components/create/ui/Slider.tsx b/src/components/create/ui/Slider.tsxnew file mode 100644index 00000000..28ac41db--- /dev/null+++ b/src/components/create/ui/Slider.tsx@@ -0,0 +1,45 @@+interface Props {+ label?: string+ value: number+ min: number+ max: number+ step: number+ onChange: (v: number) => void+ unit?: string+ format?: (v: number) => string+}++// Upgrade of src/components/settings/SliderControl.tsx — same neutral-grey fill+// and thumb as the live app, plus a unit + tabular-mono value readout.+export function Slider({ label, value, min, max, step, onChange, unit, format }: Props) {+ const pct = ((value - min) / (max - min)) * 100+ const display = format ? format(value) : `${value}${unit ? ' ' + unit : ''}`+ return (+ <div className="space-y-1.5">+ {label !== undefined && (+ <div className="flex items-center justify-between">+ <span className="t-control text-gray-400">{label}</span>+ <span className="t-mono text-gray-300">{display}</span>+ </div>+ )}+ <div className="relative h-5 flex items-center">+ <div className="absolute inset-x-0 h-1 rounded-full bg-white/10" />+ <div className="absolute left-0 h-1 rounded-full bg-gray-400" style={{ width: `${pct}%` }} />+ <input+ type="range"+ min={min}+ max={max}+ step={step}+ value={value}+ onChange={(e) => onChange(parseFloat(e.target.value))}+ className="absolute inset-x-0 w-full cursor-pointer"+ style={{ zIndex: 2, opacity: 0, top: '-4px', height: '28px' }}+ />+ <div+ className="absolute w-3.5 h-3.5 rounded-full pointer-events-none bg-gray-300 border border-gray-500"+ style={{ left: `calc(${pct}% - 7px)`, zIndex: 1, boxShadow: '0 1px 4px rgba(0,0,0,0.4)' }}+ />+ </div>+ </div>+ )+}diff --git a/src/components/create/ui/Tooltip.tsx b/src/components/create/ui/Tooltip.tsxnew file mode 100644index 00000000..017adfa6--- /dev/null+++ b/src/components/create/ui/Tooltip.tsx@@ -0,0 +1,56 @@++import { useEffect, useRef, useState } from 'react'+import { motion, AnimatePresence } from 'framer-motion'+import { cn } from './cn'++interface Props {+ content: React.ReactNode+ children: React.ReactNode+ side?: 'top' | 'bottom'+ delay?: number+ className?: string+}++export function Tooltip({ content, children, side = 'top', delay = 400, className }: Props) {+ const [show, setShow] = useState(false)+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null)++ const open = () => { timer.current = setTimeout(() => setShow(true), delay) }+ const close = () => { if (timer.current) clearTimeout(timer.current); setShow(false) }+ useEffect(() => () => { if (timer.current) clearTimeout(timer.current) }, [])++ return (+ <span+ className={cn('relative inline-flex', className)}+ onMouseEnter={open}+ onMouseLeave={close}+ onFocus={open}+ onBlur={close}+ >+ {children}+ <AnimatePresence>+ {show && (+ <motion.span+ initial={{ opacity: 0, y: side === 'top' ? 3 : -3 }}+ animate={{ opacity: 1, y: 0 }}+ exit={{ opacity: 0, y: side === 'top' ? 3 : -3 }}+ transition={{ duration: 0.12 }}+ role="tooltip"+ className={cn(+ 'lu-elevated pointer-events-none absolute z-[60] left-1/2 -translate-x-1/2 w-max max-w-[220px] px-2.5 py-1.5 rounded-lg t-body text-gray-200',+ side === 'top' ? 'bottom-full mb-1.5' : 'top-full mt-1.5',+ )}+ >+ {content}+ <span+ className={cn(+ 'absolute left-1/2 -translate-x-1/2 w-2 h-2 rotate-45 bg-lu-overlay border-white/[0.08]',+ side === 'top' ? 'top-full -mt-1 border-b border-r' : 'bottom-full -mb-1 border-t border-l',+ )}+ />+ </motion.span>+ )}+ </AnimatePresence>+ </span>+ )+}\ No newline at end of filediff --git a/src/components/create/ui/cn.ts b/src/components/create/ui/cn.tsnew file mode 100644index 00000000..22e2386b--- /dev/null+++ b/src/components/create/ui/cn.ts@@ -0,0 +1,3 @@+export function cn(...parts: (string | false | null | undefined)[]): string {+ return parts.filter(Boolean).join(' ')+}diff --git a/src/components/create/ui/useClickAway.ts b/src/components/create/ui/useClickAway.tsnew file mode 100644index 00000000..e03fbaa4--- /dev/null+++ b/src/components/create/ui/useClickAway.ts@@ -0,0 +1,18 @@++import { useEffect, type RefObject } from 'react'++export function useClickAway(ref: RefObject<HTMLElement | null>, onAway: () => void, active = true) {+ useEffect(() => {+ if (!active) return+ const onDown = (e: MouseEvent) => {+ if (ref.current && !ref.current.contains(e.target as Node)) onAway()+ }+ const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onAway() }+ document.addEventListener('mousedown', onDown)+ document.addEventListener('keydown', onKey)+ return () => {+ document.removeEventListener('mousedown', onDown)+ document.removeEventListener('keydown', onKey)+ }+ }, [ref, onAway, active])+}\ No newline at end of filediff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsxindex cfb3889e..d58a6715 100644--- a/src/components/layout/AppShell.tsx+++ b/src/components/layout/AppShell.tsx@@ -6,7 +6,7 @@ import { Sidebar } from './Sidebar'import { ChatView } from '../chat/ChatView'import { ModelManager } from '../models/ModelManager'import { SettingsPage } from '../settings/SettingsPage'-import { CreateView } from '../create/CreateView'+import { CreateExperimental } from '../create/experimental/CreateExperimental'import { BenchmarkView } from '../models/BenchmarkView'import { Onboarding } from '../onboarding/Onboarding'import { BackendSelector } from '../onboarding/BackendSelector'@@ -592,7 +592,7 @@ export function AppShell() {{currentView === 'models' && <ErrorBoundary><ModelManager /></ErrorBoundary>}{currentView === 'benchmark' && <ErrorBoundary><BenchmarkView /></ErrorBoundary>}{currentView === 'settings' && <ErrorBoundary><SettingsPage /></ErrorBoundary>}- {currentView === 'create' && <ErrorBoundary><CreateView /></ErrorBoundary>}+ {currentView === 'create' && <ErrorBoundary><CreateExperimental /></ErrorBoundary>}</main></div></div>diff --git a/src/components/layout/Header.tsx b/src/components/layout/Header.tsxindex 9ebbb3c0..07e4c664 100644--- a/src/components/layout/Header.tsx+++ b/src/components/layout/Header.tsx@@ -10,7 +10,6 @@ import { MemoryDebugToggle } from '../chat/MemoryDebugPanel'import { UpdateBadge } from './UpdateBadge'import { DownloadBadge } from './DownloadBadge'import { CloudWaitlistBadge } from './CloudWaitlistBadge'-import { CreateTopControls } from '../create/CreateTopControls'import { loadModel } from '../../api/ollama'import { getProviderIdFromModel } from '../../api/providers'import { ModelLoadError } from '../../lib/ollama-errors'@@ -202,9 +201,10 @@ export function Header() {live here has moved INTO the dropdown — each model row in`ModelSelector` has its own load/unload toggle next to the name. */}<div className="lg:absolute lg:left-1/2 lg:-translate-x-1/2 flex items-center justify-center gap-2 min-w-0 ">- {currentView === 'create' ? (- <CreateTopControls />- ) : (+ {/* The redesigned Create surface owns its own controls (IntentBar/+ Composer) — the header center stays empty there, like the chat+ model picker does not apply to Create. */}+ {currentView === 'create' ? null : (<><ModelSelector />{/* Lichtschalter (load/unload into VRAM) now lives per-row inside thediff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.tsindex 64f4c550..b70b5fae 100644--- a/src/hooks/useCreate.ts+++ b/src/hooks/useCreate.ts@@ -19,21 +19,19 @@ import {type ComfyUIOutput,type VideoBackend,} from '../api/comfyui'+import { comfyErrorHint } from '../api/vram-handoff'import {comfyWS, CLIENT_ID,LOADER_NODES, CLIP_LOADER_NODES, VAE_LOADER_NODES, SAMPLER_NODES, DECODE_NODES,type ComfyWSEvent,} from '../api/comfyui-ws'-import { buildDynamicWorkflow, WorkflowUnavailableError, checkVideoOutputCapability } from '../api/dynamic-workflow'+import { buildDynamicWorkflow } from '../api/dynamic-workflow'import { getAllNodeInfo } from '../api/comfyui-nodes'-import { installCustomNodes } from '../api/discover'-import { backendCall } from '../api/backend'+import { checkPromptSafety, SAFETY_BLOCK_MESSAGE } from '../lib/render/safety'import { useCreateStore } from '../stores/createStore'-import { useSettingsStore } from '../stores/settingsStore'import { useWorkflowStore } from '../stores/workflowStore'import { injectParameters } from '../api/workflows'import { preflightCheck } from '../api/preflight'-import { log } from '../lib/logger'export function useCreate() {const [connected, setConnected] = useState<boolean | null>(null)@@ -86,6 +84,7 @@ export function useCreate() {const fetchModels = useCallback(async () => {setModelLoadError(null)+try {// Check connection first — if ComfyUI is down, don't waste time on model queriesconst comfyOk = await checkComfyConnection()@@ -99,7 +98,7 @@ export function useCreate() {// and its internal cache hasn't updated yet.await refreshComfyModels()- const [imgModels, vidModels, samplers, schedulers, vBackend, _nodeInfo] = await Promise.all([+ const [comfyImgModels, vidModels, samplers, schedulers, vBackend, _nodeInfo] = await Promise.all([getImageModels(),getVideoModels(),getSamplers(),@@ -107,6 +106,7 @@ export function useCreate() {detectVideoBackend(),getAllNodeInfo().catch(() => null),])+ const imgModels = comfyImgModelssetImageModels(imgModels)setVideoModelsList(vidModels)setSamplerList(samplers)@@ -127,7 +127,7 @@ export function useCreate() {zeroModelRetries.current++if (zeroModelRetries.current <= 12) {// Still retrying — ComfyUI might not be done scanning yet- log.info(`[useCreate] 0 models found, retry ${zeroModelRetries.current}/12...`)+ console.log(`[useCreate] 0 models found, retry ${zeroModelRetries.current}/12...`)setModelLoadError('ComfyUI is loading models... This can take a moment after startup.')// Don't set modelsLoaded — auto-retry will keep running} else {@@ -136,11 +136,11 @@ export function useCreate() {// generate against a model that no longer exists.const state = useCreateStore.getState()if (state.imageModel) {- log.warn(`[useCreate] Clearing stale persisted imageModel "${state.imageModel}" (0 models installed).`)+ console.warn(`[useCreate] Clearing stale persisted imageModel "${state.imageModel}" (0 models installed).`)state.setImageModel('', 'unknown')}if (state.videoModel) {- log.warn(`[useCreate] Clearing stale persisted videoModel "${state.videoModel}" (0 models installed).`)+ console.warn(`[useCreate] Clearing stale persisted videoModel "${state.videoModel}" (0 models installed).`)state.setVideoModel('')}setModelsLoaded(true)@@ -161,17 +161,17 @@ export function useCreate() {}} else if (state.imageModel) {// Image models absent but videos found — clear stale image model- log.warn(`[useCreate] No image models installed, clearing stale imageModel "${state.imageModel}".`)+ console.warn(`[useCreate] No image models installed, clearing stale imageModel "${state.imageModel}".`)state.setImageModel('', 'unknown')}if (vidModels.length > 0) {if (!state.videoModel || !vidModels.find(m => m.name === state.videoModel)) {- if (state.videoModel) log.warn(`[useCreate] Persisted videoModel "${state.videoModel}" not found, resetting to ${vidModels[0].name}`)+ if (state.videoModel) console.warn(`[useCreate] Persisted videoModel "${state.videoModel}" not found, resetting to ${vidModels[0].name}`)state.setVideoModel(vidModels[0].name)}} else if (state.videoModel) {// Video models absent but images found — clear stale video model- log.warn(`[useCreate] No video models installed, clearing stale videoModel "${state.videoModel}".`)+ console.warn(`[useCreate] No video models installed, clearing stale videoModel "${state.videoModel}".`)state.setVideoModel('')}// Always re-sync model type for currently selected model (fixes stale type after restart)@@ -179,19 +179,19 @@ export function useCreate() {const current = imgModels.find(m => m.name === state.imageModel)if (current) {if (current.type !== state.imageModelType) {- log.info(`[useCreate] Fixing model type: ${state.imageModelType} -> ${current.type}`)+ console.log(`[useCreate] Fixing model type: ${state.imageModelType} -> ${current.type}`)state.setImageModel(state.imageModel, current.type)}} else {// Persisted model no longer exists in ComfyUI — reset to first available- log.warn(`[useCreate] Persisted imageModel "${state.imageModel}" not found in ComfyUI, resetting to ${imgModels[0].name}`)+ console.warn(`[useCreate] Persisted imageModel "${state.imageModel}" not found in ComfyUI, resetting to ${imgModels[0].name}`)state.setImageModel(imgModels[0].name, imgModels[0].type)}}// Run preflight check after models are loadedsetTimeout(() => runPreflight(), 100)} catch (err) {- log.error('[useCreate] Failed to fetch models', { err })+ console.error('[useCreate] Failed to fetch models:', err)setModelLoadError(`Failed to load models: ${err instanceof Error ? err.message : 'ComfyUI API error'}`)}}, [runPreflight])@@ -206,7 +206,7 @@ export function useCreate() {let cancelled = falseconst timeouts: ReturnType<typeof setTimeout>[] = []const handler = () => {- log.info('[useCreate] Model download completed, refreshing model list...')+ console.log('[useCreate] Model download completed, refreshing model list...')fetchModels()// Belt-and-braces: re-fetch at +2s and +6s in case ComfyUI's scan is slow.// fetchModels() is idempotent and cheap (object_info hits cache server-side),@@ -229,46 +229,63 @@ export function useCreate() {const retryInterval = setInterval(async () => {const ok = await checkComfyConnection()if (ok) {- log.info('[useCreate] Retrying model fetch...')+ console.log('[useCreate] Retrying model fetch...')fetchModels()}}, 3000)return () => clearInterval(retryInterval)}, [modelLoadError, modelsLoaded, fetchModels])- const generate = useCallback(async () => {+ const generateInner = useCallback(async () => {const state = useCreateStore.getState()+ // AI-CSAM gate — applies before any backend is touched.+ {+ const verdict = checkPromptSafety(`${state.prompt} ${state.negativePrompt}`)+ if (verdict.blocked) {+ state.setError(SAFETY_BLOCK_MESSAGE)+ return+ }+ }const {mode, prompt, negativePrompt, imageModel, videoModel,sampler, scheduler, steps, cfgScale, width, height, seed, batchSize, frames, fps, denoise, i2iImage, i2vImage,- // F2 + F3 (cinemazverev / vanja-san GH#4) — extended params surfaced- // in ParamPanel. selectedLoras === [] / clipSkip === 0 / vae === 'auto'- // are the "do nothing extra" defaults; the workflow builder skips- // adding nodes for those values.- selectedLoras, selectedVae, clipSkip,+ source, mask, growMaskBy, removebg, selectedLoras, selectedVae, clipSkip,setIsGenerating, setProgress, setCurrentPromptId, setError, addToGallery, addToPromptHistory,} = stateconst isI2I = mode === 'image' && state.imageSubMode === 'img2img'+ // Which redesign intent produced this run (gallery tag).+ const intent = state.intent()+ // The redesigned Create page drives its unified Stage input via `source`/`mask`+ // ImageRefs. On the local path their `.filename` IS the ComfyUI /upload/image+ // name, so they map straight onto the existing i2iImage/i2vImage handles.+ const effInputImage = source?.filename ?? i2iImage+ const effI2vImage = source?.filename ?? i2vImage+ const maskFilename = mask?.filename+ const isRemoveBg = mode === 'image' && removebg++ // Desktop port: the MLX video/image pipelines (Apple Silicon) are not+ // part of this build — ComfyUI is the only local backend.setError(null)const activeModel = mode === 'image' ? imageModel : videoModel// Always re-classify from model name to avoid stale typeconst imageModelType = classifyModel(activeModel)- if (!prompt.trim()) {+ // Background removal is prompt-free and model-independent (RMBG node).+ if (!isRemoveBg && !prompt.trim()) {setError('Please enter a prompt.')return}- if (isI2I && !i2iImage) {- setError('Please upload a source image for Image-to-Image.')+ if (isRemoveBg && !effInputImage) {+ setError('Please add an image to remove its background.')return}- if (mode === 'video' && state.videoSubMode === 'i2v' && !i2vImage) {- setError('Please upload an input image for Image-to-Video.')+ if (isI2I && !isRemoveBg && !effInputImage) {+ setError('Please add a source image first.')return}- if (!activeModel) {+ if (!isRemoveBg && !activeModel) {setError(mode === 'image'? 'No image model selected. Add checkpoints or FLUX models to ComfyUI.': 'No video model selected. Install Wan 2.1 or AnimateDiff models.')@@ -288,12 +305,11 @@ export function useCreate() {try {const baseParams = {prompt, negativePrompt, model: activeModel, sampler, scheduler, steps, cfgScale, width, height, seed, batchSize,- ...(isI2I && i2iImage ? { inputImage: i2iImage, denoise } : {}),- // F2/F3 — only thread the param when the user actually picked one.- // Empty / 'auto' / 0 means "skip this node".- ...(selectedLoras.length > 0- ? { lora: selectedLoras.map((l) => l.name), loraStrength: selectedLoras.map((l) => l.strength) }- : {}),+ ...(isRemoveBg && effInputImage ? { removebg: true, inputImage: effInputImage } : {}),+ ...(isI2I && !isRemoveBg && effInputImage ? { inputImage: effInputImage, denoise } : {}),+ ...(!isRemoveBg && maskFilename ? { maskImage: maskFilename, growMaskBy } : {}),+ // Advanced image adjustments (builder ignores these for video).+ ...(selectedLoras.length ? { loras: selectedLoras } : {}),...(selectedVae && selectedVae !== 'auto' ? { vae: selectedVae } : {}),...(clipSkip > 0 ? { clipSkip } : {}),}@@ -309,45 +325,37 @@ export function useCreate() {const hasUnet = wfNodes.includes('UNETLoader')const hasCheckpoint = wfNodes.includes('CheckpointLoaderSimple')if (needsUnet && !hasUnet && hasCheckpoint) {- log.warn('[useCreate] Custom workflow incompatible: model needs UNETLoader but workflow has CheckpointLoaderSimple. Using auto.')+ console.warn('[useCreate] Custom workflow incompatible: model needs UNETLoader but workflow has CheckpointLoaderSimple. Using auto.')customWf = null} else if (!needsUnet && hasUnet && !hasCheckpoint) {- log.warn('[useCreate] Custom workflow incompatible: model needs CheckpointLoaderSimple but workflow has UNETLoader. Using auto.')+ console.warn('[useCreate] Custom workflow incompatible: model needs CheckpointLoaderSimple but workflow has UNETLoader. Using auto.')customWf = null}}- log.info('[useCreate] Custom workflow check', { activeModel, imageModelType, found: customWf?.name ?? 'NONE (auto)' })+ console.log('[useCreate] Custom workflow check:', { activeModel, imageModelType, found: customWf?.name ?? 'NONE (auto)' })if (customWf) {builderUsed = 'custom'setProgress(5, `Using workflow: ${customWf.name}...`)- const params = mode === 'video' ? { ...baseParams, frames, fps, ...(i2vImage ? { inputImage: i2vImage } : {}) } : baseParams+ const params = mode === 'video' ? { ...baseParams, frames, fps, ...(effI2vImage ? { inputImage: effI2vImage } : {}) } : baseParamsworkflow = await injectParameters(customWf.workflow, customWf.parameterMap, params, imageModelType)} else {// Dynamic workflow builder — auto-detects nodes and builds the right pipelinesetProgress(5, 'Building workflow...')try {- const genParams = mode === 'video' ? { ...baseParams, frames, fps, ...(i2vImage ? { inputImage: i2vImage } : {}) } : baseParams+ const genParams = mode === 'video' ? { ...baseParams, frames, fps, ...(effI2vImage ? { inputImage: effI2vImage } : {}) } : baseParamsworkflow = await buildDynamicWorkflow(genParams, imageModelType)builderUsed = 'dynamic'} catch (dynErr) {- // Bug #6: when the dynamic builder reports the active ComfyUI is- // missing wrapper nodes (CogVideoX 1.5 / FramePack / LTX etc.),- // there's no point falling back to the legacy builder — it- // hits the same UNETLoader trap and surfaces "could not detect- // model type" instead. Tell the user exactly what to install.- if (dynErr instanceof WorkflowUnavailableError) {- const hint = dynErr.installHint- const guidance = hint- ? ` Install via ComfyUI Manager → Install Custom Nodes → search "${hint.pack}" (${hint.url}).`- : ''- setError(`${dynErr.message}${guidance}`)- setIsGenerating(false)- return+ // A WorkflowUnavailableError carries an actionable message ("download+ // <encoder> from the Model Manager") — surface it directly instead of+ // falling back to a legacy builder that would fail the same way with+ // a cryptic ComfyUI rejection.+ if (dynErr instanceof Error && dynErr.name === 'WorkflowUnavailableError') {+ throw dynErr}- // Other dynamic-builder failures: legacy is a reasonable fallback- // (mostly happens for classic SDXL/SD15 image paths).- log.warn('[useCreate] Dynamic builder failed, using legacy', { err: dynErr })+ // Fallback to legacy builders if dynamic fails+ console.warn('[useCreate] Dynamic builder failed, using legacy:', dynErr)builderUsed = 'legacy'setProgress(5, 'Using legacy builder...')if (mode === 'video') {@@ -356,67 +364,6 @@ export function useCreate() {workflow = await buildTxt2ImgWorkflow(baseParams, imageModelType)}}- // Bug A (v2.4.5 — miguelkodoatie Discord 2026-05-14, Turbulent_Tomato7559- // Reddit 2026-05-10): when ComfyUI lacks VHS_VideoCombine the video- // workflow falls back to SaveAnimatedWEBP and produces an animated- // .webp instead of an .mp4. v2.4.4 added a warning banner; v2.4.5- // turns it into a blocking modal with a one-click install, so users- // get actual videos instead of trying to figure out why "video gen"- // gave them an image.- if (mode === 'video' && builderUsed === 'dynamic') {- try {- const caps = await checkVideoOutputCapability()- if (caps.webpOnly) {- const choice = await new Promise<'install' | 'webp' | 'cancel'>((resolve) => {- useCreateStore.getState().setVhsInstallPrompt(resolve)- })- useCreateStore.getState().setVhsInstallPrompt(null)-- if (choice === 'cancel') {- setIsGenerating(false)- setProgress(0, '')- return- }- if (choice === 'install') {- setProgress(8, 'Installing VHS_VideoCombine (git clone + pip)...')- try {- await installCustomNodes(['videohelpersuite'])- setProgress(9, 'Restarting ComfyUI to register the new node...')- try {- await backendCall('stop_comfyui')- } catch { /* may already be stopped */ }- await new Promise(r => setTimeout(r, 2000))- await backendCall('start_comfyui')- // Wait for ComfyUI to come back; poll /object_info up to 30s- let backUp = false- for (let i = 0; i < 15; i++) {- await new Promise(r => setTimeout(r, 2000))- try {- const ok = await checkComfyConnection()- if (ok) { backUp = true; break }- } catch { /* not yet */ }- }- if (!backUp) {- setError('VHS_VideoCombine installed but ComfyUI did not come back online within 30s. Please restart ComfyUI manually and re-generate.')- setIsGenerating(false)- return- }- // Re-build the workflow now that the new node is available- const genParams = { ...baseParams, frames, fps, ...(i2vImage ? { inputImage: i2vImage } : {}) }- workflow = await buildDynamicWorkflow(genParams, imageModelType)- setProgress(10, 'VHS installed — generating MP4...')- } catch (instErr) {- setError(`Failed to install VHS_VideoCombine: ${instErr instanceof Error ? instErr.message : String(instErr)}. You can install it manually in ComfyUI Manager.`)- setIsGenerating(false)- return- }- } else {- // 'webp' — user opted to continue with the animated .webp- setProgress(8, 'Continuing with animated .webp output (no VHS_VideoCombine)')- }- }- } catch { /* non-fatal */ }- }}setProgress(10, 'Submitting to ComfyUI...')@@ -439,27 +386,20 @@ export function useCreate() {}}- // Try WebSocket-driven progress, fall back to polling.- // Bug P (v2.4.7, ake0n_official Discord 2026-05-19): CPU-only users- // on Intel UHD ran into the 20-min cap at sampling 9/25 on a single- // 1024px Juggernaut-XL gen. Move the cap into Settings so slow- // hardware can finish a gen instead of timing out mid-sampler.- // Defaults stay 20min image / 60min video to match pre-2.4.7 behavior.- const settings = useSettingsStore.getState().settings- const imgMin = Math.max(1, settings.imageGenTimeoutMinutes || 20)- const vidMin = Math.max(1, settings.videoGenTimeoutMinutes || 60)- const maxTime = mode === 'video' ? vidMin * 60 * 1000 : imgMin * 60 * 1000+ // Try WebSocket-driven progress, fall back to polling+ const maxTime = mode === 'video' ? 60 * 60 * 1000 : 20 * 60 * 1000let useWS = falsetry {await comfyWS.connect(3000)useWS = true} catch {- log.warn('[useCreate] WebSocket unavailable, using polling fallback')+ console.warn('[useCreate] WebSocket unavailable, using polling fallback')}if (useWS) {// ── WebSocket-driven progress ──await new Promise<void>((resolve, reject) => {+ const startTime = Date.now()const store = useCreateStore.getState()store.setProgressPhase('queued')setProgress(10, 'Queued...')@@ -482,18 +422,24 @@ export function useCreate() {const statusStr = history.status?.status_strif (statusStr === 'success') {completionHandled = true- log.info('[useCreate] Completion detected via polling (WS event missed)')+ console.log('[useCreate] Completion detected via polling (WS event missed)')cleanup()useCreateStore.getState().setProgressPhase('complete')setProgress(95, 'Fetching results...')+ const messages: [string, any][] = history.status?.messages ?? []+ const startMsg = messages.find(([t]: [string, any]) => t === 'execution_start')+ const endMsg = messages.find(([t]: [string, any]) => t === 'execution_success')+ const comfyTime = startMsg?.[1]?.timestamp && endMsg?.[1]?.timestamp+ ? ((endMsg[1].timestamp - startMsg[1].timestamp) / 1000).toFixed(1) : nullsetProgress(100, 'Complete!')+ useCreateStore.getState().setLastGenTime(comfyTime ? `${comfyTime}s` : null)const outputs = history.outputs ?? {}let found = falsefor (const nodeId of Object.keys(outputs)) {- // Bug R (v2.4.7) — extract files from any keyed array,- // not just images/gifs/videos. Custom save nodes use- // other keys (audio, result, files, …); previously LU- // dropped those outputs even though they existed on disk.+ // Extract files from ANY keyed array, not just images/gifs/+ // videos — custom save nodes post under other keys (audio,+ // result, files, …); previously those outputs were dropped+ // even though they existed on disk.const files: ComfyUIOutput[] = extractComfyOutputFiles(outputs[nodeId])for (const file of files) {found = true@@ -504,7 +450,7 @@ export function useCreate() {modelType: mode === 'image' ? imageModelType : (videoModelsList.find(m => m.name === activeModel)?.type ?? 'wan'),seed: seed === -1 ? 0 : seed,steps, cfgScale, sampler, scheduler, width, height, batchSize,- createdAt: Date.now(), builderUsed,+ createdAt: Date.now(), builderUsed, intent,})}}@@ -514,8 +460,10 @@ export function useCreate() {completionHandled = truecleanup()const msgs = history.status?.messages ?? []- const errMsg = msgs.find(([t]: [string, any]) => t === 'execution_error')- reject(new Error(errMsg?.[1]?.exception_message || 'ComfyUI execution error'))+ const errEntry = msgs.find(([t]: [string, any]) => t === 'execution_error')?.[1]+ const raw = errEntry?.exception_message || 'ComfyUI execution error'+ const hint = comfyErrorHint(errEntry?.node_type, errEntry?.exception_type, String(raw))+ reject(new Error(hint ? `${raw}\n\n${hint}` : raw))}} catch { /* polling failure is non-fatal */ }}, 10000)@@ -533,6 +481,7 @@ export function useCreate() {// Only handle events for our promptif ('prompt_id' in event.data && event.data.prompt_id !== promptId) return+ const elapsed = Math.round((Date.now() - startTime) / 1000)const st = useCreateStore.getState()switch (event.type) {@@ -545,19 +494,19 @@ export function useCreate() {const classType = nodeClassMap.get(nodeId) || ''if (LOADER_NODES.has(classType)) {st.setProgressPhase('loading-model')- setProgress(15, 'Loading model...')+ setProgress(15, `Loading model... ${elapsed}s`)} else if (CLIP_LOADER_NODES.has(classType)) {st.setProgressPhase('loading-clip')- setProgress(25, 'Loading text encoder...')+ setProgress(25, `Loading text encoder... ${elapsed}s`)} else if (VAE_LOADER_NODES.has(classType)) {st.setProgressPhase('loading-vae')- setProgress(30, 'Loading VAE...')+ setProgress(30, `Loading VAE... ${elapsed}s`)} else if (SAMPLER_NODES.has(classType)) {st.setProgressPhase('sampling')- setProgress(35, 'Sampling...')+ setProgress(35, `Sampling... ${elapsed}s`)} else if (DECODE_NODES.has(classType)) {st.setProgressPhase('decoding')- setProgress(90, 'Decoding...')+ setProgress(90, `Decoding... ${elapsed}s`)}break}@@ -565,7 +514,7 @@ export function useCreate() {const { value, max } = event.dataconst stepPct = 35 + (value / max) * 55 // 35% to 90%st.setProgressPhase('sampling')- setProgress(Math.round(stepPct), `Sampling step ${value}/${max}`)+ setProgress(Math.round(stepPct), `Sampling step ${value}/${max}... ${elapsed}s`)break}case 'execution_complete': {@@ -577,11 +526,17 @@ export function useCreate() {// Fetch history to get output filesgetHistory(promptId).then(history => {if (!history) { setError('No history found after completion.'); resolve(); return }+ const messages: [string, any][] = history.status?.messages ?? []+ const startMsg = messages.find(([t]) => t === 'execution_start')+ const endMsg = messages.find(([t]) => t === 'execution_success')+ const comfyTime = startMsg?.[1]?.timestamp && endMsg?.[1]?.timestamp+ ? ((endMsg[1].timestamp - startMsg[1].timestamp) / 1000).toFixed(1) : nullsetProgress(100, 'Complete!')+ useCreateStore.getState().setLastGenTime(comfyTime ? `${comfyTime}s` : null)const outputs = history.outputs ?? {}let found = falsefor (const nodeId of Object.keys(outputs)) {- // Bug R (v2.4.7) — see comment at the WS branch above.+ // Same generic extraction as the heartbeat branch above.const files: ComfyUIOutput[] = extractComfyOutputFiles(outputs[nodeId])for (const file of files) {found = true@@ -605,7 +560,8 @@ export function useCreate() {cleanup()const msg = event.data.exception_message || 'Unknown ComfyUI error'const nodeType = event.data.node_type ? ` (${event.data.node_type})` : ''- reject(new Error(msg.trim() + nodeType))+ const hint = comfyErrorHint(event.data.node_type, (event.data as any).exception_type, msg)+ reject(new Error(msg.trim() + nodeType + (hint ? `\n\n${hint}` : '')))break}}@@ -653,24 +609,31 @@ export function useCreate() {}}+ const elapsedSec = Math.round(elapsed / 1000)const expectedSteps = mode === 'video' ? steps * frames * 0.5 : steps * 2const pct = Math.min(10 + (attempts / expectedSteps * 85), 95)try {const history = await getHistory(promptId)- setProgress(pct, 'Generating...')+ setProgress(pct, `Generating... ${elapsedSec}s elapsed`)if (!history) returnif (history.status?.completed) {if (pollRef.current) clearInterval(pollRef.current)+ const messages: [string, any][] = history.status?.messages ?? []+ const startMsg = messages.find(([t]) => t === 'execution_start')+ const endMsg = messages.find(([t]) => t === 'execution_success')+ const comfyTime = startMsg?.[1]?.timestamp && endMsg?.[1]?.timestamp+ ? ((endMsg[1].timestamp - startMsg[1].timestamp) / 1000).toFixed(1) : nullsetProgress(100, 'Complete!')+ useCreateStore.getState().setLastGenTime(comfyTime ? `${comfyTime}s` : null)const outputs = history.outputs ?? {}let found = falsefor (const nodeId of Object.keys(outputs)) {- // Bug R (v2.4.7) — extract files from any keyed array,- // not just images/gifs/videos. Custom save nodes use- // other keys (audio, result, files, …); previously LU- // dropped those outputs even though they existed on disk.+ // Extract files from ANY keyed array, not just images/gifs/+ // videos — custom save nodes post under other keys (audio,+ // result, files, …); previously those outputs were dropped+ // even though they existed on disk.const files: ComfyUIOutput[] = extractComfyOutputFiles(outputs[nodeId])for (const file of files) {found = true@@ -681,7 +644,7 @@ export function useCreate() {modelType: mode === 'image' ? imageModelType : (videoModelsList.find(m => m.name === activeModel)?.type ?? 'wan'),seed: seed === -1 ? 0 : seed,steps, cfgScale, sampler, scheduler, width, height, batchSize,- createdAt: Date.now(), builderUsed,+ createdAt: Date.now(), builderUsed, intent,})}}@@ -696,10 +659,11 @@ export function useCreate() {|| messages[messages.length - 1]?.[1]?.message|| 'Unknown ComfyUI error'const nodeType = errorEntry?.[1]?.node_type ? ` (${errorEntry[1].node_type})` : ''- reject(new Error(errMsg.trim() + nodeType))+ const hint = comfyErrorHint(errorEntry?.[1]?.node_type, errorEntry?.[1]?.exception_type, String(errMsg))+ reject(new Error(errMsg.trim() + nodeType + (hint ? `\n\n${hint}` : '')))}} catch (err) {- log.warn('[useCreate] Poll error', { err })+ console.warn('[useCreate] Poll error:', err)}}, 1000)})@@ -710,7 +674,7 @@ export function useCreate() {} else {const msg = err instanceof Error ? err.message : String(err)useCreateStore.getState().setError(`Generation failed: ${msg}`)- log.error('[useCreate] Generation error', { err })+ console.error('[useCreate] Generation error:', err)}} finally {useCreateStore.getState().setIsGenerating(false)@@ -721,9 +685,23 @@ export function useCreate() {}}, [videoBackend])+ // Double-click idempotence: isGenerating only flips after the first await,+ // so a second click racing the first must be blocked SYNCHRONOUSLY — two+ // fast clicks were live-reproduced queueing two ComfyUI jobs.+ const generateInFlight = useRef(false)+ const generate = useCallback(async () => {+ if (generateInFlight.current) return+ generateInFlight.current = true+ try {+ await generateInner()+ } finally {+ generateInFlight.current = false+ }+ }, [generateInner])+const cancel = useCallback(async () => {abortRef.current?.abort()- await cancelGeneration()+ try { await cancelGeneration() } catch {}if (pollRef.current) { clearInterval(pollRef.current); pollRef.current = null }useCreateStore.getState().setIsGenerating(false)useCreateStore.getState().setProgress(0)diff --git a/src/lib/render/cloud-jobs.ts b/src/lib/render/cloud-jobs.tsnew file mode 100644index 00000000..7127b24a--- /dev/null+++ b/src/lib/render/cloud-jobs.ts@@ -0,0 +1,33 @@+// Desktop port: types + intent mapping only. The hosted render queue (fetch+// wrappers, upload/submit/poll/cancel) is a lu-labs.ai web feature and stays+// out of the desktop build — CreateContext stubs the cloud axis to null.++import type { CreateIntent } from '../../stores/createStore'++export type RenderKind = 'image' | 'video'+export type RenderOp = 'generate' | 'edit' | 'removebg' | 'animate'++export interface CloudQuota {+ tier: string+ period: string+ limits: { tokens: number; credits: number }+ costs: { image: number; video: number }+ used: { tokens_used: number; credits_used: number }+ remaining: { tokens: number; credits: number }+}++/** Which queue kind + workflow op a Create intent renders as. */+export function intentToJob(intent: CreateIntent): { kind: RenderKind; op: RenderOp } {+ switch (intent) {+ case 'edit':+ return { kind: 'image', op: 'edit' }+ case 'removebg':+ return { kind: 'image', op: 'removebg' }+ case 'video':+ return { kind: 'video', op: 'generate' }+ case 'animate':+ return { kind: 'video', op: 'animate' }+ default:+ return { kind: 'image', op: 'generate' }+ }+}diff --git a/src/lib/render/safety.ts b/src/lib/render/safety.tsnew file mode 100644index 00000000..d501a7e2--- /dev/null+++ b/src/lib/render/safety.ts@@ -0,0 +1,115 @@+// AI-CSAM gate for the image/video generation paths. Non-negotiable block:+// prompts that sexualize minors are refused on BOTH axes — client-side in the+// Create hooks (fast feedback) and server-side in POST /api/jobs (the+// authoritative gate; the client check is UX, not security).+//+// Matching is deliberately conjunctive for the general case — a minor-related+// term alone ("a child's birthday party") or an adult-content term alone is+// legitimate; the combination is not. A small set of unambiguous terms blocks+// on its own. Server hits are logged as `jobs.csam_blocked` — that log line is+// the operator's NCMEC escalation trigger (18 U.S.C. § 2258A reporting is an+// operator duty; the worker never renders the job).++const MINOR_TERMS =+ /\b(child|children|kid|kids|minor|minors|underage|under[\s-]?age|preteen|pre[\s-]?teen|prepubescent|teen|teens|teenager|teenagers|toddler|infant|baby|babies|schoolgirl|schoolboy|school[\s-]?uniform|grade[\s-]?school|elementary[\s-]?school|middle[\s-]?school|kindergart\w*|little[\s-]?(?:girl|boy)|loli|shota|(?:eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen)[\s-]*(?:yo|years?[\s-]?old)|(?:1[0-7]|[1-9])[\s-]*(?:yo|y\/o|yr[\s-]?old|year[\s-]?old|years[\s-]?old))\b/i++const SEXUAL_TERMS =+ /\b(nude|nudes|naked|nsfw|sex|sexual|sexualized|sexy|erotic|erotica|porn|pornographic|xxx|explicit|undress(?:ed|ing)?|topless|bottomless|lingerie|fetish|bdsm|bondage|genitals?|hentai|intercourse|masturbat\w*|orgasm|aroused|seductive|provocative)\b/i++const ALWAYS_BLOCKED = /\b(csam|child\s*porn(?:ography)?|jail\s*bait|lolita\s*(?:porn|nude|sex)|pedo\w*)\b/i++// Compact match for the unambiguous terms after separators are stripped — beats+// letter-spacing evasion ("c h i l d p o r n" → "childporn"). Only strings that+// are never substrings of an innocent word go here (so no bare "pedo", which+// lives in "torpedo").+const ALWAYS_BLOCKED_COMPACT = /(csam|childporn(?:ography)?|jailbait|lolita(?:porn|nude|sex))/i++// Cyrillic / Greek lookalikes → latin. Fullwidth + many compatibility forms are+// already folded by NFKC; these are the ones it leaves alone.+const HOMOGLYPHS: Record<string, string> = {+ а: 'a', е: 'e', о: 'o', р: 'p', с: 'c', х: 'x', у: 'y', ѕ: 's', і: 'i',+ ј: 'j', к: 'k', м: 'm', н: 'h', т: 't', в: 'b', г: 'r',+ α: 'a', ε: 'e', ο: 'o', ρ: 'p', ϲ: 'c', χ: 'x', υ: 'u', ι: 'i', κ: 'k', ν: 'v', τ: 't',+}+const LEET: Record<string, string> = {+ '0': 'o', '1': 'i', '3': 'e', '4': 'a', '5': 's', '7': 't', '@': 'a', $: 's', '!': 'i',+}+// Derived from LEET so the two never drift (adding a key auto-extends the+// fold). The keys (digits, @, $, !) are all literal inside a char class — do+// NOT backslash-escape them (\0/\1 would become NUL/octal escapes).+const LEET_CLASS = new RegExp(`[${Object.keys(LEET).join('')}]`, 'g')++function baseNormalize(text: string): string {+ return text+ .normalize('NFKC')+ .replace(/[\u200B-\u200D\u2060\uFEFF]/g, '') // zero-width chars+ // Strip diacritics (decompose + drop combining marks) so accented+ // lookalikes like "chîld" fold to "child" and don't defeat the terms.+ .normalize('NFKD')+ .replace(/[\u0300-\u036f]/g, '')+ .toLowerCase()+ .replace(/[^\u0000-\u007F]/g, (ch) => HOMOGLYPHS[ch] ?? ch)+}++export interface SafetyVerdict {+ blocked: boolean+ reason?: string+}++/** Check a generation prompt (positive + negative + any free-text params+ * concatenated is fine — the caller should pass everything a backend could+ * route into the effective prompt). */+export function checkPromptSafety(text: string): SafetyVerdict {+ const base = baseNormalize(text)+ // Leet-folded copy for word terms. NOT used for age digits — folding maps+ // '1'→'i'/'4'→'a', which would destroy "14 yo"; ages are matched on `base`.+ const deleeted = base.replace(LEET_CLASS, (ch) => LEET[ch] ?? ch)+ const compact = base.replace(/[\s._-]+/g, '')++ if (ALWAYS_BLOCKED.test(base) || ALWAYS_BLOCKED.test(deleeted) || ALWAYS_BLOCKED_COMPACT.test(compact)) {+ return { blocked: true, reason: 'csam' }+ }+ // Also test `compact` (separators stripped) so single-term letter-spacing+ // ("t e e n") is caught; \b still prevents mid-word substring matches.+ const minor = MINOR_TERMS.test(base) || MINOR_TERMS.test(deleeted) || MINOR_TERMS.test(compact)+ const sexual = SEXUAL_TERMS.test(base) || SEXUAL_TERMS.test(deleeted) || SEXUAL_TERMS.test(compact)+ if (minor && sexual) {+ return { blocked: true, reason: 'minor+sexual' }+ }+ return { blocked: false }+}++export const SAFETY_BLOCK_MESSAGE =+ 'This prompt was blocked: content sexualizing minors is never generated, on any backend.'++/**+ * Out-of-band alert on a CSAM block so it is not just a log line nobody tails.+ * Posts to SAFETY_ALERT_WEBHOOK_URL if set (Slack/PagerDuty/etc.). Deliberately+ * carries NO prompt content — only the user id, the match reason, and a+ * timestamp — so the alert channel never becomes a store of blocked text.+ * Fire-and-forget: never throws, never blocks the request path.+ */+export async function alertCsamBlock(meta: {+ userId: string+ reason?: string+ kind?: string+}): Promise<void> {+ const url = process.env.SAFETY_ALERT_WEBHOOK_URL+ if (!url) return+ try {+ await fetch(url, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ event: 'csam_blocked',+ user_id: meta.userId,+ reason: meta.reason ?? 'unknown',+ kind: meta.kind ?? 'unknown',+ at: new Date().toISOString(),+ note: 'A generation prompt was refused by the AI-CSAM gate. Review for 18 U.S.C. § 2258A reporting.',+ }),+ })+ } catch {+ // Alerting must never break the block itself — the 422 + log already stand.+ }+}diff --git a/src/stores/__tests__/createStore-migrate.test.ts b/src/stores/__tests__/createStore-migrate.test.tsnew file mode 100644index 00000000..f9e3e227--- /dev/null+++ b/src/stores/__tests__/createStore-migrate.test.ts@@ -0,0 +1,73 @@+import { describe, it, expect, beforeEach, vi } from 'vitest'++vi.mock('../../api/comfyui', () => ({ classifyModel: () => 'unknown' }))++// zustand/persist defaults to `window.localStorage` — in the node test env both+// need shimming BEFORE the store module is imported, or persist silently no-ops.+const backing = new Map<string, string>()+;(globalThis as any).window = globalThis+globalThis.localStorage = {+ getItem: (k: string) => backing.get(k) ?? null,+ setItem: (k: string, v: string) => void backing.set(k, String(v)),+ removeItem: (k: string) => void backing.delete(k),+ clear: () => backing.clear(),+ key: (i: number) => [...backing.keys()][i] ?? null,+ get length() {+ return backing.size+ },+} as Storage++const KEY = 'create-store'++function seedStorage(state: Record<string, unknown>, version?: number) {+ localStorage.setItem(+ KEY,+ JSON.stringify(version === undefined ? { state } : { state, version })+ )+}++// localStorage is synchronous, so persist hydrates during store creation —+// a fresh import after resetModules picks up whatever the test seeded.+async function freshStore() {+ vi.resetModules()+ const mod = await import('../createStore')+ return mod.useCreateStore+}++describe('createStore persist migration (v0 → v1)', () => {+ beforeEach(() => localStorage.clear())++ it('migrates an unversioned v0 blob with mode "i2i" to image/img2img', async () => {+ seedStorage({ mode: 'i2i', steps: 33 })+ const store = await freshStore()+ expect(store.getState().mode).toBe('image')+ expect(store.getState().imageSubMode).toBe('img2img')+ expect(store.getState().steps).toBe(33)+ })++ it('keeps a v0 blob without i2i untouched and backfills new keys from defaults', async () => {+ seedStorage({ mode: 'video', width: 768 })+ const store = await freshStore()+ const s = store.getState()+ expect(s.mode).toBe('video')+ expect(s.width).toBe(768)+ expect(Array.isArray(s.selectedLoras)).toBe(true)+ expect(typeof s.clipSkip).toBe('number')+ })++ it('never rehydrates runtime-only fields (backend stays local)', async () => {+ seedStorage({ mode: 'image', backend: 'cloud', source: { filename: 'x.png' } }, 1)+ const store = await freshStore()+ expect(store.getState().backend).toBe('local')+ expect(store.getState().source).toBeNull()+ })++ it('writes version 1 back to storage after rehydrate', async () => {+ seedStorage({ mode: 'i2i' })+ const store = await freshStore()+ store.getState().setSteps(21)+ const raw = JSON.parse(localStorage.getItem(KEY) ?? '{}')+ expect(raw.version).toBe(1)+ expect(raw.state.mode).toBe('image')+ })+})diff --git a/src/stores/__tests__/createStore.test.ts b/src/stores/__tests__/createStore.test.tsindex 436fe3a9..82909afb 100644--- a/src/stores/__tests__/createStore.test.ts+++ b/src/stores/__tests__/createStore.test.ts@@ -138,10 +138,10 @@ describe('createStore', () => {it('setImageModelList / setVideoModelList replace the lists', () => {const imgs = [- { name: 'flux-schnell.safetensors', type: 'flux' as const },- { name: 'sdxl-base.safetensors', type: 'sdxl' as const },+ { name: 'flux-schnell.safetensors', type: 'flux' as const, source: 'checkpoint' as const },+ { name: 'sdxl-base.safetensors', type: 'sdxl' as const, source: 'checkpoint' as const },]- const vids = [{ name: 'wan-2.1.safetensors', type: 'wan' as const }]+ const vids = [{ name: 'wan-2.1.safetensors', type: 'wan' as const, source: 'checkpoint' as const }]useCreateStore.getState().setImageModelList(imgs)useCreateStore.getState().setVideoModelList(vids)expect(useCreateStore.getState().imageModelList).toEqual(imgs)@@ -198,7 +198,7 @@ describe('createStore', () => {})it('passes through a real populated list unchanged', () => {- const list = [{ name: 'flux.safetensors', type: 'flux' as const }]+ const list = [{ name: 'flux.safetensors', type: 'flux' as const, source: 'checkpoint' as const }]useCreateStore.setState({ imageModelList: list, mode: 'image' })const s = useCreateStore.getState()expect(computeActiveList(s.mode, s.imageModelList, s.videoModelList)).toBe(list)@@ -507,17 +507,6 @@ describe('createStore', () => {})})- // ── clearPromptHistory (GitHub #66) ────────────────────────-- describe('clearPromptHistory', () => {- it('wipes all prompt history', () => {- useCreateStore.getState().addToPromptHistory('one')- useCreateStore.getState().addToPromptHistory('two')- useCreateStore.getState().clearPromptHistory()- expect(useCreateStore.getState().promptHistory).toEqual([])- })- })-// ── setIsGenerating ────────────────────────────────────────describe('setIsGenerating', () => {diff --git a/src/stores/createStore.ts b/src/stores/createStore.tsindex 5da14733..405a8463 100644--- a/src/stores/createStore.ts+++ b/src/stores/createStore.ts@@ -7,22 +7,78 @@ import type { PreflightError } from '../api/preflight'export type ProgressPhase = 'idle' | 'queued' | 'loading-model' | 'loading-clip' | 'loading-vae' | 'sampling' | 'decoding' | 'complete'+/**+ * Backend the redesigned Create page generates against. Runtime-only — derived+ * from session/license (a paired Bridge → `local`; a logged-in hosted tier →+ * `cloud`) and never persisted. Orthogonal to `videoBackend` (comfy|mlx), which+ * stays a local-only concern.+ */+export type CreateBackend = 'local' | 'cloud'++/**+ * The redesigned Create page's flat creation intents, derived over+ * mode / image sub-mode / video sub-mode / removebg. The `mode` + sub-mode+ * enums stay the load-bearing state; `intent` is a derived view over them.+ */+export type CreateIntent = 'image' | 'edit' | 'removebg' | 'video' | 'animate'++/**+ * A source or mask image loaded into the Stage input slot. `filename` is the+ * backend handle (a ComfyUI /upload/image name on the local path, or a+ * render-inputs storage path on the cloud path); `url` is a local object/data+ * URL for preview. Runtime-only — never persisted.+ */+export interface ImageRef { filename: string; url: string; width: number; height: number }++/** Flatten mode / sub-mode / removebg into the single intent the UI drives. */+export function deriveIntent(s: {+ removebg: boolean+ mode: 'image' | 'video'+ imageSubMode: 'text2img' | 'img2img'+ videoSubMode: 't2v' | 'i2v'+}): CreateIntent {+ if (s.removebg) return 'removebg'+ if (s.mode === 'video') return s.videoSubMode === 'i2v' ? 'animate' : 'video'+ return s.imageSubMode === 'img2img' ? 'edit' : 'image'+}++/**+ * Where video generation runs.+ *+ * - `comfy` — local ComfyUI server. Works on every OS; FP8 quirks on Mac+ * MPS, fastest on CUDA. Default for Windows + Linux.+ *+ * - `mlx` — `mlx-video` subprocess driven by the Bridge. Apple Silicon+ * only, uses Apple's MLX framework against unified memory. Faster than+ * ComfyUI-on-MPS for the models it supports (Wan 2.2, LTX-2). Default+ * for Apple Silicon Macs with ≥32 GB unified memory.+ */+export type VideoBackendKind = 'comfy' | 'mlx'+// ─── Optimal defaults per model type (research-backed: Draw Things, Fooocus, ComfyUI) ───export const MODEL_TYPE_DEFAULTS: Record<ModelType, {steps: number; cfgScale: number; sampler: string; scheduler: stringwidth: number; height: number; frames?: number; fps?: number}> = {- sd15: { steps: 25, cfgScale: 7.0, sampler: 'euler_ancestral', scheduler: 'normal', width: 512, height: 512 },- sdxl: { steps: 25, cfgScale: 7.0, sampler: 'dpmpp_2m', scheduler: 'karras', width: 1024, height: 1024 },- flux: { steps: 20, cfgScale: 1.0, sampler: 'euler', scheduler: 'simple', width: 1024, height: 1024 },- flux2: { steps: 20, cfgScale: 1.0, sampler: 'euler', scheduler: 'simple', width: 1024, height: 1024 },- zimage: { steps: 12, cfgScale: 3.5, sampler: 'euler', scheduler: 'simple', width: 1024, height: 1024 },- wan: { steps: 30, cfgScale: 6.0, sampler: 'euler', scheduler: 'normal', width: 832, height: 480, frames: 49, fps: 16 },- wan22: { steps: 30, cfgScale: 5.0, sampler: 'euler', scheduler: 'simple', width: 1024, height: 576, frames: 49, fps: 24 },- hunyuan: { steps: 30, cfgScale: 6.0, sampler: 'euler', scheduler: 'normal', width: 848, height: 480, frames: 45, fps: 24 },- ltx: { steps: 20, cfgScale: 3.0, sampler: 'euler', scheduler: 'normal', width: 768, height: 512, frames: 97, fps: 24 },- unknown: { steps: 20, cfgScale: 7.0, sampler: 'euler', scheduler: 'normal', width: 1024, height: 1024 },+ sd15: { steps: 25, cfgScale: 7.0, sampler: 'euler_ancestral', scheduler: 'normal', width: 512, height: 512 },+ sdxl: { steps: 25, cfgScale: 7.0, sampler: 'dpmpp_2m', scheduler: 'karras', width: 1024, height: 1024 },+ flux: { steps: 20, cfgScale: 1.0, sampler: 'euler', scheduler: 'simple', width: 1024, height: 1024 },+ flux2: { steps: 20, cfgScale: 1.0, sampler: 'euler', scheduler: 'simple', width: 1024, height: 1024 },+ zimage: { steps: 12, cfgScale: 3.5, sampler: 'euler', scheduler: 'simple', width: 1024, height: 1024 },+ ernie_image: { steps: 20, cfgScale: 4.0, sampler: 'euler', scheduler: 'simple', width: 1024, height: 1024 },+ wan: { steps: 25, cfgScale: 5.0, sampler: 'euler', scheduler: 'normal', width: 848, height: 480, frames: 49, fps: 16 },+ wan22: { steps: 30, cfgScale: 5.0, sampler: 'euler', scheduler: 'simple', width: 1024, height: 576, frames: 49, fps: 24 },+ hunyuan: { steps: 30, cfgScale: 6.0, sampler: 'euler', scheduler: 'normal', width: 848, height: 480, frames: 45, fps: 15 },+ ltx: { steps: 20, cfgScale: 1.0, sampler: 'euler', scheduler: 'simple', width: 768, height: 512, frames: 97, fps: 24 },+ mochi: { steps: 40, cfgScale: 4.5, sampler: 'euler', scheduler: 'normal', width: 848, height: 480, frames: 49, fps: 24 },+ cosmos: { steps: 30, cfgScale: 7.0, sampler: 'euler', scheduler: 'normal', width: 1280, height: 704, frames: 57, fps: 24 },+ cogvideo: { steps: 50, cfgScale: 6.0, sampler: 'euler', scheduler: 'normal', width: 720, height: 480, frames: 49, fps: 8 },+ svd: { steps: 25, cfgScale: 2.5, sampler: 'euler', scheduler: 'karras', width: 1024, height: 576, frames: 25, fps: 6 },+ framepack: { steps: 30, cfgScale: 5.0, sampler: 'euler', scheduler: 'normal', width: 832, height: 480, frames: 33, fps: 16 },+ pyramidflow: { steps: 20, cfgScale: 7.0, sampler: 'euler', scheduler: 'normal', width: 1280, height: 768, frames: 121, fps: 24 },+ allegro: { steps: 100, cfgScale: 7.5, sampler: 'euler', scheduler: 'normal', width: 1280, height: 720, frames: 88, fps: 15 },+ unknown: { steps: 20, cfgScale: 7.0, sampler: 'euler', scheduler: 'normal', width: 1024, height: 1024 },}export interface GalleryItem {@@ -46,15 +102,28 @@ export interface GalleryItem {builderUsed?: 'dynamic' | 'legacy' | 'custom'resolvedVAE?: stringresolvedCLIP?: string+ /** Self-contained PNG data URL for backends that don't serve files over+ * ComfyUI's /view route (e.g. MLX on Apple Silicon). When set, display ++ * download read from this instead of filename/subfolder. */+ dataUrl?: string+ /** Cloud jobs: signed result URL from the render queue. Display prefers+ * `remoteUrl` → `dataUrl` → the ComfyUI /view path (filename/subfolder). */+ remoteUrl?: string+ /** Cloud jobs: TEE attestation receipt (null on non-attested lanes). */+ attestation?: { quote: string; verify_url: string } | null+ /** Cloud jobs: the render_jobs id, so the client can re-poll/re-sign. */+ jobId?: string+ /** Which redesign intent produced this item (gallery tagging). */+ intent?: CreateIntent}interface CreateState {mode: 'image' | 'video'+ videoBackend: VideoBackendKind+ /** Set once auto-detect has run (or the user clicked the backend picker)+ * so we don't keep overriding their choice on every launch. */+ videoBackendInitialized: booleanimageSubMode: 'text2img' | 'img2img'- // Video sub-mode mirrors imageSubMode so the main Create screen can offer a- // Text-to-Video / Image-to-Video switch (the I2V upload + model filter key- // off this). Session-only (not persisted), defaults to 't2v' each launch.- videoSubMode: 't2v' | 'i2v'prompt: stringnegativePrompt: stringimageModel: string@@ -71,19 +140,31 @@ interface CreateState {frames: numberfps: numberdenoise: number // Denoise strength for I2I (0.0–1.0)- // F2 (cinemazverev GH#4), multi-LoRA (konata 2026-06-09) — ordered LoRA- // stack. Each entry chains another LoraLoader in the workflow; per-entry- // strength mirrors LoraLoader's `strength_model` slider (0..2 in the UI).- // Empty array = no LoRA. Session-only (not in partialize), like before.+ i2iImage: string | null // Uploaded image filename for I2I+ i2vImage: string | null // Uploaded image filename for I2V models (SVD, FramePack)++ // ── redesign additions: flat-intent model + unified inputs + extra params ──+ videoSubMode: 't2v' | 'i2v'+ removebg: boolean+ showNegative: booleanselectedLoras: { name: string; strength: number }[]- // F3 (vanja-san GH#4) — top extended ComfyUI params surfaced in- // the param panel. selectedVae = 'auto' lets the checkpoint's- // bundled VAE win; an explicit pick overrides with a VAELoader.- // clipSkip = 0 means no Skip-CLIP layer is injected.selectedVae: stringclipSkip: number- i2iImage: string | null // Uploaded image filename for I2I- i2vImage: string | null // Uploaded image filename for I2V models (SVD, FramePack)+ growMaskBy: number // inpaint mask edge feather (VAEEncodeForInpaint grow_mask_by)+ /** Unified Stage input slot (runtime-only). On the local path source.filename+ * maps to i2iImage/i2vImage; on the cloud path it is a render-inputs path. */+ source: ImageRef | null+ sourceSetAt: number+ mask: ImageRef | null+ /** Runtime-only: local (Bridge) vs cloud (/api/jobs), derived from session. */+ backend: CreateBackend+ /** Runtime-only: hosted model slugs (lib/render/cloud-models) for the cloud+ * backend — separate from the persisted local checkpoint names. */+ cloudImageModel: string+ cloudVideoModel: string+ /** Runtime-only: which local custom-node capabilities are installed. */+ caps: Record<'rmbg' | 'inpaint-nodes', boolean>+isGenerating: booleanprogress: numberprogressText: string@@ -102,16 +183,11 @@ interface CreateState {imageModelList: ClassifiedModel[]videoModelList: ClassifiedModel[]comfyRunning: boolean- /** Bug A (v2.4.5): when video generation is about to fall back to .webp- * because VHS_VideoCombine is missing, useCreate sets this resolver and- * CreateView pops the modal. The user picks "install", "webp", or- * "cancel"; resolver fires with the choice and useCreate continues. */- vhsInstallPrompt: ((choice: 'install' | 'webp' | 'cancel') => void) | nullsetPreflightStatus: (ready: boolean | null, errors: PreflightError[], warnings: string[]) => voidsetMode: (mode: 'image' | 'video') => void+ setVideoBackend: (backend: VideoBackendKind) => voidsetImageSubMode: (subMode: 'text2img' | 'img2img') => void- setVideoSubMode: (subMode: 't2v' | 'i2v') => voidsetPrompt: (prompt: string) => voidsetNegativePrompt: (negativePrompt: string) => voidsetImageModel: (model: string, type: ModelType) => void@@ -126,15 +202,27 @@ interface CreateState {setFrames: (frames: number) => voidsetFps: (fps: number) => voidsetDenoise: (denoise: number) => void- /** Toggle a LoRA in/out of the stack (added at the end, default 0.8). */+ setI2iImage: (image: string | null) => void+ setI2vImage: (image: string | null) => void++ // ── redesign additions ──+ intent: () => CreateIntent+ setIntent: (intent: CreateIntent) => void+ toggleNegative: () => voidtoggleLora: (name: string) => void- /** Set the strength of one stacked LoRA (clamped 0..2 like the old slider). */setLoraStrengthFor: (name: string, strength: number) => voidclearLoras: () => voidsetSelectedVae: (name: string) => void- setClipSkip: (skip: number) => void- setI2iImage: (image: string | null) => void- setI2vImage: (image: string | null) => void+ setClipSkip: (n: number) => void+ setGrowMaskBy: (n: number) => void+ setSource: (img: ImageRef | null) => void+ setMask: (img: ImageRef | null) => void+ setBackend: (backend: CreateBackend) => void+ setCloudImageModel: (id: string) => void+ setCloudVideoModel: (id: string) => void+ setCaps: (caps: Record<'rmbg' | 'inpaint-nodes', boolean>) => void+ resetParamsToModelDefaults: () => void+setIsGenerating: (generating: boolean) => voidsetProgress: (progress: number, text?: string) => voidsetProgressPhase: (phase: ProgressPhase) => void@@ -145,20 +233,28 @@ interface CreateState {removeFromGallery: (id: string) => voidclearGallery: () => voidaddToPromptHistory: (prompt: string) => void- /** GitHub #66 (rubacc80-png) — wipe the Create-tab prompt history. */- clearPromptHistory: () => voidsetImageModelList: (list: ClassifiedModel[]) => voidsetVideoModelList: (list: ClassifiedModel[]) => voidsetComfyRunning: (running: boolean) => void- setVhsInstallPrompt: (resolver: ((choice: 'install' | 'webp' | 'cancel') => void) | null) => void}export const useCreateStore = create<CreateState>()(persist(- (set) => ({+ // Explicit param/return types: LU compiles with `strict: true` (the web+ // repo does not), and zustand v5's persist loses contextual typing of the+ // state-creator there — annotating restores set/get and setter types.+ (+ set: (p: Partial<CreateState> | ((s: CreateState) => Partial<CreateState>)) => void,+ get: () => CreateState,+ ): CreateState => ({mode: 'image',+ // Default to ComfyUI; AppShell/Onboarding flips this to 'mlx' on+ // Apple Silicon Macs with enough RAM after the bridge reports+ // arch + memory. Persisted across sessions so the auto-detect only+ // runs once.+ videoBackend: 'comfy' as VideoBackendKind,+ videoBackendInitialized: false,imageSubMode: 'text2img' as 'text2img' | 'img2img',- videoSubMode: 't2v' as 't2v' | 'i2v',prompt: '',negativePrompt: '',imageModel: '',@@ -175,11 +271,25 @@ export const useCreateStore = create<CreateState>()(frames: 24,fps: 8,denoise: 0.7,- selectedLoras: [],- selectedVae: 'auto',- clipSkip: 0,i2iImage: null,i2vImage: null,++ // ── redesign additions ──+ videoSubMode: 't2v' as 't2v' | 'i2v',+ removebg: false,+ showNegative: false,+ selectedLoras: [] as { name: string; strength: number }[],+ selectedVae: 'auto',+ clipSkip: 0,+ growMaskBy: 6,+ source: null as ImageRef | null,+ sourceSetAt: 0,+ mask: null as ImageRef | null,+ backend: 'local' as CreateBackend,+ cloudImageModel: '',+ cloudVideoModel: '',+ caps: { rmbg: false, 'inpaint-nodes': false } as Record<'rmbg' | 'inpaint-nodes', boolean>,+isGenerating: false,progress: 0,progressText: '',@@ -195,9 +305,9 @@ export const useCreateStore = create<CreateState>()(imageModelList: [],videoModelList: [],comfyRunning: false,- vhsInstallPrompt: null,setPreflightStatus: (ready, errors, warnings) => set({ preflightReady: ready, preflightErrors: errors, preflightWarnings: warnings }),+ setVideoBackend: (videoBackend) => set({ videoBackend, videoBackendInitialized: true }),setMode: (mode) => set((state) => {// Reset parameters to the correct defaults when switching modes// This prevents image resolution (1024x1024) leaking into video mode (causes HTTP 500)@@ -225,10 +335,6 @@ export const useCreateStore = create<CreateState>()(return { mode }}),setImageSubMode: (subMode) => set({ imageSubMode: subMode }),- // Plain setter — CreateView owns an always-mounted effect that re-points- // videoModel to a valid entry for the chosen sub-mode (so toggling works- // whether or not the Advanced panel is open).- setVideoSubMode: (subMode: 't2v' | 'i2v') => set({ videoSubMode: subMode }),setPrompt: (prompt) => set({ prompt }),setNegativePrompt: (negativePrompt) => set({ negativePrompt }),setImageModel: (model, type) => {@@ -265,28 +371,57 @@ export const useCreateStore = create<CreateState>()(setFrames: (frames) => set({ frames: Math.max(1, Math.min(120, Math.floor(frames))) }),setFps: (fps) => set({ fps: Math.max(1, Math.min(60, Math.floor(fps))) }),setDenoise: (denoise) => set({ denoise: Math.max(0, Math.min(1, denoise)) }),- // Explicit param types: this file's creator lost contextual typing long- // ago (pre-existing TS2740 on MODEL_TYPE_DEFAULTS) — without these the- // params would be implicit-any like the older setters around them.- toggleLora: (name: string) => set((s: CreateState) => {- if (!name) return {}- const exists = s.selectedLoras.some((l) => l.name === name)- return {- selectedLoras: exists- ? s.selectedLoras.filter((l) => l.name !== name)- : [...s.selectedLoras, { name, strength: 0.8 }],+ setI2iImage: (image) => set({ i2iImage: image }),+ setI2vImage: (image) => set({ i2vImage: image }),++ // ── redesign additions ──+ intent: () => deriveIntent(get()),+ setIntent: (intent) => set((s) => {+ // Clear intent-incompatible inputs: intents without a source drop both;+ // removebg/animate keep the source but drop a stale mask. Video/animate+ // mirror setMode's reset so image resolution never leaks into video.+ // A stale error from the previous intent never carries over.+ const dropAll = { source: null, mask: null, sourceSetAt: 0 }+ const base = { removebg: false, error: null }+ switch (intent) {+ case 'image': return { ...base, mode: 'image' as const, imageSubMode: 'text2img' as const, ...dropAll }+ case 'edit': return { ...base, mode: 'image' as const, imageSubMode: 'img2img' as const }+ case 'removebg': return { removebg: true, error: null, mode: 'image' as const, imageSubMode: 'img2img' as const, mask: null }+ case 'video': {+ const d = MODEL_TYPE_DEFAULTS[classifyModel(s.videoModel)] || MODEL_TYPE_DEFAULTS.unknown+ return { ...base, mode: 'video' as const, videoSubMode: 't2v' as const, ...dropAll,+ steps: d.steps, cfgScale: d.cfgScale, sampler: d.sampler, scheduler: d.scheduler,+ width: d.width, height: d.height, ...(d.frames ? { frames: d.frames } : {}), ...(d.fps ? { fps: d.fps } : {}) }+ }+ case 'animate': {+ const d = MODEL_TYPE_DEFAULTS[classifyModel(s.videoModel)] || MODEL_TYPE_DEFAULTS.unknown+ return { ...base, mode: 'video' as const, videoSubMode: 'i2v' as const, mask: null,+ steps: d.steps, cfgScale: d.cfgScale, sampler: d.sampler, scheduler: d.scheduler,+ width: d.width, height: d.height, ...(d.frames ? { frames: d.frames } : {}), ...(d.fps ? { fps: d.fps } : {}) }+ }}}),- setLoraStrengthFor: (name: string, strength: number) => set((s: CreateState) => ({- selectedLoras: s.selectedLoras.map((l) =>- l.name === name ? { ...l, strength: Math.max(0, Math.min(2, strength)) } : l,- ),- })),+ toggleNegative: () => set((s) => ({ showNegative: !s.showNegative })),+ toggleLora: (name) => set((s) => ({ selectedLoras: s.selectedLoras.some((l) => l.name === name) ? s.selectedLoras.filter((l) => l.name !== name) : [...s.selectedLoras, { name, strength: 0.8 }] })),+ setLoraStrengthFor: (name, strength) => set((s) => ({ selectedLoras: s.selectedLoras.map((l) => l.name === name ? { ...l, strength: Math.max(0, Math.min(2, strength)) } : l) })),clearLoras: () => set({ selectedLoras: [] }),setSelectedVae: (name) => set({ selectedVae: name || 'auto' }),- setClipSkip: (skip) => set({ clipSkip: Math.max(0, Math.min(12, Math.floor(skip))) }),- setI2iImage: (image) => set({ i2iImage: image }),- setI2vImage: (image) => set({ i2vImage: image }),+ setClipSkip: (n) => set({ clipSkip: Math.max(0, Math.min(12, Math.floor(n))) }),+ setGrowMaskBy: (n) => set({ growMaskBy: Math.max(0, Math.min(64, Math.floor(n))) }),+ setSource: (source) => set({ source, sourceSetAt: source ? Date.now() : 0, ...(source ? {} : { mask: null }) }),+ setMask: (mask) => set({ mask }),+ setBackend: (backend) => set({ backend }),+ setCloudImageModel: (cloudImageModel) => set({ cloudImageModel }),+ setCloudVideoModel: (cloudVideoModel) => set({ cloudVideoModel }),+ setCaps: (caps) => set({ caps }),+ resetParamsToModelDefaults: () => {+ const s = get()+ const d = s.mode === 'video'+ ? (MODEL_TYPE_DEFAULTS[classifyModel(s.videoModel)] || MODEL_TYPE_DEFAULTS.unknown)+ : MODEL_TYPE_DEFAULTS[s.imageModelType]+ set({ sampler: d.sampler, scheduler: d.scheduler, steps: d.steps, cfgScale: d.cfgScale, width: d.width, height: d.height, ...(d.frames ? { frames: d.frames } : {}), ...(d.fps ? { fps: d.fps } : {}) })+ },+setIsGenerating: (generating) => set({ isGenerating: generating, ...(generating ? {} : { progressPhase: 'idle' as ProgressPhase }) }),setProgress: (progress, text) => set({ progress, progressText: text ?? '' }),setProgressPhase: (phase) => set({ progressPhase: phase }),@@ -300,16 +435,16 @@ export const useCreateStore = create<CreateState>()(const filtered = s.promptHistory.filter(p => p !== prompt)return { promptHistory: [prompt, ...filtered].slice(0, 50) }}),- clearPromptHistory: () => set({ promptHistory: [] }),setImageModelList: (list) => set({ imageModelList: list }),setVideoModelList: (list) => set({ videoModelList: list }),setComfyRunning: (running) => set({ comfyRunning: running }),- setVhsInstallPrompt: (resolver) => set({ vhsInstallPrompt: resolver }),}),{name: 'create-store',partialize: (state) => ({mode: state.mode,+ videoBackend: state.videoBackend,+ videoBackendInitialized: state.videoBackendInitialized,imageModel: state.imageModel,imageModelType: state.imageModelType,videoModel: state.videoModel,@@ -325,10 +460,28 @@ export const useCreateStore = create<CreateState>()(denoise: state.denoise,gallery: state.gallery,promptHistory: state.promptHistory,+ // ── redesign additions (advanced params only; runtime inputs+ // source/mask/backend/caps stay unpersisted). No version bump: these+ // are additive and merge() backfills missing keys from defaults. ──+ showNegative: state.showNegative,+ selectedLoras: state.selectedLoras,+ selectedVae: state.selectedVae,+ clipSkip: state.clipSkip,+ growMaskBy: state.growMaskBy,}),- // Migrate old 'i2i' mode to imageSubMode (v2.3.0 refactor)+ // Future schema bumps hook into migrate. NOTE: zustand only invokes it+ // when the stored blob carries a NUMERIC version that differs — legacy+ // pre-version blobs skip it entirely, so their fixups must live in merge.+ version: 1,+ migrate: (persisted: any) => persisted,merge: (persisted: any, current: any) => {- const merged = { ...current, ...persisted }+ // Never let runtime-only fields rehydrate (a foreign/corrupt blob must+ // not flip the backend axis or inject a stale source/mask), backfill+ // missing keys from defaults, and fix up legacy pre-version blobs+ // ('i2i' mode from the v2.3.0 refactor).+ const { backend, source, mask, caps, isGenerating, ...safe } =+ persisted ?? {}+ const merged = { ...current, ...safe }if (merged.mode === 'i2i') {merged.mode = 'image'merged.imageSubMode = 'img2img'