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(create): the install is visible to ComfyUI, and it never eats a render
Davidb8531b61f62b
diff --git a/src/components/create/experimental/CreateContext.tsx b/src/components/create/experimental/CreateContext.tsxindex ea66b491..9490dd80 100644--- a/src/components/create/experimental/CreateContext.tsx+++ b/src/components/create/experimental/CreateContext.tsx@@ -3,7 +3,7 @@ import { useCreate } from '../../../hooks/useCreate'import { useCloudCreate, hasActiveCloudRun } from '../../../hooks/useCloudCreate'import { useCloudSession } from '../../../hooks/useCloudSession'import { useCreateStore, type GalleryItem } from '../../../stores/createStore'-import { getLoraModels, getVAEModels, getCheckpoints, getDiffusionModels, getCLIPModels, checkComfyConnection, refreshComfyModels } from '../../../api/comfyui'+import { getLoraModels, getVAEModels, getCheckpoints, getDiffusionModels, getCLIPModels, getGgufUnetModels, checkComfyConnection, refreshComfyModels } from '../../../api/comfyui'import { getAllNodeInfo, clearNodeCache } from '../../../api/comfyui-nodes'import { installCustomNodes, getImageBundles, getVideoBundles, getAudioBundles, getLipsyncBundles, getMotionBundles, startModelDownload, getDownloadProgress, normalizeModelBase, ENUM_SUBFOLDERS } from '../../../api/discover'import { backendCall, isMacOS } from '../../../api/backend'@@ -20,6 +20,15 @@ import type { CloudQuota } from '../../../lib/render/cloud-jobs'* process keeps the port and keeps serving the stale node list — the pack* would look installed but never show up, and the register-poll would burn* 40s to end in a misleading error. Detect that case and state the real fix. */+/** Hold until nothing is rendering, so a heal never lands on a live job.+ * Bounded: a render that never reports finished must not park an install+ * forever, and the caller falls back to the plain-language error either way. */+async function waitForIdleRender(signal?: AbortSignal, attempts = 120): Promise<void> {+ for (let i = 0; i < attempts && useCreateStore.getState().isGenerating; i++) {+ await waitOrAbort(5000, signal)+ }+}+async function restartComfyForNewNodes(): Promise<void> {try { await backendCall('stop_comfyui') } catch { /* may already be stopped */ }// stop_comfyui reaps its child before returning, so LU's own engine is down@@ -387,7 +396,17 @@ export function CreateExpProvider({ children }: { children: ReactNode }) {const wanted = enumFiles.map((f) => f.filename!)const stillMissing = async (): Promise<string[]> => {try {- const lists = await Promise.all([getCheckpoints(), getDiffusionModels(), getVAEModels(), getCLIPModels()])+ // getGgufUnetModels belongs here for the same reason getImageModels+ // needs it (comfyui.ts:658): UNETLoader only enumerates .safetensors+ // and .sft, GGUF quants are listed by ComfyUI-GGUF's own loader. The+ // default Talking Character bundle IS a .gguf in diffusion_models, so+ // without this the probe can never succeed: 20 rounds of waiting, an+ // uncalled-for engine restart in the middle of whatever the user was+ // rendering, and then an error blaming the model folder for a file+ // ComfyUI lists perfectly well.+ const lists = await Promise.all([+ getCheckpoints(), getDiffusionModels(), getVAEModels(), getCLIPModels(), getGgufUnetModels(),+ ])const visible = new Set(lists.flat().map(normalizeModelBase))return wanted.filter((n) => !visible.has(normalizeModelBase(n)))} catch {@@ -400,6 +419,15 @@ export function CreateExpProvider({ children }: { children: ReactNode }) {if (missing.length > 0) {// Heal before complaining: a restart rebuilds the model index for// certain, and it is the same move that registers a new node pack.+ //+ // Never while a render is in flight. An install runs on for minutes+ // after Stage swapped its card away, so without this guard a bundle+ // that finished downloading could stop the engine in the middle of+ // somebody's video and leave nothing behind but a dead job.+ if (useCreateStore.getState().isGenerating) {+ onProgress?.('Waiting for the current render to finish before restarting ComfyUI…')+ await waitForIdleRender(signal)+ }onProgress?.('Restarting ComfyUI so it picks up the new files…')await restartComfyForNewNodes().catch(() => { /* diagnosed below */ })missing = await waitForModelsVisible({diff --git a/src/components/create/experimental/Stage.tsx b/src/components/create/experimental/Stage.tsxindex 9a1de73e..ff3bf01a 100644--- a/src/components/create/experimental/Stage.tsx+++ b/src/components/create/experimental/Stage.tsx@@ -1,4 +1,4 @@-import { useRef, useState } from 'react'+import { useRef, useState, useSyncExternalStore } from 'react'import { motion, AnimatePresence } from 'framer-motion'import { UploadCloud, ImagePlus, Scissors, Wand2, Sparkles, X, Loader2, Download, AlertTriangle, Image as ImageIcon, Film } from 'lucide-react'import { useCreateStore, type GalleryItem } from '../../../stores/createStore'@@ -9,6 +9,9 @@ import { EmptyState } from '../ui/EmptyState'import { Button } from '../ui/Button'import { cn } from '../ui/cn'import { loadImageRef } from './loadImage'+import {+ subscribeInstallRuns, getInstallRun, startInstallRun, cancelInstallRun, clearInstallRun,+} from '../../../lib/model-install-runs'import { galleryItemUrl, fetchGalleryItemBlob, recoverGalleryUrl } from './galleryUrl'import { InstallCancelled } from '../../../lib/bundle-install'import { isMlxImageHost } from '../../../api/mlx-image'@@ -512,29 +515,20 @@ const BUNDLE_COPY = {function ModelInstallCard({ kind }: { kind: 'image' | 'video' | 'audio' | 'lipsync' | 'motion' }) {const { installModelBundle } = useCreateExp()- const [installing, setInstalling] = useState(false)- const [status, setStatus] = useState('')- const [err, setErr] = useState<string | null>(null)- const abortRef = useRef<AbortController | null>(null)+ // The run outlives this card on purpose. Stage swaps the card away as soon as+ // a render starts or the lane list refills, and a 12 GB install must not lose+ // its status line, its Cancel button and its error message to that.+ const runState = useSyncExternalStore(subscribeInstallRuns, () => getInstallRun(kind))+ const { status, err, running: installing } = runStateconst mac = isMlxImageHost()const copy = (mac && (kind === 'image' || kind === 'video')) ? MAC_BUNDLE_COPY[kind] : BUNDLE_COPY[kind]- const run = async () => {- const ac = new AbortController()- abortRef.current = ac- setInstalling(true); setErr(null); setStatus('Starting…')- try {- // On success the model lists refill and Stage swaps this card away.- await installModelBundle(kind, setStatus, ac.signal)- } catch (e) {- setErr(e instanceof InstallCancelled- ? 'Cancelled. Files that finished are kept, the one in flight was dropped.'- : e instanceof Error ? e.message : String(e))- } finally {- setInstalling(false)- abortRef.current = null- }- }+ const run = () => startInstallRun(kind, (onStatus, signal) =>+ installModelBundle(kind, onStatus, signal).catch((e: unknown) => {+ throw e instanceof InstallCancelled+ ? new Error('Cancelled. Files that finished are kept, the one in flight was dropped.')+ : e+ }))return (<EmptyState@@ -545,8 +539,8 @@ function ModelInstallCard({ kind }: { kind: 'image' | 'video' | 'audio' | 'lipsy><InstallCardBodyrun={run} installing={installing} status={status} err={err}- onDismiss={() => setErr(null)}- onCancel={() => abortRef.current?.abort()}+ onDismiss={() => clearInstallRun(kind)}+ onCancel={() => cancelInstallRun(kind)}cancelTitle={mac ? 'Stops showing progress here. The download itself keeps running — pick it up in Settings → AI Backends → Local Media.' : undefined}/></EmptyState>diff --git a/src/lib/__tests__/model-install-runs.test.ts b/src/lib/__tests__/model-install-runs.test.tsnew file mode 100644index 00000000..e1046fba--- /dev/null+++ b/src/lib/__tests__/model-install-runs.test.ts@@ -0,0 +1,135 @@+/**+ * A bundle install must not lose its owner.+ *+ * Found by the review of the C8 fix (2026-08-14). Stage picks the install card+ * only while the lane list is empty and nothing is rendering, so the card+ * unmounts the moment either changes. The run kept going with no status line,+ * no Cancel button and no place for its error, and the user read the vanished+ * card as "setup finished".+ *+ * Two properties matter and both are pinned here: the run survives the card,+ * and one lane can never have two installs writing the same file.+ *+ * Run: npx vitest run src/lib/__tests__/model-install-runs.test.ts+ */+import { describe, it, expect, beforeEach, vi } from 'vitest'+import {+ startInstallRun, getInstallRun, isInstalling, cancelInstallRun, clearInstallRun,+ subscribeInstallRuns, resetInstallRuns,+} from '../model-install-runs'++const flush = () => new Promise((r) => setTimeout(r, 0))++function deferred() {+ let resolve!: () => void+ let reject!: (e: unknown) => void+ const promise = new Promise<void>((res, rej) => { resolve = res; reject = rej })+ return { promise, resolve, reject }+}++beforeEach(() => resetInstallRuns())++describe('the run belongs to the lane, not to the card', () => {+ it('status keeps arriving after the card that started it is gone', async () => {+ const d = deferred()+ let publish!: (s: string) => void+ startInstallRun('lipsync', (onStatus) => { publish = onStatus; return d.promise })++ publish('Downloading 1 of 3…')+ expect(getInstallRun('lipsync').status).toBe('Downloading 1 of 3…')++ // The card unmounts here. Nothing about the run changes.+ publish('Waiting for ComfyUI to list the new files… 12s')+ expect(getInstallRun('lipsync').status).toBe('Waiting for ComfyUI to list the new files… 12s')+ expect(isInstalling('lipsync')).toBe(true)++ d.resolve()+ await flush()+ expect(isInstalling('lipsync')).toBe(false)+ })++ it('an error survives the swap and is there when the card comes back', async () => {+ const d = deferred()+ startInstallRun('lipsync', () => d.promise)+ d.reject(new Error('ComfyUI still does not list Wan2.2-S2V-14B-Q4_K_M.gguf'))+ await flush()++ const run = getInstallRun('lipsync')+ expect(run.running).toBe(false)+ expect(run.err).toContain('still does not list')+ })++ it('dismissing the error puts the lane back to offering the install', async () => {+ const d = deferred()+ startInstallRun('video', () => d.promise)+ d.reject(new Error('boom'))+ await flush()+ clearInstallRun('video')+ expect(getInstallRun('video')).toEqual({ status: '', err: null, running: false })+ })+})++describe('one lane, one install', () => {+ it('a second start while one is running is ignored, not queued', async () => {+ const first = deferred()+ const second = vi.fn()+ startInstallRun('image', () => first.promise)+ startInstallRun('image', () => { second(); return Promise.resolve() })+ expect(second).not.toHaveBeenCalled()+ first.resolve()+ await flush()+ })++ it('after it finishes, the lane can be installed again', async () => {+ const first = deferred()+ startInstallRun('image', () => first.promise)+ first.resolve()+ await flush()++ const again = vi.fn(() => Promise.resolve())+ startInstallRun('image', again)+ expect(again).toHaveBeenCalledTimes(1)+ })++ it('a dismissed error does not block the retry either', async () => {+ const d = deferred()+ startInstallRun('audio', () => d.promise)+ d.reject(new Error('nope'))+ await flush()+ clearInstallRun('audio')++ const again = vi.fn(() => Promise.resolve())+ startInstallRun('audio', again)+ expect(again).toHaveBeenCalledTimes(1)+ })+})++describe('cancel and subscription', () => {+ it('cancel aborts the signal the runner was handed', () => {+ let seen: AbortSignal | undefined+ startInstallRun('motion', (_s, signal) => { seen = signal; return new Promise<void>(() => {}) })+ expect(seen?.aborted).toBe(false)+ cancelInstallRun('motion')+ expect(seen?.aborted).toBe(true)+ })++ it('subscribers hear every change, that is what re-renders the card', () => {+ const seen = vi.fn()+ const off = subscribeInstallRuns(seen)+ let publish!: (s: string) => void+ startInstallRun('video', (onStatus) => { publish = onStatus; return new Promise<void>(() => {}) })+ publish('one')+ publish('two')+ expect(seen.mock.calls.length).toBeGreaterThanOrEqual(3)+ off()+ publish('three')+ const after = seen.mock.calls.length+ publish('four')+ expect(seen.mock.calls.length).toBe(after)+ })++ it('an untouched lane reads as idle, never undefined', () => {+ expect(getInstallRun('lipsync')).toEqual({ status: '', err: null, running: false })+ expect(isInstalling('lipsync')).toBe(false)+ })+})diff --git a/src/lib/__tests__/model-visible-wait.test.ts b/src/lib/__tests__/model-visible-wait.test.tsindex d8ff0de9..aa2d75e3 100644--- a/src/lib/__tests__/model-visible-wait.test.ts+++ b/src/lib/__tests__/model-visible-wait.test.ts@@ -123,4 +123,50 @@ describe('the install path uses it, and says something honest when it runs out',expect(src).toContain('started ')expect(src).toContain('outside LU')})++ it('the probe asks the GGUF loader too, or the default lipsync bundle can never pass', () => {+ // UNETLoader only enumerates .safetensors and .sft (comfyui.ts:659), and+ // getLipsyncBundles()[0] ships Wan2.2-S2V-14B-Q4_K_M.gguf into+ // diffusion_models, which IS in ENUM_SUBFOLDERS. Without the GGUF loader+ // the probe fails for a file ComfyUI lists perfectly well: 20 rounds of+ // waiting, an uncalled-for engine restart, then a wrong diagnosis.+ const probe = src.slice(src.indexOf('const stillMissing'), src.indexOf('let missing'))+ expect(probe).toContain('getGgufUnetModels()')+ expect(src).toMatch(/import \{[^}]*getGgufUnetModels[^}]*\} from '\.\.\/\.\.\/\.\.\/api\/comfyui'/)+ })++ it('the heal waits for a live render instead of killing it', () => {+ // An install runs on for minutes after Stage swapped its card away, so+ // without this the bundle could stop the engine in the middle of somebody+ // else's video and leave a dead job and no explanation behind.+ // Anchored on the call site, not on the helper: a guard that exists but is+ // never called is exactly the bug this pins.+ const call = src.indexOf('await waitForIdleRender(signal)')+ const restart = src.indexOf('Restarting ComfyUI so it picks up the new files')+ expect(call).toBeGreaterThan(-1)+ expect(call).toBeLessThan(restart)+ expect(src).toContain('Waiting for the current render to finish before restarting ComfyUI')+ })++ it('waiting for the render to finish is bounded, an install must not park forever', () => {+ expect(src).toMatch(/async function waitForIdleRender\(signal\?: AbortSignal, attempts = \d+\)/)+ })+})++describe('the card is no longer the owner of the run', () => {+ const stage = readFileSync(+ resolve(dirname(fileURLToPath(import.meta.url)), '../../components/create/experimental/Stage.tsx'),+ 'utf8',+ )++ it('ModelInstallCard reads the run from the lane registry, not from its own state', () => {+ const card = stage.slice(stage.indexOf('function ModelInstallCard'), stage.indexOf('function TrainSetBoard'))+ expect(card).toContain('useSyncExternalStore(subscribeInstallRuns')+ expect(card).toContain('startInstallRun(kind')+ expect(card).toContain('cancelInstallRun(kind)')+ // The old shape: local useState plus an abortRef that nothing ever cleaned+ // up on unmount. Both are gone, and with them the headless run.+ expect(card).not.toContain('abortRef')+ expect(card).not.toContain('setInstalling(')+ })})diff --git a/src/lib/model-install-runs.ts b/src/lib/model-install-runs.tsnew file mode 100644index 00000000..ee4c53dd--- /dev/null+++ b/src/lib/model-install-runs.ts@@ -0,0 +1,98 @@+/**+ * Who owns a running bundle install.+ *+ * The install card used to own it, and only it. Stage swaps that card away the+ * moment a render starts or the lane's model list refills, and React unmounts+ * it, so a 12 GB install lost its status line, its Cancel button and its error+ * message while it was still running. The user saw the card vanish, read that+ * as "done", and any later failure landed in a setState on a dead component.+ *+ * The run lives here instead. A card that mounts for a lane picks up the run+ * that is already going rather than starting a second one, and the status and+ * the error survive every swap Stage makes.+ */++export interface InstallRun {+ status: string+ err: string | null+ running: boolean+}++type Runner = (onStatus: (s: string) => void, signal: AbortSignal) => Promise<void>++const runs = new Map<string, InstallRun & { ac: AbortController }>()+const listeners = new Set<() => void>()++const IDLE: InstallRun = { status: '', err: null, running: false }++function emit(): void {+ for (const l of listeners) l()+}++export function subscribeInstallRuns(cb: () => void): () => void {+ listeners.add(cb)+ return () => { listeners.delete(cb) }+}++/** Snapshot for one lane. Stable identity while nothing changes, so+ * useSyncExternalStore does not loop. */+export function getInstallRun(kind: string): InstallRun {+ return runs.get(kind) ?? IDLE+}++/** True while this lane has a run nobody has read the outcome of yet. */+export function isInstalling(kind: string): boolean {+ return runs.get(kind)?.running === true+}++/**+ * Start an install for a lane, or do nothing if one is already going. Pressing+ * the button twice, or a remounted card auto-resuming, must never mean two+ * downloads writing the same file.+ */+export function startInstallRun(kind: string, run: Runner): void {+ if (runs.get(kind)?.running) return+ const ac = new AbortController()+ const entry = { status: 'Starting…', err: null as string | null, running: true, ac }+ runs.set(kind, entry)+ emit()++ const onStatus = (s: string) => {+ const live = runs.get(kind)+ if (!live || live.ac !== ac) return+ runs.set(kind, { ...live, status: s })+ emit()+ }++ void run(onStatus, ac.signal)+ .then(() => {+ const live = runs.get(kind)+ if (!live || live.ac !== ac) return+ runs.delete(kind)+ emit()+ })+ .catch((e: unknown) => {+ const live = runs.get(kind)+ if (!live || live.ac !== ac) return+ runs.set(kind, { ...live, running: false, err: e instanceof Error ? e.message : String(e) })+ emit()+ })+}++export function cancelInstallRun(kind: string): void {+ runs.get(kind)?.ac.abort()+}++/** The user has read the error, so the lane goes back to offering the install. */+export function clearInstallRun(kind: string): void {+ if (runs.get(kind)?.running) return+ runs.delete(kind)+ emit()+}++/** Tests only. */+export function resetInstallRuns(): void {+ for (const r of runs.values()) r.ac.abort()+ runs.clear()+ listeners.clear()+}