Skip to content

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.

feat: Dynamic Workflow Builder + CivitAI Model Marketplace

PurpleDoubleDbbcce999c7b5
diff --git a/src/api/comfyui-nodes.ts b/src/api/comfyui-nodes.ts
new file mode 100644
index 00000000..0e3af18d
--- /dev/null
+++ b/src/api/comfyui-nodes.ts
@@ -0,0 +1,160 @@
+import { comfyuiUrl } from './backend'
+
+// ─── Types ───
+
+export interface NodeInputSpec {
+ required: Record<string, any>
+ optional?: Record<string, any>
+}
+
+export interface NodeMetadata {
+ input: NodeInputSpec
+ output: string[]
+ output_tooltips?: string[]
+ category?: string
+ display_name?: string
+ description?: string
+}
+
+export interface CategorizedNodes {
+ loaders: string[]
+ samplers: string[]
+ latentInit: string[]
+ textEncoders: string[]
+ decoders: string[]
+ savers: string[]
+ videoSavers: string[]
+ motion: string[]
+}
+
+export interface AvailableModels {
+ checkpoints: string[]
+ unets: string[]
+ vaes: string[]
+ clips: string[]
+ motionModels: string[]
+}
+
+// ─── Cache ───
+
+let nodeInfoCache: Record<string, NodeMetadata> | null = null
+let cacheTimestamp = 0
+const CACHE_TTL = 60_000 // 1 minute
+
+// ─── Fetch all node info (cached) ───
+
+export async function getAllNodeInfo(forceRefresh = false): Promise<Record<string, NodeMetadata>> {
+ if (!forceRefresh && nodeInfoCache && Date.now() - cacheTimestamp < CACHE_TTL) {
+ return nodeInfoCache
+ }
+
+ const res = await fetch(comfyuiUrl('/object_info'), { signal: AbortSignal.timeout(10000) })
+ if (!res.ok) throw new Error(`Failed to fetch node info: ${res.status}`)
+ const data = await res.json()
+
+ nodeInfoCache = data
+ cacheTimestamp = Date.now()
+ console.log(`[comfyui-nodes] Loaded ${Object.keys(data).length} node types`)
+ return data
+}
+
+export function clearNodeCache() {
+ nodeInfoCache = null
+ cacheTimestamp = 0
+}
+
+// ─── Node existence check (from cache) ───
+
+export function hasNode(name: string): boolean {
+ return nodeInfoCache ? name in nodeInfoCache : false
+}
+
+// ─── Categorize available nodes ───
+
+export function categorizeNodes(allNodes: Record<string, NodeMetadata>): CategorizedNodes {
+ const result: CategorizedNodes = {
+ loaders: [],
+ samplers: [],
+ latentInit: [],
+ textEncoders: [],
+ decoders: [],
+ savers: [],
+ videoSavers: [],
+ motion: [],
+ }
+
+ const known: Record<string, keyof CategorizedNodes> = {
+ // Loaders
+ CheckpointLoaderSimple: 'loaders',
+ UNETLoader: 'loaders',
+ VAELoader: 'loaders',
+ CLIPLoader: 'loaders',
+ DualCLIPLoader: 'loaders',
+ TripleCLIPLoader: 'loaders',
+ // Samplers
+ KSampler: 'samplers',
+ KSamplerAdvanced: 'samplers',
+ SamplerCustom: 'samplers',
+ // Latent init
+ EmptyLatentImage: 'latentInit',
+ EmptySD3LatentImage: 'latentInit',
+ EmptyHunyuanLatentVideo: 'latentInit',
+ // Text encoding
+ CLIPTextEncode: 'textEncoders',
+ CLIPTextEncodeSDXL: 'textEncoders',
+ // Decoders
+ VAEDecode: 'decoders',
+ VAEDecodeTiled: 'decoders',
+ // Image savers
+ SaveImage: 'savers',
+ PreviewImage: 'savers',
+ // Video savers
+ SaveAnimatedWEBP: 'videoSavers',
+ VHS_VideoCombine: 'videoSavers',
+ // AnimateDiff / Motion
+ ADE_LoadAnimateDiffModel: 'motion',
+ ADE_ApplyAnimateDiffModelSimple: 'motion',
+ ADE_UseEvolvedSampling: 'motion',
+ }
+
+ for (const nodeName of Object.keys(allNodes)) {
+ const category = known[nodeName]
+ if (category) {
+ result[category].push(nodeName)
+ }
+ }
+
+ return result
+}
+
+// ─── Extract available models from node info ───
+
+export function detectAvailableModels(allNodes: Record<string, NodeMetadata>): AvailableModels {
+ const extract = (nodeName: string, fieldName: string): string[] => {
+ const spec = allNodes[nodeName]?.input?.required?.[fieldName]
+ if (Array.isArray(spec) && Array.isArray(spec[0])) return spec[0]
+ return []
+ }
+
+ return {
+ checkpoints: extract('CheckpointLoaderSimple', 'ckpt_name'),
+ unets: extract('UNETLoader', 'unet_name'),
+ vaes: extract('VAELoader', 'vae_name'),
+ clips: extract('CLIPLoader', 'clip_name'),
+ motionModels: extract('ADE_LoadAnimateDiffModel', 'model_name'),
+ }
+}
+
+// ─── Extract sampler/scheduler options ───
+
+export function getSamplerOptions(allNodes: Record<string, NodeMetadata>): string[] {
+ const spec = allNodes.KSampler?.input?.required?.sampler_name
+ if (Array.isArray(spec) && Array.isArray(spec[0])) return spec[0]
+ return ['euler']
+}
+
+export function getSchedulerOptions(allNodes: Record<string, NodeMetadata>): string[] {
+ const spec = allNodes.KSampler?.input?.required?.scheduler
+ if (Array.isArray(spec) && Array.isArray(spec[0])) return spec[0]
+ return ['normal']
+}
diff --git a/src/api/discover.ts b/src/api/discover.ts
index d98ba494..59c2e091 100644
--- a/src/api/discover.ts
+++ b/src/api/discover.ts
@@ -298,6 +298,87 @@ export function getVideoBundles(): ModelBundle[] {
]
}
+// ─── CivitAI Model Search ───
+
+export interface CivitAIModelResult {
+ id: number
+ name: string
+ description: string
+ type: string
+ thumbnailUrl?: string
+ downloadUrl?: string
+ filename?: string
+ subfolder?: string
+ sizeGB?: number
+ stats?: { downloads: number; likes: number }
+ creator?: string
+ sourceUrl: string
+}
+
+export async function searchCivitaiModels(
+ query: string,
+ type: 'Checkpoint' | 'LORA' | 'VAE' | 'TextualInversion' = 'Checkpoint'
+): Promise<CivitAIModelResult[]> {
+ try {
+ const params = new URLSearchParams({
+ query,
+ types: type,
+ limit: '20',
+ sort: 'Most Downloaded',
+ })
+ const resp = await fetch(`/civitai-api/v1/models?${params}`)
+ if (!resp.ok) return []
+
+ const data = await resp.json()
+ const items: any[] = data.items ?? []
+
+ return items.map((item) => {
+ const version = item.modelVersions?.[0]
+ const file = version?.files?.[0]
+ const thumb = version?.images?.[0]?.url
+ const downloadUrl = version?.downloadUrl ?? file?.downloadUrl
+ const sizeKB = file?.sizeKB ?? 0
+
+ // Determine subfolder based on model type
+ let subfolder = 'checkpoints'
+ if (type === 'LORA') subfolder = 'loras'
+ else if (type === 'VAE') subfolder = 'vae'
+ else if (type === 'TextualInversion') subfolder = 'embeddings'
+ // Check if it's a diffusion model (FLUX, Wan, etc.)
+ const name = item.name?.toLowerCase() || ''
+ if (name.includes('flux') || name.includes('wan') || name.includes('hunyuan')) {
+ subfolder = 'diffusion_models'
+ }
+
+ const filename = file?.name || `${item.name?.replace(/[^a-zA-Z0-9._-]/g, '_')}.safetensors`
+
+ const descParts: string[] = []
+ const rawDesc = (item.description ?? '').replace(/<[^>]*>/g, '').trim()
+ if (rawDesc) descParts.push(rawDesc.slice(0, 120))
+ if (item.stats?.downloadCount) descParts.push(`${item.stats.downloadCount.toLocaleString()} downloads`)
+ if (item.creator?.username) descParts.push(`by ${item.creator.username}`)
+
+ return {
+ id: item.id,
+ name: item.name || `Model #${item.id}`,
+ description: descParts.join(' — '),
+ type: type,
+ thumbnailUrl: thumb,
+ downloadUrl,
+ filename,
+ subfolder,
+ sizeGB: sizeKB > 0 ? Math.round(sizeKB / 1024 / 1024 * 10) / 10 : undefined,
+ stats: item.stats ? { downloads: item.stats.downloadCount || 0, likes: item.stats.thumbsUpCount || 0 } : undefined,
+ creator: item.creator?.username,
+ sourceUrl: `https://civitai.com/models/${item.id}`,
+ }
+ })
+ } catch (err) {
+ console.warn('[discover] CivitAI model search failed:', err)
+ return []
+ }
+}
+
// Flat list for backwards compatibility (individual files)
export function getVideoModelsDiscover(): DiscoverModel[] {
const bundles = getVideoBundles()
diff --git a/src/api/dynamic-workflow.ts b/src/api/dynamic-workflow.ts
new file mode 100644
index 00000000..42aea08a
--- /dev/null
+++ b/src/api/dynamic-workflow.ts
@@ -0,0 +1,335 @@
+import { classifyModel, findMatchingVAE, findMatchingCLIP } from './comfyui'
+import type { ModelType, GenerateParams, VideoParams } from './comfyui'
+import {
+ getAllNodeInfo,
+ categorizeNodes,
+ detectAvailableModels,
+ type NodeMetadata,
+ type CategorizedNodes,
+ type AvailableModels,
+} from './comfyui-nodes'
+
+// ─── Strategy Detection ───
+
+export type WorkflowStrategy =
+ | 'unet_flux' // FLUX/FLUX2: UNETLoader + CLIPLoader + VAELoader + EmptySD3LatentImage
+ | 'unet_video' // Wan/Hunyuan: UNETLoader + CLIPLoader + VAELoader + EmptyHunyuanLatentVideo
+ | 'checkpoint' // SDXL/SD1.5: CheckpointLoaderSimple + EmptyLatentImage
+ | 'animatediff' // AnimateDiff: CheckpointLoaderSimple + ADE_* nodes
+ | 'unavailable'
+
+interface StrategyResult {
+ strategy: WorkflowStrategy
+ reason: string
+}
+
+function determineStrategy(
+ modelType: ModelType,
+ isVideo: boolean,
+ nodes: CategorizedNodes,
+ models: AvailableModels,
+): StrategyResult {
+ const hasUNET = nodes.loaders.includes('UNETLoader')
+ const hasCheckpoint = nodes.loaders.includes('CheckpointLoaderSimple')
+ const hasCLIPLoader = nodes.loaders.includes('CLIPLoader')
+ const hasVAELoader = nodes.loaders.includes('VAELoader')
+ const hasAnimateDiff = nodes.motion.includes('ADE_LoadAnimateDiffModel')
+
+ // FLUX / FLUX2 → always UNET-based
+ if (modelType === 'flux' || modelType === 'flux2') {
+ if (hasUNET && hasCLIPLoader && hasVAELoader) {
+ return { strategy: 'unet_flux', reason: `${modelType} model → UNETLoader pipeline` }
+ }
+ return { strategy: 'unavailable', reason: 'FLUX requires UNETLoader + CLIPLoader + VAELoader nodes' }
+ }
+
+ // Wan / Hunyuan → UNET-based with video latent
+ if (modelType === 'wan' || modelType === 'hunyuan') {
+ if (hasUNET && hasCLIPLoader && hasVAELoader) {
+ return { strategy: 'unet_video', reason: `${modelType} model → UNETLoader + video latent` }
+ }
+ return { strategy: 'unavailable', reason: 'Wan/Hunyuan requires UNETLoader + CLIPLoader + VAELoader nodes' }
+ }
+
+ // SDXL / SD1.5 / Unknown
+ if (isVideo && hasAnimateDiff && hasCheckpoint && models.motionModels.length > 0) {
+ return { strategy: 'animatediff', reason: 'Video mode → AnimateDiff pipeline' }
+ }
+
+ if (hasCheckpoint) {
+ return { strategy: 'checkpoint', reason: 'Checkpoint-based pipeline' }
+ }
+
+ // Last resort: try UNET if available
+ if (hasUNET && hasCLIPLoader && hasVAELoader) {
+ return { strategy: 'unet_flux', reason: 'Fallback to UNETLoader (no checkpoint loader)' }
+ }
+
+ return { strategy: 'unavailable', reason: 'No compatible loader nodes found in ComfyUI' }
+}
+
+// ─── Dynamic Workflow Builder ───
+
+export async function buildDynamicWorkflow(
+ params: GenerateParams | VideoParams,
+ modelType?: ModelType,
+): Promise<Record<string, any>> {
+ const type = modelType || classifyModel(params.model)
+ const isVideo = 'frames' in params
+ const videoParams = params as VideoParams
+
+ // Fetch node info (cached)
+ const allNodes = await getAllNodeInfo()
+ const nodes = categorizeNodes(allNodes)
+ const models = detectAvailableModels(allNodes)
+
+ const { strategy, reason } = determineStrategy(type, isVideo, nodes, models)
+ console.log(`[dynamic-workflow] Strategy: ${strategy} (${reason})`)
+
+ if (strategy === 'unavailable') {
+ throw new Error(reason)
+ }
+
+ const workflow: Record<string, any> = {}
+ let n = 1 // node counter
+
+ const seed = params.seed === -1 ? Math.floor(Math.random() * 2147483647) : params.seed
+
+ // ─── Phase 1: Model Loading ───
+
+ let modelNodeId: string
+ let clipSourceId: string
+ let clipOutputSlot: number
+ let vaeSourceId: string
+ let vaeOutputSlot: number
+ let samplerModelId: string
+
+ if (strategy === 'checkpoint') {
+ // Single loader: outputs MODEL (0), CLIP (1), VAE (2)
+ modelNodeId = String(n++)
+ workflow[modelNodeId] = {
+ class_type: 'CheckpointLoaderSimple',
+ inputs: { ckpt_name: params.model },
+ }
+ clipSourceId = modelNodeId
+ clipOutputSlot = 1
+ vaeSourceId = modelNodeId
+ vaeOutputSlot = 2
+ samplerModelId = modelNodeId
+
+ } else if (strategy === 'unet_flux' || strategy === 'unet_video') {
+ // Separate loaders
+ const unetId = String(n++)
+ const clipId = String(n++)
+ const vaeId = String(n++)
+
+ const clipType = type === 'flux2' ? 'flux2'
+ : type === 'flux' ? 'flux'
+ : (type === 'wan' || type === 'hunyuan') ? 'wan'
+ : 'flux'
+
+ let vae: string, clip: string
+ try { vae = await findMatchingVAE(type) } catch { vae = models.vaes[0] || '' }
+ try { clip = await findMatchingCLIP(type) } catch { clip = models.clips[0] || '' }
+
+ workflow[unetId] = {
+ class_type: 'UNETLoader',
+ inputs: { unet_name: params.model, weight_dtype: 'default' },
+ }
+ workflow[clipId] = {
+ class_type: 'CLIPLoader',
+ inputs: { clip_name: clip, type: clipType, device: 'default' },
+ }
+ workflow[vaeId] = {
+ class_type: 'VAELoader',
+ inputs: { vae_name: vae },
+ }
+
+ modelNodeId = unetId
+ clipSourceId = clipId
+ clipOutputSlot = 0
+ vaeSourceId = vaeId
+ vaeOutputSlot = 0
+ samplerModelId = unetId
+
+ } else {
+ // AnimateDiff: checkpoint + motion model
+ const ckptId = String(n++)
+ const motionLoadId = String(n++)
+ const motionApplyId = String(n++)
+ const evolvedId = String(n++)
+
+ workflow[ckptId] = {
+ class_type: 'CheckpointLoaderSimple',
+ inputs: { ckpt_name: params.model },
+ }
+ workflow[motionLoadId] = {
+ class_type: 'ADE_LoadAnimateDiffModel',
+ inputs: { model_name: models.motionModels[0] },
+ }
+ workflow[motionApplyId] = {
+ class_type: 'ADE_ApplyAnimateDiffModelSimple',
+ inputs: { motion_model: [motionLoadId, 0] },
+ }
+ workflow[evolvedId] = {
+ class_type: 'ADE_UseEvolvedSampling',
+ inputs: {
+ model: [ckptId, 0],
+ m_models: [motionApplyId, 0],
+ beta_schedule: 'autoselect',
+ },
+ }
+
+ modelNodeId = ckptId
+ clipSourceId = ckptId
+ clipOutputSlot = 1
+ vaeSourceId = ckptId
+ vaeOutputSlot = 2
+ samplerModelId = evolvedId
+ }
+
+ // ─── Phase 2: Text Encoding ───
+
+ const posId = String(n++)
+ const negId = String(n++)
+
+ workflow[posId] = {
+ class_type: 'CLIPTextEncode',
+ inputs: { text: params.prompt, clip: [clipSourceId, clipOutputSlot] },
+ }
+ workflow[negId] = {
+ class_type: 'CLIPTextEncode',
+ inputs: {
+ text: params.negativePrompt || '',
+ clip: [clipSourceId, clipOutputSlot],
+ },
+ }
+
+ // ─── Phase 3: Latent Initialization ───
+
+ const latentId = String(n++)
+
+ if (strategy === 'unet_video') {
+ // Wan/Hunyuan video latent
+ const latentNode = nodes.latentInit.includes('EmptyHunyuanLatentVideo')
+ ? 'EmptyHunyuanLatentVideo'
+ : 'EmptyLatentImage'
+
+ workflow[latentId] = {
+ class_type: latentNode,
+ inputs: latentNode === 'EmptyHunyuanLatentVideo'
+ ? { width: params.width, height: params.height, length: videoParams.frames, batch_size: 1 }
+ : { width: params.width, height: params.height, batch_size: videoParams.frames },
+ }
+ } else if (strategy === 'animatediff') {
+ // AnimateDiff: batch_size = frames
+ workflow[latentId] = {
+ class_type: 'EmptyLatentImage',
+ inputs: { width: params.width, height: params.height, batch_size: videoParams.frames },
+ }
+ } else if (strategy === 'unet_flux') {
+ // FLUX uses SD3 latent
+ const latentNode = nodes.latentInit.includes('EmptySD3LatentImage')
+ ? 'EmptySD3LatentImage'
+ : 'EmptyLatentImage'
+
+ workflow[latentId] = {
+ class_type: latentNode,
+ inputs: { width: params.width, height: params.height, batch_size: params.batchSize },
+ }
+ } else {
+ // Checkpoint (SDXL/SD1.5)
+ workflow[latentId] = {
+ class_type: 'EmptyLatentImage',
+ inputs: { width: params.width, height: params.height, batch_size: params.batchSize },
+ }
+ }
+
+ // ─── Phase 4: Sampling ───
+
+ const samplerId = String(n++)
+
+ workflow[samplerId] = {
+ class_type: 'KSampler',
+ inputs: {
+ model: [samplerModelId, 0],
+ positive: [posId, 0],
+ negative: [negId, 0],
+ latent_image: [latentId, 0],
+ seed,
+ steps: params.steps,
+ cfg: params.cfgScale,
+ sampler_name: params.sampler,
+ scheduler: params.scheduler,
+ denoise: 1.0,
+ },
+ }
+
+ // ─── Phase 5: Decode ───
+
+ const decodeId = String(n++)
+
+ workflow[decodeId] = {
+ class_type: 'VAEDecode',
+ inputs: {
+ samples: [samplerId, 0],
+ vae: [vaeSourceId, vaeOutputSlot],
+ },
+ }
+
+ // ─── Phase 6: Output ───
+
+ const saveId = String(n++)
+
+ if (isVideo) {
+ // Video output: prefer VHS > SaveAnimatedWEBP > SaveImage
+ if (nodes.videoSavers.includes('VHS_VideoCombine')) {
+ workflow[saveId] = {
+ class_type: 'VHS_VideoCombine',
+ inputs: {
+ images: [decodeId, 0],
+ frame_rate: videoParams.fps,
+ loop_count: 0,
+ filename_prefix: 'locally_uncensored_vid',
+ format: 'video/h264-mp4',
+ pingpong: false,
+ save_output: true,
+ },
+ }
+ } else if (nodes.videoSavers.includes('SaveAnimatedWEBP')) {
+ workflow[saveId] = {
+ class_type: 'SaveAnimatedWEBP',
+ inputs: {
+ images: [decodeId, 0],
+ filename_prefix: 'locally_uncensored_vid',
+ fps: videoParams.fps,
+ lossless: false,
+ quality: 90,
+ method: 'default',
+ },
+ }
+ } else {
+ workflow[saveId] = {
+ class_type: 'SaveImage',
+ inputs: {
+ images: [decodeId, 0],
+ filename_prefix: 'locally_uncensored_vid',
+ },
+ }
+ }
+ } else {
+ workflow[saveId] = {
+ class_type: 'SaveImage',
+ inputs: {
+ images: [decodeId, 0],
+ filename_prefix: 'locally_uncensored',
+ },
+ }
+ }
+
+ console.log(`[dynamic-workflow] Built ${Object.keys(workflow).length} nodes:`,
+ Object.entries(workflow).map(([id, node]) => `${id}:${node.class_type}`).join(' → ')
+ )
+
+ return workflow
+}
diff --git a/src/components/models/DiscoverModels.tsx b/src/components/models/DiscoverModels.tsx
index 2613b2aa..72c40e72 100644
--- a/src/components/models/DiscoverModels.tsx
+++ b/src/components/models/DiscoverModels.tsx
@@ -3,8 +3,8 @@ import { motion } from 'framer-motion'
import { Download, RefreshCw, ExternalLink, Search, Info, CheckCircle, XCircle, Loader2 } from 'lucide-react'
import {
fetchAbliteratedModels, getImageBundles, getVideoBundles,
- startModelDownload, getDownloadProgress,
- type DiscoverModel, type DownloadProgress, type ModelBundle,
+ startModelDownload, getDownloadProgress, searchCivitaiModels,
+ type DiscoverModel, type DownloadProgress, type ModelBundle, type CivitAIModelResult,
} from '../../api/discover'
import { useModels } from '../../hooks/useModels'
import { GlassCard } from '../ui/GlassCard'
@@ -19,6 +19,9 @@ interface Props {
export function DiscoverModels({ category }: Props) {
const [textModels, setTextModels] = useState<DiscoverModel[]>([])
+ const [civitaiResults, setCivitaiResults] = useState<CivitAIModelResult[]>([])
+ const [civitaiSearching, setCivitaiSearching] = useState(false)
+ const [civitaiQuery, setCivitaiQuery] = useState('')
const [loading, setLoading] = useState(false)
const [search, setSearch] = useState('')
const [downloads, setDownloads] = useState<Record<string, DownloadProgress>>({})
@@ -39,7 +42,16 @@ export function DiscoverModels({ category }: Props) {
if (hasActive && !pollRef.current) {
pollRef.current = setInterval(async () => {
const prog = await getDownloadProgress()
- setDownloads(prog)
+ setDownloads(prev => {
+ // Check if any download just completed
+ for (const [id, d] of Object.entries(prog)) {
+ if (d.status === 'complete' && prev[id]?.status !== 'complete') {
+ // Trigger model list refresh across the app
+ window.dispatchEvent(new CustomEvent('comfyui-model-downloaded'))
+ }
+ }
+ return prog
+ })
const stillActive = Object.values(prog).some(d => d.status === 'downloading' || d.status === 'connecting')
if (!stillActive && pollRef.current) {
clearInterval(pollRef.current)
@@ -85,6 +97,27 @@ export function DiscoverModels({ category }: Props) {
setDownloads(prog)
}
+ const handleCivitaiSearch = async () => {
+ if (!civitaiQuery.trim()) return
+ setCivitaiSearching(true)
+ const results = await searchCivitaiModels(civitaiQuery, 'Checkpoint')
+ setCivitaiResults(results)
+ setCivitaiSearching(false)
+ }
+
+ const handleCivitaiDownload = async (model: CivitAIModelResult) => {
+ if (!model.downloadUrl || !model.filename || !model.subfolder) return
+ // CivitAI downloads need the proxy
+ const url = model.downloadUrl.startsWith('http')
+ ? `/local-api/proxy-download?url=${encodeURIComponent(model.downloadUrl)}`
+ : model.downloadUrl
+ const result = await startModelDownload(model.downloadUrl, model.subfolder, model.filename)
+ if (result.status === 'started' || result.status === 'already_exists') {
+ const prog = await getDownloadProgress()
+ setDownloads(prog)
+ }
+ }
+
const isBundleComplete = (bundle: ModelBundle): boolean => {
return bundle.files.every(f => f.filename && downloads[f.filename]?.status === 'complete')
}
@@ -291,6 +324,76 @@ export function DiscoverModels({ category }: Props) {
</div>
)}
+ {/* CivitAI Search (Image & Video) */}
+ {(isImage || isVideo) && (
+ <GlassCard className="p-4 space-y-3">
+ <h3 className="text-sm font-semibold text-gray-900 dark:text-white">Search CivitAI</h3>
+ <div className="flex gap-2">
+ <input
+ value={civitaiQuery}
+ onChange={(e) => setCivitaiQuery(e.target.value)}
+ onKeyDown={(e) => e.key === 'Enter' && handleCivitaiSearch()}
+ placeholder="e.g. flux, sdxl realistic, anime..."
+ className="flex-1 px-3 py-2 rounded-lg bg-gray-100 dark:bg-white/5 border border-gray-200 dark:border-white/10 text-sm text-gray-900 dark:text-white placeholder-gray-500 focus:outline-none focus:border-gray-400 dark:focus:border-white/20"
+ />
+ <button
+ onClick={handleCivitaiSearch}
+ disabled={civitaiSearching || !civitaiQuery.trim()}
+ className="px-3 py-2 rounded-lg bg-gray-100 dark:bg-white/10 hover:bg-gray-200 dark:hover:bg-white/15 disabled:opacity-50 text-gray-700 dark:text-white transition-colors"
+ >
+ {civitaiSearching ? <Loader2 size={16} className="animate-spin" /> : <Search size={16} />}
+ </button>
+ </div>
+
+ {civitaiResults.length > 0 && (
+ <div className="space-y-2 max-h-[50vh] overflow-y-auto">
+ {civitaiResults.map((model) => {
+ const dlState = model.filename ? downloads[model.filename] : null
+ const isDl = dlState?.status === 'downloading' || dlState?.status === 'connecting'
+ const isDone = dlState?.status === 'complete'
+
+ return (
+ <div key={model.id} className="flex gap-3 p-3 rounded-lg bg-gray-50 dark:bg-white/5 border border-gray-200 dark:border-white/10">
+ {model.thumbnailUrl && (
+ <img src={model.thumbnailUrl} alt="" className="w-14 h-14 rounded-lg object-cover flex-shrink-0" loading="lazy" />
+ )}
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium text-gray-900 dark:text-white truncate">{model.name}</span>
+ {model.sizeGB && <span className="text-[10px] text-gray-400 flex-shrink-0">{model.sizeGB} GB</span>}
+ </div>
+ {model.description && <p className="text-[11px] text-gray-500 line-clamp-1 mt-0.5">{model.description}</p>}
+ {isDl && dlState && dlState.total > 0 && (
+ <div className="mt-1.5">
+ <ProgressBar progress={(dlState.progress / dlState.total) * 100} />
+ <span className="text-[10px] text-gray-400">{formatBytes(dlState.progress)} / {formatBytes(dlState.total)}</span>
+ </div>
+ )}
+ </div>
+ <div className="flex items-center gap-1 shrink-0">
+ {isDone ? (
+ <CheckCircle size={16} className="text-green-500" />
+ ) : isDl ? (
+ <Loader2 size={16} className="animate-spin text-gray-400" />
+ ) : model.downloadUrl ? (
+ <button onClick={() => handleCivitaiDownload(model)} className="p-2 rounded-lg bg-green-100 dark:bg-green-500/15 hover:bg-green-200 dark:hover:bg-green-500/25 text-green-700 dark:text-green-400 transition-all" title="Download">
+ <Download size={14} />
+ </button>
+ ) : null}
+ <a href={model.sourceUrl} target="_blank" rel="noopener noreferrer" className="p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-white/10 text-gray-500 transition-all" title="View on CivitAI">
+ <ExternalLink size={14} />
+ </a>
+ </div>
+ </div>
+ )
+ })}
+ </div>
+ )}
+
+ {civitaiSearching && <div className="text-center py-4 text-gray-500 text-sm">Searching CivitAI...</div>}
+ </GlassCard>
+ )}
+
{loading ? (
<div className="text-center py-8 text-gray-500">Loading models...</div>
) : !isVideo && (
diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.ts
index 4a1addac..28714b62 100644
--- a/src/hooks/useCreate.ts
+++ b/src/hooks/useCreate.ts
@@ -17,6 +17,8 @@ import {
type ComfyUIOutput,
type VideoBackend,
} from '../api/comfyui'
+import { buildDynamicWorkflow } from '../api/dynamic-workflow'
+import { getAllNodeInfo } from '../api/comfyui-nodes'
import { useCreateStore, type GalleryItem } from '../stores/createStore'
import { useWorkflowStore } from '../stores/workflowStore'
import { injectParameters } from '../api/workflows'
@@ -39,6 +41,16 @@ export function useCreate() {
}
}, [])
+ // Auto-refresh models when a ComfyUI model download completes
+ useEffect(() => {
+ const handler = () => {
+ console.log('[useCreate] Model download completed, refreshing model list...')
+ fetchModels()
+ }
+ window.addEventListener('comfyui-model-downloaded', handler)
+ return () => window.removeEventListener('comfyui-model-downloaded', handler)
+ }, [fetchModels])
+
const checkConnection = useCallback(async () => {
const ok = await checkComfyConnection()
setConnected(ok)
@@ -47,12 +59,13 @@ export function useCreate() {
const fetchModels = useCallback(async () => {
try {
- const [imgModels, vidModels, samplers, schedulers, vBackend] = await Promise.all([
+ const [imgModels, vidModels, samplers, schedulers, vBackend, _nodeInfo] = await Promise.all([
getImageModels(),
getVideoModels(),
getSamplers(),
getSchedulers(),
detectVideoBackend(),
+ getAllNodeInfo().catch(() => null),
])
setImageModels(imgModels)
setVideoModelsList(vidModels)
@@ -142,12 +155,21 @@ export function useCreate() {
setProgress(5, `Using workflow: ${customWf.name}...`)
const params = mode === 'video' ? { ...baseParams, frames, fps } : baseParams
workflow = await injectParameters(customWf.workflow, customWf.parameterMap, params, imageModelType)
- } else if (mode === 'video') {
- setProgress(5, 'Building video workflow...')
- workflow = await buildTxt2VidWorkflow({ ...baseParams, frames, fps }, videoBackend)
} else {
- setProgress(5, 'Building image workflow...')
- workflow = await buildTxt2ImgWorkflow(baseParams, imageModelType)
+ // Dynamic workflow builder — auto-detects nodes and builds the right pipeline
+ setProgress(5, 'Building workflow...')
+ try {
+ const genParams = mode === 'video' ? { ...baseParams, frames, fps } : baseParams
+ workflow = await buildDynamicWorkflow(genParams, imageModelType)
+ } catch (dynErr) {
+ // Fallback to legacy builders if dynamic fails
+ console.warn('[useCreate] Dynamic builder failed, using legacy:', dynErr)
+ if (mode === 'video') {
+ workflow = await buildTxt2VidWorkflow({ ...baseParams, frames, fps }, videoBackend)
+ } else {
+ workflow = await buildTxt2ImgWorkflow(baseParams, imageModelType)
+ }
+ }
}
setProgress(10, 'Submitting to ComfyUI...')