Skip to content

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.

Fix SDXL checkpoint selection for catalog downloads and Run (#17582)

Lee Jackson74d2c1cef953
diff --git a/studio/backend/core/inference/diffusion_hub_evidence.py b/studio/backend/core/inference/diffusion_hub_evidence.py
index 298e583f346..6e4c982a72d 100644
--- a/studio/backend/core/inference/diffusion_hub_evidence.py
+++ b/studio/backend/core/inference/diffusion_hub_evidence.py
@@ -86,6 +86,27 @@ def cached_family(repo_id: Optional[str], filename: Optional[str] = None) -> Opt
return _dit_family(inspect_checkpoint(local))
+def read_hub_checkpoint_family(
+ repo_id: str,
+ filename: str,
+ hf_token: Any,
+ revision: Optional[str] = None,
+) -> Optional[str]:
+ """Identify a bundled pipeline by its tensor header, independent of the repo and file names."""
+ from huggingface_hub import HfApi
+
+ from .diffusion_content import classify_tensors
+
+ from hub.utils.hf_tokens import normalize_token
+
+ token = normalize_token(hf_token)
+ meta = HfApi().parse_safetensors_file_metadata(
+ repo_id, filename, token = token, revision = revision
+ )
+ shapes = {name: list(info.shape) for name, info in meta.tensors.items()}
+ return _dit_family(classify_tensors(shapes, meta.metadata))
+
+
def prefetch_for_pick(
repo_id: Optional[str],
filename: Optional[str],
@@ -114,19 +135,31 @@ def prefetch_for_pick(
and _family_from_hub_evidence(repo_id, filename) is None
):
return
- from huggingface_hub import HfApi
-
- from .diffusion_content import classify_tensors
-
- from hub.utils.hf_tokens import normalize_token
-
- token = normalize_token(hf_token)
- meta = HfApi().parse_safetensors_file_metadata(repo_id, filename, token = token)
- shapes = {name: list(info.shape) for name, info in meta.tensors.items()}
- family = _dit_family(classify_tensors(shapes, meta.metadata))
+ family = read_hub_checkpoint_family(repo_id, filename, hf_token)
except Exception: # noqa: BLE001 - evidence is best effort; validation and the load still decide
return
+ _remember(repo_id, filename, family)
+
+
+def _remember(repo_id: str, filename: str, family: Optional[str]) -> None:
with _LOCK:
if len(_HEADER_VERDICTS) >= _MAX_VERDICTS:
_HEADER_VERDICTS.clear()
_HEADER_VERDICTS[_key(repo_id, filename)] = (time.monotonic(), family)
+
+
+def hub_checkpoint_loads_as_sdxl(
+ repo_id: str,
+ filename: str,
+ hf_token: Any,
+ revision: Optional[str] = None,
+) -> bool:
+ """A whole-SDXL header AND the loader's own verdict, so name-vetoed variants (inpaint, edit) are not offered."""
+ from .diffusion_families import detect_family_for_pick
+
+ family = read_hub_checkpoint_family(repo_id, filename, hf_token, revision)
+ if family != "sdxl":
+ return False
+ _remember(repo_id, filename, family)
+ fam = detect_family_for_pick(repo_id, filename, None)
+ return fam is not None and fam.name == "sdxl"
diff --git a/studio/backend/hub/routes/inventory.py b/studio/backend/hub/routes/inventory.py
index 1dae18b8671..a2558d0d205 100644
--- a/studio/backend/hub/routes/inventory.py
+++ b/studio/backend/hub/routes/inventory.py
@@ -31,6 +31,7 @@ from hub.schemas.downloads import (
DownloadStartResponse,
TransportStatusResponse,
)
+from hub.services.models import account_access
from hub.utils.hf_tokens import HfTokenArg
from hub.schemas.inventory import (
AddScanFolderRequest,
@@ -149,6 +150,33 @@ def get_models_folder(
return redact_inventory_host_paths(payload, via_api_key = via_api_key)
[email protected]("/sdxl-checkpoint", response_model = bool)
+def is_sdxl_checkpoint(
+ repo_id: str = Query(..., min_length = 1, max_length = 192),
+ filename: str = Query(..., pattern = r"(?i)^[^/\\]+\.safetensors$"),
+ revision: Optional[str] = Query(None, pattern = r"^[0-9a-f]{40}$"),
+ hf_token: HfTokenArg = Depends(get_request_hf_token),
+ current_subject: str = Depends(get_current_subject),
+):
+ from core.inference.diffusion_hub_evidence import hub_checkpoint_loads_as_sdxl
+ from huggingface_hub.utils import HFValidationError, validate_repo_id
+
+ try:
+ validate_repo_id(repo_id)
+ except HFValidationError:
+ raise HTTPException(status_code = 422, detail = "Invalid repository ID") from None
+ # A managed account must never read through the installation's ambient token.
+ if account_access.managed_account():
+ account_access.require_model_allowed(repo_id)
+ hf_token = account_access.account_hf_token(hf_token)
+ try:
+ return hub_checkpoint_loads_as_sdxl(repo_id, filename, hf_token, revision)
+ except Exception:
+ raise HTTPException(
+ status_code = 502, detail = "Could not read the checkpoint header"
+ ) from None
+
+
@router.get("/gguf-variants", response_model = GgufVariantsResponse)
async def get_gguf_variants(
repo_id: str = Query(
diff --git a/studio/backend/tests/test_cache_inventory_path_boundary.py b/studio/backend/tests/test_cache_inventory_path_boundary.py
index 07ba0f406e9..f98ae965e6d 100644
--- a/studio/backend/tests/test_cache_inventory_path_boundary.py
+++ b/studio/backend/tests/test_cache_inventory_path_boundary.py
@@ -502,6 +502,7 @@ def test_download_progress_hides_the_cache_dir_it_measured(
_ROUTES_WITHOUT_HOST_PATHS = {
"remove_scan_folder_endpoint": "status and id only",
"get_gguf_variants": "filenames and quant labels, no directory",
+ "is_sdxl_checkpoint": "a boolean; repo_id must be a Hub id",
"download_model": "job id and status",
"cancel_download_model": "job id and status",
"get_active_downloads": "repo ids and byte counts",
diff --git a/studio/backend/tests/test_diffusion_vpred_sdxl_detect.py b/studio/backend/tests/test_diffusion_vpred_sdxl_detect.py
index e7ba68011f6..0eb0638dbe7 100644
--- a/studio/backend/tests/test_diffusion_vpred_sdxl_detect.py
+++ b/studio/backend/tests/test_diffusion_vpred_sdxl_detect.py
@@ -350,6 +350,22 @@ def _stub_header(monkeypatch, keys_by_call):
return calls
+def test_catalog_identifies_whole_sdxl_files_by_content_even_when_names_are_neutral(monkeypatch):
+ from hub.routes.inventory import is_sdxl_checkpoint
+
+ keys = [
+ ["transformer.single_transformer_blocks.0.attn.to_k.lora_A.weight"],
+ SDXL_DIFFUSERS_UNET_ONLY_KEYS,
+ SDXL_UNET_KEYS,
+ ]
+ _stub_header(monkeypatch, keys)
+ picks = [
+ is_sdxl_checkpoint("example/checkpoint", filename, "1" * 40, False, "test-user")
+ for filename in ("edition-1.safetensors", "unet.safetensors", "edition-2.safetensors")
+ ]
+ assert picks == [False, False, True]
+
+
def test_a_denoiser_only_unet_is_not_evidence_for_a_whole_pipeline_family(hub_cache, monkeypatch):
import huggingface_hub
@@ -1028,3 +1044,50 @@ def test_the_marker_read_overlaps_only_a_staged_snapshot():
assert "_base_local_dir" in gate
first = calls[0].body.args[0]
assert ast.unparse(first) == "_base_local_dir"
+
+
+def test_a_managed_account_reads_checkpoint_headers_without_the_installation_token(monkeypatch):
+ import huggingface_hub
+ from fastapi import HTTPException
+
+ from hub.routes import inventory
+ from hub.services.models import account_access
+
+ tokens = []
+
+ def parse(
+ self,
+ repo_id,
+ filename,
+ token = None,
+ **kw,
+ ):
+ tokens.append(token)
+ return types.SimpleNamespace(
+ tensors = {k: types.SimpleNamespace(shape = [0]) for k in SDXL_UNET_KEYS},
+ metadata = {},
+ )
+
+ monkeypatch.setattr(huggingface_hub.HfApi, "parse_safetensors_file_metadata", parse)
+ for managed in (False, True):
+ monkeypatch.setattr(account_access, "managed_account", lambda managed = managed: managed)
+ assert inventory.is_sdxl_checkpoint("example/ckpt", "a.safetensors", None, None, "u")
+ assert tokens == [None, False]
+
+ monkeypatch.setattr(account_access, "model_allowlist", lambda: ["allowed/*"])
+ with pytest.raises(HTTPException):
+ inventory.is_sdxl_checkpoint("example/ckpt", "a.safetensors", None, None, "u")
+ assert len(tokens) == 2
+
+
+def test_the_catalog_never_offers_a_checkpoint_the_loader_vetoes_by_name(monkeypatch):
+ from core.inference.diffusion import get_diffusion_backend
+ from hub.routes.inventory import is_sdxl_checkpoint
+
+ _stub_header(monkeypatch, [SDXL_UNET_KEYS])
+ repo = "example/neutral-mix"
+ assert is_sdxl_checkpoint(repo, "edition.safetensors", None, False, "u")
+ assert not is_sdxl_checkpoint(repo, "edition-inpaint.safetensors", None, False, "u")
+ get_diffusion_backend().validate_load_request(
+ repo, gguf_filename = "edition.safetensors", family_override = None, model_kind = "single_file"
+ )
diff --git a/studio/frontend/src/features/hub/catalog/download-section.tsx b/studio/frontend/src/features/hub/catalog/download-section.tsx
index e4fe5802446..10058c330b6 100644
--- a/studio/frontend/src/features/hub/catalog/download-section.tsx
+++ b/studio/frontend/src/features/hub/catalog/download-section.tsx
@@ -32,6 +32,7 @@ export function DownloadSection({
cachePath,
knownBytes,
onRun,
+ onRunCheckpoint,
runPending = false,
onChange,
showMemoryBar = true,
@@ -62,6 +63,7 @@ export function DownloadSection({
cachePath?: string | null;
knownBytes?: number | null;
onRun?: (selection: HubModelRunSelection) => void;
+ onRunCheckpoint?: (filename: string) => void;
runPending?: boolean;
onChange?: () => void;
/** False for diffusion/audio/video GGUFs, which do not load through llama.cpp. */
@@ -110,6 +112,7 @@ export function DownloadSection({
cachePath={cachePath}
knownBytes={knownBytes}
onRun={onRun ? () => onRun({}) : undefined}
+ onRunCheckpoint={onRunCheckpoint}
runPending={runPending}
onChange={onChange}
/>
diff --git a/studio/frontend/src/features/hub/catalog/model-inspector.tsx b/studio/frontend/src/features/hub/catalog/model-inspector.tsx
index 659072accaa..e4dedd99c16 100644
--- a/studio/frontend/src/features/hub/catalog/model-inspector.tsx
+++ b/studio/frontend/src/features/hub/catalog/model-inspector.tsx
@@ -785,6 +785,9 @@ export const ModelInspector = memo(function ModelInspector({
onChange={onInventoryChange}
isMlx={isMlx}
onRunPrecision={precisionRunAction}
+ onRunCheckpoint={mediaPage === "images" && onRun && model.hubRepoId
+ ? (checkpointFilename) => onRun({ checkpointFilename }, "images")
+ : undefined}
/>
)}
</InspectorDownloadSlot>
diff --git a/studio/frontend/src/features/hub/catalog/safetensors-download-card.tsx b/studio/frontend/src/features/hub/catalog/safetensors-download-card.tsx
index baf63a81795..452ff0bb928 100644
--- a/studio/frontend/src/features/hub/catalog/safetensors-download-card.tsx
+++ b/studio/frontend/src/features/hub/catalog/safetensors-download-card.tsx
@@ -1,7 +1,13 @@
// 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 {
+ confirmedSdxlCheckpoints,
+ rememberedSdxlCheckpoints,
+ rememberSdxlCheckpoints,
+} from "../lib/sdxl-checkpoints";
+import { imageCheckpointSelection, type ImageCheckpointFile } from "../download-manager/required-assets";
+import { useHubDownloadPlan, useHubQueue } 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";
@@ -10,12 +16,17 @@ import {
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
-import { useEffect, useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import { useHttpPartialsResumable, useRepoDownload } from "../download-manager";
import { useOnlineStatus } from "../hooks/use-online-status";
import { deleteCachedModel } from "../inventory";
import type { ModelInventoryFormat } from "../inventory";
-import { fetchModelSize } from "../lib/dataset-size";
+import {
+ groupForRepoId,
+ IMAGE_CATALOG,
+} from "@/features/model-picker/components/model-selector/model-catalog";
+import { bumpInventoryVersion } from "../stores/inventory-events";
+import { fetchModelSize, type ModelSizeInfo } from "../lib/dataset-size";
import { formatBytes } from "../lib/format";
import { fingerprintToken } from "../lib/token-fingerprint";
import { useHfTokenStore } from "../stores/hf-token-store";
@@ -61,6 +72,7 @@ export function SafetensorsDownloadCard({
cachePath,
knownBytes,
onRun,
+ onRunCheckpoint,
runPending = false,
onChange,
assetRuntime,
@@ -77,25 +89,69 @@ export function SafetensorsDownloadCard({
cachePath?: string | null;
knownBytes?: number | null;
onRun?: () => void;
+ onRunCheckpoint?: (filename: string) => void;
runPending?: boolean;
onChange?: () => void;
assetRuntime?: AssetRuntime;
}) {
const hfToken = useHfTokenStore((s) => s.token);
const online = useOnlineStatus();
- const assets = useRequiredAssetsDownload({ repoId, runtime: assetRuntime });
+ const discoverCheckpoints =
+ assetRuntime === "images" &&
+ !repoId.toLowerCase().startsWith("unsloth/") &&
+ !groupForRepoId(repoId, IMAGE_CATALOG);
const hfEndpoint = useHfEndpoint();
const sizeKey = `${hfEndpoint}::${repoId}::${fingerprintToken(hfToken)}`;
- const [modelSize, setModelSize] = useState<{
- key: string;
- bytes: number | null;
- }>(() => ({ key: sizeKey, bytes: null }));
+ const [metadata, setMetadata] = useState<{ key: string; info: ModelSizeInfo | null; choices?: ImageCheckpointFile[] }>();
+ const info = metadata?.key === sizeKey ? metadata.info : undefined;
+ const remembered = useMemo(
+ () => (discoverCheckpoints && !online ? rememberedSdxlCheckpoints(repoId) : undefined),
+ [discoverCheckpoints, online, repoId],
+ );
+ const choices = !discoverCheckpoints
+ ? undefined
+ : metadata?.key === sizeKey
+ ? metadata.choices
+ : remembered;
+ const job = useRepoDownload({
+ kind: "model",
+ repoId,
+ activeVariant: null,
+ autoAdopt: true,
+ includeScopedJobs: true,
+ });
+
+ const progress = job.progress;
+ const cancelling = job.cancelling;
+ const setJobExpectedBytes = job.setExpectedBytes;
+
+ const [picked, setPicked] = useState<{ key: string; filename: string }>();
+ const queuedFilename = useHubQueue((state) =>
+ state.plans.find((plan) => plan.origin?.repoId === repoId && plan.origin.filename)?.origin?.filename,
+ );
+ const { active, selected: checkpoint } = imageCheckpointSelection(
+ repoId, choices, picked?.key === sizeKey ? picked.filename : undefined,
+ queuedFilename, progress?.scopedFiles,
+ );
+ const activeFilename = active?.filename;
+ // A reopened card keeps the transferred file selected when its queue entry disappears.
+ useEffect(() => {
+ if (activeFilename) setPicked({ key: sizeKey, filename: activeFilename });
+ }, [sizeKey, activeFilename]);
+ const discovering = discoverCheckpoints && online && info === undefined;
+ const assets = useRequiredAssetsDownload({
+ repoId,
+ filename: checkpoint?.filename,
+ runtime: discovering ? undefined : assetRuntime,
+ modelLabel: checkpoint?.filename,
+ });
+ const installed = checkpoint ? assets.checkpointInstalled : isDownloaded;
+ const partial = !checkpoint && isPartial;
+ const run = checkpoint ? onRunCheckpoint?.bind(null, checkpoint.filename) : onRun;
const modelTotalBytes =
knownBytes && knownBytes > 0
? knownBytes
- : modelSize.key === sizeKey
- ? modelSize.bytes
- : null;
+ : info?.weightsBytes ?? info?.totalBytes ?? null;
const [deleteRepoOpen, setDeleteRepoOpen] = useState(false);
const { deleting, runDelete } = useCardDelete({
action: () =>
@@ -108,48 +164,43 @@ export function SafetensorsDownloadCard({
},
});
- const job = useRepoDownload({
- kind: "model",
- repoId,
- activeVariant: null,
- autoAdopt: true,
- includeScopedJobs: true,
- });
-
- const progress = job.progress;
- const cancelling = job.cancelling;
- const repoPeerActive = job.repoPeerActive;
- const setJobExpectedBytes = job.setExpectedBytes;
-
useEffect(() => {
if (knownBytes && knownBytes > 0) {
setJobExpectedBytes(knownBytes);
- return;
+ if (!discoverCheckpoints) return;
}
if (!online) return;
if (!repoId) return;
const controller = new AbortController();
const { signal } = controller;
void fetchModelSize(repoId, hfToken || undefined, signal)
- .then((info) => {
- if (signal.aborted || !info) return;
- const upstream = info.weightsBytes ?? info.totalBytes;
- if (upstream && upstream > 0) {
- setModelSize({ key: sizeKey, bytes: upstream });
- setJobExpectedBytes(upstream);
- }
+ .then(async (info) => {
+ if (signal.aborted) return;
+ const choices = discoverCheckpoints && info
+ ? await confirmedSdxlCheckpoints(repoId, info, hfToken || undefined, signal)
+ : undefined;
+ if (signal.aborted) return;
+ if (choices?.length) rememberSdxlCheckpoints(repoId, choices);
+ setMetadata({ key: sizeKey, info, choices });
+ const upstream = info?.weightsBytes ?? info?.totalBytes;
+ if (!knownBytes && upstream) setJobExpectedBytes(upstream);
})
.catch((err) => {
- if (!signal.aborted && import.meta.env.DEV) {
+ if (signal.aborted) return;
+ setMetadata({ key: sizeKey, info: null });
+ if (import.meta.env.DEV) {
console.debug("Model size lookup failed", err);
}
});
return () => {
controller.abort();
};
- }, [repoId, hfToken, sizeKey, setJobExpectedBytes, knownBytes, online]);
+ }, [repoId, hfToken, sizeKey, setJobExpectedBytes, knownBytes, online, discoverCheckpoints]);
- const downloading = isRepoDownloadProgress(progress);
+ const repoDownloading = isRepoDownloadProgress(progress);
+ const downloading = repoDownloading &&
+ (!checkpoint || progress?.variant === null || progress?.scopedFiles?.includes(checkpoint.filename) === true);
+ const repoPeerActive = job.repoPeerActive || (repoDownloading && !downloading);
const partialsResumable = useHttpPartialsResumable();
const downloadAction = useDownloadCardState({
job,
@@ -162,13 +213,15 @@ export function SafetensorsDownloadCard({
partialResumable,
partialsResumable,
});
- const hubPlan = useHubDownloadPlan(repoId);
+ const hubPlan = useHubDownloadPlan(repoId, checkpoint?.filename);
+ const displayBytes = checkpoint ? checkpoint.bytes : modelTotalBytes;
const showDownloadAction = !hubPlan && (
- !isDownloaded || downloading || cancelling || downloadAction.starting);
+ !installed || downloading || cancelling || downloadAction.starting);
const showRunAction = !hubPlan &&
- Boolean(onRun) &&
- isDownloaded &&
- !isPartial &&
+ Boolean(run) &&
+ !discovering &&
+ installed &&
+ !partial &&
!downloading &&
!cancelling &&
!downloadAction.starting &&
@@ -220,12 +273,25 @@ export function SafetensorsDownloadCard({
}
>
<div className="relative flex h-9 min-w-0 flex-1 items-center pl-3 pr-2">
- <span className="flex items-center gap-1.5 text-ui-12 text-muted-foreground">
- {isDownloaded && <DotTag tone="success" label="On device" />}
- {!isDownloaded && downloading && (
+ <span className="flex min-w-0 items-center gap-1.5 text-ui-12 text-muted-foreground">
+ {checkpoint && (
+ <select
+ aria-label="Image checkpoint"
+ className="min-w-0 truncate rounded bg-background text-foreground"
+ value={checkpoint.filename}
+ disabled={downloading || Boolean(hubPlan) || assets.checking}
+ onChange={(event) => setPicked({ key: sizeKey, filename: event.target.value })}
+ >
+ {choices?.map((file) => (
+ <option key={file.filename}>{file.filename}</option>
+ ))}
+ </select>
+ )}
+ {installed && <DotTag tone="success" label="On device" />}
+ {!installed && downloading && (
<DotTag tone="downloading" label="Downloading" />
)}
- {!isDownloaded && isPartial && !downloading && (
+ {!installed && partial && !downloading && (
<Tooltip>
<TooltipTrigger asChild={true}>
<span className="inline-flex">
@@ -237,13 +303,12 @@ export function SafetensorsDownloadCard({
</TooltipContent>
</Tooltip>
)}
- <DotTag
- tone={formatModelTone(modelFormat)}
- label={formatModelLabel(modelFormat)}
- />
- {modelTotalBytes && modelTotalBytes > 0 && (
+ {!checkpoint && (
+ <DotTag tone={formatModelTone(modelFormat)} label={formatModelLabel(modelFormat)} />
+ )}
+ {displayBytes && displayBytes > 0 && (
<span className="tabular-nums">
- {formatBytes(modelTotalBytes)}
+ {formatBytes(displayBytes)}
</span>
)}
</span>
@@ -266,26 +331,29 @@ export function SafetensorsDownloadCard({
)}
</div>
</div>
- {showDownloadAction && !(showRunAction && onRun) && <CardDivider />}
+ {showDownloadAction && !showRunAction && <CardDivider />}
{showDownloadAction && (
<DownloadActionButton
downloading={downloadAction.downloading}
cancelling={downloadAction.cancelling}
- loading={downloadAction.starting || assets.checking}
- isPartial={downloadAction.isPartial}
+ loading={discovering || downloadAction.starting || assets.checking}
+ isPartial={!checkpoint && downloadAction.isPartial}
partialResumable={downloadAction.partialResumable}
stopMode={downloadAction.stopMode}
progressPercent={downloadAction.progressPercent}
- disabled={downloadAction.disabled || assets.checking}
- onClick={() => downloading ? downloadAction.onClick() : void assets.request(downloadAction.onClick)}
+ disabled={discovering || downloadAction.disabled || assets.checking}
+ onClick={() => {
+ if (downloading) downloadAction.onClick();
+ else void assets.request(checkpoint ? bumpInventoryVersion : downloadAction.onClick);
+ }}
className={repoPeerActive ? "opacity-70" : undefined}
/>
)}
{hubPlan && <span className="px-3 text-ui-12 text-muted-foreground">Downloading…</span>}
- {showRunAction && onRun && (
+ {showRunAction && run && (
<ModelRunActionButton
- label={`Configure and run ${repoId}`}
- onClick={onRun}
+ label={`Configure and run ${checkpoint?.filename ?? repoId}`}
+ onClick={run}
loading={runPending}
/>
)}
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.tsx
index ff601c72910..325f0d55d00 100644
--- a/studio/frontend/src/features/hub/catalog/use-required-assets-download.tsx
+++ b/studio/frontend/src/features/hub/catalog/use-required-assets-download.tsx
@@ -8,6 +8,7 @@ import {
} from "@/features/images/api";
import { getVideoDownloadPlan } from "@/features/video/api";
import { getAudioDownloadPlan } from "@/features/audio/api";
+import { diffusionFileKind } from "@/lib/diffusion-route-pick";
import { toast } from "@/lib/toast";
import { useInventoryVersion } from "../stores/inventory-events";
import { useHfTokenStore } from "../stores/hf-token-store";
@@ -41,7 +42,7 @@ export function useRequiredAssetsDownload({
const body = {
model_path: repoId,
gguf_filename: filename,
- model_kind: filename ? ("gguf" as const) : ("pipeline" as const),
+ model_kind: diffusionFileKind(filename),
hf_token: token || undefined,
};
const result =
@@ -86,13 +87,26 @@ export function useRequiredAssetsDownload({
});
return record.promise;
}, [fetchPlan, inventoryVersion]);
+ const [installed, setInstalled] = useState<{ plan: typeof resolvePlan } | null>(null);
useEffect(() => {
if (!runtime) return;
+ let current = true;
const timer = window.setTimeout(() => {
- void resolvePlan().catch(() => {});
+ void resolvePlan()
+ .then((plan) => {
+ if (!current || !filename || diffusionFileKind(filename) !== "single_file") return;
+ const missing = plan.entries.some(
+ (entry) => entry.repo_id === repoId && entry.files.includes(filename),
+ );
+ setInstalled(missing ? null : { plan: resolvePlan });
+ })
+ .catch(() => {});
}, 200);
- return () => window.clearTimeout(timer);
- }, [resolvePlan, runtime]);
+ return () => {
+ current = false;
+ window.clearTimeout(timer);
+ };
+ }, [resolvePlan, runtime, repoId, filename]);
useEffect(() => {
++sequence.current;
setPending(null);
@@ -141,6 +155,7 @@ export function useRequiredAssetsDownload({
};
return {
checking,
+ checkpointInstalled: installed?.plan === resolvePlan,
request,
dialog: (
<RequiredAssetsDownloadDialog
diff --git a/studio/frontend/src/features/hub/download-manager/required-assets.ts b/studio/frontend/src/features/hub/download-manager/required-assets.ts
index ae27474d33c..709c300404d 100644
--- a/studio/frontend/src/features/hub/download-manager/required-assets.ts
+++ b/studio/frontend/src/features/hub/download-manager/required-assets.ts
@@ -56,3 +56,26 @@ export function checkpointFirst<T extends { checkpoint?: boolean }>(
...entries.filter((e) => e.checkpoint === false),
];
}
+
+export interface ImageCheckpointFile {
+ filename: string;
+ bytes: number | null;
+}
+
+/** Reopening the card should show the active transfer, including a scoped job adopted after reload. */
+export function imageCheckpointSelection(
+ repoId: string,
+ files: readonly ImageCheckpointFile[] | undefined,
+ picked: string | undefined,
+ queued: string | undefined,
+ transferring: readonly string[] | undefined,
+) {
+ const active = files?.find((file) => transferring?.includes(file.filename)) ??
+ files?.find((file) => file.filename === queued);
+ const repoFilename = repoId.split("/").pop()?.toLowerCase() + ".safetensors";
+ const selected = active ??
+ files?.find((file) => file.filename === picked) ??
+ files?.find((file) => file.filename.toLowerCase() === repoFilename) ??
+ files?.[0];
+ return { active, selected };
+}
diff --git a/studio/frontend/src/features/hub/download-manager/use-repo-download.ts b/studio/frontend/src/features/hub/download-manager/use-repo-download.ts
index 05428eaad77..63507d39790 100644
--- a/studio/frontend/src/features/hub/download-manager/use-repo-download.ts
+++ b/studio/frontend/src/features/hub/download-manager/use-repo-download.ts
@@ -20,6 +20,7 @@ import {
} from "./download-manager-controller";
export interface DownloadJobProgress {
+ scopedFiles?: readonly string[];
variant: string | null;
expectedBytes: number;
downloadedBytes: number;
@@ -217,6 +218,7 @@ export function useRepoDownload(config: RepoDownloadConfig): DownloadJob {
active
? {
variant: active.variant,
+ scopedFiles: active.scopedFiles,
expectedBytes: active.expectedBytes,
downloadedBytes: active.downloadedBytes,
fraction: active.fraction,
diff --git a/studio/frontend/src/features/hub/lib/dataset-size.ts b/studio/frontend/src/features/hub/lib/dataset-size.ts
index 7ef4f9a002b..1a64d0355ff 100644
--- a/studio/frontend/src/features/hub/lib/dataset-size.ts
+++ b/studio/frontend/src/features/hub/lib/dataset-size.ts
@@ -6,6 +6,7 @@ import {
getHfEndpoint,
hasDatasetsServer,
} from "@/lib/hf-endpoint";
+import type { ImageCheckpointFile } from "../download-manager/required-assets";
import { LruMap } from "./lru-map";
import { fetchWithTimeout } from "./network";
import { fingerprintToken } from "./token-fingerprint";
@@ -79,7 +80,7 @@ function fetchCachedSize<T>(
return Promise.resolve(entry.kind === "value" ? entry.value : null);
}
const existing = inflight.get(cacheKey);
- if (existing) return attachInflight(existing, signal);
+ if (existing && !existing.cancelledByConsumers) return attachInflight(existing, signal);
let timedOut = false;
const controller = new AbortController();
@@ -98,6 +99,7 @@ function fetchCachedSize<T>(
inflightEntry.promise = (async (): Promise<T | null> => {
try {
const result = await load(controller.signal);
+ if (inflightEntry.cancelledByConsumers) return null;
if ("value" in result) {
cache.set(cacheKey, { kind: "value", value: result.value });
return result.value;
@@ -135,7 +137,7 @@ function fetchCachedSize<T>(
} finally {
clearTimeout(timeout);
inflightEntry.settled = true;
- inflight.delete(cacheKey);
+ if (inflight.get(cacheKey) === inflightEntry) inflight.delete(cacheKey);
}
})();
@@ -259,9 +261,13 @@ export function fetchDatasetSize(
export interface ModelSizeInfo {
totalBytes: number | null;
weightsBytes: number | null;
+ revision?: string;
+ imageCheckpointCandidates?: ImageCheckpointFile[];
}
interface ModelInfoApiResponse {
+ sha?: string;
+ config?: { diffusers?: { _class_name?: string } };
siblings?: Array<{
rfilename?: string;
size?: number;
@@ -471,6 +477,14 @@ export function fetchModelSize(
}
const data = (await res.json()) as ModelInfoApiResponse;
const siblings = data.siblings ?? [];
+ // SDXL repos can package alternate whole checkpoints alongside their Diffusers component folders.
+ const imageCheckpointCandidates = data.config?.diffusers?._class_name === "StableDiffusionXLPipeline"
+ ? siblings.flatMap(({ rfilename, size }) =>
+ rfilename && /^[^/\\]+\.safetensors$/i.test(rfilename) && !/[-_]\d+-of-\d+\./i.test(rfilename)
+ ? [{ filename: rfilename, bytes: size ?? null }]
+ : [],
+ )
+ : [];
const skipConsolidated = shipsTransformersWeights(siblings);
const skipDuplicateFormats = shipsRootSafetensors(siblings);
const names = siblings.map((s) => s.rfilename ?? "");
@@ -506,6 +520,7 @@ export function fetchModelSize(
value: {
totalBytes: total > 0 ? total : null,
weightsBytes: weights > 0 ? weights : null,
+ ...(imageCheckpointCandidates.length ? { imageCheckpointCandidates, revision: data.sha } : {}),
},
};
},
diff --git a/studio/frontend/src/features/hub/lib/model-run-selection.ts b/studio/frontend/src/features/hub/lib/model-run-selection.ts
index 7740571dd5b..2ebb0e2bdf2 100644
--- a/studio/frontend/src/features/hub/lib/model-run-selection.ts
+++ b/studio/frontend/src/features/hub/lib/model-run-selection.ts
@@ -18,6 +18,7 @@ import { EMBEDDING_TAGS } from "./hf-model-meta.ts";
import { routableToMediaPage } from "./local-path.ts";
export interface HubModelRunSelection {
+ checkpointFilename?: string;
ggufVariant?: string;
ggufFilename?: string;
expectedBytes?: number;
diff --git a/studio/frontend/src/features/hub/lib/sdxl-checkpoints.ts b/studio/frontend/src/features/hub/lib/sdxl-checkpoints.ts
new file mode 100644
index 00000000000..9f813f58bc5
--- /dev/null
+++ b/studio/frontend/src/features/hub/lib/sdxl-checkpoints.ts
@@ -0,0 +1,78 @@
+// 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 { authFetch } from "@/features/auth/api";
+import type { ImageCheckpointFile } from "../download-manager/required-assets";
+import type { ModelSizeInfo } from "./dataset-size";
+import { hubTokenHeader } from "./hub-token-header";
+
+// ModelSizeInfo is already cached by endpoint, repo and token. Keep only confirmed header verdicts.
+const headers = new WeakMap<ModelSizeInfo, Map<string, boolean>>();
+
+export async function confirmedSdxlCheckpoints(
+ repoId: string,
+ info: ModelSizeInfo,
+ token: string | undefined,
+ signal: AbortSignal,
+): Promise<ImageCheckpointFile[]> {
+ const candidates = info.imageCheckpointCandidates ?? [];
+ const verdicts = headers.get(info) ?? new Map<string, boolean>();
+ headers.set(info, verdicts);
+ const unchecked = candidates.filter(({ filename }) => !verdicts.has(filename));
+ for (let i = 0; i < unchecked.length; i += 4) {
+ if (signal.aborted) break;
+ await Promise.all(unchecked.slice(i, i + 4).map(async ({ filename }) => {
+ const query = new URLSearchParams({ repo_id: repoId, filename });
+ if (info.revision) query.set("revision", info.revision);
+ try {
+ const res = await authFetch(`/api/hub/sdxl-checkpoint?${query}`, {
+ headers: hubTokenHeader(token),
+ signal,
+ });
+ if (res.ok) {
+ const verdict: unknown = await res.json();
+ if (typeof verdict === "boolean") verdicts.set(filename, verdict);
+ }
+ } catch {
+ // A failed header read can be retried on the next visit.
+ }
+ }));
+ }
+ return candidates.filter(({ filename }) => verdicts.get(filename) === true);
+}
+
+// Offline reopen has no metadata to rediscover from; without this, Run falls back to a pipeline pick.
+const STORAGE_KEY = "unsloth.hub.sdxlCheckpoints";
+const MAX_REPOS = 50;
+
+function readRemembered(): Record<string, ImageCheckpointFile[]> {
+ try {
+ const parsed: unknown = JSON.parse(window.localStorage.getItem(STORAGE_KEY) ?? "{}");
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
+ ? (parsed as Record<string, ImageCheckpointFile[]>)
+ : {};
+ } catch {
+ return {};
+ }
+}
+
+export function rememberSdxlCheckpoints(repoId: string, files: ImageCheckpointFile[]): void {
+ const key = repoId.toLowerCase();
+ const next = readRemembered();
+ delete next[key];
+ next[key] = files;
+ const keys = Object.keys(next);
+ for (const old of keys.slice(0, Math.max(0, keys.length - MAX_REPOS))) delete next[old];
+ try {
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
+ } catch {
+ // Storage full or disabled: online discovery still works.
+ }
+}
+
+export function rememberedSdxlCheckpoints(repoId: string): ImageCheckpointFile[] | undefined {
+ const files = readRemembered()[repoId.toLowerCase()];
+ return Array.isArray(files)
+ ? files.filter((f) => typeof f?.filename === "string" && /^[^/\\]+\.safetensors$/i.test(f.filename))
+ : undefined;
+}
diff --git a/studio/frontend/src/features/images/images-page.tsx b/studio/frontend/src/features/images/images-page.tsx
index ebec28d6829..f9ebacc1e1c 100644
--- a/studio/frontend/src/features/images/images-page.tsx
+++ b/studio/frontend/src/features/images/images-page.tsx
@@ -227,7 +227,7 @@ import {
} from "@/lib/resolved-precision";
import { diffusionPipelineLoadTarget, diffusionStagingEntries } from "@/lib/diffusion-pipeline-load-target";
import {
- routedGgufFilename,
+ routedImageFilename,
routedGgufLabel,
} from "@/lib/diffusion-route-search";
import { toast } from "@/lib/toast";
@@ -4647,8 +4647,8 @@ export function ImagesPage({
}
// `routeSearch` is rebuilt every render, so depend on the two fields.
const routed = { quant: routeSearch?.quant, ggufQuant: routeSearch?.ggufQuant };
- const routedFilename = routedGgufFilename(routed);
- const routedLabel = routedGgufLabel(routed);
+ const routedFilename = routedImageFilename(routed);
+ const routedLabel = routedFilename ? null : routedGgufLabel(routed);
const key = `${wanted}|${routeSearch?.quant ?? ""}|${routeSearch?.ggufQuant ?? ""}`;
if (handledRouteModel.current === key) return;
handledRouteModel.current = key;
@@ -4685,7 +4685,7 @@ export function ImagesPage({
wanted,
"auto",
false,
- pick.opts.kind === "gguf" ? (pick.opts.filename ?? null) : null,
+ pick.opts.kind === "pipeline" ? null : (pick.opts.filename ?? null),
);
}
void loadOrStage(pick.repoId, pick.opts, "hub", token).then((started) => {
diff --git a/studio/frontend/src/lib/diffusion-route-pick.ts b/studio/frontend/src/lib/diffusion-route-pick.ts
index b746e8284b4..6422a24cf4e 100644
--- a/studio/frontend/src/lib/diffusion-route-pick.ts
+++ b/studio/frontend/src/lib/diffusion-route-pick.ts
@@ -6,6 +6,11 @@ export interface DiffusionRoutePick {
opts: { kind: "gguf" | "single_file" | "pipeline"; filename?: string };
}
+export function diffusionFileKind(filename?: string | null): DiffusionRoutePick["opts"]["kind"] {
+ if (!filename) return "pipeline";
+ return filename.toLowerCase().endsWith(".safetensors") ? "single_file" : "gguf";
+}
+
/** Chat-routed picks carry only search params, so recognise bare local single files here (a pipeline
* load would evict the resident model and fail). `spec` covers curated single-file artifacts. */
export function diffusionRoutePick(
@@ -13,7 +18,9 @@ export function diffusionRoutePick(
quant?: string | null,
spec?: { kind: "gguf" | "single_file" | "pipeline"; filename?: string } | null,
): DiffusionRoutePick {
- if (quant) return { repoId: model, opts: { kind: "gguf", filename: quant } };
+ if (quant) {
+ return { repoId: model, opts: { kind: diffusionFileKind(quant), filename: quant } };
+ }
// A spec exists only for catalog repo ids, so it beats extension sniffing.
if (spec) return { repoId: model, opts: { kind: spec.kind, filename: spec.filename } };
const norm = model.replace(/\\/g, "/");
diff --git a/studio/frontend/src/lib/diffusion-route-search.ts b/studio/frontend/src/lib/diffusion-route-search.ts
index c82c525c530..476f1a438e5 100644
--- a/studio/frontend/src/lib/diffusion-route-search.ts
+++ b/studio/frontend/src/lib/diffusion-route-search.ts
@@ -17,9 +17,13 @@ const trimmed = (value: string | null | undefined): string | null =>
/** The label rides its own param because `quant` is consumed as a filename. */
export function diffusionRouteSearch(
model: string,
- meta: { ggufFilename?: string | null; ggufVariant?: string | null },
+ meta: {
+ checkpointFilename?: string;
+ ggufFilename?: string | null;
+ ggufVariant?: string | null;
+ },
): DiffusionRouteSearch {
- const filename = trimmed(meta.ggufFilename);
+ const filename = trimmed(meta.checkpointFilename) ?? trimmed(meta.ggufFilename);
if (filename) return { model, quant: filename };
const label = trimmed(meta.ggufVariant);
return label ? { model, ggufQuant: label } : { model };
@@ -32,6 +36,11 @@ export function routedGgufFilename(
return quant && isGgufName(quant) ? quant : null;
}
+export function routedImageFilename(search: Pick<DiffusionRouteSearch, "quant">): string | null {
+ const filename = trimmed(search.quant);
+ return filename?.toLowerCase().endsWith(".safetensors") ? filename : routedGgufFilename(search);
+}
+
/** A non-filename in `quant` (hand-built link, older producer) is a label too. */
export function routedGgufLabel(
search: Pick<DiffusionRouteSearch, "quant" | "ggufQuant">,
diff --git a/studio/frontend/tests/diffusion-route-search.test.ts b/studio/frontend/tests/diffusion-route-search.test.ts
index 9ccf71366d6..4b0934125fd 100644
--- a/studio/frontend/tests/diffusion-route-search.test.ts
+++ b/studio/frontend/tests/diffusion-route-search.test.ts
@@ -9,8 +9,11 @@ import {
diffusionRouteSearch,
routedGgufFilename,
routedGgufLabel,
+ routedImageFilename,
} from "../src/lib/diffusion-route-search.ts";
+import { diffusionFileKind, diffusionRoutePick } from "../src/lib/diffusion-route-pick.ts";
+
const REPO = "unsloth/Z-Image-Turbo-GGUF";
test("an expander pick routes its exact filename as the quant", () => {
@@ -98,3 +101,15 @@ 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");
});
+
+test("Download and Run use the same selected SDXL checkpoint", () => {
+ const repo = "cagliostrolab/animagine-xl-4.0";
+ for (const filename of ["animagine-xl-4.0.safetensors", "animagine-xl-4.0-opt.safetensors"]) {
+ const search = diffusionRouteSearch(repo, { checkpointFilename: filename });
+ assert.equal(diffusionFileKind(filename), "single_file");
+ assert.deepEqual(diffusionRoutePick(search.model, routedImageFilename(search)), {
+ repoId: repo,
+ opts: { kind: "single_file", filename },
+ });
+ }
+});
diff --git a/studio/frontend/tests/hub-model-size-diffusers-pickles.test.ts b/studio/frontend/tests/hub-model-size-diffusers-pickles.test.ts
index b7c4c727f43..ab847083e32 100644
--- a/studio/frontend/tests/hub-model-size-diffusers-pickles.test.ts
+++ b/studio/frontend/tests/hub-model-size-diffusers-pickles.test.ts
@@ -12,10 +12,11 @@ const { fetchModelSize } = await import(
"../src/features/hub/lib/dataset-size.ts"
);
-function stubSiblings(sizes: Record<string, number>): void {
+function stubSiblings(sizes: Record<string, number>, pipelineClass?: string): void {
globalThis.fetch = (async () =>
new Response(
JSON.stringify({
+ config: { diffusers: { _class_name: pipelineClass } },
siblings: Object.entries(sizes).map(([rfilename, size]) => ({
rfilename,
size,
@@ -54,3 +55,93 @@ test("an adapter safetensors never drops a component's only .bin", async () => {
weightsBytes: 5 + 200 + 10 + 20,
});
});
+
+test("SDXL checkpoint candidates include both Animagine variants and exclude components and shards", async () => {
+ stubSiblings({
+ "model_index.json": 671,
+ "unet/diffusion_pytorch_model.safetensors": 512,
+ "model-00001-of-00002.safetensors": 256,
+ "animagine-xl-4.0.safetensors": 6938434056,
+ "animagine-xl-4.0-opt.safetensors": 6938350040,
+ }, "StableDiffusionXLPipeline");
+ const info = await fetchModelSize("cagliostrolab/animagine-xl-4.0");
+ assert.deepEqual(info?.imageCheckpointCandidates, [
+ { filename: "animagine-xl-4.0.safetensors", bytes: 6938434056 },
+ { filename: "animagine-xl-4.0-opt.safetensors", bytes: 6938350040 },
+ ]);
+});
+
+function deferredResponse() {
+ let resolve!: (response: Response) => void;
+ const promise = new Promise<Response>((done) => { resolve = done; });
+ return { promise, resolve };
+}
+
+test("reopening a model while its canceled metadata lookup settles starts one fresh lookup", async (t) => {
+ const repo = "acme/reopened-sdxl";
+ const first = new AbortController();
+ const canceled = deferredResponse();
+ const fresh = deferredResponse();
+ const requests = [canceled, fresh];
+ const fetch = t.mock.method(globalThis, "fetch", () => {
+ const request = requests.shift();
+ assert.ok(request, "concurrent readers must share the replacement lookup");
+ return request.promise;
+ });
+ const initial = fetchModelSize(repo, undefined, first.signal);
+ first.abort();
+ const reopened = fetchModelSize(repo);
+ assert.equal(await initial, null);
+ // Let the old fetch finish after the replacement has taken ownership of the key.
+ canceled.resolve(Response.json({ siblings: [] }));
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ const secondReader = fetchModelSize(repo);
+ fresh.resolve(Response.json({ siblings: [{ rfilename: "weights.safetensors", size: 42 }] }));
+ const expected = { totalBytes: 42, weightsBytes: 42 };
+ assert.deepEqual(await reopened, expected);
+ assert.deepEqual(await secondReader, expected);
+ assert.equal(fetch.mock.callCount(), 2);
+});
+
+test("the picker offers only confirmed checkpoints from a mixed SDXL repo", async (t) => {
+ const { confirmedSdxlCheckpoints } = await import("../src/features/hub/lib/sdxl-checkpoints.ts");
+ const { installLocalStorageFake } = await import("./helpers/kit.ts");
+ installLocalStorageFake();
+ const names = ["edition.safetensors", "unet.safetensors", "model.safetensors"];
+ const info = {
+ revision: "1".repeat(40), totalBytes: null, weightsBytes: null,
+ imageCheckpointCandidates: names.map((filename) => ({ filename, bytes: null })),
+ };
+ const calls: string[] = [];
+ const fetch = t.mock.method(globalThis, "fetch", async (input: RequestInfo | URL) => {
+ const params = new URL(String(input), "http://localhost").searchParams;
+ assert.equal(params.get("revision"), info.revision);
+ assert.equal(params.get("repo_id"), "acme/mixed");
+ const filename = params.get("filename")!;
+ calls.push(filename);
+ return Response.json(filename === "model.safetensors");
+ });
+ const read = () => confirmedSdxlCheckpoints("acme/mixed", info, undefined, new AbortController().signal);
+ const expected = [info.imageCheckpointCandidates[2]];
+ assert.deepEqual(await read(), expected);
+ assert.deepEqual(await read(), expected);
+ assert.deepEqual(calls.sort(), [...names].sort());
+ assert.equal(fetch.mock.callCount(), 3);
+});
+
+test("confirmed SDXL checkpoints survive a reload for offline reopening", async () => {
+ const { rememberSdxlCheckpoints, rememberedSdxlCheckpoints } = await import(
+ "../src/features/hub/lib/sdxl-checkpoints.ts"
+ );
+ const { installLocalStorageFake } = await import("./helpers/kit.ts");
+ installLocalStorageFake();
+ assert.equal(rememberedSdxlCheckpoints("acme/sdxl"), undefined);
+ const files = [{ filename: "edition.safetensors", bytes: 7 }];
+ rememberSdxlCheckpoints("Acme/SDXL", files);
+ assert.deepEqual(rememberedSdxlCheckpoints("acme/sdxl"), files);
+ for (let i = 0; i < 60; i++) rememberSdxlCheckpoints(`acme/r${i}`, files);
+ assert.equal(rememberedSdxlCheckpoints("acme/sdxl"), undefined);
+ assert.deepEqual(rememberedSdxlCheckpoints("acme/r59"), files);
+ window.localStorage.setItem("unsloth.hub.sdxlCheckpoints", JSON.stringify({ "acme/x": [{ filename: "../a.safetensors" }] }));
+ assert.deepEqual(rememberedSdxlCheckpoints("acme/x"), []);
+});
diff --git a/studio/frontend/tests/image-generation-defaults.test.ts b/studio/frontend/tests/image-generation-defaults.test.ts
index fed0103d8c9..4ffdee6ddd8 100644
--- a/studio/frontend/tests/image-generation-defaults.test.ts
+++ b/studio/frontend/tests/image-generation-defaults.test.ts
@@ -337,13 +337,21 @@ test("a GGUF filename naming Krea 2 Raw outranks its multi-checkpoint repo", ()
);
});
-test("every GGUF pick path keys its defaults on the selected filename", () => {
+test("every GGUF or single-file pick path keys its defaults on the selected filename", () => {
const src = readSrc("features/images/images-page.tsx");
assert.match(src, /applyImageModelDefaults\(repoId, effectiveFamilyOverride, false, filename\)/);
assert.match(src, /applyImageModelDefaults\(id, nextFamilyOverride, false, meta\.ggufFilename\)/);
assert.match(src, /applyImageModelDefaults\(id, nextFamilyOverride, false, filename\)/);
- assert.match(src, /pick\.opts\.kind === "gguf" \? \(pick\.opts\.filename \?\? null\) : null/);
+ assert.match(src, /"auto",\s*false,\s*pick\.opts\.kind === "pipeline" \? null : \(pick\.opts\.filename \?\? null\)/);
assert.match(src, /defaultsKeyFor\(repoId, effectiveFamilyOverride, ggufFilename\)/);
assert.match(src, /status\?\.resolved\?\.family_override,\s*status\?\.gguf_filename/);
assert.match(src, /loaded\.resolved\?\.family_override,\s*loaded\.gguf_filename/);
});
+
+test("a Hub-routed single-file checkpoint keys its recipe on the selected file", () => {
+ const key = defaultsKeyFor("acme/sdxl-checkpoints", "auto", "sdxl-turbo.safetensors");
+ assert.deepEqual(
+ { steps: defaultsFor(key).steps, guidance: defaultsFor(key).guidance },
+ { steps: 1, guidance: 0 },
+ );
+});
diff --git a/studio/frontend/tests/required-assets.test.ts b/studio/frontend/tests/required-assets.test.ts
index 88654c0b1b9..189a345351b 100644
--- a/studio/frontend/tests/required-assets.test.ts
+++ b/studio/frontend/tests/required-assets.test.ts
@@ -4,6 +4,7 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
+ imageCheckpointSelection,
checkpointFirst,
assetLabel,
additionalAssetDownloads,
@@ -112,3 +113,20 @@ test("the download manager names companion files, falling back to required asset
"Qwen-Image-2.1",
);
});
+
+test("reopening an SDXL card follows its queued or adopted checkpoint through completion", () => {
+ const repo = "owner/animagine";
+ const standard = { filename: "animagine.safetensors", bytes: 123 };
+ const opt = { filename: "animagine-opt.safetensors", bytes: 124 };
+ const files = [opt, standard];
+ const select = (picked?: string, queued?: string, scoped?: string[]) =>
+ imageCheckpointSelection(repo, files, picked, queued, scoped);
+ assert.equal(select().selected, standard);
+ const reopened = select(undefined, opt.filename);
+ assert.equal(reopened.active, opt);
+ assert.equal(reopened.selected, opt);
+ assert.equal(select(reopened.active?.filename).selected, opt);
+ assert.equal(select(standard.filename, undefined, [opt.filename]).selected, opt);
+ assert.equal(select(undefined, standard.filename, [opt.filename]).selected, opt);
+ assert.equal(select(undefined, undefined, ["tokenizer/config.json"]).active, undefined);
+});