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.

fix(create): show the download, and let people stop it

purple0baba7ed4105
diff --git a/src/components/create/experimental/CreateContext.tsx b/src/components/create/experimental/CreateContext.tsx
index 79746305..0f4bfc9f 100644
--- a/src/components/create/experimental/CreateContext.tsx
+++ b/src/components/create/experimental/CreateContext.tsx
@@ -7,6 +7,8 @@ import { getLoraModels, getVAEModels, checkComfyConnection, refreshComfyModels }
import { getAllNodeInfo, clearNodeCache } from '../../../api/comfyui-nodes'
import { installCustomNodes, getImageBundles, getVideoBundles, getAudioBundles, getLipsyncBundles, getMotionBundles, startModelDownload, getDownloadProgress } from '../../../api/discover'
import { backendCall } from '../../../api/backend'
+import { useDownloadStore } from '../../../stores/downloadStore'
+import { downloadBundleFiles, waitOrAbort } from '../../../lib/bundle-install'
import { ensureLocalFilename } from './loadImage'
import type { CloudQuota } from '../../../lib/render/cloud-jobs'
@@ -72,14 +74,14 @@ interface CreateExpValue {
* and throws on failure. 'rmbg' = the RMBG cutout node; 'inpaint-nodes' =
* ComfyUI's core inpaint nodes (nothing to clone — present on any current
* install once ComfyUI is up). */
- installCapability: (cap: 'rmbg' | 'inpaint-nodes' | 'dwpose', onProgress?: (msg: string) => void) => Promise<void>
+ installCapability: (cap: 'rmbg' | 'inpaint-nodes' | 'dwpose', onProgress?: (msg: string) => void, signal?: AbortSignal) => Promise<void>
/** One-click "everything you need" for a fresh PC: ensure ComfyUI runs
* (installing it first if needed), then download the default starter
* bundle for the intent kind (image → SDXL checkpoint, video → Wan 2.1,
* 2.5.8 lanes → ACE / S2V / VACE starters incl. their node packs)
* with streamed progress, refresh ComfyUI's model enums and re-fetch the
* model lists. Throws on failure. */
- installModelBundle: (kind: 'image' | 'video' | 'audio' | 'lipsync' | 'motion', onProgress?: (msg: string) => void) => Promise<void>
+ installModelBundle: (kind: 'image' | 'video' | 'audio' | 'lipsync' | 'motion', onProgress?: (msg: string) => void, signal?: AbortSignal) => Promise<void>
/** Runtime backend axis: hosted rendering offered for this session? */
cloudAvailable: boolean
quota: CloudQuota | null
@@ -181,20 +183,26 @@ export function CreateExpProvider({ children }: { children: ReactNode }) {
// start it if it's merely stopped, INSTALL it first if it's missing (the
// "complete noob PC" case: every Create tab's Download & install button must
// deliver a 100% functional run, not assume ComfyUI exists).
- const ensureComfyRunning = useCallback(async (onProgress?: (msg: string) => void) => {
+ // Every wait in here reports a ticking second count. A line that never
+ // changes for 40s reads as frozen, which is exactly what David hit on the
+ // Motion Control card: the only feedback was a spinner, so "is it doing
+ // anything" had no answer. A counter answers it without promising a duration
+ // we cannot know.
+ const ensureComfyRunning = useCallback(async (onProgress?: (msg: string) => void, signal?: AbortSignal) => {
if (await checkComfyConnection()) return
onProgress?.('Starting ComfyUI…')
try { await backendCall('start_comfyui') } catch { /* not installed yet — handled below */ }
for (let i = 0; i < 15; i++) {
- await new Promise((r) => setTimeout(r, 2000))
+ onProgress?.(`Starting ComfyUI… ${i * 2}s`)
+ await waitOrAbort(2000, signal)
if (await checkComfyConnection()) { checkConnection(); return }
}
- onProgress?.('ComfyUI is not installed. Downloading & installing it now (one-time, a few GB)…')
+ onProgress?.('ComfyUI is not installed. Downloading and installing it now, this is a one time step of a few GB…')
await backendCall('install_comfyui')
// Poll the same status contract the Settings installer uses. Generous cap:
// a slow connection legitimately needs a while for the one-time install.
for (let i = 0; i < 2700; i++) {
- await new Promise((r) => setTimeout(r, 2000))
+ await waitOrAbort(2000, signal)
const st = await backendCall<{ status?: string; logs?: string[] }>('install_comfyui_status').catch(() => null)
const lastLog = st?.logs?.length ? String(st.logs[st.logs.length - 1]) : ''
if (lastLog) onProgress?.(lastLog)
@@ -206,7 +214,8 @@ export function CreateExpProvider({ children }: { children: ReactNode }) {
onProgress?.('Starting ComfyUI…')
await backendCall('start_comfyui')
for (let i = 0; i < 30; i++) {
- await new Promise((r) => setTimeout(r, 2000))
+ onProgress?.(`Starting ComfyUI… ${i * 2}s`)
+ await waitOrAbort(2000, signal)
if (await checkComfyConnection()) { checkConnection(); return }
}
throw new Error('Installed ComfyUI but it did not come up. Check Settings → AI Backends.')
@@ -218,8 +227,8 @@ export function CreateExpProvider({ children }: { children: ReactNode }) {
// the node cache each round so we don't read the stale pre-install
// catalogue) until the node shows up. The BiRefNet / RMBG-2.0 cutout model
// is fetched by the node itself on the first run.
- const installCapability = useCallback(async (cap: 'rmbg' | 'inpaint-nodes' | 'dwpose', onProgress?: (msg: string) => void) => {
- await ensureComfyRunning(onProgress)
+ const installCapability = useCallback(async (cap: 'rmbg' | 'inpaint-nodes' | 'dwpose', onProgress?: (msg: string) => void, signal?: AbortSignal) => {
+ await ensureComfyRunning(onProgress, signal)
const capsFrom = (names: Set<string>) => ({
rmbg: names.has('RMBG'),
'inpaint-nodes': names.has('VAEEncodeForInpaint') || names.has('InpaintModelConditioning'),
@@ -248,9 +257,9 @@ export function CreateExpProvider({ children }: { children: ReactNode }) {
await installCustomNodes([pack])
onProgress?.('Restarting ComfyUI to register the node…')
await restartComfyForNewNodes()
- onProgress?.('Waiting for ComfyUI to come back…')
for (let i = 0; i < 20; i++) {
- await new Promise((r) => setTimeout(r, 2000))
+ onProgress?.(`Waiting for ComfyUI to come back… ${i * 2}s`)
+ await waitOrAbort(2000, signal)
try {
clearNodeCache()
const nodes = await getAllNodeInfo()
@@ -274,8 +283,8 @@ export function CreateExpProvider({ children }: { children: ReactNode }) {
// then refresh ComfyUI's model enums so the new files are pickable without
// a restart. Bundles that need a custom node pack (GGUF loader, pose
// extractor) install + register it first — one click really means one click.
- const installModelBundle = useCallback(async (kind: 'image' | 'video' | 'audio' | 'lipsync' | 'motion', onProgress?: (msg: string) => void) => {
- await ensureComfyRunning(onProgress)
+ const installModelBundle = useCallback(async (kind: 'image' | 'video' | 'audio' | 'lipsync' | 'motion', onProgress?: (msg: string) => void, signal?: AbortSignal) => {
+ await ensureComfyRunning(onProgress, signal)
const bundle = (
kind === 'image' ? getImageBundles()
: kind === 'video' ? getVideoBundles()
@@ -285,37 +294,46 @@ export function CreateExpProvider({ children }: { children: ReactNode }) {
)[0]
if (!bundle) throw new Error('No starter bundle available for this intent.')
if (bundle.customNodes?.length) {
- onProgress?.('Installing the required node packs…')
+ onProgress?.('Installing the required node packs. This can take a minute…')
await installCustomNodes(bundle.customNodes)
onProgress?.('Restarting ComfyUI to register the new nodes…')
await restartComfyForNewNodes()
for (let i = 0; i < 20; i++) {
- await new Promise((r) => setTimeout(r, 2000))
+ onProgress?.(`Waiting for ComfyUI to come back… ${i * 2}s`)
+ await waitOrAbort(2000, signal)
if (await checkComfyConnection()) break
}
clearNodeCache()
}
- for (const file of bundle.files) {
- if (!file.downloadUrl || !file.filename || !file.subfolder) continue
- const size = file.sizeGB ? ` (${file.sizeGB} GB)` : ''
- onProgress?.(`Downloading ${file.filename}${size}…`)
- const expected = file.sizeGB ? Math.round(file.sizeGB * 1_073_741_824) : undefined
- const start = await startModelDownload(file.downloadUrl, file.subfolder, file.filename, expected)
- if (start.status === 'error') throw new Error(start.error || `Could not start the ${file.filename} download.`)
- // 'exists' = already complete on disk — skip polling.
- if (start.status !== 'exists') {
- for (;;) {
- await new Promise((r) => setTimeout(r, 1500))
- const all = await getDownloadProgress()
- const p = Object.values(all).find((d) => d.filename === file.filename)
- if (!p || p.status === 'complete') break
- if (p.status === 'error') throw new Error(p.error || `Download failed: ${file.filename}`)
- if (p.total > 0) {
- onProgress?.(`Downloading ${file.filename}: ${Math.round((p.progress / p.total) * 100)}%`)
- }
- }
- }
- }
+ // Put the transfer in the header Downloads tray BEFORE the first byte.
+ // Until now this path talked to the Rust downloader directly and never
+ // touched the store, so the tray read "No active downloads" through a
+ // 10.5 GB download and its cancel + retry buttons were unreachable
+ // (David 2026-07-25). setBundleGroup collapses the files into one row,
+ // setMeta is what the tray's retry needs to restart a failed file.
+ const dl = useDownloadStore.getState()
+ const files = bundle.files.filter((f) => f.downloadUrl && f.filename && f.subfolder)
+ if (files.length > 1) dl.setBundleGroup(bundle.name, files.map((f) => f.filename!))
+ for (const f of files) dl.setMeta(f.filename!, f.downloadUrl!, f.subfolder!)
+ dl.startPolling()
+
+ await downloadBundleFiles(
+ files.map((f) => ({
+ filename: f.filename!, subfolder: f.subfolder!, downloadUrl: f.downloadUrl!, sizeGB: f.sizeGB,
+ })),
+ {
+ start: startModelDownload,
+ progress: getDownloadProgress,
+ onStatus: onProgress,
+ // The tray's poller auto stops after an idle window, so re-arm it per
+ // file instead of assuming the first call holds for the whole bundle.
+ keepTrayLive: () => useDownloadStore.getState().startPolling(),
+ // Cancel on the card must kill the Rust transfer too, or the download
+ // keeps running invisibly after the card says it stopped.
+ stop: (filename) => { void useDownloadStore.getState().cancel(filename) },
+ signal,
+ },
+ )
onProgress?.('Refreshing the model list…')
await refreshComfyModels().catch(() => false)
clearNodeCache()
diff --git a/src/components/create/experimental/SpecialIntentControls.tsx b/src/components/create/experimental/SpecialIntentControls.tsx
index 35f78a3a..f51c213b 100644
--- a/src/components/create/experimental/SpecialIntentControls.tsx
+++ b/src/components/create/experimental/SpecialIntentControls.tsx
@@ -19,6 +19,7 @@ import {
TRAINER_BASE_FILES, type TrainerStatus,
} from '../../../api/trainer'
import { startModelDownload, getDownloadProgress } from '../../../api/discover'
+import { useDownloadStore } from '../../../stores/downloadStore'
import { getLoraModels } from '../../../api/comfyui'
import { useCreateExp } from './CreateContext'
import { loadImageRef } from './loadImage'
@@ -320,10 +321,17 @@ function LocalTrainControls() {
(f.subfolder === 'diffusion_models' && !status.dit) ||
(f.subfolder === 'text_encoders' && !status.textEncoder) ||
(f.subfolder === 'vae' && !status.vae))
+ // Same tray registration the Create install cards do: without it the header
+ // Downloads tray reads "No active downloads" through a multi GB transfer and
+ // its cancel + retry buttons never appear.
+ const dl = useDownloadStore.getState()
+ if (missing.length > 1) dl.setBundleGroup('Character Studio base models', missing.map((f) => f.filename))
for (const f of missing) {
+ dl.setMeta(f.filename, f.url, f.subfolder)
try { await startModelDownload(f.url, f.subfolder, f.filename) } catch (e) {
setNote(e instanceof Error ? e.message : `Could not start ${f.filename}.`)
}
+ dl.startPolling()
}
}
diff --git a/src/components/create/experimental/Stage.tsx b/src/components/create/experimental/Stage.tsx
index 3942456a..19d5f6d1 100644
--- a/src/components/create/experimental/Stage.tsx
+++ b/src/components/create/experimental/Stage.tsx
@@ -10,6 +10,7 @@ import { Button } from '../ui/Button'
import { cn } from '../ui/cn'
import { loadImageRef } from './loadImage'
import { galleryItemUrl, fetchGalleryItemBlob, recoverGalleryUrl } from './galleryUrl'
+import { InstallCancelled } from '../../../lib/bundle-install'
interface Props {
displayed?: GalleryItem
@@ -322,15 +323,29 @@ function ChangeImageButton({ onChange }: { onChange: (r: Awaited<ReturnType<type
}
// ── Shared install-card chrome: spinner + streamed status + dismissible error ──
-function InstallCardBody({ run, installing, status, err, onDismiss }: {
- run: () => void; installing: boolean; status: string; err: string | null; onDismiss: () => void
+// The Cancel button is not optional chrome. David 2026-07-25 clicked Download &
+// install on Motion Control, got a spinner, and had no way to stop or even see
+// a 10.5 GB transfer. Cancel here aborts the install loop and kills the running
+// download in Rust; the partial file stays, so a later run resumes.
+function InstallCardBody({ run, installing, status, err, onDismiss, onCancel }: {
+ run: () => void; installing: boolean; status: string; err: string | null
+ onDismiss: () => void; onCancel: () => void
}) {
return (
<div className="flex flex-col items-center gap-2.5 pt-1">
{installing ? (
- <div className="t-control text-gray-400 flex items-center gap-2">
- <Loader2 size={14} className="animate-spin shrink-0" />
- <span>{status || 'Installing…'}</span>
+ <div className="flex flex-col items-center gap-1.5">
+ <div className="t-control text-gray-400 flex items-center gap-2">
+ <Loader2 size={14} className="animate-spin shrink-0" />
+ <span>{status || 'Installing…'}</span>
+ </div>
+ <button
+ onClick={onCancel}
+ title="Stops the setup. A download in flight is dropped, finished files stay."
+ className="t-control text-gray-500 hover:text-gray-300 underline underline-offset-2 transition-colors"
+ >
+ Cancel
+ </button>
</div>
) : (
<Button variant="primary" icon={Download} onClick={run}>Download &amp; install</Button>
@@ -369,28 +384,58 @@ const CAP_COPY = {
},
} as const
+/** While an install runs, the card must not keep saying "needs a one-time
+ * download" with a bare spinner under it, which is what made David ask whether
+ * anything was happening at all. Title and description both switch. */
+const BUSY_DESCRIPTION = {
+ capability: 'This installs a small node pack and restarts ComfyUI. Cancel any time.',
+ // Cancel really does throw the partial file away (cancel_download deletes the
+ // .download temp), so the copy says that rather than the friendlier thing.
+ // A connection that DROPS is the opposite case: that partial survives and the
+ // next try resumes from it, which is what the retry line promises.
+ bundle: 'Follow it in the Downloads tray up top. You can cancel any time, which stops the download and drops what it had so far.',
+} as const
+
function CapabilityCard({ cap }: { cap: 'rmbg' | 'inpaint-nodes' | 'dwpose' }) {
const { installCapability } = useCreateExp()
const [installing, setInstalling] = useState(false)
const [status, setStatus] = useState('')
const [err, setErr] = useState<string | null>(null)
+ const abortRef = useRef<AbortController | null>(null)
const copy = CAP_COPY[cap]
const run = async () => {
+ const ac = new AbortController()
+ abortRef.current = ac
setInstalling(true); setErr(null); setStatus('Starting…')
try {
// On success the capability flips true and Stage swaps this card for the input slot.
- await installCapability(cap, setStatus)
+ await installCapability(cap, setStatus, ac.signal)
} catch (e) {
- setErr(e instanceof Error ? e.message : String(e))
+ // A cancel is a decision, not a failure: say so plainly and add the one
+ // thing that is not obvious, that the node install itself finishes in the
+ // background because there is nothing to roll back.
+ setErr(e instanceof InstallCancelled
+ ? 'Cancelled. Any node install already running finishes on its own in the background.'
+ : e instanceof Error ? e.message : String(e))
} finally {
setInstalling(false)
+ abortRef.current = null
}
}
return (
- <EmptyState icon={copy.icon} tone="accent" title={copy.title} description={copy.description}>
- <InstallCardBody run={run} installing={installing} status={status} err={err} onDismiss={() => setErr(null)} />
+ <EmptyState
+ icon={copy.icon}
+ tone="accent"
+ title={installing ? 'Setting this up for you' : copy.title}
+ description={installing ? BUSY_DESCRIPTION.capability : copy.description}
+ >
+ <InstallCardBody
+ run={run} installing={installing} status={status} err={err}
+ onDismiss={() => setErr(null)}
+ onCancel={() => abortRef.current?.abort()}
+ />
</EmptyState>
)
}
@@ -429,23 +474,38 @@ function ModelInstallCard({ kind }: { kind: 'image' | 'video' | 'audio' | 'lipsy
const [installing, setInstalling] = useState(false)
const [status, setStatus] = useState('')
const [err, setErr] = useState<string | null>(null)
+ const abortRef = useRef<AbortController | null>(null)
const copy = 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)
+ await installModelBundle(kind, setStatus, ac.signal)
} catch (e) {
- setErr(e instanceof Error ? e.message : String(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
}
}
return (
- <EmptyState icon={copy.icon} tone="accent" title={copy.title} description={copy.description}>
- <InstallCardBody run={run} installing={installing} status={status} err={err} onDismiss={() => setErr(null)} />
+ <EmptyState
+ icon={copy.icon}
+ tone="accent"
+ title={installing ? 'Setting this up for you' : copy.title}
+ description={installing ? BUSY_DESCRIPTION.bundle : copy.description}
+ >
+ <InstallCardBody
+ run={run} installing={installing} status={status} err={err}
+ onDismiss={() => setErr(null)}
+ onCancel={() => abortRef.current?.abort()}
+ />
</EmptyState>
)
}
diff --git a/src/lib/__tests__/bundle-install.test.ts b/src/lib/__tests__/bundle-install.test.ts
new file mode 100644
index 00000000..dbd48d12
--- /dev/null
+++ b/src/lib/__tests__/bundle-install.test.ts
@@ -0,0 +1,214 @@
+import { describe, it, expect, vi } from 'vitest'
+import {
+ downloadBundleFiles, formatProgressLine, friendlyDownloadError, waitOrAbort,
+ InstallCancelled, MAX_FILE_ATTEMPTS, type BundleFile, type DownloadDeps,
+} from '../bundle-install'
+import type { DownloadProgress } from '../../api/discover'
+
+const FILE: BundleFile = {
+ filename: 'wan2.1_vace_1.3B_fp16.safetensors',
+ subfolder: 'diffusion_models',
+ downloadUrl: 'https://example.invalid/vace.safetensors',
+ sizeGB: 4.01,
+}
+
+function prog(over: Partial<DownloadProgress> = {}): DownloadProgress {
+ return {
+ progress: 0, total: 0, speed: 0, filename: FILE.filename, status: 'downloading', ...over,
+ }
+}
+
+/** Deps with no real waiting, plus a scripted sequence of progress maps. */
+function deps(
+ rounds: Array<Record<string, DownloadProgress>>,
+ over: Partial<DownloadDeps> = {},
+): DownloadDeps & { lines: string[]; starts: number } {
+ const lines: string[] = []
+ let i = 0
+ const d = {
+ lines,
+ starts: 0,
+ start: vi.fn(async () => { d.starts++; return { status: 'started' } }),
+ progress: vi.fn(async () => rounds[Math.min(i++, rounds.length - 1)]),
+ onStatus: (m: string) => { lines.push(m) },
+ wait: async () => { /* no real time in tests */ },
+ ...over,
+ } as DownloadDeps & { lines: string[]; starts: number }
+ return d
+}
+
+describe('formatProgressLine', () => {
+ it('reports percent, bytes and speed, because a bare percent does not answer "is it moving"', () => {
+ const line = formatProgressLine(
+ prog({ progress: 1_229_661_185, total: 4_309_519_800, speed: 3_049_536 }),
+ FILE.filename,
+ 'File 1 of 3. ',
+ )
+ expect(line).toBe(
+ 'File 1 of 3. Downloading wan2.1_vace_1.3B_fp16.safetensors. 29%, 1.1 GB of 4.0 GB, 2.9 MB/s',
+ )
+ })
+
+ it('degrades gracefully before the server reports a size', () => {
+ expect(formatProgressLine(prog(), FILE.filename)).toBe(
+ 'Downloading wan2.1_vace_1.3B_fp16.safetensors.',
+ )
+ })
+})
+
+describe('friendlyDownloadError', () => {
+ it('translates the raw reqwest text David actually hit', () => {
+ const msg = friendlyDownloadError('Stream error: error decoding response body', FILE.filename)
+ expect(msg).toContain('The connection dropped')
+ expect(msg).toContain('kept')
+ expect(msg).not.toContain('Stream error')
+ })
+
+ it('names the real cause for a full disk and for a blocked folder', () => {
+ expect(friendlyDownloadError('No space left on device', FILE.filename)).toContain('ran out of space')
+ expect(friendlyDownloadError('Access is denied. (os error 5)', FILE.filename)).toContain('Windows blocked')
+ })
+
+ it('keeps an unrecognised message visible instead of swallowing it', () => {
+ const msg = friendlyDownloadError('kaboom', FILE.filename)
+ expect(msg).toContain('kaboom')
+ })
+})
+
+describe('waitOrAbort', () => {
+ it('throws immediately when the signal is already aborted', async () => {
+ const ac = new AbortController()
+ ac.abort()
+ await expect(waitOrAbort(60_000, ac.signal)).rejects.toBeInstanceOf(InstallCancelled)
+ })
+
+ it('returns early when the signal fires mid wait, and still reports the cancel', async () => {
+ const ac = new AbortController()
+ const started = Date.now()
+ const p = waitOrAbort(30_000, ac.signal)
+ ac.abort()
+ await expect(p).rejects.toBeInstanceOf(InstallCancelled)
+ expect(Date.now() - started).toBeLessThan(5_000)
+ })
+})
+
+describe('downloadBundleFiles', () => {
+ it('finishes when the file reports complete', async () => {
+ const d = deps([
+ { [FILE.filename]: prog({ progress: 10, total: 100 }) },
+ { [FILE.filename]: prog({ status: 'complete', progress: 100, total: 100 }) },
+ ])
+ await downloadBundleFiles([FILE], d)
+ expect(d.starts).toBe(1)
+ expect(d.lines.at(-1)).toContain('done')
+ })
+
+ it('skips polling when the file is already on disk', async () => {
+ const d = deps([{}], { start: vi.fn(async () => ({ status: 'exists' })) })
+ await downloadBundleFiles([FILE], d)
+ expect(d.progress).not.toHaveBeenCalled()
+ expect(d.lines.at(-1)).toContain('already on disk')
+ })
+
+ it('registers the transfer with the tray before the first byte', async () => {
+ const keepTrayLive = vi.fn()
+ const d = deps([{ [FILE.filename]: prog({ status: 'complete' }) }], { keepTrayLive })
+ await downloadBundleFiles([FILE], d)
+ expect(keepTrayLive).toHaveBeenCalled()
+ })
+
+ it('resumes a dropped transfer instead of failing the bundle (Davids 1.2 GB of 4.3 GB death)', async () => {
+ let call = 0
+ const d = deps([], {
+ progress: vi.fn(async () => {
+ call++
+ if (call === 1) return { [FILE.filename]: prog({ progress: 1_229_661_185, total: 4_309_519_800 }) }
+ if (call === 2) {
+ return {
+ [FILE.filename]: prog({ status: 'error', error: 'Stream error: error decoding response body' }),
+ }
+ }
+ return { [FILE.filename]: prog({ status: 'complete' }) }
+ }),
+ })
+ await downloadBundleFiles([FILE], d)
+ // Second start_model_download = the resume; Rust picks up from the .download temp.
+ expect(d.starts).toBe(2)
+ expect(d.lines.some((l) => l.includes('Resuming'))).toBe(true)
+ })
+
+ it('gives up after the attempt budget and says something a person can act on', async () => {
+ const d = deps([{ [FILE.filename]: prog({ status: 'error', error: 'Stream error: error decoding response body' }) }])
+ await expect(downloadBundleFiles([FILE], d)).rejects.toThrow(/connection dropped/i)
+ expect(d.starts).toBe(MAX_FILE_ATTEMPTS)
+ })
+
+ it('treats a vanished entry as a cancel, because Rust only removes on cancel', async () => {
+ const stop = vi.fn()
+ const d = deps([
+ { [FILE.filename]: prog({ progress: 5, total: 100 }) },
+ {}, // cancel_download removed it
+ ], { stop })
+ await expect(downloadBundleFiles([FILE], d)).rejects.toBeInstanceOf(InstallCancelled)
+ // A cancel must NOT be retried like a network blip.
+ expect(d.starts).toBe(1)
+ })
+
+ it('does not mistake a slow first round for a cancel', async () => {
+ const d = deps([
+ {}, {}, // Rust has not registered it yet
+ { [FILE.filename]: prog({ status: 'complete' }) },
+ ])
+ await expect(downloadBundleFiles([FILE], d)).resolves.toBeUndefined()
+ })
+
+ it('keeps waiting while the user has it paused in the tray', async () => {
+ const d = deps([
+ { [FILE.filename]: prog({ status: 'paused' }) },
+ { [FILE.filename]: prog({ status: 'paused' }) },
+ { [FILE.filename]: prog({ status: 'complete' }) },
+ ])
+ await downloadBundleFiles([FILE], d)
+ expect(d.lines.some((l) => l.includes('paused'))).toBe(true)
+ })
+
+ it('stops the Rust transfer when the user cancels, not just the loop', async () => {
+ const ac = new AbortController()
+ const stop = vi.fn()
+ const d = deps([{ [FILE.filename]: prog({ progress: 5, total: 100 }) }], {
+ stop,
+ signal: ac.signal,
+ // Abort during the poll wait, the way the Cancel button does.
+ wait: async () => { ac.abort(); if (ac.signal.aborted) throw new InstallCancelled() },
+ })
+ await expect(downloadBundleFiles([FILE], d)).rejects.toBeInstanceOf(InstallCancelled)
+ expect(stop).toHaveBeenCalledWith(FILE.filename)
+ })
+
+ it('labels each file of a multi file bundle so the card shows where it is', async () => {
+ const files: BundleFile[] = [
+ FILE,
+ { filename: 'umt5.safetensors', subfolder: 'text_encoders', downloadUrl: 'https://x.invalid/a', sizeGB: 6.27 },
+ ]
+ let n = 0
+ const d = deps([], {
+ progress: vi.fn(async () => {
+ n++
+ const name = n <= 2 ? FILE.filename : 'umt5.safetensors'
+ return { [name]: prog({ filename: name, status: n % 2 === 0 ? 'complete' : 'downloading', progress: 1, total: 2 }) }
+ }),
+ })
+ await downloadBundleFiles(files, d)
+ expect(d.lines.some((l) => l.startsWith('File 1 of 2.'))).toBe(true)
+ expect(d.lines.some((l) => l.startsWith('File 2 of 2.'))).toBe(true)
+ })
+
+ it('ignores catalogue rows that have no usable download url', async () => {
+ const d = deps([{ [FILE.filename]: prog({ status: 'complete' }) }])
+ await downloadBundleFiles(
+ [{ filename: 'x', subfolder: '', downloadUrl: '', sizeGB: 1 }, FILE],
+ d,
+ )
+ expect(d.starts).toBe(1)
+ })
+})
diff --git a/src/lib/bundle-install.ts b/src/lib/bundle-install.ts
new file mode 100644
index 00000000..c46a7e1f
--- /dev/null
+++ b/src/lib/bundle-install.ts
@@ -0,0 +1,208 @@
+import { formatBytes } from './formatters'
+import type { DownloadProgress } from '../api/discover'
+
+/**
+ * The download half of the Create tab's "Download & install" cards, pulled out
+ * of CreateContext so every branch is unit-testable without a live ComfyUI.
+ *
+ * David 2026-07-25, on the Motion Control card: he clicked Download & install,
+ * got a spinner, and had no way to tell whether anything was still downloading.
+ * Three separate defects sat behind that:
+ *
+ * 1. The card was the ONLY place progress showed. installModelBundle called
+ * the Rust downloader directly and never registered with downloadStore, so
+ * the header Downloads tray said "No active downloads" through a 10.5 GB
+ * transfer, and the tray's cancel + retry buttons were unreachable.
+ * 2. There was no way out. No cancel on the card, no cancel in the tray.
+ * 3. One dropped connection killed the whole bundle. His run died at 1.2 GB of
+ * 4.3 GB with the raw reqwest text "Stream error: error decoding response
+ * body" and no retry. The Rust side resumes from the .download temp file on
+ * the next start_model_download, so a retry is nearly free, it just was
+ * never wired.
+ */
+
+/** User pressed Cancel (on the card or in the Downloads tray). Rendered as a
+ * plain "Cancelled." line, never as a red failure. */
+export class InstallCancelled extends Error {
+ constructor(message = 'Cancelled.') {
+ super(message)
+ this.name = 'InstallCancelled'
+ }
+}
+
+/** A sleep that returns the moment the user cancels, so Cancel does not have to
+ * wait out a poll tick. Throws before AND after the wait: cancelling during the
+ * sleep must not let one more poll round run. */
+export async function waitOrAbort(ms: number, signal?: AbortSignal): Promise<void> {
+ if (signal?.aborted) throw new InstallCancelled()
+ await new Promise<void>((resolve) => {
+ const finish = () => {
+ clearTimeout(timer)
+ signal?.removeEventListener('abort', finish)
+ resolve()
+ }
+ const timer = setTimeout(finish, ms)
+ signal?.addEventListener('abort', finish, { once: true })
+ })
+ if (signal?.aborted) throw new InstallCancelled()
+}
+
+/** The status line under the card spinner. Bytes and speed are the whole point:
+ * a bare percentage still leaves "is this thing moving" unanswered. */
+export function formatProgressLine(p: DownloadProgress, filename: string, fileLabel = ''): string {
+ const parts: string[] = []
+ if (p.total > 0) parts.push(`${Math.round((p.progress / p.total) * 100)}%`)
+ if (p.total > 0) parts.push(`${formatBytes(p.progress)} of ${formatBytes(p.total)}`)
+ if (p.speed > 0) parts.push(`${formatBytes(p.speed)}/s`)
+ const detail = parts.length > 0 ? ` ${parts.join(', ')}` : ''
+ return `${fileLabel}Downloading ${filename}.${detail}`
+}
+
+/**
+ * Turn a downloader error into something a person can act on. The raw strings
+ * come from reqwest ("Stream error: error decoding response body", "os error
+ * 10054") and mean nothing to anyone who is not us. Every message says what to
+ * do next, and the resume note is literally true: the partial .download file
+ * stays on disk and the next attempt continues from its length.
+ */
+export function friendlyDownloadError(raw: string, filename: string): string {
+ const low = (raw || '').toLowerCase()
+ const resume = 'Nothing is lost, the part already on disk is kept and the next try continues from there.'
+ if (
+ low.includes('stream error') || low.includes('decoding response') ||
+ low.includes('connection') || low.includes('timed out') || low.includes('timeout') ||
+ low.includes('10054') || low.includes('dns') || low.includes('reset')
+ ) {
+ return `The connection dropped while downloading ${filename}. ${resume} Hit Download & install again when your network is back.`
+ }
+ if (low.includes('no space') || low.includes('disk full') || low.includes('os error 112')) {
+ return `The drive ran out of space while downloading ${filename}. Free some room, then hit Download & install again. ${resume}`
+ }
+ if (low.includes('permission') || low.includes('access is denied') || low.includes('os error 5')) {
+ return `Windows blocked writing ${filename} to the ComfyUI models folder. Check that folder is not read only, then try again.`
+ }
+ if (low.includes('404') || low.includes('not found')) {
+ return `The download link for ${filename} is gone (404). This one is on us, please report it.`
+ }
+ return `Could not download ${filename}: ${raw}. ${resume}`
+}
+
+/** One file of a bundle. Mirrors the DiscoverModel fields the downloader needs. */
+export interface BundleFile {
+ filename: string
+ subfolder: string
+ downloadUrl: string
+ sizeGB?: number
+}
+
+export interface DownloadDeps {
+ /** start_model_download. Resolves once the transfer is registered, not done. */
+ start: (url: string, subfolder: string, filename: string, expectedBytes?: number) =>
+ Promise<{ status: string; error?: string }>
+ /** download_progress, the whole Rust map keyed by filename. */
+ progress: () => Promise<Record<string, DownloadProgress>>
+ /** Streams the line under the card spinner. */
+ onStatus?: (msg: string) => void
+ /** Makes the transfer visible in the header Downloads tray (and its cancel +
+ * retry buttons reachable). Called before the first byte and again per file,
+ * because the tray's poller auto stops when it sees an idle window. */
+ keepTrayLive?: () => void
+ /** cancel_download for the file in flight. Aborting the JS loop alone would
+ * leave the Rust task happily eating bandwidth, so Cancel has to reach the
+ * transfer itself. */
+ stop?: (filename: string) => void
+ signal?: AbortSignal
+ /** Injected so tests do not spend real seconds. */
+ wait?: (ms: number, signal?: AbortSignal) => Promise<void>
+}
+
+/** A 10 GB transfer over a home line drops. Four tries, each resuming. */
+export const MAX_FILE_ATTEMPTS = 4
+
+/** How many empty poll rounds to allow before calling a download stillborn.
+ * Rust inserts the entry inside start_model_download, so this only ever
+ * covers a slow first round. */
+const MAX_MISSING_ROUNDS = 8
+
+async function downloadOneFile(file: BundleFile, fileLabel: string, deps: DownloadDeps): Promise<void> {
+ const { start, progress, onStatus, keepTrayLive, signal } = deps
+ const wait = deps.wait ?? waitOrAbort
+ const expected = file.sizeGB ? Math.round(file.sizeGB * 1_073_741_824) : undefined
+
+ onStatus?.(`${fileLabel}Starting ${file.filename}.`)
+ const started = await start(file.downloadUrl, file.subfolder, file.filename, expected)
+ if (started.status === 'error') {
+ throw new Error(started.error || `Could not start the ${file.filename} download.`)
+ }
+ keepTrayLive?.()
+ // 'exists' = already complete on disk, nothing to poll.
+ if (started.status === 'exists') {
+ onStatus?.(`${fileLabel}${file.filename} is already on disk.`)
+ return
+ }
+
+ // Cancel has to stop the Rust transfer, not just this loop.
+ const onAbort = () => deps.stop?.(file.filename)
+ signal?.addEventListener('abort', onAbort, { once: true })
+ try {
+ let seen = false
+ let missing = 0
+ for (;;) {
+ await wait(1000, signal)
+ const all = await progress()
+ const p = all[file.filename] ?? Object.values(all).find((d) => d.filename === file.filename)
+ if (!p) {
+ // Rust drops an entry from the map only on cancel (a finished one keeps
+ // status 'complete'), so a vanished entry we had already seen means the
+ // user hit cancel somewhere. Before we ever saw it, it is just a slow
+ // first round.
+ if (seen) throw new InstallCancelled()
+ if (++missing > MAX_MISSING_ROUNDS) {
+ throw new Error(`The ${file.filename} download never started. Check Settings, AI Backends.`)
+ }
+ continue
+ }
+ seen = true
+ if (p.status === 'complete') {
+ onStatus?.(`${fileLabel}${file.filename} done.`)
+ return
+ }
+ if (p.status === 'error') throw new Error(p.error || `Download failed: ${file.filename}`)
+ if (p.status === 'paused' || p.status === 'pausing') {
+ onStatus?.(`${fileLabel}${file.filename} is paused. Resume it from the Downloads tray up top.`)
+ continue
+ }
+ onStatus?.(formatProgressLine(p, file.filename, fileLabel))
+ }
+ } finally {
+ signal?.removeEventListener('abort', onAbort)
+ }
+}
+
+/**
+ * Download every file of a bundle, in order, retrying a dropped transfer where
+ * it left off. Cancel and a genuinely dead link both stop the whole bundle, a
+ * flaky connection does not.
+ */
+export async function downloadBundleFiles(files: BundleFile[], deps: DownloadDeps): Promise<void> {
+ const wait = deps.wait ?? waitOrAbort
+ const usable = files.filter((f) => f.downloadUrl && f.filename && f.subfolder)
+ for (let i = 0; i < usable.length; i++) {
+ const file = usable[i]
+ const fileLabel = usable.length > 1 ? `File ${i + 1} of ${usable.length}. ` : ''
+ for (let attempt = 1; ; attempt++) {
+ try {
+ await downloadOneFile(file, fileLabel, deps)
+ break
+ } catch (err) {
+ if (err instanceof InstallCancelled) throw err
+ const raw = err instanceof Error ? err.message : String(err)
+ if (attempt >= MAX_FILE_ATTEMPTS) throw new Error(friendlyDownloadError(raw, file.filename))
+ deps.onStatus?.(
+ `${fileLabel}The connection dropped. Resuming ${file.filename}, try ${attempt + 1} of ${MAX_FILE_ATTEMPTS}.`,
+ )
+ await wait(3000, deps.signal)
+ }
+ }
+ }
+}