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
Fix ComfyUI integration: auto-start, auto-stop, live status
PurpleDoubleDaa72131136c5
diff --git a/package-lock.json b/package-lock.jsonindex 01640537..767c096e 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,18 +1,20 @@{- "name": "uncensored-ai",- "version": "0.0.0",+ "name": "locally-uncensored",+ "version": "1.0.0","lockfileVersion": 3,"requires": true,"packages": {"": {- "name": "uncensored-ai",- "version": "0.0.0",+ "name": "locally-uncensored",+ "version": "1.0.0",+ "license": "MIT","dependencies": {"@react-three/drei": "^10.7.7","@react-three/fiber": "^9.5.0","@tailwindcss/vite": "^4.2.2","@types/react-syntax-highlighter": "^15.5.13","@types/uuid": "^10.0.0",+ "dotenv": "^17.3.1","framer-motion": "^12.38.0","lucide-react": "^1.0.1","react": "^19.2.4",@@ -2202,6 +2204,18 @@"url": "https://github.com/sponsors/wooorm"}},+ "node_modules/dotenv": {+ "version": "17.3.1",+ "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.3.1.tgz",+ "integrity": "sha512-IO8C/dzEb6O3F9/twg6ZLXz164a2fhTnEWb95H23Dm4OuN+92NmEAlTrupP9VW6Jm3sO26tQlqyvyi4CsnY9GA==",+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://dotenvx.com"+ }+ },"node_modules/draco3d": {"version": "1.5.7","resolved": "https://registry.npmjs.org/draco3d/-/draco3d-1.5.7.tgz",diff --git a/package.json b/package.jsonindex e3771462..9689fda1 100644--- a/package.json+++ b/package.json@@ -9,7 +9,17 @@"type": "git","url": "https://github.com/purpledoubled/locally-uncensored.git"},- "keywords": ["ai", "local", "ollama", "comfyui", "uncensored", "private", "chat", "image-generation", "video-generation"],+ "keywords": [+ "ai",+ "local",+ "ollama",+ "comfyui",+ "uncensored",+ "private",+ "chat",+ "image-generation",+ "video-generation"+ ],"type": "module","scripts": {"dev": "vite",@@ -23,6 +33,7 @@"@tailwindcss/vite": "^4.2.2","@types/react-syntax-highlighter": "^15.5.13","@types/uuid": "^10.0.0",+ "dotenv": "^17.3.1","framer-motion": "^12.38.0","lucide-react": "^1.0.1","react": "^19.2.4",diff --git a/src/components/create/CreateView.tsx b/src/components/create/CreateView.tsxindex e0770ccd..cba2e1ec 100644--- a/src/components/create/CreateView.tsx+++ b/src/components/create/CreateView.tsx@@ -1,5 +1,5 @@import { useEffect, useState, useCallback, useRef } from 'react'-import { Image, Video, WifiOff, Play, Loader2, CheckCircle, AlertTriangle } from 'lucide-react'+import { Image, Video, WifiOff, Loader2, CheckCircle, AlertTriangle, RefreshCw } from 'lucide-react'import { useCreate } from '../../hooks/useCreate'import { useCreateStore } from '../../stores/createStore'import { PromptInput } from './PromptInput'@@ -7,87 +7,139 @@ import { ParamPanel } from './ParamPanel'import { OutputDisplay } from './OutputDisplay'import { Gallery } from './Gallery'+interface ComfyStatus {+ running: boolean+ starting: boolean+ found: boolean+ path: string | null+ logs: string[]+}+export function CreateView() {- const { connected, checkpoints, videoModels, samplerList, videoBackend, checkConnection, fetchModels, generate, cancel } = useCreate()+ const { connected, checkpoints, videoModels, samplerList, videoBackend, error, checkConnection, fetchModels, generate, cancel } = useCreate()const { mode, setMode } = useCreateStore()- const [starting, setStarting] = useState(false)+ const [status, setStatus] = useState<ComfyStatus | null>(null)+ const [startupLogs, setStartupLogs] = useState<string[]>([])const pollRef = useRef<ReturnType<typeof setInterval> | null>(null)- const tryConnect = useCallback(async () => {- const ok = await checkConnection()- if (ok) fetchModels()- return ok+ // Poll ComfyUI status with logs+ const pollStatus = useCallback(async () => {+ try {+ const res = await fetch('/local-api/comfyui-status')+ const data: ComfyStatus = await res.json()+ setStatus(data)+ if (data.logs.length > 0) setStartupLogs(data.logs)++ if (data.running) {+ const wasConnected = await checkConnection()+ if (wasConnected) fetchModels()+ return true+ }+ } catch { /* ignore */ }+ return false}, [checkConnection, fetchModels])+ // Initial check + auto-poll until connecteduseEffect(() => {- tryConnect()- }, [tryConnect])+ let stopped = false++ const init = async () => {+ const ready = await pollStatus()+ if (ready || stopped) return++ // Keep polling every 3s while ComfyUI is starting+ pollRef.current = setInterval(async () => {+ if (stopped) return+ const ready = await pollStatus()+ if (ready && pollRef.current) {+ clearInterval(pollRef.current)+ pollRef.current = null+ }+ }, 3000)+ }+ init()- useEffect(() => {return () => {+ stopped = trueif (pollRef.current) clearInterval(pollRef.current)}- }, [])-- const startComfyUI = async () => {- setStarting(true)- try {- await fetch('/local-api/start-comfyui')- } catch { /* ignore */ }-- let attempts = 0- pollRef.current = setInterval(async () => {- attempts++- const ok = await checkConnection()- if (ok) {- if (pollRef.current) clearInterval(pollRef.current)- setStarting(false)- fetchModels()- }- if (attempts > 30) {- if (pollRef.current) clearInterval(pollRef.current)- setStarting(false)- }- }, 3000)+ }, [pollStatus])++ const retryConnect = async () => {+ try { await fetch('/local-api/start-comfyui') } catch { /* ignore */ }+ // Start polling again+ if (!pollRef.current) {+ pollRef.current = setInterval(async () => {+ const ready = await pollStatus()+ if (ready && pollRef.current) {+ clearInterval(pollRef.current)+ pollRef.current = null+ }+ }, 3000)+ }}+ const isStarting = status?.starting || (status && !status.running && status.found)+ const notFound = status && !status.found && !status.running+return (<div className="h-full flex flex-col">- {/* Connection status */}- {connected === false && !starting && (+ {/* Status: ComfyUI not found */}+ {notFound && (<div className="flex items-center justify-between px-4 py-3 bg-red-50 dark:bg-red-500/10 border-b border-red-200 dark:border-red-500/20"><div className="flex items-center gap-2 text-red-600 dark:text-red-400 text-sm"><WifiOff size={16} />- <span>ComfyUI is not running on port 8188.</span>+ <span>ComfyUI not found. Install it or set COMFYUI_PATH in .env to enable image/video generation.</span></div>- <button- onClick={startComfyUI}- className="flex items-center gap-1.5 px-4 py-1.5 rounded-lg bg-green-600 hover:bg-green-700 text-white text-sm font-medium transition-colors"- >- <Play size={14} /> Start ComfyUI- </button></div>)}- {starting && (- <div className="flex items-center gap-3 px-4 py-3 bg-yellow-50 dark:bg-yellow-500/10 border-b border-yellow-200 dark:border-yellow-500/20 text-yellow-700 dark:text-yellow-400 text-sm">- <Loader2 size={16} className="animate-spin" />- <span>Starting ComfyUI... This may take up to 30 seconds.</span>+ {/* Status: ComfyUI is starting */}+ {isStarting && !connected && (+ <div className="border-b border-yellow-200 dark:border-yellow-500/20">+ <div className="flex items-center gap-3 px-4 py-3 bg-yellow-50 dark:bg-yellow-500/10 text-yellow-700 dark:text-yellow-400 text-sm">+ <Loader2 size={16} className="animate-spin shrink-0" />+ <span>ComfyUI is loading... This can take a minute on first start.</span>+ </div>+ {startupLogs.length > 0 && (+ <div className="px-4 py-2 bg-gray-900 text-gray-400 text-xs font-mono max-h-24 overflow-y-auto">+ {startupLogs.slice(-8).map((log, i) => (+ <div key={i} className="truncate">{log.trim()}</div>+ ))}+ </div>+ )}</div>)}+ {/* Status: Not running but was found — offer retry */}+ {status && !status.running && status.found && !isStarting && !connected && (+ <div className="flex items-center justify-between px-4 py-3 bg-orange-50 dark:bg-orange-500/10 border-b border-orange-200 dark:border-orange-500/20">+ <div className="flex items-center gap-2 text-orange-600 dark:text-orange-400 text-sm">+ <AlertTriangle size={16} />+ <span>ComfyUI found but not responding. It may still be loading.</span>+ </div>+ <button+ onClick={retryConnect}+ className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-orange-600 hover:bg-orange-700 text-white text-xs font-medium transition-colors"+ >+ <RefreshCw size={12} /> Retry+ </button>+ </div>+ )}++ {/* Status: Connected */}{connected === true && (<div className="flex items-center gap-2 px-4 py-2 bg-green-50 dark:bg-green-500/10 border-b border-green-200 dark:border-green-500/20 text-green-600 dark:text-green-400 text-sm"><CheckCircle size={16} />- <span>ComfyUI connected — {checkpoints.length} model{checkpoints.length !== 1 ? 's' : ''} found</span>+ <span>ComfyUI connected — {checkpoints.length} image model{checkpoints.length !== 1 ? 's' : ''}, {videoModels.length} video model{videoModels.length !== 1 ? 's' : ''}</span></div>)}<div className="flex-1 flex overflow-hidden">{/* Main content */}<div className="flex-1 flex flex-col overflow-hidden p-4 gap-4">- {/* Top section: Mode switcher + Prompt (~25%) */}+ {/* Mode switcher + Prompt */}<div className="space-y-3"><div className="flex gap-1 p-1 bg-gray-100 dark:bg-white/5 rounded-lg w-fit"><button@@ -122,9 +174,16 @@ export function CreateView() {)}<PromptInput onGenerate={generate} onCancel={cancel} />++ {error && (+ <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-red-50 dark:bg-red-500/10 border border-red-200 dark:border-red-500/20 text-red-600 dark:text-red-400 text-xs">+ <AlertTriangle size={14} className="shrink-0" />+ <span>{error}</span>+ </div>+ )}</div>- {/* Output area (~75%) — centered in a distinct card */}+ {/* Output area */}<div className="flex-1 min-h-0 rounded-xl border border-gray-200 dark:border-white/10 bg-gray-50 dark:bg-[#1a1a1a] overflow-hidden flex flex-col"><OutputDisplay /><Gallery />diff --git a/src/hooks/useCreate.ts b/src/hooks/useCreate.tsindex 126ab6f9..a5ffc733 100644--- a/src/hooks/useCreate.ts+++ b/src/hooks/useCreate.ts@@ -22,6 +22,7 @@ export function useCreate() {const [videoModels, setVideoModels] = useState<string[]>([])const [samplerList, setSamplerList] = useState<string[]>([])const [videoBackend, setVideoBackend] = useState<VideoBackend>('none')+ const [error, setError] = useState<string | null>(null)const pollRef = useRef<ReturnType<typeof setInterval> | null>(null)const checkConnection = useCallback(async () => {@@ -54,7 +55,23 @@ export function useCreate() {setIsGenerating, setProgress, setCurrentPromptId, addToGallery,} = useCreateStore.getState()- if (!prompt.trim() || !model) return+ setError(null)++ if (!prompt.trim()) {+ setError('Please enter a prompt.')+ return+ }+ if (!model) {+ setError('No model selected. Make sure ComfyUI has models installed.')+ return+ }++ // Check ComfyUI is actually running+ const isRunning = await checkComfyConnection()+ if (!isRunning) {+ setError('ComfyUI is not running. Wait for it to start or check the connection.')+ return+ }setIsGenerating(true)setProgress(0)@@ -64,19 +81,26 @@ export function useCreate() {? buildTxt2VidWorkflow({ prompt, negativePrompt, model, sampler, steps, cfgScale, width, height, seed, frames, fps }, videoBackend): buildTxt2ImgWorkflow({ prompt, negativePrompt, model, sampler, steps, cfgScale, width, height, seed })- const promptId = await submitWorkflow(workflow)+ let promptId: string+ try {+ promptId = await submitWorkflow(workflow)+ } catch (err) {+ setError(`Failed to submit to ComfyUI: ${err instanceof Error ? err.message : String(err)}`)+ setIsGenerating(false)+ return+ }setCurrentPromptId(promptId)// Poll for completionawait new Promise<void>((resolve, reject) => {let attempts = 0- const maxAttempts = 1200 // 20 minutes for video (can be slow)+ const maxAttempts = 1200pollRef.current = setInterval(async () => {attempts++if (attempts > maxAttempts) {clearInterval(pollRef.current!)- reject(new Error('Generation timed out'))+ reject(new Error('Generation timed out after 20 minutes'))return}@@ -91,8 +115,8 @@ export function useCreate() {clearInterval(pollRef.current!)setProgress(100)- // Extract outputs — check images, gifs, and videosconst outputs = history.outputs || {}+ let found = falsefor (const nodeId of Object.keys(outputs)) {const nodeOutput = outputs[nodeId]const files: ComfyUIOutput[] = [@@ -101,6 +125,7 @@ export function useCreate() {...(nodeOutput.videos || []),]for (const file of files) {+ found = trueconst galleryItem: GalleryItem = {id: uuid(),type: mode,@@ -119,10 +144,14 @@ export function useCreate() {addToGallery(galleryItem)}}+ if (!found) {+ setError('Generation completed but no output was produced. Check ComfyUI logs.')+ }resolve()} else if (history.status?.status_str === 'error') {clearInterval(pollRef.current!)- reject(new Error('Generation failed'))+ const errMsg = history.status?.messages?.[0]?.[1]?.message || 'Unknown error in ComfyUI'+ reject(new Error(errMsg))}} catch {// Keep polling on network errors@@ -130,6 +159,8 @@ export function useCreate() {}, 1000)})} catch (err) {+ const msg = err instanceof Error ? err.message : String(err)+ setError(`Generation failed: ${msg}`)console.error('Generation error:', err)} finally {setIsGenerating(false)@@ -146,6 +177,7 @@ export function useCreate() {store.setIsGenerating(false)store.setProgress(0)store.setCurrentPromptId(null)+ setError(null)}, [store])return {@@ -154,6 +186,7 @@ export function useCreate() {videoModels,samplerList,videoBackend,+ error,checkConnection,fetchModels,generate,diff --git a/start.bat b/start.batindex 933d13de..075e8283 100644--- a/start.bat+++ b/start.bat@@ -6,25 +6,11 @@ if %errorlevel% neq 0 (start "" /b ollama serve >nul 2>nul)-:: Check for .env and start ComfyUI silently if configured-set COMFYUI_PATH=-if exist "%~dp0.env" (- for /f "tokens=1,* delims==" %%a in (%~dp0.env) do (- if "%%a"=="COMFYUI_PATH" set COMFYUI_PATH=%%b- )-)-if defined COMFYUI_PATH (- if exist "%COMFYUI_PATH%\main.py" (- start "" /min cmd /c "cd /d %COMFYUI_PATH% && python main.py --listen 127.0.0.1 --port 8188 >nul 2>nul"- )-)--:: Start dev server in background+:: Start dev server (ComfyUI auto-starts via Vite plugin)start "" /b cmd /c "cd /d "%~dp0" && npm run dev >nul 2>nul"-:: Wait for server to be ready, then open browser+:: Wait for server, then open browsertimeout /t 3 /nobreak >nulstart "" http://localhost:5173-:: Close this terminalexitdiff --git a/vite.config.ts b/vite.config.tsindex ca6171c8..8437dddb 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -1,37 +1,128 @@import { defineConfig, type Plugin } from 'vite'import react from '@vitejs/plugin-react'import tailwindcss from '@tailwindcss/vite'-import { spawn } from 'child_process'-import { existsSync } from 'fs'-import { resolve } from 'path'+import { spawn, execSync, type ChildProcess } from 'child_process'+import { existsSync, readdirSync } from 'fs'+import { resolve, join } from 'path'+import { config } from 'dotenv'++// Load .env file+config()function findComfyUI(): string | null {- // Check environment variable first- if (process.env.COMFYUI_PATH && existsSync(process.env.COMFYUI_PATH)) {+ // 1. Check .env / environment variable+ if (process.env.COMFYUI_PATH && existsSync(resolve(process.env.COMFYUI_PATH, 'main.py'))) {return process.env.COMFYUI_PATH}- // Check common locationsconst home = process.env.USERPROFILE || process.env.HOME || ''- const candidates = [+ // 2. Check common locations+ const fixed = [resolve(home, 'ComfyUI'),resolve(home, 'Desktop/ComfyUI'),resolve(home, 'Documents/ComfyUI'),'C:\\ComfyUI',]- for (const p of candidates) {+ for (const p of fixed) {if (existsSync(resolve(p, 'main.py'))) return p}+ // 3. Deep scan Desktop and Documents (one level of subdirectories)+ const scanDirs = [resolve(home, 'Desktop'), resolve(home, 'Documents')]+ for (const dir of scanDirs) {+ try {+ const entries = readdirSync(dir, { withFileTypes: true })+ for (const entry of entries) {+ if (entry.isDirectory()) {+ const candidate = join(dir, entry.name, 'ComfyUI')+ if (existsSync(resolve(candidate, 'main.py'))) return candidate+ // Also check if the folder itself IS ComfyUI+ if (existsSync(resolve(dir, entry.name, 'main.py'))) return join(dir, entry.name)+ }+ }+ } catch { /* skip unreadable dirs */ }+ }return null}+function isComfyRunning(): Promise<boolean> {+ return fetch('http://localhost:8188/system_stats')+ .then(r => r.ok)+ .catch(() => false)+}+function comfyLauncher(): Plugin {- let comfyProcess: ReturnType<typeof spawn> | null = null+ let comfyProcess: ChildProcess | null = null+ let comfyLogs: string[] = []++ const startComfy = (comfyPath: string): { status: string; path: string } => {+ if (comfyProcess && !comfyProcess.killed) {+ return { status: 'already_running', path: comfyPath }+ }++ comfyLogs = []+ comfyProcess = spawn('python', ['main.py', '--listen', '127.0.0.1', '--port', '8188'], {+ cwd: comfyPath,+ stdio: ['ignore', 'pipe', 'pipe'],+ })++ comfyProcess.stdout?.on('data', (d) => {+ const line = d.toString()+ comfyLogs.push(line)+ if (comfyLogs.length > 200) comfyLogs.shift()+ })+ comfyProcess.stderr?.on('data', (d) => {+ const line = d.toString()+ comfyLogs.push(line)+ if (comfyLogs.length > 200) comfyLogs.shift()+ })+ comfyProcess.on('exit', () => { comfyProcess = null })++ console.log(`[ComfyUI] Starting from: ${comfyPath}`)+ return { status: 'started', path: comfyPath }+ }++ const stopComfy = () => {+ if (comfyProcess && !comfyProcess.killed) {+ // Kill process tree on Windows+ try {+ if (process.platform === 'win32' && comfyProcess.pid) {+ execSync(`taskkill /pid ${comfyProcess.pid} /T /F`, { stdio: 'ignore' })+ } else {+ comfyProcess.kill('SIGTERM')+ }+ } catch { /* already dead */ }+ comfyProcess = null+ console.log('[ComfyUI] Stopped')+ }+ }return {name: 'comfy-launcher',configureServer(server) {- server.middlewares.use('/local-api/start-comfyui', (_req, res) => {- if (comfyProcess && !comfyProcess.killed) {+ // Auto-start ComfyUI when dev server starts+ isComfyRunning().then(running => {+ if (!running) {+ const comfyPath = findComfyUI()+ if (comfyPath) {+ console.log(`[ComfyUI] Auto-starting from: ${comfyPath}`)+ startComfy(comfyPath)+ } else {+ console.log('[ComfyUI] Not found. Set COMFYUI_PATH in .env or install ComfyUI.')+ }+ } else {+ console.log('[ComfyUI] Already running on port 8188')+ }+ })++ // Auto-stop ComfyUI when dev server closes+ server.httpServer?.on('close', stopComfy)+ process.on('exit', stopComfy)+ process.on('SIGINT', () => { stopComfy(); process.exit() })+ process.on('SIGTERM', () => { stopComfy(); process.exit() })++ // API: Manual start+ server.middlewares.use('/local-api/start-comfyui', async (_req, res) => {+ const alreadyRunning = await isComfyRunning()+ if (alreadyRunning) {res.writeHead(200, { 'Content-Type': 'application/json' })res.end(JSON.stringify({ status: 'already_running' }))return@@ -45,30 +136,34 @@ function comfyLauncher(): Plugin {}try {- comfyProcess = spawn('python', ['main.py', '--listen', '127.0.0.1', '--port', '8188'], {- detached: true,- stdio: 'ignore',- cwd: comfyPath,- })- comfyProcess.unref()-+ const result = startComfy(comfyPath)res.writeHead(200, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ status: 'started', path: comfyPath }))+ res.end(JSON.stringify(result))} catch (err) {res.writeHead(500, { 'Content-Type': 'application/json' })res.end(JSON.stringify({ status: 'error', message: String(err) }))}})+ // API: Stop+ server.middlewares.use('/local-api/stop-comfyui', (_req, res) => {+ stopComfy()+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({ status: 'stopped' }))+ })++ // API: Status + logsserver.middlewares.use('/local-api/comfyui-status', async (_req, res) => {- try {- const check = await fetch('http://localhost:8188/system_stats')- res.writeHead(200, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ running: check.ok }))- } catch {- res.writeHead(200, { 'Content-Type': 'application/json' })- res.end(JSON.stringify({ running: false }))- }+ const running = await isComfyRunning()+ const comfyPath = findComfyUI()+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.end(JSON.stringify({+ running,+ starting: comfyProcess !== null && !running,+ found: comfyPath !== null,+ path: comfyPath,+ logs: comfyLogs.slice(-20),+ }))})},}