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
Fix on-device GGUF image/video picks asking for a quantization (#8149)
Michael Han7ff60bec2602
diff --git a/studio/frontend/src/app/routes/images.tsx b/studio/frontend/src/app/routes/images.tsxindex ccba6e34878..5608fd64e24 100644--- a/studio/frontend/src/app/routes/images.tsx+++ b/studio/frontend/src/app/routes/images.tsx@@ -10,12 +10,16 @@ export const Route = createRoute({getParentRoute: () => rootRoute,path: "/images",staticData: { title: "Images" },- // A diffusion pick made from the chat picker arrives here as ?model= (+ ?quant=), which the page loads and then clears.+ // A chat-picker pick arrives as ?model= (+ ?quant= for an exact filename, ?ggufQuant= for a label the page resolves),+ // which the page loads and then clears.validateSearch: (search: Record<string, unknown>,- ): { model?: string; quant?: string } => ({+ ): { model?: string; quant?: string; ggufQuant?: string } => ({...(typeof search.model === "string" ? { model: search.model } : {}),...(typeof search.quant === "string" ? { quant: search.quant } : {}),+ ...(typeof search.ggufQuant === "string"+ ? { ggufQuant: search.ggufQuant }+ : {}),}),beforeLoad: () => requireAuth(),component: () => null,diff --git a/studio/frontend/src/app/routes/video.tsx b/studio/frontend/src/app/routes/video.tsxindex 999926d04ce..4a91b8118c1 100644--- a/studio/frontend/src/app/routes/video.tsx+++ b/studio/frontend/src/app/routes/video.tsx@@ -10,12 +10,16 @@ export const Route = createRoute({getParentRoute: () => rootRoute,path: "/video",staticData: { title: "Video" },- // A diffusion pick made from the chat picker arrives here as ?model= (+ ?quant=), which the page loads and then clears.+ // A chat-picker pick arrives as ?model= (+ ?quant= for an exact filename, ?ggufQuant= for a label the page resolves),+ // which the page loads and then clears.validateSearch: (search: Record<string, unknown>,- ): { model?: string; quant?: string } => ({+ ): { model?: string; quant?: string; ggufQuant?: string } => ({...(typeof search.model === "string" ? { model: search.model } : {}),...(typeof search.quant === "string" ? { quant: search.quant } : {}),+ ...(typeof search.ggufQuant === "string"+ ? { ggufQuant: search.ggufQuant }+ : {}),}),beforeLoad: () => requireAuth(),component: () => null,diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsxindex 201c95b1562..2e721617168 100644--- a/studio/frontend/src/features/images/images-page.tsx+++ b/studio/frontend/src/features/images/images-page.tsx@@ -73,7 +73,13 @@ import { ChevronDown } from "lucide-react";import { NegativePromptField } from "@/components/negative-prompt-field";import { cn } from "@/lib/utils";import { BlobUrlCache } from "@/lib/blob-url-cache";+import { resolveDiffusionGgufFilename } from "@/lib/diffusion-gguf-filename";+import { createPickGuard, runGgufRepoPick } from "@/lib/diffusion-gguf-pick";import { diffusionRoutePick } from "@/lib/diffusion-route-pick";+import {+ routedGgufFilename,+ routedGgufLabel,+} from "@/lib/diffusion-route-search";import { toast } from "@/lib/toast";import {@@ -1190,6 +1196,9 @@ export function ImagesPage({ active = true }: { active?: boolean }) {const lastLoadRevert = useRef<{ prev: typeof lastLoad.current } | null>(null);// A trained adapter awaiting deployment: applied once the base is loaded and LoRA-capable for its family.const pendingDeploy = useRef<{ loraId: string; family: string } | null>(null);+ // Which pick owns the page: resolving and staging are requests that do not set `busy`, so a pick can land on an awaiting+ // one. Lazy state, not a ref: a ref cannot be written during render.+ const [pickGuard] = useState(createPickGuard);const dismissLoadToast = useCallback(() => {if (loadToastId.current != null) toast.dismiss(loadToastId.current);@@ -1836,12 +1845,22 @@ export function ImagesPage({ active = true }: { active?: boolean }) {// The Advanced values the plan was built from. Staging does not set `busy`, so the user can change precision or LoRAs while// the download runs; without this the completed load would use the new values against the old file set.advanced: LoadAdvanced;+ // The pick that staged it: a download outlives its pick, so it must not evict a newer one when it lands.+ token: number;} | null>(null);const handleLoadRef = useRef(handleLoad);handleLoadRef.current = handleLoad;// Set when a staged download finished while this page was hidden: both diffusion pages stay mounted and a load evicts// whatever holds the GPU. The pick is not dropped; it fires when this page comes back.const stagedLoadDeferred = useRef(false);+ // A pick made while the download ran already owns the page; only the newest may load. `isLatest`, not `holds`: leaving the+ // page is not a new pick, and the deferred load below is exactly that case.+ const runStagedLoad = useCallback(() => {+ const pending = pendingStagedLoad.current;+ pendingStagedLoad.current = null;+ if (!pending || !pickGuard.isLatest(pending.token)) return;+ void handleLoadRef.current(pending.repoId, pending.opts, pending.advanced);+ }, [pickGuard]);const { stage } = useStagedDownload({scopeId: "diffusion",onReady: () => {@@ -1849,27 +1868,26 @@ export function ImagesPage({ active = true }: { active?: boolean }) {stagedLoadDeferred.current = true;return;}- const pending = pendingStagedLoad.current;- pendingStagedLoad.current = null;- if (pending) void handleLoadRef.current(pending.repoId, pending.opts, pending.advanced);+ runStagedLoad();},});useEffect(() => {if (!active || !stagedLoadDeferred.current) return;stagedLoadDeferred.current = false;- const pending = pendingStagedLoad.current;- pendingStagedLoad.current = null;- if (pending) void handleLoadRef.current(pending.repoId, pending.opts, pending.advanced);- }, [active]);+ runStagedLoad();+ }, [active, runStagedLoad]);// Stage a not-yet-downloaded hub pick, else load it directly. Returns true when the pick was accepted either way.+ // `token` lets an awaiting caller drop out: the plan below is a second window for a newer pick to take the page.const loadOrStage = useCallback(async (repoId: string,opts: { kind: "gguf" | "single_file" | "pipeline"; filename?: string },isDownloaded?: boolean,+ token?: number,): Promise<boolean> => {+ const owns = () => token === undefined || pickGuard.holds(token);if (isDownloaded !== false) return handleLoadRef.current(repoId, opts);// ONE snapshot for the plan and the load it fires: the download runs for minutes without setting `busy`.const advanced = currentLoadAdvanced(repoId);@@ -1889,8 +1907,10 @@ export function ImagesPage({ active = true }: { active?: boolean }) {// planned a quantized file set and staged too little. Same list handleLoad bakes.loras: advanced.loras,});+ // Superseded mid-plan: neither stage nor load, and leave `pendingStagedLoad` to its new owner.+ if (!owns()) return false;if (plan.entries.length > 0) {- pendingStagedLoad.current = { repoId, opts, advanced };+ pendingStagedLoad.current = { repoId, opts, advanced, token: token ?? pickGuard.claim() };stage(plan.entries.map((e) => ({repoId: e.repo_id,@@ -1904,15 +1924,65 @@ export function ImagesPage({ active = true }: { active?: boolean }) {} catch {// No plan (older backend, metadata hiccup): fall back to the load's own download.}+ if (!owns()) return false;return handleLoadRef.current(repoId, opts);},- [stage, currentLoadAdvanced],+ [stage, currentLoadAdvanced, pickGuard],+ );++ // A GGUF pick can arrive with only a repo id (a pinned row, a curated artifact, a local GGUF directory). The backend+ // rejects a gguf load with no filename and a pipeline load of a GGUF repo, so name the file from the listing first.+ const loadGgufRepoPick = useCallback(+ async (+ repoId: string,+ quantHint: string | null,+ isDownloaded?: boolean,+ localPath?: string | null,+ ): Promise<boolean> => {+ // Claimed here so every entry point is covered; the next pick's claim makes this one inert.+ const token = pickGuard.claim();+ const isCurrent = () => isMounted.current && pickGuard.holds(token);+ const prevQuant = quant;+ return runGgufRepoPick({+ isCurrent,+ resolve: () =>+ resolveDiffusionGgufFilename(repoId, {+ quant: quantHint,+ localPath,+ hfToken: hfApiToken(getHfToken()),+ }),+ // Still ambiguous (several quants, or the listing failed): only the expander can say which.+ onAmbiguous: () =>+ toast.error("Pick a quantization for this model to load it"),+ // Optimistic label, reverted if the load never starts, like the curated GGUF branch below.+ onResolved: (filename) => {+ quantRevert.current = { prev: prevQuant };+ setQuant(quantHint ?? filename);+ const d = defaultsFor(repoId);+ setSteps(d.steps);+ setGuidance(d.guidance);+ },+ onNotStarted: () => {+ setQuant(prevQuant);+ quantRevert.current = null;+ },+ load: (filename) =>+ loadOrStage(repoId, { kind: "gguf", filename }, isDownloaded, token),+ });+ },+ [loadOrStage, pickGuard, quant],);+ // A hidden page owns nothing: both stay mounted, so a resolution started here must not load after the user switched.+ useEffect(() => {+ if (!active) pickGuard.release();+ }, [active, pickGuard]);+// A diffusion model picked from the chat picker arrives as ?model= on this route. Load it once, then clear the params.const routeSearch = useSearch({ strict: false }) as {model?: string;quant?: string;+ ggufQuant?: string;};const navigateSelf = useNavigate();const handledRouteModel = useRef<string | null>(null);@@ -1927,18 +1997,48 @@ export function ImagesPage({ active = true }: { active?: boolean }) {handledRouteModel.current = null;return;}- const key = `${wanted}|${routeSearch.quant ?? ""}`;+ // `quant` is used verbatim as a filename; a label there (a hand-built link, an older producer) is resolved instead.+ // The two fields, not the object: `routeSearch` is rebuilt every render, so it would churn the deps.+ const routed = { quant: routeSearch.quant, ggufQuant: routeSearch.ggufQuant };+ const routedFilename = routedGgufFilename(routed);+ const routedLabel = routedGgufLabel(routed);+ const key = `${wanted}|${routeSearch.quant ?? ""}|${routeSearch.ggufQuant ?? ""}`;if (handledRouteModel.current === key) return;handledRouteModel.current = key;+ // This arrival owns the page like a direct pick, so a download staged by an earlier one cannot land on top.+ const token = pickGuard.claim();void navigateSelf({ to: "/images", search: {}, replace: true });+ // A label means a GGUF repo whatever the catalog says, and is not loadable, so resolve it instead of routing it as a+ // filename.+ if (routedLabel) {+ // Deferred, not inline: resolution is a request, and the load it fires owns the state a direct pick sets.+ void Promise.resolve().then(() =>+ loadGgufRepoPick(wanted, routedLabel, false),+ );+ return;+ }// Same catalog lookup a direct pick makes: the chat picker can only forward a GGUF filename.const pick = diffusionRoutePick(wanted,- routeSearch.quant,+ routedFilename ?? undefined,loadSpecFor(wanted, IMAGE_CATALOG),);- void loadOrStage(pick.repoId, pick.opts, false);- }, [active, routeSearch.model, routeSearch.quant, loadOrStage, navigateSelf]);+ // A curated GGUF artifact resolves to kind "gguf" with no filename: the catalog lists the repo, not its files.+ if (pick.opts.kind === "gguf" && !pick.opts.filename) {+ void Promise.resolve().then(() => loadGgufRepoPick(pick.repoId, null, false));+ return;+ }+ void loadOrStage(pick.repoId, pick.opts, false, token);+ }, [+ active,+ routeSearch.model,+ routeSearch.quant,+ routeSearch.ggufQuant,+ loadOrStage,+ loadGgufRepoPick,+ navigateSelf,+ pickGuard,+ ]);// Reload the current model with the current advanced options.const handleReapply = useCallback(() => {@@ -1951,6 +2051,9 @@ export function ImagesPage({ active = true }: { active?: boolean }) {(id: string, meta: ModelSelectorChangeMeta) => {// Ignore picks while a load/generation/unload is in flight: the backend rejects a second load with a 409.if (busy !== null) return;+ // This pick owns the page now, so one still awaiting a listing or a plan drops out. Before any branch: staging never+ // sets `busy`, so any pick can land on an awaiting one.+ const token = pickGuard.claim();// Curated non-GGUF model: load as a full pipeline or single-file safetensors.const spec = loadSpecFor(id, IMAGE_CATALOG);if (spec && spec.kind !== "gguf") {@@ -1958,7 +2061,12 @@ export function ImagesPage({ active = true }: { active?: boolean }) {const d = defaultsFor(id);setSteps(d.steps);setGuidance(d.guidance);- void loadOrStage(id, { kind: spec.kind, filename: spec.filename }, meta.isDownloaded);+ void loadOrStage(+ id,+ { kind: spec.kind, filename: spec.filename },+ meta.isDownloaded,+ token,+ );return;}// GGUF quant pick from the variant expander. Optimistic for instant picker feedback, but revert if the load fails to START@@ -1974,8 +2082,10 @@ export function ImagesPage({ active = true }: { active?: boolean }) {id,{ kind: "gguf", filename: meta.ggufFilename },meta.isDownloaded,+ token,).then((started) => {- if (!started) {+ // `quantRevert` is one slot, so only the pick that set the label may take it back.+ if (!started && pickGuard.holds(token)) {setQuant(prevQuant);quantRevert.current = null;}@@ -1989,8 +2099,14 @@ export function ImagesPage({ active = true }: { active?: boolean }) {const filename = slash >= 0 ? norm.slice(slash + 1) : norm;const dir = slash >= 0 ? norm.slice(0, slash) : ".";if (!filename.toLowerCase().endsWith(".gguf")) {- // A repo pick that reached here has no filename to load, and a quant label cannot be mapped back to one.- toast.error("Pick a quantization for this model to load it");+ // A repo id or local directory, not a file. The listing names its .gguf and the label picks between siblings; a+ // local pick passes its directory so the listing reads that path, not a hub repo.+ void loadGgufRepoPick(+ id,+ meta.ggufVariant ?? null,+ meta.isDownloaded,+ meta.source === "local" ? id : null,+ );return;}// A direct pick carries no curated variant label; surface the filename so the selector stops advertising the old quant.@@ -2030,6 +2146,18 @@ export function ImagesPage({ active = true }: { active?: boolean }) {});return;}+ // A GGUF repo with no filename: these used to fall through to the pipeline branch below, which the backend rejects+ // for a single-file GGUF repo.+ if (spec?.kind === "gguf" || meta.ggufVariant) {+ // An artifact that names its file short-circuits the listing; otherwise the label is the hint.+ void loadGgufRepoPick(+ id,+ spec?.filename ?? meta.ggufVariant ?? null,+ meta.isDownloaded,+ meta.source === "local" ? id : null,+ );+ return;+ }// Otherwise treat it as a full diffusers repo. The backend gates loads to unsloth/* repos or on-device paths.if (meta.source !== "local" && !id.toLowerCase().startsWith("unsloth/")) {toast.error("Only unsloth or on-device image models can be loaded here");@@ -2042,14 +2170,16 @@ export function ImagesPage({ active = true }: { active?: boolean }) {const d = defaultsFor(id);setSteps(d.steps);setGuidance(d.guidance);- void loadOrStage(id, { kind: "pipeline" }, meta.isDownloaded).then((started) => {- if (!started) {- setQuant(prevQuant);- quantRevert.current = null;- }- });+ void loadOrStage(id, { kind: "pipeline" }, meta.isDownloaded, token).then(+ (started) => {+ if (!started && pickGuard.holds(token)) {+ setQuant(prevQuant);+ quantRevert.current = null;+ }+ },+ );},- [busy, handleLoad, loadOrStage, quant],+ [busy, handleLoad, loadGgufRepoPick, loadOrStage, pickGuard, quant],);// Deploy a freshly-trained adapter from the Train tab: switch to Create, load the base, and queue the adapter for the LoRA discovery effect.@@ -2066,6 +2196,8 @@ export function ImagesPage({ active = true }: { active?: boolean }) {toast.error("Could not resolve the trained adapter's name.");return;}+ // The deploy owns the page now: a resolving pick or a staged download would load over the base it is about to.+ pickGuard.cancel();pendingDeploy.current = { loraId: stem, family: args.family };if (args.trigger.trim()) setPrompt(args.trigger.trim());setPageMode("create");@@ -2077,11 +2209,13 @@ export function ImagesPage({ active = true }: { active?: boolean }) {if (!started) pendingDeploy.current = null;});},- [busy, handleLoad, setPageMode],+ [busy, handleLoad, pickGuard, setPageMode],);const handleUnload = useCallback(async () => {// Ejecting cancels any in-flight replacement load, so tear down its client-side tracking too, or the toast leaks forever.+ // Cancel, not release: a resolving pick or a staged download would load back what was just ejected.+ pickGuard.cancel();if (pollTimer.current) clearTimeout(pollTimer.current);pollTimer.current = null;dismissLoadToast();@@ -2099,7 +2233,7 @@ export function ImagesPage({ active = true }: { active?: boolean }) {} finally {setBusy(null);}- }, [refreshStatus, dismissLoadToast]);+ }, [refreshStatus, dismissLoadToast, pickGuard]);const handleGenerate = useCallback(async () => {if (!prompt.trim()) {diff --git a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsxindex 571b32789a1..54e2816f4f0 100644--- a/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx+++ b/studio/frontend/src/features/model-picker/components/model-selector/pickers.tsx@@ -58,6 +58,7 @@ import {useOnlineStatus,} from "@/features/hub";import { useDebouncedValue, useGpuInfo, useInferenceGpuInfo } from "@/hooks";+import { diffusionRouteSearch } from "@/lib/diffusion-route-search";import { extractParamLabel } from "@/lib/model-size";import { toast } from "@/lib/toast";import { cn, formatCompact } from "@/lib/utils";@@ -2651,8 +2652,9 @@ export function HubModelPicker({if (page) {void navigateToPage({to: `/${page}`,- // The target page uses this verbatim as the gguf filename, so it must be ggufFilename (an exact repo filename), never ggufVariant (a label like "Q4_K_M", which routed a file that does not exist). No filename means a curated non-GGUF pick.- search: { model: id, quant: meta.ggufFilename ?? undefined },+ // `quant` is used verbatim as the gguf filename, so a label like "Q4_K_M" rides ggufQuant instead; dropping it+ // made every non-curated GGUF repo arrive as a bare repo id.+ search: diffusionRouteSearch(id, meta),});return;}@@ -3462,6 +3464,9 @@ export function HubModelPicker({isLora: false,ggufVariant: entry.quant,isDownloaded: true,+ // The row loads one quant, so it is a GGUF pick like the expander's; without this the pages asked for a+ // pipeline, which a GGUF repo rejects. No filename: the pin stores a label, resolved against the listing.+ isGguf: true,})}vramStatus={null}diff --git a/studio/frontend/src/features/video/video-page.tsx b/studio/frontend/src/features/video/video-page.tsxindex 818500e739e..dd2bd832a0f 100644--- a/studio/frontend/src/features/video/video-page.tsx+++ b/studio/frontend/src/features/video/video-page.tsx@@ -65,7 +65,13 @@ import { formatBytes, formatEta } from "@/features/hub/lib/format";import { useNavigate, useSearch } from "@tanstack/react-router";import { useStagedDownload } from "@/features/hub/download-manager";import { cn } from "@/lib/utils";+import { resolveDiffusionGgufFilename } from "@/lib/diffusion-gguf-filename";+import { createPickGuard, runGgufRepoPick } from "@/lib/diffusion-gguf-pick";import { diffusionRoutePick } from "@/lib/diffusion-route-pick";+import {+ routedGgufFilename,+ routedGgufLabel,+} from "@/lib/diffusion-route-search";import { toast } from "@/lib/toast";import {@@ -631,6 +637,9 @@ function VideoGenerator({ active = true }: { active?: boolean }) {// The Reapply target (and its canReapply flag) to restore if the optimistic swap fails: handleLoad overwrites lastLoad at// load start, and a load failing AFTER that leaves the previous model resident, so the poll rolls it back.const lastLoadRevert = useRef<{ prev: typeof lastLoad.current; canReapply: boolean } | null>(null);+ // Which pick owns the page: resolving and staging are requests that do not set `busy`, so a pick can land on an awaiting+ // one. Lazy state, not a ref: a ref cannot be written during render.+ const [pickGuard] = useState(createPickGuard);const dismissLoadToast = useCallback(() => {if (loadToastId.current != null) toast.dismiss(loadToastId.current);@@ -1178,11 +1187,21 @@ function VideoGenerator({ active = true }: { active?: boolean }) {const pendingStagedLoad = useRef<{repoId: string;opts: { kind: "gguf" | "single_file" | "pipeline"; filename?: string };+ // The pick that staged it: a download outlives its pick, so it must not evict a newer one when it lands.+ token: number;} | null>(null);const handleLoadRef = useRef(handleLoad);handleLoadRef.current = handleLoad;// A download finishing while this page is hidden must not evict the model the visible page loaded. The pick is held, not dropped.const stagedLoadDeferred = useRef(false);+ // A pick made while the download ran already owns the page; only the newest may load. `isLatest`, not `holds`: leaving the+ // page is not a new pick, and the deferred load below is exactly that case.+ const runStagedLoad = useCallback(() => {+ const pending = pendingStagedLoad.current;+ pendingStagedLoad.current = null;+ if (!pending || !pickGuard.isLatest(pending.token)) return;+ void handleLoadRef.current(pending.repoId, pending.opts);+ }, [pickGuard]);const { stage } = useStagedDownload({scopeId: "diffusion",onReady: () => {@@ -1190,27 +1209,26 @@ function VideoGenerator({ active = true }: { active?: boolean }) {stagedLoadDeferred.current = true;return;}- const pending = pendingStagedLoad.current;- pendingStagedLoad.current = null;- if (pending) void handleLoadRef.current(pending.repoId, pending.opts);+ runStagedLoad();},});useEffect(() => {if (!active || !stagedLoadDeferred.current) return;stagedLoadDeferred.current = false;- const pending = pendingStagedLoad.current;- pendingStagedLoad.current = null;- if (pending) void handleLoadRef.current(pending.repoId, pending.opts);- }, [active]);+ runStagedLoad();+ }, [active, runStagedLoad]);// Stage a not-yet-downloaded hub pick, else load it directly.+ // `token` lets an awaiting caller drop out: the plan below is a second window for a newer pick to take the page.const loadOrStage = useCallback(async (repoId: string,opts: { kind: "gguf" | "single_file" | "pipeline"; filename?: string },isDownloaded?: boolean,+ token?: number,): Promise<boolean> => {+ const owns = () => token === undefined || pickGuard.holds(token);if (isDownloaded !== false) return handleLoadRef.current(repoId, opts);try {const plan = await getVideoDownloadPlan({@@ -1220,8 +1238,10 @@ function VideoGenerator({ active = true }: { active?: boolean }) {// Same token handleLoad sends: without it the metadata lookup fails on a gated base and the plan drops the companion entry, so the load pulls those files inline.hf_token: hfApiToken(getHfToken()),});+ // Superseded mid-plan: neither stage nor load, and leave `pendingStagedLoad` to its new owner.+ if (!owns()) return false;if (plan.entries.length > 0) {- pendingStagedLoad.current = { repoId, opts };+ pendingStagedLoad.current = { repoId, opts, token: token ?? pickGuard.claim() };stage(plan.entries.map((e) => ({repoId: e.repo_id,@@ -1235,15 +1255,66 @@ function VideoGenerator({ active = true }: { active?: boolean }) {} catch {// No plan (older backend, metadata hiccup): fall back to the load's own download.}+ if (!owns()) return false;return handleLoadRef.current(repoId, opts);},- [stage],+ [stage, pickGuard],+ );++ // A GGUF pick can arrive with only a repo id (a pinned row, a curated artifact, a local GGUF directory). The backend+ // rejects a gguf load with no filename and a pipeline load of a GGUF repo, so name the file from the listing first.+ const loadGgufRepoPick = useCallback(+ async (+ repoId: string,+ quantHint: string | null,+ isDownloaded?: boolean,+ localPath?: string | null,+ ): Promise<boolean> => {+ // Claimed here so every entry point is covered; the next pick's claim makes this one inert.+ const token = pickGuard.claim();+ const isCurrent = () => isMounted.current && pickGuard.holds(token);+ const prevQuant = quant;+ return runGgufRepoPick({+ isCurrent,+ resolve: () =>+ resolveDiffusionGgufFilename(repoId, {+ quant: quantHint,+ localPath,+ hfToken: hfApiToken(getHfToken()),+ }),+ // Still ambiguous (several quants, or the listing failed): only the expander can say which.+ onAmbiguous: () =>+ toast.error("Pick a quantization for this model to load it"),+ // Optimistic label, reverted if the load never starts, like the curated GGUF branch below.+ onResolved: (filename) => {+ quantRevert.current = { prev: prevQuant };+ setQuant(quantHint ?? filename);+ // Filename-qualified like the expander branch: the LTX variant lives in the checkpoint name, not the repo id.+ const d = defaultsFor(`${repoId}/${filename}`);+ setSteps(d.steps);+ setGuidance(d.guidance);+ },+ onNotStarted: () => {+ setQuant(prevQuant);+ quantRevert.current = null;+ },+ load: (filename) =>+ loadOrStage(repoId, { kind: "gguf", filename }, isDownloaded, token),+ });+ },+ [loadOrStage, pickGuard, quant],);+ // A hidden page owns nothing: both stay mounted, so a resolution started here must not load after the user switched.+ useEffect(() => {+ if (!active) pickGuard.release();+ }, [active, pickGuard]);+// A diffusion model picked from the chat picker arrives as ?model= on this route. Load it once, then clear the params.const routeSearch = useSearch({ strict: false }) as {model?: string;quant?: string;+ ggufQuant?: string;};const navigateSelf = useNavigate();const handledRouteModel = useRef<string | null>(null);@@ -1257,18 +1328,48 @@ function VideoGenerator({ active = true }: { active?: boolean }) {handledRouteModel.current = null;return;}- const key = `${wanted}|${routeSearch.quant ?? ""}`;+ // `quant` is used verbatim as a filename; a label there (a hand-built link, an older producer) is resolved instead.+ // The two fields, not the object: `routeSearch` is rebuilt every render, so it would churn the deps.+ const routed = { quant: routeSearch.quant, ggufQuant: routeSearch.ggufQuant };+ const routedFilename = routedGgufFilename(routed);+ const routedLabel = routedGgufLabel(routed);+ const key = `${wanted}|${routeSearch.quant ?? ""}|${routeSearch.ggufQuant ?? ""}`;if (handledRouteModel.current === key) return;handledRouteModel.current = key;+ // This arrival owns the page like a direct pick, so a download staged by an earlier one cannot land on top.+ const token = pickGuard.claim();void navigateSelf({ to: "/video", search: {}, replace: true });+ // A label means a GGUF repo whatever the catalog says, and is not loadable, so resolve it instead of routing it as a+ // filename.+ if (routedLabel) {+ // Deferred, not inline: resolution is a request, and the load it fires owns the state a direct pick sets.+ void Promise.resolve().then(() =>+ loadGgufRepoPick(wanted, routedLabel, false),+ );+ return;+ }// Same catalog lookup a direct pick makes: the chat picker can only forward a GGUF filename, so a curated single-file artifact would load as a pipeline and fail.const pick = diffusionRoutePick(wanted,- routeSearch.quant,+ routedFilename ?? undefined,loadSpecFor(wanted, VIDEO_CATALOG),);- void loadOrStage(pick.repoId, pick.opts, false);- }, [active, routeSearch.model, routeSearch.quant, loadOrStage, navigateSelf]);+ // A curated GGUF artifact resolves to kind "gguf" with no filename: the catalog lists the repo, not its files.+ if (pick.opts.kind === "gguf" && !pick.opts.filename) {+ void Promise.resolve().then(() => loadGgufRepoPick(pick.repoId, null, false));+ return;+ }+ void loadOrStage(pick.repoId, pick.opts, false, token);+ }, [+ active,+ routeSearch.model,+ routeSearch.quant,+ routeSearch.ggufQuant,+ loadOrStage,+ loadGgufRepoPick,+ navigateSelf,+ pickGuard,+ ]);// Reload the current model with the current advanced options.const handleReapply = useCallback(() => {@@ -1281,6 +1382,9 @@ function VideoGenerator({ active = true }: { active?: boolean }) {(id: string, meta: ModelSelectorChangeMeta) => {// Ignore picks while a load/generation/unload is in flight.if (busy !== null) return;+ // This pick owns the page now, so one still awaiting a listing or a plan drops out. Before any branch: staging never+ // sets `busy`, so any pick can land on an awaiting one.+ const token = pickGuard.claim();// Curated non-GGUF model: load as a full pipeline.const spec = loadSpecFor(id, VIDEO_CATALOG);if (spec && spec.kind !== "gguf") {@@ -1290,7 +1394,12 @@ function VideoGenerator({ active = true }: { active?: boolean }) {const d = defaultsFor(spec.filename ? `${id}/${spec.filename}` : id);setSteps(d.steps);setGuidance(d.guidance);- void loadOrStage(id, { kind: spec.kind, filename: spec.filename }, meta.isDownloaded);+ void loadOrStage(+ id,+ { kind: spec.kind, filename: spec.filename },+ meta.isDownloaded,+ token,+ );return;}// GGUF quant pick from the variant expander. Optimistic for picker feedback, reverted if the load fails to START; the poll owns the after-start revert.@@ -1306,8 +1415,10 @@ function VideoGenerator({ active = true }: { active?: boolean }) {id,{ kind: "gguf", filename: meta.ggufFilename },meta.isDownloaded,+ token,).then((started) => {- if (!started) {+ // `quantRevert` is one slot, so only the pick that set the label may take it back.+ if (!started && pickGuard.holds(token)) {setQuant(prevQuant);quantRevert.current = null;}@@ -1321,8 +1432,14 @@ function VideoGenerator({ active = true }: { active?: boolean }) {const filename = slash >= 0 ? norm.slice(slash + 1) : norm;const dir = slash >= 0 ? norm.slice(0, slash) : ".";if (!filename.toLowerCase().endsWith(".gguf")) {- // No filename to load, and a quant label can't be mapped back to one.- toast.error("Pick a quantization for this model to load it");+ // A repo id or local directory, not a file. The listing names its .gguf and the label picks between siblings; a+ // local pick passes its directory so the listing reads that path, not a hub repo.+ void loadGgufRepoPick(+ id,+ meta.ggufVariant ?? null,+ meta.isDownloaded,+ meta.source === "local" ? id : null,+ );return;}const prevQuant = quant;@@ -1359,6 +1476,18 @@ function VideoGenerator({ active = true }: { active?: boolean }) {});return;}+ // A GGUF repo with no filename: these used to fall through to the pipeline branch below, which the backend rejects+ // for a single-file GGUF repo.+ if (spec?.kind === "gguf" || meta.ggufVariant) {+ // An artifact that names its file short-circuits the listing; otherwise the label is the hint.+ void loadGgufRepoPick(+ id,+ spec?.filename ?? meta.ggufVariant ?? null,+ meta.isDownloaded,+ meta.source === "local" ? id : null,+ );+ return;+ }// Otherwise treat it as a full diffusers repo. The backend gates loads to unsloth/* repos, the family bases, or on-device paths.if (meta.source !== "local" && !id.toLowerCase().startsWith("unsloth/")) {toast.error("Only unsloth or on-device video models can be loaded here");@@ -1368,12 +1497,14 @@ function VideoGenerator({ active = true }: { active?: boolean }) {const d = defaultsFor(id);setSteps(d.steps);setGuidance(d.guidance);- void loadOrStage(id, { kind: "pipeline" }, meta.isDownloaded);+ void loadOrStage(id, { kind: "pipeline" }, meta.isDownloaded, token);},- [busy, handleLoad, loadOrStage, quant],+ [busy, handleLoad, loadGgufRepoPick, loadOrStage, pickGuard, quant],);const handleUnload = useCallback(async () => {+ // Cancel, not release: a resolving pick or a staged download would load back what was just ejected.+ pickGuard.cancel();if (pollTimer.current) clearTimeout(pollTimer.current);pollTimer.current = null;dismissLoadToast();@@ -1390,7 +1521,7 @@ function VideoGenerator({ active = true }: { active?: boolean }) {} finally {setBusy(null);}- }, [refreshStatus, dismissLoadToast]);+ }, [refreshStatus, dismissLoadToast, pickGuard]);const handleCancelGenerate = useCallback(async () => {try {diff --git a/studio/frontend/src/lib/diffusion-gguf-filename.ts b/studio/frontend/src/lib/diffusion-gguf-filename.tsnew file mode 100644index 00000000000..d40a1b960d0--- /dev/null+++ b/studio/frontend/src/lib/diffusion-gguf-filename.ts@@ -0,0 +1,33 @@+// 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 { listGgufVariants } from "@/features/hub";+import { isGgufName, pickGgufFilename } from "./gguf-filename-pick";++/** The .gguf for a pick that arrived with only a repo id (and maybe a quant label). Shares the picker rows' cached listing,+ * so the row just clicked usually costs no request. Null when the repo is ambiguous or unreadable. */+export async function resolveDiffusionGgufFilename(+ repoId: string,+ options?: {+ quant?: string | null;+ localPath?: string | null;+ hfToken?: string;+ },+): Promise<string | null> {+ const quant = options?.quant?.trim() || null;+ // Already a filename: no listing needed.+ if (quant && isGgufName(quant)) return quant;+ try {+ const res = await listGgufVariants(repoId, options?.hfToken, {+ preferLocalCache: true,+ localPath: options?.localPath ?? null,+ });+ return pickGgufFilename(+ Array.isArray(res?.variants) ? res.variants : [],+ quant,+ );+ } catch {+ // Unreachable Hub or unreadable directory: the caller prompts instead.+ return null;+ }+}diff --git a/studio/frontend/src/lib/diffusion-gguf-pick.ts b/studio/frontend/src/lib/diffusion-gguf-pick.tsnew file mode 100644index 00000000000..a729b3a8780--- /dev/null+++ b/studio/frontend/src/lib/diffusion-gguf-pick.ts@@ -0,0 +1,72 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Ownership of a diffusion page's model pick across an await: resolving is a slow listing request and neither page sets+// `busy` for it. No app deps, so both pages share this and the ordering is testable.++/** Which pick owns the page. A claim invalidates every token handed out before it, so the newest pick wins. */+export interface PickGuard {+ claim(): number;+ /** Leave the page unowned without ending the pick: a page switch, an unmount. */+ release(): void;+ /** End the pick outright: an eject or a deploy, which the staged download must not undo. */+ cancel(): void;+ /** Is this token still the owner? False after a release, so nothing lands on a page nobody is looking at. */+ holds(token: number): boolean;+ /** Is this still the last pick made? Survives a release, so a staged download resumes on the way back. */+ isLatest(token: number): boolean;+}++export function createPickGuard(): PickGuard {+ let latest = 0;+ let owner = 0;+ return {+ claim: () => {+ latest += 1;+ owner = latest;+ return latest;+ },+ release: () => {+ owner = 0;+ },+ cancel: () => {+ // Past every token handed out, so nothing outstanding is the latest pick either.+ latest += 1;+ owner = 0;+ },+ holds: (token) => token !== 0 && token === owner,+ isLatest: (token) => token !== 0 && token === latest,+ };+}++/** The page's own halves of a repo-level GGUF pick. Only `isCurrent` is about staleness. */+export interface GgufRepoPickHandlers {+ /** The one .gguf this pick means, or null when the repo cannot name it. */+ resolve(): Promise<string | null>;+ isCurrent(): boolean;+ /** Nothing to load: several quants on disk, a stale label, or an unreadable listing. */+ onAmbiguous(): void;+ /** Optimistic quant label plus per-model defaults, applied before the load starts. */+ onResolved(filename: string): void;+ /** Undo `onResolved`: the load never started. */+ onNotStarted(): void;+ load(filename: string): Promise<boolean>;+}++/** Resolve a repo-level GGUF pick and load it; does nothing once the pick no longer owns the page. */+export async function runGgufRepoPick(+ handlers: GgufRepoPickHandlers,+): Promise<boolean> {+ const filename = await handlers.resolve();+ // Silent, not just load-free: a toast would blame a model the user has moved on from.+ if (!handlers.isCurrent()) return false;+ if (!filename) {+ handlers.onAmbiguous();+ return false;+ }+ handlers.onResolved(filename);+ const started = await handlers.load(filename);+ // `quantRevert` is one slot, so only the pick that set the label may take it back.+ if (!started && handlers.isCurrent()) handlers.onNotStarted();+ return started;+}diff --git a/studio/frontend/src/lib/diffusion-route-search.ts b/studio/frontend/src/lib/diffusion-route-search.tsnew file mode 100644index 00000000000..eddcb7130a0--- /dev/null+++ b/studio/frontend/src/lib/diffusion-route-search.ts@@ -0,0 +1,46 @@+// 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 { isGgufName } from "./gguf-filename-pick.ts";++/** What the chat picker puts in the URL when a diffusion pick routes to /images or /video. */+export interface DiffusionRouteSearch {+ model: string;+ /** An exact repo filename, never a label: the target page uses it verbatim as the gguf filename. */+ quant?: string;+ /** A quant label (`Q4_K_S`) for a pick that has no filename, e.g. a pinned row. The page resolves it against the listing. */+ ggufQuant?: string;+}++const trimmed = (value: string | null | undefined): string | null =>+ typeof value === "string" && value.trim().length > 0 ? value.trim() : null;++/** Search params for a diffusion pick routed out of the chat picker. The label rides its own param because `quant` is+ * consumed as a filename; forwarding the filename alone left a pinned row as a bare repo id that read as a pipeline. */+export function diffusionRouteSearch(+ model: string,+ meta: { ggufFilename?: string | null; ggufVariant?: string | null },+): DiffusionRouteSearch {+ const filename = trimmed(meta.ggufFilename);+ if (filename) return { model, quant: filename };+ const label = trimmed(meta.ggufVariant);+ return label ? { model, ggufQuant: label } : { model };+}++/** The exact .gguf a routed pick names, if it names one. */+export function routedGgufFilename(+ search: Pick<DiffusionRouteSearch, "quant">,+): string | null {+ const quant = trimmed(search.quant);+ return quant && isGgufName(quant) ? quant : null;+}++/** The quant label a routed pick carries. A non-filename in `quant` (hand-built link, older producer) is a label too, so it+ * joins ggufQuant to be resolved rather than posted verbatim. */+export function routedGgufLabel(+ search: Pick<DiffusionRouteSearch, "quant" | "ggufQuant">,+): string | null {+ const quant = trimmed(search.quant);+ if (quant && isGgufName(quant)) return null;+ return trimmed(search.ggufQuant) ?? quant;+}diff --git a/studio/frontend/src/lib/gguf-filename-pick.ts b/studio/frontend/src/lib/gguf-filename-pick.tsnew file mode 100644index 00000000000..2f711d2d698--- /dev/null+++ b/studio/frontend/src/lib/gguf-filename-pick.ts@@ -0,0 +1,59 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Picking the .gguf a repo-level pick means. No app deps so it stays testable; the request lives in diffusion-gguf-filename.ts.++/** A row of the repo's GGUF listing. Loose so an older response still resolves. */+export interface GgufFilenameCandidate {+ filename?: unknown;+ quant?: unknown;+ downloaded?: unknown;+}++function asName(value: unknown): string | null {+ return typeof value === "string" && value.length > 0 ? value : null;+}++export const isGgufName = (value: string): boolean =>+ value.toLowerCase().endsWith(".gguf");++/** The .gguf to load, given the listing and what the pick carried: a filename, a quant label, or nothing. A load needs a real+ * filename and a label is not one. Null when the repo is ambiguous, so the caller keeps its prompt. */+export function pickGgufFilename(+ variants: readonly GgufFilenameCandidate[],+ quant?: string | null,+): string | null {+ const listed = variants.flatMap((v) => {+ const filename = asName(v.filename);+ return filename && isGgufName(filename)+ ? [+ {+ filename,+ quant: asName(v.quant),+ downloaded: v.downloaded === true,+ },+ ]+ : [];+ });+ const wanted = quant?.trim() || null;++ // Already a filename. Prefer the listing's spelling, but honour an unlisted one: a failed listing must not lose the caller's.+ if (wanted && isGgufName(wanted)) {+ const match = listed.find(+ (v) => v.filename.toLowerCase() === wanted.toLowerCase(),+ );+ return match?.filename ?? wanted;+ }+ // A label. Downloaded first (a remote sibling can share it), and before the fallbacks so a stale label prompts.+ if (wanted) {+ const byLabel = listed.filter(+ (v) => v.quant?.toLowerCase() === wanted.toLowerCase(),+ );+ return (byLabel.find((v) => v.downloaded) ?? byLabel[0])?.filename ?? null;+ }+ // No label: only a lone file names itself. Downloaded first, so a fully listed remote repo resolves to the quant on disk.+ const downloaded = listed.filter((v) => v.downloaded);+ if (downloaded.length === 1) return downloaded[0].filename;+ if (listed.length === 1) return listed[0].filename;+ return null;+}diff --git a/studio/frontend/tests/diffusion-gguf-pick.test.ts b/studio/frontend/tests/diffusion-gguf-pick.test.tsnew file mode 100644index 00000000000..155261b1dd7--- /dev/null+++ b/studio/frontend/tests/diffusion-gguf-pick.test.ts@@ -0,0 +1,177 @@+// 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 {+ type GgufRepoPickHandlers,+ createPickGuard,+ runGgufRepoPick,+} from "../src/lib/diffusion-gguf-pick.ts";++/** A listing whose completion the test controls. */+function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((r) => {+ resolve = r;+ });+ return { promise, resolve };+}++const flush = () => new Promise((r) => setTimeout(r, 0));++/** Every side effect a pick may have, so a stale one can be asserted to have had none. */+function recorder(+ overrides: Partial<Omit<GgufRepoPickHandlers, "load">> & {+ /** What `load` reports back: false is "the load never started". */+ starts?: boolean | (() => boolean);+ } = {},+): { handlers: GgufRepoPickHandlers; log: string[] } {+ const { starts = true, ...rest } = overrides;+ const log: string[] = [];+ const handlers: GgufRepoPickHandlers = {+ resolve: () => Promise.resolve("model-Q4_K_S.gguf"),+ isCurrent: () => true,+ onAmbiguous: () => log.push("ambiguous"),+ onResolved: (filename) => log.push(`resolved:${filename}`),+ onNotStarted: () => log.push("reverted"),+ load: (filename) => {+ log.push(`load:${filename}`);+ return Promise.resolve(typeof starts === "function" ? starts() : starts);+ },+ ...rest,+ };+ return { handlers, log };+}++test("a resolved pick applies its label and loads", async () => {+ const { handlers, log } = recorder();+ assert.equal(await runGgufRepoPick(handlers), true);+ assert.deepEqual(log, [+ "resolved:model-Q4_K_S.gguf",+ "load:model-Q4_K_S.gguf",+ ]);+});++test("an unresolvable pick prompts and loads nothing", async () => {+ const { handlers, log } = recorder({ resolve: () => Promise.resolve(null) });+ assert.equal(await runGgufRepoPick(handlers), false);+ assert.deepEqual(log, ["ambiguous"]);+});++test("a load that never starts takes its own label back", async () => {+ const { handlers, log } = recorder({ starts: false });+ assert.equal(await runGgufRepoPick(handlers), false);+ assert.deepEqual(log, [+ "resolved:model-Q4_K_S.gguf",+ "load:model-Q4_K_S.gguf",+ "reverted",+ ]);+});++test("a superseded pick does nothing at all when its listing lands", async () => {+ // Not even the prompt: it would blame a model the user has already moved on from.+ const listing = deferred<string | null>();+ const { handlers, log } = recorder({+ resolve: () => listing.promise,+ isCurrent: () => false,+ });+ const done = runGgufRepoPick(handlers);+ listing.resolve("model-Q4_K_S.gguf");+ assert.equal(await done, false);+ assert.deepEqual(log, []);+});++test("a superseded pick does not prompt either", async () => {+ const { handlers, log } = recorder({+ resolve: () => Promise.resolve(null),+ isCurrent: () => false,+ });+ assert.equal(await runGgufRepoPick(handlers), false);+ assert.deepEqual(log, []);+});++test("a stale failure does not revert the newer selection's label", async () => {+ // quantRevert is one slot, so a late rollback would restore this pick's old label over the one that replaced it.+ let current = true;+ const { handlers, log } = recorder({+ isCurrent: () => current,+ // The next pick takes the page while this load is in flight, and the load then reports it never started.+ starts: () => {+ current = false;+ return false;+ },+ });+ assert.equal(await runGgufRepoPick(handlers), false);+ assert.deepEqual(log, [+ "resolved:model-Q4_K_S.gguf",+ "load:model-Q4_K_S.gguf",+ ]);+});++test("the newest pick owns the page, whatever order the listings land in", async () => {+ const guard = createPickGuard();+ const listings = [deferred<string | null>(), deferred<string | null>()];+ const log: string[] = [];+ const run = (index: number) => {+ const token = guard.claim();+ return runGgufRepoPick({+ resolve: () => listings[index].promise,+ isCurrent: () => guard.holds(token),+ onAmbiguous: () => log.push(`ambiguous:${index}`),+ onResolved: () => {},+ onNotStarted: () => {},+ load: (filename) => {+ log.push(`load:${index}:${filename}`);+ return Promise.resolve(true);+ },+ });+ };++ const first = run(0);+ await flush();+ const second = run(1);+ await flush();+ // The newer listing lands first, then the stale one.+ listings[1].resolve("b.gguf");+ await flush();+ listings[0].resolve("a.gguf");++ assert.deepEqual(await Promise.all([first, second]), [false, true]);+ assert.deepEqual(log, ["load:1:b.gguf"]);+});++test("releasing the page invalidates the pick holding it", () => {+ // A page switch, an unload or an unmount: nobody owns the page afterwards.+ const guard = createPickGuard();+ const token = guard.claim();+ assert.equal(guard.holds(token), true);+ guard.release();+ assert.equal(guard.holds(token), false);+ // And the token a release lands on is not claimable by an outstanding holder.+ assert.notEqual(guard.claim(), token);+});++test("an eject ends the pick, so a staged download does not come back", () => {+ // Release and cancel differ exactly here: leaving the page defers the staged load, ejecting drops it.+ const guard = createPickGuard();+ const staged = guard.claim();+ guard.cancel();+ assert.equal(guard.holds(staged), false);+ assert.equal(guard.isLatest(staged), false);+ // And the page is claimable again afterwards, with a token of its own.+ const next = guard.claim();+ assert.notEqual(next, staged);+ assert.equal(guard.holds(next), true);+});++test("a release is not a new pick, so a staged download still lands", () => {+ // Leaving the page defers the staged load rather than dropping it; only another pick may take it.+ const guard = createPickGuard();+ const staged = guard.claim();+ guard.release();+ assert.equal(guard.isLatest(staged), true);+ guard.claim();+ assert.equal(guard.isLatest(staged), false);+});diff --git a/studio/frontend/tests/diffusion-route-search.test.ts b/studio/frontend/tests/diffusion-route-search.test.tsnew file mode 100644index 00000000000..583bbe7aaf4--- /dev/null+++ b/studio/frontend/tests/diffusion-route-search.test.ts@@ -0,0 +1,105 @@+// 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 {+ type DiffusionRouteSearch,+ diffusionRouteSearch,+ routedGgufFilename,+ routedGgufLabel,+} from "../src/lib/diffusion-route-search.ts";++const REPO = "unsloth/Z-Image-Turbo-GGUF";++test("an expander pick routes its exact filename as the quant", () => {+ assert.deepEqual(+ diffusionRouteSearch(REPO, {+ ggufFilename: "z-image-turbo-Q4_K_S.gguf",+ ggufVariant: "Q4_K_S",+ }),+ { model: REPO, quant: "z-image-turbo-Q4_K_S.gguf" },+ );+});++test("a pinned pick routes its label, and never as the quant", () => {+ // The target reads `quant` verbatim as a filename, so a label there routes a file that does not exist.+ const search: DiffusionRouteSearch = diffusionRouteSearch(REPO, {+ ggufVariant: "Q4_K_S",+ });+ // Asserted before the shape below: deepEqual narrows `search` to the literal it matched.+ assert.equal(search.quant, undefined);+ assert.deepEqual(search, { model: REPO, ggufQuant: "Q4_K_S" });+});++test("a non-catalog repo keeps its label too", () => {+ // The gap this closes: with no catalog entry for the repo, the label is the page's only evidence that it is GGUF.+ assert.deepEqual(+ diffusionRouteSearch("QuantStack/SomeDiffusion-GGUF", {+ ggufVariant: "Q6_K",+ }),+ { model: "QuantStack/SomeDiffusion-GGUF", ggufQuant: "Q6_K" },+ );+});++test("a curated non-GGUF pick routes the model alone", () => {+ assert.deepEqual(diffusionRouteSearch("unsloth/FLUX.1-schnell", {}), {+ model: "unsloth/FLUX.1-schnell",+ });+});++test("blank metadata is dropped rather than routed", () => {+ assert.deepEqual(+ diffusionRouteSearch(REPO, { ggufFilename: " ", ggufVariant: "" }),+ { model: REPO },+ );+ // A filename wins over a label, and both are trimmed.+ assert.deepEqual(+ diffusionRouteSearch(REPO, {+ ggufFilename: " a-Q8_0.gguf ",+ ggufVariant: " Q8_0 ",+ }),+ { model: REPO, quant: "a-Q8_0.gguf" },+ );+ assert.deepEqual(+ diffusionRouteSearch(REPO, { ggufFilename: null, ggufVariant: " Q8_0 " }),+ { model: REPO, ggufQuant: "Q8_0" },+ );+});++test("an arrival naming a real file loads it, label or no label", () => {+ const search = { model: "m", quant: "a-Q8_0.gguf", ggufQuant: "Q4_K_S" };+ assert.equal(routedGgufFilename(search), "a-Q8_0.gguf");+ assert.equal(+ routedGgufLabel(search),+ null,+ "the exact filename wins and needs no listing",+ );+});++test("a label left in the filename slot is resolved, not posted", () => {+ // A hand-built link, or a producer predating the split: posting "Q4_K_S" as a filename is a certain error.+ assert.equal(routedGgufLabel({ quant: "Q4_K_S" }), "Q4_K_S");+ assert.equal(routedGgufFilename({ quant: "Q4_K_S" }), null);+});++test("an arrival with only the label slot resolves it", () => {+ assert.equal(routedGgufLabel({ ggufQuant: "Q6_K" }), "Q6_K");+ assert.equal(+ routedGgufFilename({}),+ null,+ "and nothing lands in the filename slot",+ );+});++test("an arrival with neither leaves the old path alone", () => {+ assert.equal(routedGgufLabel({}), null);+ assert.equal(routedGgufFilename({}), null);+ assert.equal(routedGgufLabel({ quant: " ", ggufQuant: "" }), null);+});++test("case and whitespace do not change which slot a value belongs to", () => {+ assert.equal(routedGgufFilename({ quant: " A-Q8_0.GGUF " }), "A-Q8_0.GGUF");+ assert.equal(routedGgufLabel({ ggufQuant: " Q4_K_S " }), "Q4_K_S");+});diff --git a/studio/frontend/tests/gguf-filename-pick.test.ts b/studio/frontend/tests/gguf-filename-pick.test.tsnew file mode 100644index 00000000000..95e79b01514--- /dev/null+++ b/studio/frontend/tests/gguf-filename-pick.test.ts@@ -0,0 +1,75 @@+// 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 { pickGgufFilename } from "../src/lib/gguf-filename-pick.ts";++const Q4 = {+ filename: "z-image-turbo-Q4_K_S.gguf",+ quant: "Q4_K_S",+ downloaded: true,+};+const Q8 = {+ filename: "z-image-turbo-Q8_0.gguf",+ quant: "Q8_0",+ downloaded: false,+};++test("a repo holding one quant names it without a label", () => {+ // The On Device row with a lone quant chip: the click carries only the repo.+ assert.equal(pickGgufFilename([Q4]), Q4.filename);+});++test("one downloaded quant wins over undownloaded siblings", () => {+ assert.equal(pickGgufFilename([Q4, Q8]), Q4.filename);+});++test("a quant label resolves to that quant's real filename", () => {+ // Filenames do not follow the repo name, so a label is never a filename.+ assert.equal(pickGgufFilename([Q4, Q8], "Q8_0"), Q8.filename);+ assert.equal(pickGgufFilename([Q4, Q8], "q8_0"), Q8.filename);+});++test("a label prefers the copy on disk when both are listed", () => {+ const remoteDup = {+ ...Q4,+ filename: "mirror/z-image.gguf",+ downloaded: false,+ };+ assert.equal(pickGgufFilename([remoteDup, Q4], "Q4_K_S"), Q4.filename);+});++test("a label that matches nothing does not fall back to the sole file", () => {+ // A pin left from a deleted quant must prompt, not load another quant.+ assert.equal(pickGgufFilename([Q4], "Q2_K"), null);+});++test("an exact filename passes through, normalised to the listing", () => {+ assert.equal(pickGgufFilename([Q4], Q4.filename), Q4.filename);+ assert.equal(+ pickGgufFilename([Q4], "Z-IMAGE-TURBO-Q4_K_S.GGUF"),+ Q4.filename,+ );+ // Unlisted (offline or failed listing): the caller's own name still routes.+ assert.equal(+ pickGgufFilename([], "some-model-Q6_K.gguf"),+ "some-model-Q6_K.gguf",+ );+});++test("several downloaded quants stay ambiguous", () => {+ const both = [Q4, { ...Q8, downloaded: true }];+ assert.equal(pickGgufFilename(both), null);+});++test("an empty or malformed listing resolves to nothing", () => {+ assert.equal(pickGgufFilename([]), null);+ assert.equal(pickGgufFilename([{ filename: 42, quant: null }]), null);+ // A companion .safetensors row is not a GGUF checkpoint.+ assert.equal(+ pickGgufFilename([{ filename: "model.safetensors", quant: "BF16" }]),+ null,+ );+});