Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: disclose required assets before media downloads (#12387)
Lee Jackson3a9c27598e42
diff --git a/studio/frontend/src/features/hub/catalog/download-card.tsx b/studio/frontend/src/features/hub/catalog/download-card.tsxindex fef8697ea70..c6387fba151 100644--- a/studio/frontend/src/features/hub/catalog/download-card.tsx+++ b/studio/frontend/src/features/hub/catalog/download-card.tsx@@ -51,11 +51,13 @@ export function DownloadCard({progress,children,dialogs,+ footer,}: {job: DownloadJob;progress: DownloadJobProgress | null;children: ReactNode;dialogs?: ReactNode;+ footer?: ReactNode;}) {return (<>@@ -73,6 +75,7 @@ export function DownloadCard({/></div>)}+ {footer}</div><TransportConflictDialogconflict={job.transportConflict}diff --git a/studio/frontend/src/features/hub/catalog/download-section.tsx b/studio/frontend/src/features/hub/catalog/download-section.tsxindex 4c53b546061..200d90fd80a 100644--- a/studio/frontend/src/features/hub/catalog/download-section.tsx+++ b/studio/frontend/src/features/hub/catalog/download-section.tsx@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import type { AssetRuntime } from "./use-required-assets-download";import type { MediaStudioPage } from "../hooks/use-media-companion-bytes";import type { ModelInventoryFormat } from "../inventory";import type { HubModelRunSelection } from "../lib/model-run-selection";@@ -32,6 +33,7 @@ export function DownloadSection({onChange,showMemoryBar = true,mediaPage,+ assetRuntime,}: {repoId: string;isGguf: boolean;@@ -59,6 +61,7 @@ export function DownloadSection({* llama.cpp and so have nothing the KV estimator can say about them. */showMemoryBar?: boolean;mediaPage?: MediaStudioPage;+ assetRuntime?: AssetRuntime;}) {if (isGguf || preferredGgufFile) {return (@@ -84,6 +87,7 @@ export function DownloadSection({}return (<SafetensorsDownloadCard+ assetRuntime={assetRuntime}repoId={repoId}isDownloaded={isDownloaded}isPartial={isPartial}diff --git a/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx b/studio/frontend/src/features/hub/catalog/gguf-download-card.tsxindex c996256f61a..9330b383603 100644--- a/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx+++ b/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx@@ -1,6 +1,9 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import { useHubDownloadPlan } from "../download-manager/use-hub-download-queue";+import { HubPlanProgress } from "../download-manager/hub-plan-progress";+import { useRequiredAssetsDownload } from "./use-required-assets-download";import { ModelMemoryBarFor } from "@/components/model-memory-bar";import {DropdownMenu,@@ -840,6 +843,12 @@ export function GgufDownloadCard({);}, [loading, error, refreshError, variants]);+ const assets = useRequiredAssetsDownload({+ repoId,+ filename: selected?.filename,+ runtime: selected ? mediaPage : undefined,+ modelLabel: `${repoId} · ${selectedQuant ?? ""}`,+ });const selectedLiveState = selectedQuant? liveVariantStates.get(normalizeGgufVariantIdentity(selectedQuant)): undefined;@@ -985,9 +994,10 @@ export function GgufDownloadCard({...(presentation ? { presentation } : {}),});}, [updateTarget, updateTargetVariant, repoId]);+ const hubPlan = useHubDownloadPlan(repoId, selected?.filename);const variantListUnavailable = !sortedVariants || sortedVariants.length === 0;const showVariantLoadingState = loading && variantListUnavailable;- const showUpdateAction =+ const showUpdateAction = !hubPlan &&selected?.downloaded === true &&online &&updateAvailable &&@@ -997,12 +1007,12 @@ export function GgufDownloadCard({!cancelling &&!downloadAction.starting &&!downloadingThisVariant;- const showDownloadAction =+ const showDownloadAction = !hubPlan && (!selected?.downloaded ||downloadingThisVariant ||cancelling ||- downloadAction.starting;- const showRunAction =+ downloadAction.starting);+ const showRunAction = !hubPlan &&Boolean(onRun) &&selected?.downloaded === true &&selected.partial !== true &&@@ -1058,6 +1068,7 @@ export function GgufDownloadCard({return (<div className="flex w-full flex-col gap-2"><DownloadCard+ footer={hubPlan ? <HubPlanProgress plan={hubPlan} /> : undefined}job={job}progress={downloadingThisVariant ? progress : null}dialogs={@@ -1267,8 +1278,8 @@ export function GgufDownloadCard({{showDownloadAction && (<buttontype="button"- disabled={downloadAction.disabled}- onClick={downloadAction.onClick}+ disabled={downloadAction.disabled || assets.checking}+ onClick={() => downloadingThisVariant ? downloadAction.onClick() : void assets.request(downloadAction.onClick)}aria-label={selectedScopedLive ? "Downloading" : downloadAction.ariaLabel}@@ -1308,12 +1319,13 @@ export function GgufDownloadCard({) : (<><HugeiconsIcon icon={Download01Icon} strokeWidth={1.75} />- {downloadAction.downloadLabel}+ {assets.checking ? "Checking…" : downloadAction.downloadLabel}</>)}</button>)}+ {hubPlan && <span className="px-3 text-ui-12 text-muted-foreground">Downloading…</span>}{showRunAction && onRun && selected && (<ModelRunActionButtonlabel={`Configure and run ${repoId} ${selectedLabel ?? selected.quant}`}@@ -1332,6 +1344,7 @@ export function GgufDownloadCard({/>)}</DownloadCard>+ {assets.dialog}{/* Only a quant actually on disk gets charted: an undownloaded one has noweights to measure, and the fit badge already tiers those. */}{selected?.downloaded && showMemoryBar ? (diff --git a/studio/frontend/src/features/hub/catalog/model-inspector.tsx b/studio/frontend/src/features/hub/catalog/model-inspector.tsxindex c34e4dfcfb1..dbcd3d6ed2c 100644--- a/studio/frontend/src/features/hub/catalog/model-inspector.tsx+++ b/studio/frontend/src/features/hub/catalog/model-inspector.tsx@@ -705,6 +705,7 @@ export const ModelInspector = memo(function ModelInspector({<DownloadSectionshowMemoryBar={!runsOnMediaRuntime}mediaPage={mediaPage}+ assetRuntime={mediaPage ?? (["text-to-speech", "text-to-audio"].includes(model.pipelineTag ?? model.task ?? "") ? "audio" : undefined)}repoId={model.isLocal ? (model.hubRepoId ?? model.id) : model.id}isGguf={model.isGguf}{...downloadState}diff --git a/studio/frontend/src/features/hub/catalog/safetensors-download-card.tsx b/studio/frontend/src/features/hub/catalog/safetensors-download-card.tsxindex 2f4abe6ee69..21d404d892f 100644--- a/studio/frontend/src/features/hub/catalog/safetensors-download-card.tsx+++ b/studio/frontend/src/features/hub/catalog/safetensors-download-card.tsx@@ -1,6 +1,9 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import { useHubDownloadPlan } from "../download-manager/use-hub-download-queue";+import { HubPlanProgress } from "../download-manager/hub-plan-progress";+import { useRequiredAssetsDownload, type AssetRuntime } from "./use-required-assets-download";import { useHfEndpoint } from "@/lib/hf-endpoint";import {Tooltip,@@ -60,6 +63,7 @@ export function SafetensorsDownloadCard({onRun,runPending = false,onChange,+ assetRuntime,}: {repoId: string;isDownloaded: boolean;@@ -76,9 +80,11 @@ export function SafetensorsDownloadCard({onRun?: () => void;runPending?: boolean;onChange?: () => void;+ assetRuntime?: AssetRuntime;}) {const hfToken = useHfTokenStore((s) => s.token);const online = useOnlineStatus();+ const assets = useRequiredAssetsDownload({ repoId, runtime: assetRuntime });const hfEndpoint = useHfEndpoint();const sizeKey = `${hfEndpoint}::${repoId}::${fingerprintToken(hfToken)}`;const [modelSize, setModelSize] = useState<{@@ -157,9 +163,10 @@ export function SafetensorsDownloadCard({partialResumable,partialsResumable,});- const showDownloadAction =- !isDownloaded || downloading || cancelling || downloadAction.starting;- const showRunAction =+ const hubPlan = useHubDownloadPlan(repoId);+ const showDownloadAction = !hubPlan && (+ !isDownloaded || downloading || cancelling || downloadAction.starting);+ const showRunAction = !hubPlan &&Boolean(onRun) &&isDownloaded &&!isPartial &&@@ -187,6 +194,7 @@ export function SafetensorsDownloadCard({return (<div className="flex w-full flex-col gap-2"><DownloadCard+ footer={hubPlan ? <HubPlanProgress plan={hubPlan} /> : undefined}job={job}progress={downloading ? progress : null}dialogs={@@ -267,16 +275,17 @@ export function SafetensorsDownloadCard({<DownloadActionButtondownloading={downloadAction.downloading}cancelling={downloadAction.cancelling}- loading={downloadAction.starting}+ loading={downloadAction.starting || assets.checking}isPartial={downloadAction.isPartial}partialResumable={downloadAction.partialResumable}stopMode={downloadAction.stopMode}progressPercent={downloadAction.progressPercent}- disabled={downloadAction.disabled}- onClick={downloadAction.onClick}+ disabled={downloadAction.disabled || assets.checking}+ onClick={() => downloading ? downloadAction.onClick() : void assets.request(downloadAction.onClick)}className={repoPeerActive ? "opacity-70" : undefined}/>)}+ {hubPlan && <span className="px-3 text-ui-12 text-muted-foreground">Downloading…</span>}{showRunAction && onRun && (<ModelRunActionButtonlabel={`Configure and run ${repoId}`}@@ -285,6 +294,7 @@ export function SafetensorsDownloadCard({/>)}</DownloadCard>+ {assets.dialog}</div>);}diff --git a/studio/frontend/src/features/hub/catalog/use-required-assets-download.tsx b/studio/frontend/src/features/hub/catalog/use-required-assets-download.tsxnew file mode 100644index 00000000000..ff601c72910--- /dev/null+++ b/studio/frontend/src/features/hub/catalog/use-required-assets-download.tsx@@ -0,0 +1,167 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { useCallback, useEffect, useRef, useState } from "react";+import {+ getDiffusionDownloadPlan,+ type DiffusionDownloadPlan,+} from "@/features/images/api";+import { getVideoDownloadPlan } from "@/features/video/api";+import { getAudioDownloadPlan } from "@/features/audio/api";+import { toast } from "@/lib/toast";+import { useInventoryVersion } from "../stores/inventory-events";+import { useHfTokenStore } from "../stores/hf-token-store";+import {+ additionalAssetDownloads,+ selectDownloadEntries,+} from "../download-manager/required-assets";+import { RequiredAssetsDownloadDialog } from "../download-manager/required-assets-dialog";+import { enqueueHubDownload } from "../download-manager/use-hub-download-queue";+import type { StagedDownloadEntry } from "../download-manager/use-staged-download";+export type AssetRuntime = "images" | "video" | "audio";++export function useRequiredAssetsDownload({+ repoId,+ filename,+ runtime,+ modelLabel,+}: {+ repoId: string;+ filename?: string;+ runtime?: AssetRuntime;+ modelLabel?: string;+}) {+ const token = useHfTokenStore((s) => s.token);+ const [checking, setChecking] = useState(false);+ const [pending, setPending] = useState<StagedDownloadEntry[] | null>(null);+ const inventoryVersion = useInventoryVersion();+ const sequence = useRef(0);+ const starting = useRef(false);+ const fetchPlan = useCallback(async () => {+ const body = {+ model_path: repoId,+ gguf_filename: filename,+ model_kind: filename ? ("gguf" as const) : ("pipeline" as const),+ hf_token: token || undefined,+ };+ const result =+ runtime === "audio"+ ? await getAudioDownloadPlan(repoId, token || undefined)+ : runtime === "video"+ ? await getVideoDownloadPlan(body)+ : await getDiffusionDownloadPlan(body);+ const resultPlan: DiffusionDownloadPlan = result;+ if (resultPlan.plan_failed)+ throw new Error(+ "Required file information is incomplete. Please try again.",+ );+ if (resultPlan.incompatible_reason)+ throw new Error(resultPlan.incompatible_reason);+ return resultPlan;+ }, [repoId, filename, token, runtime]);+ const cached = useRef<{+ fetch: typeof fetchPlan;+ inventory: number;+ expires: number;+ promise: ReturnType<typeof fetchPlan>;+ } | null>(null);+ const resolvePlan = useCallback(() => {+ const previous = cached.current;+ if (+ previous &&+ previous.fetch === fetchPlan &&+ previous.inventory === inventoryVersion &&+ previous.expires > Date.now()+ )+ return previous.promise;+ const record = {+ fetch: fetchPlan,+ inventory: inventoryVersion,+ expires: Date.now() + 30_000,+ promise: fetchPlan(),+ };+ cached.current = record;+ void record.promise.catch(() => {+ if (cached.current === record) cached.current = null;+ });+ return record.promise;+ }, [fetchPlan, inventoryVersion]);+ useEffect(() => {+ if (!runtime) return;+ const timer = window.setTimeout(() => {+ void resolvePlan().catch(() => {});+ }, 200);+ return () => window.clearTimeout(timer);+ }, [resolvePlan, runtime]);+ useEffect(() => {+ ++sequence.current;+ setPending(null);+ setChecking(false);+ starting.current = false;+ return () => {+ ++sequence.current;+ };+ }, [fetchPlan, runtime]);+ const request = async (fallback: () => void) => {+ if (!runtime) {+ fallback();+ return;+ }+ if (starting.current) return;+ starting.current = true;+ setChecking(true);+ const id = ++sequence.current;+ try {+ const p = await resolvePlan();+ if (sequence.current !== id) return;+ const entries = p.entries.map((e) => ({+ repoId: e.repo_id,+ files: e.files,+ bytes: e.bytes,+ ggufFilename: e.gguf_filename,+ checkpoint:+ e.checkpoint ??+ (filename ? e.files.includes(filename) : e.repo_id === repoId),+ }));+ if (additionalAssetDownloads(entries).length) setPending(entries);+ else if (entries.length)+ enqueueHubDownload(entries, { repoId, filename });+ else fallback();+ } catch (e) {+ if (sequence.current !== id) return;+ toast.error("Could not check required files", {+ description: e instanceof Error ? e.message : "Please try again.",+ });+ } finally {+ if (sequence.current === id) {+ starting.current = false;+ setChecking(false);+ }+ }+ };+ return {+ checking,+ request,+ dialog: (+ <RequiredAssetsDownloadDialog+ entries={pending}+ checking={checking}+ modelLabel={modelLabel ?? repoId}+ onCancel={() => {+ ++sequence.current;+ starting.current = false;+ setChecking(false);+ setPending(null);+ }}+ onConfirm={(include) => {+ if (pending)+ enqueueHubDownload(selectDownloadEntries(pending, include), {+ repoId,+ filename,+ });+ setPending(null);+ }}+ />+ ),+ };+}diff --git a/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsx b/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsxindex 889d5d127a0..b6c1e118bfe 100644--- a/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsx+++ b/studio/frontend/src/features/hub/download-manager/download-manager-panel.tsx@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import { useHubDownloadQueue, useQueuedHubEntries } from "./use-hub-download-queue";import {Tooltip,TooltipContent,@@ -195,6 +196,7 @@ export function DownloadManagerPanel({}: { positioned?: boolean } = {}) {const pathname = useRouterState({ select: (s) => s.location.pathname });const enabled = canUseDownloadManager(pathname);+ useHubDownloadQueue();const [collapsed, setCollapsed] = useState(false);useEffect(() => {@@ -204,9 +206,10 @@ export function DownloadManagerPanel({const selectOrderedJobKeys = useMemo(createOrderedJobKeysSelector, []);const jobKeys = useDownloadManagerStore(selectOrderedJobKeys);- const activeCount = useDownloadManagerStore(selectActiveJobCount);+ const queued = useQueuedHubEntries();+ const activeCount = useDownloadManagerStore(selectActiveJobCount) + queued.length;- if (!enabled || jobKeys.length === 0) return null;+ if (!enabled || (jobKeys.length === 0 && queued.length === 0)) return null;const headerLabel =activeCount > 0@@ -270,6 +273,10 @@ export function DownloadManagerPanel({{jobKeys.map((jobKey) => (<DownloadRow key={jobKey} jobKey={jobKey} />))}+ {queued.map((entry, i) => <li key={`${entry.planId}:${i}`} className="flex flex-col gap-1.5 py-2.5 pl-4 pr-3">+ <span className="truncate text-ui-12p5 font-medium">{entry.repoId}<span className="text-muted-foreground"> · {entry.checkpoint !== false ? "Model file" : "Required assets"}</span></span>+ <span className="text-ui-11 text-muted-foreground">Queued</span>+ </li>)}</ul></div>)}diff --git a/studio/frontend/src/features/hub/download-manager/hub-plan-progress.tsx b/studio/frontend/src/features/hub/download-manager/hub-plan-progress.tsxnew file mode 100644index 00000000000..02ef02ac4df--- /dev/null+++ b/studio/frontend/src/features/hub/download-manager/hub-plan-progress.tsx@@ -0,0 +1,60 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import {+ downloadManager,+ useDownloadManagerStore,+} from "./download-manager-controller";+import { DownloadProgressBar } from "./download-progress-bar";+import type { Plan } from "./use-hub-download-queue";+export function HubPlanProgress({ plan }: { plan: Plan }) {+ const entry = plan.remaining[0];+ const job = useDownloadManagerStore((s) =>+ Object.values(s.jobs).find(+ (j) =>+ j.repoId === entry?.repoId &&+ j.variant === "@hub-assets" &&+ (j.state === "running" || j.state === "cancelling") &&+ entry.files.length === j.scopedFiles?.length &&+ entry.files.every((f) => j.scopedFiles?.includes(f)),+ ),+ );+ const total = plan.entries.reduce((n, e) => n + Math.max(0, e.bytes), 0);+ const remaining = plan.remaining.reduce(+ (n, e) => n + Math.max(0, e.bytes),+ 0,+ );+ const downloaded =+ total - remaining + Math.min(entry?.bytes ?? 0, job?.downloadedBytes ?? 0);+ return (+ <div className="px-3">+ <div className="mb-2 flex justify-between text-ui-11 text-muted-foreground">+ <span>+ {job+ ? entry.checkpoint !== false+ ? "Downloading model file"+ : "Downloading required files"+ : "Queued"}+ </span>+ {job && (+ <button+ type="button"+ disabled={job.state === "cancelling"}+ onClick={() => void downloadManager.cancel(job.key)}+ >+ Cancel download+ </button>+ )}+ </div>+ <DownloadProgressBar+ progress={{+ expectedBytes: total,+ downloadedBytes: downloaded,+ fraction: total > 0 ? downloaded / total : 0,+ }}+ bytesPerSec={job?.bytesPerSec ?? 0}+ cancelling={job?.state === "cancelling"}+ />+ </div>+ );+}diff --git a/studio/frontend/src/features/hub/download-manager/required-assets-dialog.tsx b/studio/frontend/src/features/hub/download-manager/required-assets-dialog.tsxnew file mode 100644index 00000000000..14e95c11d05--- /dev/null+++ b/studio/frontend/src/features/hub/download-manager/required-assets-dialog.tsx@@ -0,0 +1,189 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { useId, useState } from "react";+import { Checkbox as CheckboxPrimitive } from "radix-ui";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import {+ additionalAssetDownloads,+ assetLabel,+ downloadBytes,+ formatDownloadBytes,+ type PlannedDownloadEntry,+} from "./required-assets";++export function RequiredAssetsDownloadDialog({+ entries,+ onConfirm,+ onCancel,+ modelLabel,+ checking = false,+}: {+ checking?: boolean;+ entries: readonly PlannedDownloadEntry[] | null;+ onConfirm: (includeAssets: boolean) => void;+ onCancel: () => void;+ modelLabel?: string;+}) {+ // Keep one portal/content mounted through the metadata check.+ return (+ <AlertDialog+ open={checking || entries !== null}+ onOpenChange={(open) => {+ if (!open) onCancel();+ }}+ >+ {(checking || entries !== null) && (+ <DownloadChoice+ entries={entries ?? []}+ checking={checking}+ onConfirm={onConfirm}+ modelLabel={modelLabel}+ />+ )}+ </AlertDialog>+ );+}+function DownloadChoice({+ checking,+ entries,+ onConfirm,+ modelLabel,+}: {+ checking: boolean;+ entries: readonly PlannedDownloadEntry[];+ onConfirm: (includeAssets: boolean) => void;+ modelLabel?: string;+}) {+ const [includeAssets, setIncludeAssets] = useState(true);+ const choiceId = useId();+ const assets = additionalAssetDownloads(entries);+ const checkpoints = entries.filter((e) => e.checkpoint !== false);+ const modelSize = checkpoints.some((e) => e.bytes <= 0)+ ? "Size unknown"+ : formatDownloadBytes(downloadBytes(checkpoints));+ const fullSize = entries.some((e) => e.bytes <= 0)+ ? "Size unknown"+ : formatDownloadBytes(downloadBytes(entries));+ const displayName = modelLabel+ ?.replace(/^[^/]+\//, "")+ .replace(/-GGUF(?=\s|$)/i, "");+ const assetSize = assets.some((e) => e.bytes <= 0)+ ? "Size unknown"+ : formatDownloadBytes(downloadBytes(assets));+ const total = includeAssets ? fullSize : modelSize;+ return (+ <AlertDialogContent className="sm:max-w-[calc(490px*var(--ui-space-scale,1))]">+ <AlertDialogHeader className="flex flex-row flex-wrap items-center justify-between gap-x-4 gap-y-2 text-left sm:group-data-[size=default]/alert-dialog-content:place-items-center">+ <AlertDialogTitle className="shrink-0">Download model</AlertDialogTitle>+ <AlertDialogDescription className="min-w-0 text-xs break-words sm:ml-auto sm:text-right">+ {displayName ?? "Choose which files to download."}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <div+ className="relative min-h-[calc(246px*var(--ui-space-scale,1))] text-sm"+ aria-busy={checking}+ >+ {checking && (+ <div+ role="status"+ className="absolute inset-0 flex items-center justify-center gap-3 text-muted-foreground"+ >+ <span className="size-4 animate-spin rounded-full border-2 border-current border-r-transparent" />+ Checking required files…+ </div>+ )}+ <div+ className="space-y-4"+ style={{ visibility: checking ? "hidden" : "visible" }}+ >+ {(checkpoints.length > 0 || checking) && (+ <div className="flex justify-between gap-4">+ <span>Model files</span>+ <span className="tabular-nums">+ {formatDownloadBytes(downloadBytes(checkpoints))}+ </span>+ </div>+ )}+ <div className="flex items-center gap-3">+ <CheckboxPrimitive.Root+ id={choiceId}+ checked={includeAssets}+ onCheckedChange={(checked) => setIncludeAssets(checked === true)}+ className="relative flex size-4 shrink-0 cursor-pointer items-center justify-center rounded-full border-0 bg-transparent p-0 leading-none outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"+ >+ <svg+ aria-hidden="true"+ viewBox="0 0 16 16"+ width="16"+ height="16"+ className="block size-4 shrink-0 overflow-visible"+ >+ <circle+ cx="8"+ cy="8"+ r="7.5"+ className={+ includeAssets+ ? "fill-emerald-600 stroke-emerald-600"+ : "fill-transparent stroke-input"+ }+ />+ {includeAssets && <circle cx="8" cy="8" r="3" fill="white" />}+ </svg>+ </CheckboxPrimitive.Root>+ <label htmlFor={choiceId} className="cursor-pointer">+ Include required files+ </label>+ <span className="ml-auto shrink-0 tabular-nums">{assetSize}</span>+ </div>+ <ul className="mt-3 h-12 space-y-2 overflow-y-auto pl-7 text-xs text-muted-foreground">+ {assets.map((entry, i) => (+ <li+ key={`${entry.repoId}:${i}`}+ className="flex justify-between gap-4"+ >+ <span title={entry.repoId}>{assetLabel(entry)}</span>+ <span className="shrink-0 tabular-nums">+ {formatDownloadBytes(entry.bytes)}+ </span>+ </li>+ ))}+ </ul>+ <p className="text-xs leading-relaxed text-muted-foreground">+ Required to run · Shared across compatible variants+ </p>+ <div className="flex justify-between border-t pt-4 font-medium">+ <span>Total download</span>+ <span className="tabular-nums">{total}</span>+ </div>+ <p className="text-xs text-muted-foreground">+ Downloading will not load this model or switch your current model.+ </p>+ </div>+ </div>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ disabled={checking}+ className="w-full sm:w-32"+ onClick={(e) => {+ e.preventDefault();+ onConfirm(includeAssets);+ }}+ >+ Download+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ );+}diff --git a/studio/frontend/src/features/hub/download-manager/required-assets.ts b/studio/frontend/src/features/hub/download-manager/required-assets.tsnew file mode 100644index 00000000000..0c1a3b79623--- /dev/null+++ b/studio/frontend/src/features/hub/download-manager/required-assets.ts@@ -0,0 +1,56 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export interface PlannedDownloadEntry {+ repoId: string;+ files?: string[];+ bytes: number;+ checkpoint?: boolean;+}++/** Missing file entries, including unsized entries: zero is not proof of a cache hit. */+export function additionalAssetDownloads<T extends PlannedDownloadEntry>(+ entries: readonly T[],+): T[] {+ return entries.filter((entry) => entry.checkpoint === false);+}+export function downloadBytes(+ entries: readonly PlannedDownloadEntry[],+): number {+ return entries.reduce((sum, entry) => sum + Math.max(0, entry.bytes), 0);+}+export function selectDownloadEntries<T extends PlannedDownloadEntry>(+ entries: readonly T[],+ includeAssets: boolean,+): T[] {+ return entries.filter((entry) => includeAssets || entry.checkpoint !== false);+}+export function formatDownloadBytes(bytes: number): string {+ if (!Number.isFinite(bytes) || bytes <= 0) return "Size unknown";+ if (bytes >= 1e12) return `${(bytes / 1e12).toFixed(1)} TB`;+ if (bytes >= 1e9) return `${(bytes / 1e9).toFixed(1)} GB`;+ if (bytes >= 1e6) return `${(bytes / 1e6).toFixed(1)} MB`;+ return `${Math.ceil(bytes / 1e3)} KB`;+}+export function assetLabel(entry: PlannedDownloadEntry): string {+ const files = entry.files ?? [];+ const weights = files.filter((f) =>+ /\.(safetensors|gguf|bin|pt|pth|ckpt)$/i.test(f),+ );+ const encoder = weights.some((f) => /text_encoder|clip|t5|qwen.*vl/i.test(f));+ const decoder = weights.some((f) => /vae|decoder|codec/i.test(f));+ if (encoder && decoder) return "Encoder & decoder";+ if (encoder) return "Text encoder";+ if (decoder) return "Decoder & configuration";+ return entry.repoId.split("/").pop() || "Required files";+}++/** Preserve dependency order while presenting and transferring checkpoints first. */+export function checkpointFirst<T extends { checkpoint?: boolean }>(+ entries: readonly T[],+): T[] {+ return [+ ...entries.filter((e) => e.checkpoint !== false),+ ...entries.filter((e) => e.checkpoint === false),+ ];+}diff --git a/studio/frontend/src/features/hub/download-manager/use-hub-download-queue.ts b/studio/frontend/src/features/hub/download-manager/use-hub-download-queue.tsnew file mode 100644index 00000000000..f0669329586--- /dev/null+++ b/studio/frontend/src/features/hub/download-manager/use-hub-download-queue.ts@@ -0,0 +1,121 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { checkpointFirst } from "./required-assets";+import { useEffect, useRef } from "react";+import { create } from "zustand";+import {+ AUTH_SESSION_CLEARED_EVENT,+ AUTH_SESSION_STORED_EVENT,+} from "@/features/auth";+import { useDownloadManagerStore } from "./download-manager-controller";+import { toast } from "@/lib/toast";+import {+ useStagedDownload,+ type StagedDownloadEntry,+} from "./use-staged-download";+export type Plan = {+ id: number;+ origin?: { repoId: string; filename?: string };+ entries: StagedDownloadEntry[];+ remaining: StagedDownloadEntry[];+};+let nextId = 0;+export const useHubQueue = create<{ plans: Plan[] }>(() => ({ plans: [] }));+export function enqueueHubDownload(+ entries: StagedDownloadEntry[],+ origin?: { repoId: string; filename?: string },+) {+ if (!entries.length) return;+ entries = checkpointFirst(entries);+ const key = (rows: StagedDownloadEntry[]) =>+ JSON.stringify(rows.map((e) => [e.repoId, [...e.files].sort()]));+ useHubQueue.setState((state) =>+ state.plans.some((p) => key(p.entries) === key(entries))+ ? state+ : {+ plans: [+ ...state.plans,+ { id: ++nextId, origin, entries, remaining: entries },+ ],+ },+ );+}+export function useHubDownloadQueue() {+ const plan = useHubQueue((s) => s.plans[0]);+ const started = useRef<number | null>(null);+ const finish = () =>+ useHubQueue.setState((s) => ({+ plans: s.plans.filter((p) => p.id !== started.current),+ }));+ const { stage, remaining } = useStagedDownload({+ scopeId: "hub-assets",+ onReady: () => {+ finish();+ toast.success("Download complete", {+ description: "Select the model when you are ready to load it.",+ });+ },+ onCancelled: finish,+ });+ useEffect(() => {+ if (!remaining) return;+ useHubQueue.setState((s) => ({+ plans: s.plans.map((p) =>+ p.id === started.current ? { ...p, remaining } : p,+ ),+ }));+ }, [remaining]);+ useEffect(() => {+ const reset = () => {+ useHubQueue.setState({ plans: [] });+ started.current = null;+ stage([]);+ };+ window.addEventListener(AUTH_SESSION_CLEARED_EVENT, reset);+ window.addEventListener(AUTH_SESSION_STORED_EVENT, reset);+ return () => {+ window.removeEventListener(AUTH_SESSION_CLEARED_EVENT, reset);+ window.removeEventListener(AUTH_SESSION_STORED_EVENT, reset);+ };+ }, [stage]);+ useEffect(() => {+ if (!plan || started.current === plan.id) return;+ started.current = plan.id;+ stage(plan.entries);+ }, [plan, stage]);+}++export function useHubDownloadPlan(repoId: string, filename?: string) {+ return useHubQueue((s) =>+ s.plans.find((p) =>+ p.origin+ ? p.origin.repoId === repoId && p.origin.filename === filename+ : p.entries.some(+ (e) =>+ e.repoId === repoId &&+ e.checkpoint !== false &&+ (!filename || e.files.includes(filename)),+ ),+ ),+ );+}+export function useQueuedHubEntries() {+ const plans = useHubQueue((s) => s.plans);+ const jobs = useDownloadManagerStore((s) => s.jobs);+ return plans.flatMap((p) =>+ p.remaining+ .filter(+ (e) =>+ !Object.values(jobs).some(+ (j) =>+ j.variant === "@hub-assets" &&+ j.repoId === e.repoId &&+ (j.state === "running" || j.state === "cancelling") &&+ e.files.length === j.scopedFiles?.length &&+ e.files.every((f) => j.scopedFiles?.includes(f)),+ ),+ )+ .map((e) => ({ ...e, planId: p.id })),+ );+}diff --git a/studio/frontend/src/features/hub/download-manager/use-staged-download.ts b/studio/frontend/src/features/hub/download-manager/use-staged-download.tsindex a36f1e7c348..0d7d870ea7e 100644--- a/studio/frontend/src/features/hub/download-manager/use-staged-download.ts+++ b/studio/frontend/src/features/hub/download-manager/use-staged-download.ts@@ -169,5 +169,5 @@ export function useStagedDownload({[downloadedBytes, totalBytes, plan],);- return { stage, staging: queue !== null, progress };+ return { stage, remaining: queue, staging: queue !== null, progress };}diff --git a/studio/frontend/tests/download-panel-not-permanent.test.ts b/studio/frontend/tests/download-panel-not-permanent.test.tsindex 6d8ba0f7374..8679c03d62c 100644--- a/studio/frontend/tests/download-panel-not-permanent.test.ts+++ b/studio/frontend/tests/download-panel-not-permanent.test.ts@@ -115,7 +115,11 @@ function isEmptyTest(node: ts.Node, jobKeys: string): boolean {type Truth = true | false | null;function underAnEmptyList(node: ts.Node, jobKeys: string): Truth {- if (isEmptyTest(node, jobKeys)) return true;+ // Queued plans show before their first job exists, so the panel hides only when both are empty.+ const queued = panelComponent().body?.statements.flatMap(statement =>+ ts.isVariableStatement(statement) ? [...statement.declarationList.declarations] : []+ ).find(declaration => declaration.initializer?.getText() === "useQueuedHubEntries()")?.name.getText();+ if (isEmptyTest(node, jobKeys) || (queued && isEmptyTest(node, queued))) return true;if (ts.isParenthesizedExpression(node)) {return underAnEmptyList(node.expression, jobKeys);}diff --git a/studio/frontend/tests/media-plan-failure-fallback.test.ts b/studio/frontend/tests/media-plan-failure-fallback.test.tsnew file mode 100644index 00000000000..2439a42b4a5--- /dev/null+++ b/studio/frontend/tests/media-plan-failure-fallback.test.ts@@ -0,0 +1,28 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Offline the plan fails; a load must fall back to its inline download or a cached model cannot load.++import assert from "node:assert/strict";+import test from "node:test";++import { readSrc } from "./helpers/kit.ts";++test("images: only a download-only pick refuses a plan_failed plan", () => {+ const source = readSrc("features/images/images-page.tsx");+ assert.match(source, /if \(downloadOnly && plan\.plan_failed\) \{/);+ assert.doesNotMatch(source, /toast\.error\("Could not check required files"/);+});++test("video: a failed plan falls back to the load", () => {+ const source = readSrc("features/video/video-page.tsx");+ assert.doesNotMatch(source, /if \(plan\.plan_failed\) throw/);+ assert.doesNotMatch(source, /toast\.error\("Could not check required files"/);+});++test("audio: a downloaded TTS model still loads when its plan errors", () => {+ const source = readSrc("features/audio/audio-page.tsx");+ const start = source.indexOf("plan = await getAudioDownloadPlan(");+ const fallback = source.slice(start, source.indexOf("const plannedEntries = plan.entries;", start));+ assert.match(fallback, /if \(meta\.isDownloaded === true\) \{\s*void loadTtsModelRef\.current\(/);+});diff --git a/studio/frontend/tests/required-assets.test.ts b/studio/frontend/tests/required-assets.test.tsnew file mode 100644index 00000000000..d6b68c2dbef--- /dev/null+++ b/studio/frontend/tests/required-assets.test.ts@@ -0,0 +1,77 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import {+ checkpointFirst,+ assetLabel,+ additionalAssetDownloads,+ selectDownloadEntries,+ downloadBytes,+ formatDownloadBytes,+} from "../src/features/hub/download-manager/required-assets.ts";+const model = {+ repoId: "m",+ files: ["model.gguf"],+ checkpoint: true,+ bytes: 6.3e9,+};+const assets = {+ repoId: "a",+ files: ["encoder.bin"],+ checkpoint: false,+ bytes: 10.8e9,+};+test("model-only preserves checkpoints and excludes explicitly identified assets", () => {+ assert.deepEqual(selectDownloadEntries([model, assets], false), [model]);+ assert.deepEqual(selectDownloadEntries([model, assets], true), [+ model,+ assets,+ ]);+ assert.equal(formatDownloadBytes(downloadBytes([model, assets])), "17.1 GB");+});+test("unknown-size assets still need disclosure; an absent marker is not an asset", () => {+ const unsized = { ...assets, bytes: 0 };+ assert.deepEqual(+ additionalAssetDownloads([model, unsized, { repoId: "legacy", bytes: 2 }]),+ [unsized],+ );+ assert.equal(formatDownloadBytes(0), "Size unknown");+});+test("cache-aware plans with only checkpoints do not request an asset download", () => {+ assert.deepEqual(additionalAssetDownloads([model]), []);+ assert.deepEqual(additionalAssetDownloads([]), []);+});++test("encoder configuration does not mislabel a decoder asset group", () => {+ assert.equal(+ assetLabel({+ repoId: "unsloth/Qwen-Image-2.1",+ bytes: 1.4e9,+ files: [+ "text_encoder/config.json",+ "text_encoder/model.safetensors.index.json",+ "vae/diffusion_pytorch_model.safetensors",+ "processor/tokenizer.json",+ ],+ }),+ "Decoder & configuration",+ );+ assert.equal(+ assetLabel({+ repoId: "unsloth/Qwen-Image-2.1-FP8",+ bytes: 9.4e9,+ files: ["Qwen-Image-2.1-text_encoder-FP8.safetensors"],+ }),+ "Text encoder",+ );+});++test("encoder-first plans download the checkpoint first without mutating the plan", () => {+ const decoder = { ...assets, repoId: "decoder" };+ const original = [assets, model, decoder];+ assert.deepEqual(checkpointFirst(original), [model, assets, decoder]);+ assert.deepEqual(original, [assets, model, decoder]);+ assert.deepEqual(checkpointFirst([assets, decoder]), [assets, decoder]);+});