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.

Model picker: default Show all quantizations off, collapse single-quant rows, say Reveal in Folder outside macOS (#7736)

Michael Han63307b17f335
diff --git a/studio/backend/hub/schemas/inventory.py b/studio/backend/hub/schemas/inventory.py
index ca0f4658a3d..2fce5c5c0e5 100644
--- a/studio/backend/hub/schemas/inventory.py
+++ b/studio/backend/hub/schemas/inventory.py
@@ -177,6 +177,14 @@ class CachedRepoBase(BaseModel):
class CachedGgufRepo(CachedRepoBase):
model_format: ModelFormat = "gguf"
+ has_variant_state: bool = Field(
+ False,
+ description = (
+ "Whether a download manifest or cancel marker exists for some quant. A sibling "
+ "cancelled before any file landed changes nothing else on this row, so callers "
+ "watching for on-disk change need this to notice it."
+ ),
+ )
class CachedGgufResponse(BaseModel):
diff --git a/studio/backend/hub/services/models/cache_inventory.py b/studio/backend/hub/services/models/cache_inventory.py
index 862b1eeb24f..a501a7ec0cd 100644
--- a/studio/backend/hub/services/models/cache_inventory.py
+++ b/studio/backend/hub/services/models/cache_inventory.py
@@ -449,6 +449,8 @@ def _scan_cached_gguf() -> list[dict]:
"size_bytes": max(total_size, variant_state_size),
"cache_path": str(repo_info.repo_path),
"partial": partial,
+ # A marker-only sibling moves neither size nor mtime.
+ "has_variant_state": has_variant_state,
# GGUF row-level transport is ambiguous (variants may differ);
# per-variant detail lives on GgufVariantDetail.
"partial_transport": None,
diff --git a/studio/backend/hub/services/models/gguf_variants.py b/studio/backend/hub/services/models/gguf_variants.py
index bfbc939f62c..4d6cc5a55e8 100644
--- a/studio/backend/hub/services/models/gguf_variants.py
+++ b/studio/backend/hub/services/models/gguf_variants.py
@@ -631,6 +631,35 @@ async def get_gguf_variants_response(
default_variant = default_variant,
)
+ def _with_state_partials(response: GgufVariantsResponse) -> GgufVariantsResponse:
+ """Add quants known only from download state. A sibling cancelled
+ before any file landed has no snapshot entry, so a listing built
+ from the cache alone reads as if it were never asked for, and the
+ row loses its resume."""
+ state = list_partial_gguf_variants_from_state(repo_id, hub_cache = hub_cache)
+ if state is None:
+ return response
+ listed = {v.quant.lower() for v in response.variants if v.quant}
+ extra = [
+ GgufVariantDetail(
+ filename = v.filename,
+ quant = v.quant,
+ display_label = v.display_label,
+ size_bytes = v.size_bytes,
+ download_size_bytes = v.download_size_bytes or v.size_bytes,
+ downloaded = False,
+ partial = True,
+ partial_transport = _partial_transport_for_variant(
+ repo_id, v.quant, repo_cache_dir
+ ),
+ )
+ for v in state[0]
+ if v.quant and v.quant.lower() not in listed
+ ]
+ if not extra:
+ return response
+ return response.model_copy(update = {"variants": [*response.variants, *extra]})
+
# Local directory path (e.g. LM Studio models) — scan filesystem
if is_local_path(repo_id):
variants, has_vision = list_local_gguf_variants(repo_id)
@@ -649,8 +678,10 @@ async def get_gguf_variants_response(
variants, has_vision = list_local_gguf_variants(str(snapshot_scope))
if not (variants or has_vision):
return None
- return _local_response(
- repo_id, variants, has_vision, _complete_quants_under(str(snapshot_scope))
+ return _with_state_partials(
+ _local_response(
+ repo_id, variants, has_vision, _complete_quants_under(str(snapshot_scope))
+ )
)
local_only = prefer_local_cache or offline
@@ -662,7 +693,9 @@ async def get_gguf_variants_response(
if cached is not None:
variants, has_vision, complete = cached
# The lister leaves torn quants in: they stay listed for management, but not ready.
- return _local_response(repo_id, variants, has_vision, complete)
+ return _with_state_partials(
+ _local_response(repo_id, variants, has_vision, complete)
+ )
if local_path and is_local_path(local_path):
variants, has_vision = list_local_gguf_variants(local_path)
if variants or has_vision:
@@ -696,8 +729,11 @@ async def get_gguf_variants_response(
cached = list_gguf_variants_from_hf_cache(repo_id, root = hub_cache)
if cached is not None:
variants, has_vision, complete = cached
- # Same reason as the local_only branch above.
- return _local_response(repo_id, variants, has_vision, complete)
+ # Same reason as the local_only branch above, state partials included:
+ # an unreachable Hub is exactly when a resume has nowhere else to surface.
+ return _with_state_partials(
+ _local_response(repo_id, variants, has_vision, complete)
+ )
partial = list_partial_gguf_variants_from_state(repo_id, hub_cache = hub_cache)
if partial is not None:
variants, has_vision = partial
diff --git a/studio/backend/tests/test_cached_gguf_routes.py b/studio/backend/tests/test_cached_gguf_routes.py
index 05e3efaa2ff..4444f28649c 100644
--- a/studio/backend/tests/test_cached_gguf_routes.py
+++ b/studio/backend/tests/test_cached_gguf_routes.py
@@ -2076,3 +2076,131 @@ def test_legacy_delete_delegates_to_shared_service(monkeypatch):
assert result == {"status": "deleted", "repo_id": "org/repo"}
assert calls == [("org/repo", None, "token", "/data/hf/hub")]
+
+
+def test_a_cancelled_siblings_resume_survives_the_local_listing(monkeypatch, tmp_path):
+ """A sibling cancelled before any file landed lives only in download state. The disk-only
+ listing is built from the cache, which cannot see it, so the repo reads as holding one quant
+ and the picker collapses it into a single row, taking the sibling's resume with it."""
+ active = tmp_path / "active"
+ repo_dir = active / "models--Org--Quant"
+ snapshot = repo_dir / "snapshots" / ("d" * 40)
+ snapshot.mkdir(parents = True)
+ (snapshot / "Model-Q4_K_M.gguf").write_bytes(b"\0" * 256)
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text("d" * 40, encoding = "utf-8")
+
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(
+ hub_cache = active, hf_home = tmp_path, source = "studio", cache_home = tmp_path
+ ),
+ )
+ monkeypatch.setattr("hub.utils.hf_cache_state.hf_cache_roots", lambda **kw: [active])
+ monkeypatch.setattr(
+ "hub.utils.hf_cache_state.hf_cache_root",
+ lambda create = False, root = None: (root if root is not None else active),
+ )
+
+ # Disk-only means disk-only: a remote listing here would be the bug this route avoids.
+ def _no_remote(*args, **kwargs):
+ raise AssertionError("remote listing attempted")
+
+ monkeypatch.setattr(GV, "list_gguf_variants", _no_remote)
+
+ # Control: nothing cancelled, so the repo holds one quant and nothing else.
+ only_complete = asyncio.run(GV.get_gguf_variants_response("Org/Quant", prefer_local_cache = True))
+ assert [(v.quant, v.downloaded) for v in only_complete.variants] == [("Q4_K_M", True)]
+
+ from hub.utils import download_manifest
+
+ assert download_manifest.write_cancel_marker("model", "Org/Quant", "Q8_0", hub_cache = active)
+
+ response = asyncio.run(GV.get_gguf_variants_response("Org/Quant", prefer_local_cache = True))
+ assert {v.quant for v in response.variants if v.downloaded} == {"Q4_K_M"}
+ assert {v.quant for v in response.variants if v.partial} == {"Q8_0"}
+
+
+def test_a_cancelled_sibling_survives_a_failed_remote_listing(monkeypatch, tmp_path):
+ """The expander asks the remote-first route. When the Hub cannot answer, offline or a private
+ repo, the fallback reads the cache, which cannot see a sibling cancelled before any file
+ landed. That is exactly when a resume has nowhere else to surface."""
+ active = tmp_path / "active"
+ repo_dir = active / "models--Org--Quant"
+ snapshot = repo_dir / "snapshots" / ("d" * 40)
+ snapshot.mkdir(parents = True)
+ (snapshot / "Model-Q4_K_M.gguf").write_bytes(b"\0" * 256)
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text("d" * 40, encoding = "utf-8")
+
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(
+ hub_cache = active, hf_home = tmp_path, source = "studio", cache_home = tmp_path
+ ),
+ )
+ monkeypatch.setattr("hub.utils.hf_cache_state.hf_cache_roots", lambda **kw: [active])
+ monkeypatch.setattr(
+ "hub.utils.hf_cache_state.hf_cache_root",
+ lambda create = False, root = None: (root if root is not None else active),
+ )
+
+ def _unreachable(*args, **kwargs):
+ raise RuntimeError("hub unreachable")
+
+ monkeypatch.setattr(GV, "list_gguf_variants", _unreachable)
+
+ from hub.utils import download_manifest
+
+ assert download_manifest.write_cancel_marker("model", "Org/Quant", "Q8_0", hub_cache = active)
+
+ # No prefer_local_cache: this is the route the expander uses.
+ response = asyncio.run(GV.get_gguf_variants_response("Org/Quant"))
+ assert {v.quant for v in response.variants if v.downloaded} == {"Q4_K_M"}
+ assert {v.quant for v in response.variants if v.partial} == {"Q8_0"}
+
+
+def test_a_cancelled_siblings_marker_shows_on_the_repo_row(monkeypatch, tmp_path):
+ """A sibling cancelled before any file landed moves neither the repo's bytes nor its mtime,
+ and its own partial flag stays false while another quant is clean. Without a signal of its
+ own on the row, a reader watching for on-disk change cannot see it happen."""
+ active = tmp_path / "active"
+ repo_dir = active / "models--Org--Quant"
+ snapshot = repo_dir / "snapshots" / ("d" * 40)
+ snapshot.mkdir(parents = True)
+ (snapshot / "Model-Q4_K_M.gguf").write_bytes(b"\0" * 256)
+ (repo_dir / "refs").mkdir(parents = True)
+ (repo_dir / "refs" / "main").write_text("d" * 40, encoding = "utf-8")
+
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.get_hf_cache_paths",
+ lambda: SimpleNamespace(
+ hub_cache = active, hf_home = tmp_path, source = "studio", cache_home = tmp_path
+ ),
+ )
+ monkeypatch.setattr("hub.utils.hf_cache_state.hf_cache_roots", lambda **kw: [active])
+ monkeypatch.setattr(
+ "hub.utils.hf_cache_state.hf_cache_root",
+ lambda create = False, root = None: (root if root is not None else active),
+ )
+
+ from hub.services.models import cache_inventory
+ from hub.utils import download_manifest, inventory_scan
+
+ def _row():
+ inventory_scan.invalidate_hf_cache_scans()
+ cache_inventory.invalidate_hf_cache_scans()
+ rows = cache_inventory._scan_cached_gguf()
+ return next(r for r in rows if r["repo_id"] == "Org/Quant")
+
+ before = _row()
+ assert before["has_variant_state"] is False
+
+ assert download_manifest.write_cancel_marker("model", "Org/Quant", "Q8_0", hub_cache = active)
+
+ after = _row()
+ # The signals that would otherwise have to carry it.
+ assert after["size_bytes"] == before["size_bytes"]
+ assert after["last_modified"] == before["last_modified"]
+ assert after["partial"] is False
+ assert after["has_variant_state"] is True
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index c2db5137f02..2bb0a58fead 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -355,6 +355,9 @@ export interface CachedGgufRepo {
/** True when the repo ships an mmproj adapter (image inputs). Optional for
* older-backend compatibility. */
has_vision?: boolean;
+ /** True when some quant has a download manifest or cancel marker. Optional
+ * for older-backend compatibility. */
+ has_variant_state?: boolean;
partial?: boolean;
capabilities?: CachedRepoCapabilities | null;
}
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index 4a8ad80dabb..4b71561cc83 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -1597,7 +1597,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
loadedGpuIds: null,
loadedGpuIndexKind: null,
expandQuantizations: loadBool(CHAT_EXPAND_QUANTIZATIONS_KEY, false),
- showAllQuantizations: loadBool(CHAT_SHOW_ALL_QUANTIZATIONS_KEY, true),
+ // Off by default: On Device lists what is on disk, not the whole repo.
+ showAllQuantizations: loadBool(CHAT_SHOW_ALL_QUANTIZATIONS_KEY, false),
fitOnDeviceOnly: loadBool(MODELS_FIT_ON_DEVICE_ONLY_KEY, false),
loadedIsMultimodal: false,
loadedIsDiffusion: false,
diff --git a/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx b/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx
index cbe5f8974a5..6f6fd685a0e 100644
--- a/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx
+++ b/studio/frontend/src/features/hub/catalog/gguf-download-card.tsx
@@ -291,11 +291,7 @@ export function QuantOptionsMenu({
const pinned = pinnedKeys.includes(pinKey(repoId, quant));
const deviceType = usePlatformStore((s) => s.deviceType);
const revealLabel =
- deviceType === "mac"
- ? "Reveal in Finder"
- : deviceType === "windows"
- ? "Reveal in File Explorer"
- : "Reveal in File Manager";
+ deviceType === "mac" ? "Reveal in Finder" : "Reveal in Folder";
const handleCopyPath = useCallback(async () => {
try {
const { path } = await getCachedModelPath(repoId, quant);
diff --git a/studio/frontend/src/features/hub/catalog/path-info-button.tsx b/studio/frontend/src/features/hub/catalog/path-info-button.tsx
index 403bb0148e7..31463dc8833 100644
--- a/studio/frontend/src/features/hub/catalog/path-info-button.tsx
+++ b/studio/frontend/src/features/hub/catalog/path-info-button.tsx
@@ -29,11 +29,7 @@ export function RevealPathButton({
}) {
const deviceType = usePlatformStore((s) => s.deviceType);
const revealLabel =
- deviceType === "mac"
- ? "Reveal in Finder"
- : deviceType === "windows"
- ? "Reveal in File Explorer"
- : "Reveal in File Manager";
+ deviceType === "mac" ? "Reveal in Finder" : "Reveal in Folder";
return (
<Tooltip>
diff --git a/studio/frontend/src/features/hub/index.ts b/studio/frontend/src/features/hub/index.ts
index c2925f5790b..933b5203e37 100644
--- a/studio/frontend/src/features/hub/index.ts
+++ b/studio/frontend/src/features/hub/index.ts
@@ -21,6 +21,7 @@ export {
listGgufVariants,
listScanFolders,
removeScanFolder,
+ useGgufVariantsCacheVersions,
} from "./inventory";
export {
type HfModelResult,
diff --git a/studio/frontend/src/features/hub/inventory/index.ts b/studio/frontend/src/features/hub/inventory/index.ts
index dd8e161708d..5d832edace0 100644
--- a/studio/frontend/src/features/hub/inventory/index.ts
+++ b/studio/frontend/src/features/hub/inventory/index.ts
@@ -70,7 +70,10 @@ export {
type HubInventoryKind,
type HubInventory,
} from "./use-hub-inventory";
-export { useGgufVariantsCacheVersion } from "./use-gguf-variants-cache-version";
+export {
+ useGgufVariantsCacheVersion,
+ useGgufVariantsCacheVersions,
+} from "./use-gguf-variants-cache-version";
export type {
CachedInventoryRow,
InventoryHint,
diff --git a/studio/frontend/src/features/hub/inventory/types.ts b/studio/frontend/src/features/hub/inventory/types.ts
index d1f2f993cde..9e6af055718 100644
--- a/studio/frontend/src/features/hub/inventory/types.ts
+++ b/studio/frontend/src/features/hub/inventory/types.ts
@@ -50,6 +50,9 @@ export interface CachedInventoryRow {
lastModified?: number | null;
partial?: boolean;
partialTransport?: string | null;
+ /** A download manifest or cancel marker exists for some quant. Moves when a
+ * sibling is cancelled, which changes neither bytes nor mtime. */
+ hasVariantState?: boolean;
pipelineTag?: string | null;
tags?: string[];
libraryName?: string | null;
diff --git a/studio/frontend/src/features/hub/inventory/use-gguf-variants-cache-version.ts b/studio/frontend/src/features/hub/inventory/use-gguf-variants-cache-version.ts
index ad8bfc9fbaf..6188cc42e61 100644
--- a/studio/frontend/src/features/hub/inventory/use-gguf-variants-cache-version.ts
+++ b/studio/frontend/src/features/hub/inventory/use-gguf-variants-cache-version.ts
@@ -1,18 +1,32 @@
// 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 { useSyncExternalStore } from "react";
+import { useCallback, useSyncExternalStore } from "react";
import {
getGgufVariantsCacheVersion,
subscribeGgufVariantsCache,
} from "./gguf-variants-cache-events";
-export function useGgufVariantsCacheVersion(
- repoId?: string | null,
-): string {
+export function useGgufVariantsCacheVersion(repoId?: string | null): string {
return useSyncExternalStore(
subscribeGgufVariantsCache,
() => getGgufVariantsCacheVersion(repoId),
() => getGgufVariantsCacheVersion(repoId),
);
}
+
+/** One snapshot over several repos. Invalidation is per repo, so a caller
+ * watching a list has to read every repo's version, not just the global one. */
+export function useGgufVariantsCacheVersions(
+ repoIds: readonly string[],
+): string {
+ const getSnapshot = useCallback(
+ () => repoIds.map((id) => getGgufVariantsCacheVersion(id)).join(","),
+ [repoIds],
+ );
+ return useSyncExternalStore(
+ subscribeGgufVariantsCache,
+ getSnapshot,
+ getSnapshot,
+ );
+}
diff --git a/studio/frontend/src/features/hub/inventory/view-models.ts b/studio/frontend/src/features/hub/inventory/view-models.ts
index 41b4733d192..c31a48ee3bc 100644
--- a/studio/frontend/src/features/hub/inventory/view-models.ts
+++ b/studio/frontend/src/features/hub/inventory/view-models.ts
@@ -166,6 +166,7 @@ export function buildCachedInventoryRow(
cache_path?: string;
partial?: boolean;
partial_transport?: string | null;
+ has_variant_state?: boolean;
pipeline_tag?: string | null;
tags?: string[];
library_name?: string | null;
@@ -224,6 +225,7 @@ export function buildCachedInventoryRow(
: null,
partial: row.partial ?? false,
partialTransport: row.partial_transport ?? null,
+ hasVariantState: row.has_variant_state ?? false,
pipelineTag: row.pipeline_tag ?? null,
tags: row.tags,
libraryName: row.library_name ?? null,
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/model-row-menu.tsx b/studio/frontend/src/features/model-picker/components/model-selector/model-row-menu.tsx
index c807d8957fc..e2d86abb4c4 100644
--- a/studio/frontend/src/features/model-picker/components/model-selector/model-row-menu.tsx
+++ b/studio/frontend/src/features/model-picker/components/model-selector/model-row-menu.tsx
@@ -101,11 +101,7 @@ export function ModelRowMenu({
}) {
const deviceType = usePlatformStore((s) => s.deviceType);
const revealLabel =
- deviceType === "mac"
- ? "Reveal in Finder"
- : deviceType === "windows"
- ? "Reveal in File Explorer"
- : "Reveal in File Manager";
+ deviceType === "mac" ? "Reveal in Finder" : "Reveal in Folder";
const [deleteOpen, setDeleteOpen] = useState(false);
const [deleting, setDeleting] = useState(false);
const [updateOpen, setUpdateOpen] = useState(false);
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.tsx
index 68d86bb4fff..f1bad51550d 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
@@ -34,7 +34,9 @@ import {
TrainIcon,
TransportConflictDialog,
deleteCachedModel,
+ invalidateGgufVariantsCache,
listGgufVariants as listGgufVariantsCached,
+ useGgufVariantsCacheVersions,
useHubInfiniteScroll,
} from "@/features/hub";
import {
@@ -118,7 +120,21 @@ import {
matchesFormatFilter,
paramsFromId,
} from "./recommended-fit";
+import {
+ ggufVariantsMatchForPicker,
+ modelIdsMatchForPicker,
+ soleQuantRowState,
+} from "./row-identity";
import { parseMetaTokens, splitRepoLabel } from "./row-meta";
+import {
+ type SoleQuantEntry,
+ type SoleQuantTarget,
+ createSoleQuantReader,
+ partitionSoleQuants,
+ soleQuantFingerprint,
+ soleQuantKey,
+ takeDriftedRepos,
+} from "./sole-quant-cache";
import type {
DeletedModelRef,
ExternalModelOption,
@@ -126,6 +142,11 @@ import type {
ModelOption,
ModelSelectorChangeMeta,
} from "./types";
+import {
+ shouldMountVariantExpander,
+ toggleAutoExpandedRow,
+ visibleGgufVariants,
+} from "./variant-visibility";
function dedupe(values: string[]): string[] {
return [...new Set(values.filter(Boolean))];
@@ -389,41 +410,6 @@ function CapabilityIcons({ caps }: { caps: ModelCapabilities }) {
);
}
-function normalizeModelIdForPicker(modelId: string): string {
- const trimmed = modelId.trim();
- const slashPath = trimmed.replace(/\\/g, "/").replace(/\/+$/, "");
- const caseInsensitive =
- !/^(\/|\.{1,2}\/|~\/)/.test(slashPath) ||
- /^[A-Za-z]:\//.test(slashPath) ||
- slashPath.startsWith("//") ||
- /^\/mnt\/[A-Za-z](?:\/|$)/.test(slashPath);
- return caseInsensitive ? slashPath.toLowerCase() : slashPath;
-}
-
-function modelIdsMatchForPicker(
- left: string | null | undefined,
- right: string | null | undefined,
-): boolean {
- return Boolean(
- left &&
- right &&
- normalizeModelIdForPicker(left) === normalizeModelIdForPicker(right),
- );
-}
-
-function normalizeGgufVariantForPicker(variant: string | null | undefined) {
- return variant?.trim().toLowerCase() ?? "";
-}
-
-function ggufVariantsMatchForPicker(
- left: string | null | undefined,
- right: string | null | undefined,
-): boolean {
- return (
- normalizeGgufVariantForPicker(left) === normalizeGgufVariantForPicker(right)
- );
-}
-
function isRuntimeLoadedModel(
loadedModelId: string | undefined,
activeGgufVariant: string | null | undefined,
@@ -458,6 +444,7 @@ function ModelRow({
hideOwner,
downloaded,
showVision,
+ quantChip,
className,
}: {
label: string;
@@ -484,6 +471,8 @@ function ModelRow({
downloaded?: boolean;
/** Show a Vision badge on the name (On Device, read from GGUF metadata). */
showVision?: boolean;
+ /** Grey chip beside the name, for rows that load one specific quant. */
+ quantChip?: string | null;
className?: string;
}) {
const exceeds = vramStatus === "exceeds";
@@ -532,6 +521,11 @@ function ModelRow({
</span>
) : null}
<span className="min-w-0 flex-1 truncate">{name}</span>
+ {quantChip ? (
+ <span className="ml-2 shrink-0 rounded-md bg-black/[0.06] px-1.5 py-px font-mono text-ui-10 text-muted-foreground dark:bg-white/[0.1]">
+ {quantChip}
+ </span>
+ ) : null}
</span>
<span className="ml-auto flex shrink-0 items-center gap-1.5">
{showCaps && <CapabilityIcons caps={caps} />}
@@ -715,6 +709,129 @@ function ggufVariantExpectedBytes(variant: GgufVariantDetail): number {
: variant.size_bytes;
}
+/** The one quant a repo holds, plus the vision flag read with it. The
+ * collapsed row never mounts the expander, so this is its only source. */
+interface SoleDownloadedQuant {
+ variant: GgufVariantDetail;
+ hasVision: boolean;
+}
+
+/** The repo's one complete quant, or null when it holds none, holds several,
+ * or could not be read. Disk-only and client-cached: no remote listing. */
+async function readSoleQuant(
+ target: SoleQuantTarget,
+ hfToken?: string,
+): Promise<SoleDownloadedQuant | null> {
+ try {
+ const res = await listGgufVariantsCached(target.repoId, hfToken, {
+ preferLocalCache: true,
+ localPath: target.localSource,
+ });
+ const normalized = normalizeGgufVariantsResponse(res);
+ const local = normalized.variants;
+ // One file on disk and nothing torn beside it. A partial quant keeps the
+ // expander, where it can be resumed.
+ if (local.length !== 1 || local[0].downloaded !== true) return null;
+ return { variant: local[0], hasVision: normalized.hasVision };
+ } catch {
+ return null;
+ }
+}
+
+const EMPTY_SOLE_QUANT_ENTRIES: ReadonlyMap<
+ string,
+ SoleQuantEntry<SoleDownloadedQuant>
+> = new Map();
+// Reads run a few at a time, so a large cache doesn't fire one request per
+// repo. A worker pool, not fixed batches: one slow repo holds up only itself.
+const SOLE_QUANT_WORKERS = 6;
+
+/** On Device repos holding exactly one quant on disk, keyed by repo id. With
+ * "Show all quantizations" off there is nothing else to pick, so those repos
+ * collapse into one pinned-style row. Results are kept per repo, so one
+ * repo's download or delete leaves every other row as it was. */
+function useSoleDownloadedQuants(
+ repos: readonly CachedGgufRepo[],
+ { enabled, hfToken }: { enabled: boolean; hfToken?: string },
+): {
+ quants: ReadonlyMap<string, SoleDownloadedQuant>;
+ pending: ReadonlySet<string>;
+} {
+ const repoIds = useMemo(() => repos.map((repo) => repo.repo_id), [repos]);
+ // A download or delete invalidates one repo, so watch each repo's version.
+ const variantsVersion = useGgufVariantsCacheVersions(repoIds);
+ const targets = useMemo(() => {
+ const versions = variantsVersion.split(",");
+ return repos.map((repo, index) => {
+ const localSource = repo.load_id || repo.cache_path || null;
+ const fingerprint = soleQuantFingerprint(repo);
+ return {
+ repoId: repo.repo_id,
+ localSource,
+ fingerprint,
+ key: soleQuantKey(versions[index], localSource, fingerprint),
+ };
+ });
+ }, [repos, variantsVersion]);
+
+ const [entries, setEntries] =
+ useState<ReadonlyMap<string, SoleQuantEntry<SoleDownloadedQuant>>>(
+ EMPTY_SOLE_QUANT_ENTRIES,
+ );
+ const { quants, pending, stale } = useMemo(
+ () => partitionSoleQuants(targets, entries, { enabled }),
+ [targets, entries, enabled],
+ );
+
+ // A change outside this tab, another window or the CLI, moves the row's
+ // bytes without touching this instance's variants cache. Drop that repo's
+ // cached listing so the read, and every other reader, sees disk again.
+ const fingerprintsRef = useRef(new Map<string, string>());
+ useEffect(() => {
+ for (const repoId of takeDriftedRepos(targets, fingerprintsRef.current)) {
+ invalidateGgufVariantsCache(repoId);
+ }
+ }, [targets]);
+
+ // Reads outlive a render, so they run outside it. The token is read at call
+ // time, so a change to it does not strand the reader.
+ const hfTokenRef = useRef(hfToken);
+ hfTokenRef.current = hfToken;
+ const mountedRef = useRef(true);
+ useEffect(() => {
+ // Set on setup, not just cleared on teardown: StrictMode replays effects,
+ // and a ref left false would discard every later read.
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ };
+ }, []);
+
+ const readerRef = useRef<ReturnType<
+ typeof createSoleQuantReader<SoleDownloadedQuant>
+ > | null>(null);
+ if (readerRef.current === null) {
+ readerRef.current = createSoleQuantReader<SoleDownloadedQuant>({
+ workers: SOLE_QUANT_WORKERS,
+ read: (target) => readSoleQuant(target, hfTokenRef.current),
+ commit: (target, quant) => {
+ if (!mountedRef.current) return;
+ setEntries((prev) => {
+ const next = new Map(prev);
+ next.set(target.repoId, { key: target.key, quant });
+ return next;
+ });
+ },
+ });
+ }
+
+ useEffect(() => {
+ if (stale.length > 0) readerRef.current?.start(stale);
+ }, [stale]);
+
+ return { quants, pending };
+}
+
function GgufVariantExpander({
repoId,
loadId,
@@ -934,15 +1051,16 @@ function GgufVariantExpander({
}, [variants, effectiveRecommended, getGgufFit]);
// On Device only: when Show all quantizations is off, list quants already on
- // disk. Recommended and other browse lists always show every quant.
+ // disk, torn ones included. Browse lists always show every quant.
const showAllQuantizations = useChatRuntimeStore(
(s) => s.showAllQuantizations,
);
const displayVariants = useMemo(() => {
if (!sortedVariants) return sortedVariants;
- return showAllQuantizations || !onDevice
- ? sortedVariants
- : sortedVariants.filter((v) => v.downloaded);
+ return visibleGgufVariants(sortedVariants, {
+ onDevice,
+ showAll: showAllQuantizations,
+ });
}, [sortedVariants, showAllQuantizations, onDevice]);
const variantOptionKeys = useMemo(
@@ -1518,19 +1636,30 @@ export function HubModelPicker({
}, []);
// When on, On Device GGUF repos show their quantizations without a click.
const expandQuantizations = useChatRuntimeStore((s) => s.expandQuantizations);
+ // Off: On Device lists only downloaded quants, so a repo holding one collapses
+ // into a single row instead of hiding it behind an expander.
+ const showAllQuantizations = useChatRuntimeStore(
+ (s) => s.showAllQuantizations,
+ );
// Shared with the Hub page: list only models sized within the device budget.
const fitOnDeviceOnly = useChatRuntimeStore((s) => s.fitOnDeviceOnly);
const setFitOnDeviceOnly = useChatRuntimeStore((s) => s.setFitOnDeviceOnly);
- // Repos the user clicked to collapse while expand-by-default is on. Kept in
- // memory only, so it resets on reload (and when the setting is toggled).
+ // Repos the user clicked to collapse while expand-by-default is on, and the
+ // ones they clicked back open. Kept in memory only, so both reset on reload
+ // (and when the setting is toggled).
const [collapsedGgufState, setCollapsedGgufState] = useState<{
expandQuantizations: boolean;
value: Set<string>;
- }>(() => ({ expandQuantizations, value: new Set() }));
- const collapsedGguf =
- collapsedGgufState.expandQuantizations === expandQuantizations
- ? collapsedGgufState.value
- : new Set<string>();
+ reopened: Set<string>;
+ }>(() => ({ expandQuantizations, value: new Set(), reopened: new Set() }));
+ const expansionMatchesSetting =
+ collapsedGgufState.expandQuantizations === expandQuantizations;
+ const collapsedGguf = expansionMatchesSetting
+ ? collapsedGgufState.value
+ : new Set<string>();
+ const reopenedGguf = expansionMatchesSetting
+ ? collapsedGgufState.reopened
+ : new Set<string>();
const isGgufExpanded = useCallback(
(id: string) =>
expandQuantizations ? !collapsedGguf.has(id) : expandedGguf === id,
@@ -1539,23 +1668,31 @@ export function HubModelPicker({
// Toggle a repo's quantizations: flip the collapse set when expand-by-default
// is on, otherwise drive the single-open expandedGguf state.
const toggleGgufExpanded = useCallback(
- (id: string) => {
- if (expandQuantizations) {
- setCollapsedGgufState((prev) => {
- const current =
- prev.expandQuantizations === expandQuantizations
- ? prev.value
- : new Set<string>();
- const next = new Set(current);
- if (next.has(id)) next.delete(id);
- else next.add(id);
- return { expandQuantizations, value: next };
- });
- } else {
+ // `showing` is what the row actually renders, which is not the collapse
+ // set alone: a row held back by its sole-quant probe shows nothing, and a
+ // click on it should open it rather than collapse what is already hidden.
+ (id: string, showing = isGgufExpanded(id)) => {
+ if (!expandQuantizations) {
setExpandedGguf((prev) => (prev === id ? null : id));
+ return;
}
+ setCollapsedGgufState((prev) => {
+ const matches = prev.expandQuantizations === expandQuantizations;
+ const next = toggleAutoExpandedRow(
+ {
+ collapsed: matches ? prev.value : new Set(),
+ reopened: matches ? prev.reopened : new Set(),
+ },
+ { repoId: id, showing },
+ );
+ return {
+ expandQuantizations,
+ value: next.collapsed,
+ reopened: next.reopened,
+ };
+ });
},
- [expandQuantizations],
+ [expandQuantizations, isGgufExpanded],
);
const [pinnedCollapsed, setPinnedCollapsed] = useState(false);
@@ -2106,6 +2243,12 @@ export function HubModelPicker({
// logic must use this (not visibleCachedModels) or the picker can go blank.
const visibleCachedModelRows = chatOnly ? [] : visibleCachedModels;
+ // Unfiltered list, so typing a query doesn't re-run resolution.
+ const soleQuants = useSoleDownloadedQuants(sortedCachedGguf, {
+ enabled: section === "downloaded" && !showAllQuantizations,
+ hfToken: hfToken || undefined,
+ });
+
// Pinned entries surface in their own section above the Unsloth heading.
// GGUF quants pin individually and their repo stays listed below; non-GGUF
// repos pin whole and leave the Unsloth / Other models groups.
@@ -2895,10 +3038,114 @@ export function HubModelPicker({
);
};
+ // One quant on disk with "Show all quantizations" off: the expander would
+ // list just that quant, so the row carries it as a chip and loads it in one
+ // click, like a pinned quant.
+ const renderSoleQuantGgufRow = (
+ c: (typeof visibleCachedGguf)[number],
+ sole: SoleDownloadedQuant,
+ ) => {
+ const variant = sole.variant;
+ const optionKey = makeModelOptionKey("downloaded-gguf", c.repo_id);
+ // The row names one quant, so the repo running a different one is not it.
+ const rowState = soleQuantRowState({
+ pickerValue: value,
+ repoId: c.repo_id,
+ quant: variant.quant,
+ loadedModelId,
+ activeGgufVariant,
+ });
+ const isSelected = rowState.selected;
+ const expectedBytes = ggufVariantExpectedBytes(variant);
+ const isPinned = pinnedSet.has(pinKey(c.repo_id, variant.quant));
+ const selectMeta: ModelSelectorChangeMeta = {
+ source: "hub",
+ isLora: false,
+ loadId: c.load_id,
+ ggufVariant: variant.quant,
+ isDownloaded: true,
+ expectedBytes,
+ isGguf: true,
+ };
+ return (
+ <div key={c.repo_id} className={downloadedRowShellClassName(isSelected)}>
+ <div className="min-w-0 flex-1">
+ <ModelRow
+ label={c.repo_id}
+ tooltipText={localPathTooltip(c.repo_id, c.cache_path)}
+ meta={`GGUF · ${formatBytes(variant.size_bytes)}`}
+ quantChip={variant.quant}
+ showVision={c.has_vision || sole.hasVision}
+ selected={isSelected}
+ loaded={rowState.loaded}
+ optionProps={hubModelList.getOptionProps(optionKey, isSelected)}
+ onClick={() => onSelect(c.repo_id, selectMeta)}
+ vramStatus={null}
+ className={downloadedRowButtonClassName}
+ />
+ </div>
+ <span className="mr-1 flex shrink-0 items-center opacity-0 transition-opacity focus-within:opacity-100 group-hover:opacity-100 group-focus-within:opacity-100">
+ {onConfigure && (
+ <ModelLoadSettingsAction
+ ariaLabel={`Inference settings for ${c.repo_id} ${variant.quant}`}
+ onConfigure={() => onConfigure(c.repo_id, selectMeta)}
+ />
+ )}
+ <ModelRowMenu
+ ariaLabel={`More options for ${c.repo_id} ${variant.quant}`}
+ iconClassName="size-3"
+ cachePath={{ repoId: c.repo_id, variant: variant.quant }}
+ pin={{
+ pinned: isPinned,
+ pinLabel: "Pin to top",
+ unpinLabel: "Unpin",
+ onToggle: () => togglePinned(c.repo_id, variant.quant),
+ }}
+ del={{
+ title: "Delete cached model?",
+ description: (
+ <>
+ This will remove{" "}
+ <span className="font-medium text-foreground">
+ {c.repo_id} ({variant.quant})
+ </span>{" "}
+ from disk. You can re-download it later.
+ </>
+ ),
+ successMessage: `Deleted ${c.repo_id} ${variant.quant}`,
+ disabled: deleteDisabled,
+ onConfirm: async () => {
+ await deleteCachedModel(
+ c.repo_id,
+ variant.quant,
+ hfToken || undefined,
+ c.cache_path || undefined,
+ );
+ // The file is gone, so drop its pin too.
+ if (isPinned) togglePinned(c.repo_id, variant.quant);
+ prunePinnedQuantValidation(c.repo_id, variant.quant);
+ refreshCachedLists();
+ },
+ }}
+ />
+ </span>
+ </div>
+ );
+ };
+
// Shared row renderers so Downloaded (Unsloth) and Other models render alike.
const renderDownloadedGgufRow = (c: (typeof visibleCachedGguf)[number]) => {
const optionKey = makeModelOptionKey("downloaded-gguf", c.repo_id);
const isSelected = value === c.repo_id;
+ const soleQuant = soleQuants.quants.get(c.repo_id);
+ if (soleQuant) return renderSoleQuantGgufRow(c, soleQuant);
+ // Auto-expansion waits for the probe: expanding every row first would
+ // mount an expander, and its remote listing, for repos about to collapse.
+ const expanderOpen = shouldMountVariantExpander({
+ expanded: isGgufExpanded(c.repo_id),
+ autoExpand: expandQuantizations && !reopenedGguf.has(c.repo_id),
+ soleQuantsPending: soleQuants.pending.has(c.repo_id),
+ });
return (
<div key={c.repo_id}>
<div className={downloadedRowShellClassName(isSelected)}>
@@ -2916,9 +3163,9 @@ export function HubModelPicker({
"required",
)}
optionProps={hubModelList.getOptionProps(optionKey, isSelected)}
- onClick={() => toggleGgufExpanded(c.repo_id)}
+ onClick={() => toggleGgufExpanded(c.repo_id, expanderOpen)}
onArrowDownIntoChildren={
- isGgufExpanded(c.repo_id)
+ expanderOpen
? () => focusFirstChildOption(optionKey)
: undefined
}
@@ -2928,7 +3175,7 @@ export function HubModelPicker({
</div>
<span aria-hidden="true" className="mr-1 h-6 w-[26px] shrink-0" />
</div>
- {isGgufExpanded(c.repo_id) && (
+ {expanderOpen && (
<GgufVariantExpander
repoId={c.repo_id}
loadId={c.load_id}
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/row-identity.ts b/studio/frontend/src/features/model-picker/components/model-selector/row-identity.ts
new file mode 100644
index 00000000000..0bda944fdfd
--- /dev/null
+++ b/studio/frontend/src/features/model-picker/components/model-selector/row-identity.ts
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Pure identity helpers for picker rows: id and quant comparison, and the
+// selected/loaded state of a row that stands for one exact quant. No
+// React/DOM deps so they stay easy to test.
+
+export function normalizeModelIdForPicker(modelId: string): string {
+ const trimmed = modelId.trim();
+ const slashPath = trimmed.replace(/\\/g, "/").replace(/\/+$/, "");
+ const caseInsensitive =
+ !/^(\/|\.{1,2}\/|~\/)/.test(slashPath) ||
+ /^[A-Za-z]:\//.test(slashPath) ||
+ slashPath.startsWith("//") ||
+ /^\/mnt\/[A-Za-z](?:\/|$)/.test(slashPath);
+ return caseInsensitive ? slashPath.toLowerCase() : slashPath;
+}
+
+export function modelIdsMatchForPicker(
+ left: string | null | undefined,
+ right: string | null | undefined,
+): boolean {
+ return Boolean(
+ left &&
+ right &&
+ normalizeModelIdForPicker(left) === normalizeModelIdForPicker(right),
+ );
+}
+
+export function normalizeGgufVariantForPicker(
+ variant: string | null | undefined,
+) {
+ return variant?.trim().toLowerCase() ?? "";
+}
+
+export function ggufVariantsMatchForPicker(
+ left: string | null | undefined,
+ right: string | null | undefined,
+): boolean {
+ return (
+ normalizeGgufVariantForPicker(left) === normalizeGgufVariantForPicker(right)
+ );
+}
+
+/** Selected and loaded state for a row that names one quant, such as a pinned
+ * quant or an On Device repo holding a single quant.
+ *
+ * Loaded is exact: only the running quant wears the badge. Selected follows
+ * the picker's value, minus the case where the repo is running a different
+ * quant, so the row cannot claim a pick that points elsewhere. Compare panes
+ * hold a staged value while another pane's model is resident, so a repo that
+ * is not the loaded one stays selected on its value alone. */
+export function soleQuantRowState({
+ pickerValue,
+ repoId,
+ quant,
+ loadedModelId,
+ activeGgufVariant,
+}: {
+ pickerValue: string | null | undefined;
+ repoId: string;
+ quant: string;
+ loadedModelId: string | null | undefined;
+ activeGgufVariant: string | null | undefined;
+}): { selected: boolean; loaded: boolean } {
+ const repoIsLoaded = modelIdsMatchForPicker(loadedModelId, repoId);
+ const quantIsLoaded =
+ repoIsLoaded && ggufVariantsMatchForPicker(activeGgufVariant, quant);
+ return {
+ selected: pickerValue === repoId && (!repoIsLoaded || quantIsLoaded),
+ loaded: quantIsLoaded,
+ };
+}
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/sole-quant-cache.ts b/studio/frontend/src/features/model-picker/components/model-selector/sole-quant-cache.ts
new file mode 100644
index 00000000000..4817f891e92
--- /dev/null
+++ b/studio/frontend/src/features/model-picker/components/model-selector/sole-quant-cache.ts
@@ -0,0 +1,147 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Bookkeeping for the On Device sole-quant probe: what is known, what is
+// still being read, and what needs reading. Per repo, so one repo's
+// invalidation leaves the rest of the list alone. No React/DOM deps so it
+// stays easy to test.
+
+/** A repo to probe, tagged with the cache version and location it reads at,
+ * and separately with the bytes on disk behind it. */
+export interface SoleQuantTarget {
+ repoId: string;
+ localSource: string | null;
+ fingerprint: string;
+ key: string;
+}
+
+/** A probe result. A null quant means the repo has no single complete quant,
+ * including when the read failed: either way the row stays expandable. */
+export interface SoleQuantEntry<T> {
+ key: string;
+ quant: T | null;
+}
+
+/** Identity of one repo's probe. Moves when that repo's variants cache is
+ * invalidated, the row points at another directory, or the bytes on disk
+ * change under us. */
+export function soleQuantKey(
+ version: string | undefined,
+ localSource: string | null,
+ fingerprint = "",
+): string {
+ return `${version ?? ""}::${localSource ?? ""}::${fingerprint}`;
+}
+
+/** What the inventory reports about a repo's files. A change here means disk
+ * moved, including from outside this tab, so the cached listing is suspect.
+ *
+ * Download state is part of it: a sibling cancelled before any file landed
+ * moves neither the bytes nor the mtime, and the repo's own partial flag
+ * stays false while another quant is clean, so nothing else would notice. */
+export function soleQuantFingerprint(repo: {
+ size_bytes?: number;
+ last_modified?: number;
+ has_variant_state?: boolean;
+}): string {
+ return `${repo.size_bytes ?? ""}:${repo.last_modified ?? ""}:${
+ repo.has_variant_state ? "state" : ""
+ }`;
+}
+
+/** Split the listed repos into resolved rows, repos still being read, and
+ * repos needing a read. A repo holds its result until its own key moves. */
+export function partitionSoleQuants<T>(
+ targets: readonly SoleQuantTarget[],
+ entries: ReadonlyMap<string, SoleQuantEntry<T>>,
+ { enabled }: { enabled: boolean },
+): {
+ quants: ReadonlyMap<string, T>;
+ pending: ReadonlySet<string>;
+ stale: SoleQuantTarget[];
+} {
+ const quants = new Map<string, T>();
+ const pending = new Set<string>();
+ const stale: SoleQuantTarget[] = [];
+ if (!enabled) return { quants, pending, stale };
+ for (const target of targets) {
+ const entry = entries.get(target.repoId);
+ if (!entry || entry.key !== target.key) {
+ pending.add(target.repoId);
+ stale.push(target);
+ continue;
+ }
+ if (entry.quant) quants.set(target.repoId, entry.quant);
+ }
+ return { quants, pending, stale };
+}
+
+/** Runs the reads. Kept apart from React so the ordering rules below can be
+ * exercised directly: a repo is read once per key, and a read whose repo has
+ * since moved on is dropped rather than committed over the newer result. */
+export function createSoleQuantReader<T>({
+ workers,
+ read,
+ commit,
+}: {
+ workers: number;
+ read: (target: SoleQuantTarget) => Promise<T | null>;
+ commit: (target: SoleQuantTarget, quant: T | null) => void;
+}): { start: (targets: readonly SoleQuantTarget[]) => void } {
+ const inFlight = new Map<string, string>();
+ const queue: SoleQuantTarget[] = [];
+ let active = 0;
+
+ const owns = (target: SoleQuantTarget) =>
+ inFlight.get(target.repoId) === target.key;
+
+ const drain = async () => {
+ while (queue.length > 0) {
+ const target = queue.shift();
+ // Superseded before it started, so there is nothing to read.
+ if (!(target && owns(target))) continue;
+ const quant = await read(target).catch(() => null);
+ // Superseded while reading: the newer read owns this repo now.
+ if (!owns(target)) continue;
+ inFlight.delete(target.repoId);
+ commit(target, quant);
+ }
+ active -= 1;
+ };
+
+ return {
+ start(targets) {
+ for (const target of targets) {
+ if (owns(target)) continue;
+ inFlight.set(target.repoId, target.key);
+ queue.push(target);
+ }
+ while (active < workers && queue.length > 0) {
+ active += 1;
+ void drain();
+ }
+ },
+ };
+}
+
+/** Repos whose bytes moved since they were last seen, recording what is seen
+ * now. Their cached listing predates the change, so it should be dropped.
+ *
+ * Compares the fingerprint alone, never the probe key: the key also carries
+ * the variants cache version, and dropping a listing bumps that version, so
+ * comparing keys would invalidate on its own effect forever. */
+export function takeDriftedRepos(
+ targets: readonly SoleQuantTarget[],
+ seen: Map<string, string>,
+): string[] {
+ const drifted: string[] = [];
+ for (const target of targets) {
+ const previous = seen.get(target.repoId);
+ seen.set(target.repoId, target.fingerprint);
+ // First sight records only: there is no earlier listing to drop.
+ if (previous !== undefined && previous !== target.fingerprint) {
+ drifted.push(target.repoId);
+ }
+ }
+ return drifted;
+}
diff --git a/studio/frontend/src/features/model-picker/components/model-selector/variant-visibility.ts b/studio/frontend/src/features/model-picker/components/model-selector/variant-visibility.ts
new file mode 100644
index 00000000000..01ca2fbbeb5
--- /dev/null
+++ b/studio/frontend/src/features/model-picker/components/model-selector/variant-visibility.ts
@@ -0,0 +1,56 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// What a quantization expander shows, and when it opens. No React/DOM deps
+// so it stays easy to test.
+
+/** On Device with "Show all quantizations" off lists what the repo holds on
+ * disk: complete quants, plus torn ones, which still occupy space and need a
+ * resume. Quants that were never downloaded stay hidden. Browse lists
+ * (Recommended and the rest) always show every quant. */
+export function visibleGgufVariants<
+ T extends { downloaded?: boolean; partial?: boolean },
+>(
+ variants: readonly T[],
+ { onDevice, showAll }: { onDevice: boolean; showAll: boolean },
+): readonly T[] {
+ if (showAll || !onDevice) return variants;
+ return variants.filter((v) => v.downloaded === true || v.partial === true);
+}
+
+/** Whether a row's expander should mount. Auto-expansion waits for the
+ * sole-quant probe: without the wait, every On Device row opens an expander,
+ * and its remote listing, moments before collapsing into a single row. A
+ * row the user opened is not held back. */
+export function shouldMountVariantExpander({
+ expanded,
+ autoExpand,
+ soleQuantsPending,
+}: {
+ expanded: boolean;
+ autoExpand: boolean;
+ soleQuantsPending: boolean;
+}): boolean {
+ return expanded && !(autoExpand && soleQuantsPending);
+}
+
+/** Next collapse/reopen sets after a click on an auto-expanded row.
+ * `showing` is what the row renders, not what the collapse set says: a row
+ * held back by its sole-quant probe shows nothing, so a click opens it. A
+ * reopened row stops following the auto-expand preference until it is
+ * collapsed again. */
+export function toggleAutoExpandedRow(
+ state: { collapsed: ReadonlySet<string>; reopened: ReadonlySet<string> },
+ { repoId, showing }: { repoId: string; showing: boolean },
+): { collapsed: Set<string>; reopened: Set<string> } {
+ const collapsed = new Set(state.collapsed);
+ const reopened = new Set(state.reopened);
+ if (showing) {
+ collapsed.add(repoId);
+ reopened.delete(repoId);
+ } else {
+ collapsed.delete(repoId);
+ reopened.add(repoId);
+ }
+ return { collapsed, reopened };
+}
diff --git a/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts b/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts
index d60995011ad..7434190e579 100644
--- a/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts
+++ b/studio/frontend/src/features/model-picker/inventory/use-chat-picker-inventory.ts
@@ -34,6 +34,7 @@ function toCachedGgufRepo(row: CachedInventoryRow): CachedGgufRepo {
cache_path: row.cachePath ?? "",
last_modified: row.lastModified ?? undefined,
has_vision: row.capabilities.supportsVision,
+ has_variant_state: row.hasVariantState ?? false,
};
}
diff --git a/studio/frontend/tests/gguf-variants-cache-version.test.ts b/studio/frontend/tests/gguf-variants-cache-version.test.ts
new file mode 100644
index 00000000000..40583e0933f
--- /dev/null
+++ b/studio/frontend/tests/gguf-variants-cache-version.test.ts
@@ -0,0 +1,62 @@
+// 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 {
+ bumpGgufVariantsCacheVersion,
+ getGgufVariantsCacheVersion,
+} from "../src/features/hub/inventory/gguf-variants-cache-events.ts";
+
+const REPO = "unsloth/Qwen3-8B-GGUF";
+const OTHER = "unsloth/Llama-3.1-8B-Instruct-GGUF";
+
+/** What the picker watches: one snapshot over the repos it lists. */
+const snapshot = (repoIds: string[]) =>
+ repoIds.map((id) => getGgufVariantsCacheVersion(id)).join(",");
+
+test("a per-repo invalidation does not move the global version", () => {
+ const before = getGgufVariantsCacheVersion();
+ bumpGgufVariantsCacheVersion(REPO);
+ // Why watching the global version alone leaves a list stale.
+ assert.equal(getGgufVariantsCacheVersion(), before);
+});
+
+test("a per-repo invalidation moves that repo's version", () => {
+ const before = getGgufVariantsCacheVersion(REPO);
+ bumpGgufVariantsCacheVersion(REPO);
+ assert.notEqual(getGgufVariantsCacheVersion(REPO), before);
+});
+
+test("the aggregated snapshot moves when any listed repo is invalidated", () => {
+ const repos = [REPO, OTHER];
+ const before = snapshot(repos);
+ bumpGgufVariantsCacheVersion(OTHER);
+ assert.notEqual(snapshot(repos), before);
+});
+
+test("an unrelated repo's invalidation leaves the snapshot alone", () => {
+ const repos = [REPO, OTHER];
+ const before = snapshot(repos);
+ bumpGgufVariantsCacheVersion("unsloth/gemma-3-4b-it-GGUF");
+ assert.equal(snapshot(repos), before);
+});
+
+test("a global invalidation moves the snapshot too", () => {
+ const repos = [REPO, OTHER];
+ const before = snapshot(repos);
+ bumpGgufVariantsCacheVersion();
+ assert.notEqual(snapshot(repos), before);
+});
+
+test("a version carries no comma, so a joined snapshot splits back per repo", () => {
+ const repos = [REPO, OTHER];
+ bumpGgufVariantsCacheVersion(REPO);
+ const joined = snapshot(repos);
+ // The picker splits the snapshot and pairs it with its repo list by index.
+ assert.deepEqual(
+ joined.split(","),
+ repos.map((id) => getGgufVariantsCacheVersion(id)),
+ );
+});
diff --git a/studio/frontend/tests/sole-quant-cache.test.ts b/studio/frontend/tests/sole-quant-cache.test.ts
new file mode 100644
index 00000000000..1811ed38ef8
--- /dev/null
+++ b/studio/frontend/tests/sole-quant-cache.test.ts
@@ -0,0 +1,368 @@
+// 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 SoleQuantEntry,
+ type SoleQuantTarget,
+ createSoleQuantReader,
+ partitionSoleQuants,
+ soleQuantFingerprint,
+ soleQuantKey,
+ takeDriftedRepos,
+} from "../src/features/model-picker/components/model-selector/sole-quant-cache.ts";
+
+const A = "unsloth/Qwen3-8B-GGUF";
+const B = "unsloth/Llama-3.1-8B-Instruct-GGUF";
+
+/** Two listed repos, each at its own cache version. */
+const targetsAt = (versionA: string, versionB: string): SoleQuantTarget[] => [
+ {
+ repoId: A,
+ localSource: null,
+ fingerprint: "",
+ key: soleQuantKey(versionA, null),
+ },
+ {
+ repoId: B,
+ localSource: null,
+ fingerprint: "",
+ key: soleQuantKey(versionB, null),
+ },
+];
+
+const settled = (
+ targets: SoleQuantTarget[],
+ quants: (string | null)[],
+): Map<string, SoleQuantEntry<string>> =>
+ new Map(
+ targets.map((target, index) => [
+ target.repoId,
+ { key: target.key, quant: quants[index] ?? null },
+ ]),
+ );
+
+test("resolved repos are rows, unread repos are pending", () => {
+ const targets = targetsAt("1:0", "1:0");
+ const { quants, pending, stale } = partitionSoleQuants(
+ targets,
+ settled([targets[0]], ["Q4_K_M"]),
+ { enabled: true },
+ );
+ assert.deepEqual([...quants], [[A, "Q4_K_M"]]);
+ assert.deepEqual([...pending], [B]);
+ assert.deepEqual(
+ stale.map((target) => target.repoId),
+ [B],
+ );
+});
+
+test("one repo's invalidation leaves the other repo's row alone", () => {
+ const before = targetsAt("1:0", "1:0");
+ const entries = settled(before, ["Q4_K_M", "Q8_0"]);
+ // B is downloaded into, so only B's version moves.
+ const after = targetsAt("1:0", "1:7");
+
+ const { quants, pending, stale } = partitionSoleQuants(after, entries, {
+ enabled: true,
+ });
+ assert.deepEqual([...quants], [[A, "Q4_K_M"]]);
+ assert.deepEqual([...pending], [B]);
+ assert.deepEqual(
+ stale.map((target) => target.repoId),
+ [B],
+ );
+});
+
+test("a repo pointed at another directory is re-read", () => {
+ const targets = targetsAt("1:0", "1:0");
+ const entries = settled(targets, ["Q4_K_M", "Q8_0"]);
+ const moved: SoleQuantTarget[] = [
+ {
+ repoId: A,
+ localSource: "/other/cache",
+ fingerprint: "",
+ key: soleQuantKey("1:0", "/other/cache"),
+ },
+ targets[1],
+ ];
+
+ const { quants, pending } = partitionSoleQuants(moved, entries, {
+ enabled: true,
+ });
+ assert.deepEqual([...quants], [[B, "Q8_0"]]);
+ assert.deepEqual([...pending], [A]);
+});
+
+test("a repo with no single quant is settled, not pending", () => {
+ const targets = targetsAt("1:0", "1:0");
+ // A holds two quants, or could not be read: either way no row, no re-read.
+ const { quants, pending, stale } = partitionSoleQuants(
+ targets,
+ settled(targets, [null, "Q8_0"]),
+ { enabled: true },
+ );
+ assert.deepEqual([...quants], [[B, "Q8_0"]]);
+ assert.deepEqual([...pending], []);
+ assert.deepEqual(stale, []);
+});
+
+test("disabled reports nothing and asks for nothing", () => {
+ const targets = targetsAt("1:0", "1:0");
+ const { quants, pending, stale } = partitionSoleQuants(
+ targets,
+ settled(targets, ["Q4_K_M", "Q8_0"]),
+ { enabled: false },
+ );
+ assert.deepEqual([...quants], []);
+ assert.deepEqual([...pending], []);
+ assert.deepEqual(stale, []);
+});
+
+test("a global invalidation moves every repo's key", () => {
+ const before = targetsAt("1:0", "1:0");
+ const entries = settled(before, ["Q4_K_M", "Q8_0"]);
+ const after = targetsAt("2:0", "2:0");
+ const { quants, pending } = partitionSoleQuants(after, entries, {
+ enabled: true,
+ });
+ assert.deepEqual([...quants], []);
+ assert.deepEqual([...pending], [A, B]);
+});
+
+/** A read 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));
+
+const targetAt = (repoId: string, key: string): SoleQuantTarget => ({
+ repoId,
+ localSource: null,
+ fingerprint: "",
+ key,
+});
+
+test("a superseded read never overwrites the fresher result", async () => {
+ const reads = new Map<string, ReturnType<typeof deferred<string | null>>>();
+ const committed: [string, string | null][] = [];
+ const reader = createSoleQuantReader<string>({
+ workers: 4,
+ read: (target) => {
+ const pending = deferred<string | null>();
+ reads.set(target.key, pending);
+ return pending.promise;
+ },
+ commit: (target, quant) => committed.push([target.key, quant]),
+ });
+
+ // First read is still running when the repo is invalidated.
+ reader.start([targetAt(A, "v1")]);
+ await flush();
+ reader.start([targetAt(A, "v2")]);
+ await flush();
+
+ // The newer read lands first, then the stale one.
+ reads.get("v2")?.resolve("Q8_0");
+ await flush();
+ reads.get("v1")?.resolve("Q4_K_M");
+ await flush();
+
+ assert.deepEqual(committed, [["v2", "Q8_0"]]);
+});
+
+test("a repo already being read at the same key is not read again", async () => {
+ let calls = 0;
+ const pending = deferred<string | null>();
+ const reader = createSoleQuantReader<string>({
+ workers: 4,
+ read: () => {
+ calls += 1;
+ return pending.promise;
+ },
+ commit: () => {},
+ });
+
+ reader.start([targetAt(A, "v1")]);
+ reader.start([targetAt(A, "v1")]);
+ await flush();
+ assert.equal(calls, 1);
+ pending.resolve(null);
+});
+
+test("reads are capped at the worker count", async () => {
+ let open = 0;
+ let peak = 0;
+ const gates: ((value: string | null) => void)[] = [];
+ const reader = createSoleQuantReader<string>({
+ workers: 2,
+ read: () => {
+ open += 1;
+ peak = Math.max(peak, open);
+ const gate = deferred<string | null>();
+ gates.push((value) => {
+ open -= 1;
+ gate.resolve(value);
+ });
+ return gate.promise;
+ },
+ commit: () => {},
+ });
+
+ reader.start(
+ ["r1", "r2", "r3", "r4", "r5"].map((repoId) => targetAt(repoId, "v1")),
+ );
+ await flush();
+ assert.equal(peak, 2);
+
+ while (gates.length > 0) {
+ gates.shift()?.(null);
+ await flush();
+ }
+ assert.equal(peak, 2);
+});
+
+test("a failed read commits as no sole quant", async () => {
+ const committed: [string, string | null][] = [];
+ const reader = createSoleQuantReader<string>({
+ workers: 1,
+ read: () => Promise.reject(new Error("offline")),
+ commit: (target, quant) => committed.push([target.repoId, quant]),
+ });
+
+ reader.start([targetAt(A, "v1")]);
+ await flush();
+ assert.deepEqual(committed, [[A, null]]);
+});
+
+test("bytes changing on disk moves the key, so the repo is read again", () => {
+ const beforePrint = soleQuantFingerprint({
+ size_bytes: 100,
+ last_modified: 10,
+ });
+ const before = {
+ repoId: A,
+ localSource: null,
+ fingerprint: beforePrint,
+ key: soleQuantKey(
+ "1:0",
+ null,
+ soleQuantFingerprint({ size_bytes: 100, last_modified: 10 }),
+ ),
+ };
+ const entries = new Map([[A, { key: before.key, quant: "Q4_K_M" }]]);
+
+ // Another tab replaced the quant: same cache version, different bytes.
+ const afterPrint = soleQuantFingerprint({
+ size_bytes: 250,
+ last_modified: 99,
+ });
+ const after = [
+ {
+ repoId: A,
+ localSource: null,
+ fingerprint: afterPrint,
+ key: soleQuantKey("1:0", null, afterPrint),
+ },
+ ];
+ const { quants, pending } = partitionSoleQuants(after, entries, {
+ enabled: true,
+ });
+ assert.deepEqual([...quants], []);
+ assert.deepEqual([...pending], [A]);
+});
+
+test("unchanged bytes keep the repo settled", () => {
+ const fingerprint = soleQuantFingerprint({
+ size_bytes: 100,
+ last_modified: 10,
+ });
+ const target = {
+ repoId: A,
+ localSource: null,
+ fingerprint,
+ key: soleQuantKey("1:0", null, fingerprint),
+ };
+ const entries = new Map([[A, { key: target.key, quant: "Q4_K_M" }]]);
+ const { quants, pending } = partitionSoleQuants([target], entries, {
+ enabled: true,
+ });
+ assert.deepEqual([...quants], [[A, "Q4_K_M"]]);
+ assert.deepEqual([...pending], []);
+});
+
+const targetWith = (
+ repoId: string,
+ fingerprint: string,
+ version: string,
+): SoleQuantTarget => ({
+ repoId,
+ localSource: null,
+ fingerprint,
+ key: soleQuantKey(version, null, fingerprint),
+});
+
+test("first sight records without asking for an invalidation", () => {
+ const seen = new Map<string, string>();
+ assert.deepEqual(
+ takeDriftedRepos([targetWith(A, "100:10", "1:0")], seen),
+ [],
+ );
+ assert.equal(seen.get(A), "100:10");
+});
+
+test("a version bump alone does not count as drift", () => {
+ const seen = new Map<string, string>();
+ takeDriftedRepos([targetWith(A, "100:10", "1:0")], seen);
+ // Dropping a listing bumps the version, which moves the key. Reacting to
+ // that would invalidate on its own effect forever.
+ assert.deepEqual(
+ takeDriftedRepos([targetWith(A, "100:10", "1:9")], seen),
+ [],
+ );
+});
+
+test("changed bytes drift once, not on every pass", () => {
+ const seen = new Map<string, string>();
+ takeDriftedRepos([targetWith(A, "100:10", "1:0")], seen);
+ assert.deepEqual(takeDriftedRepos([targetWith(A, "250:99", "1:0")], seen), [
+ A,
+ ]);
+ // The bump that follows the invalidation must not drift again.
+ assert.deepEqual(
+ takeDriftedRepos([targetWith(A, "250:99", "1:9")], seen),
+ [],
+ );
+});
+
+test("only the repo whose bytes moved drifts", () => {
+ const seen = new Map<string, string>();
+ const before = [targetWith(A, "100:10", "1:0"), targetWith(B, "7:1", "1:0")];
+ takeDriftedRepos(before, seen);
+ const after = [targetWith(A, "100:10", "1:0"), targetWith(B, "9:2", "1:0")];
+ assert.deepEqual(takeDriftedRepos(after, seen), [B]);
+});
+
+test("a cancelled sibling moves the key even though bytes do not", () => {
+ // Another tab cancelled a sibling before any file landed: same bytes, same
+ // mtime, and the repo's own partial flag stays false while a quant is clean.
+ const disk = { size_bytes: 256, last_modified: 10 };
+ const before = soleQuantFingerprint(disk);
+ const after = soleQuantFingerprint({ ...disk, has_variant_state: true });
+ assert.notEqual(after, before);
+});
+
+test("download state clearing moves the key back", () => {
+ const disk = { size_bytes: 256, last_modified: 10, has_variant_state: true };
+ assert.notEqual(
+ soleQuantFingerprint({ ...disk, has_variant_state: false }),
+ soleQuantFingerprint(disk),
+ );
+});
diff --git a/studio/frontend/tests/sole-quant-row-state.test.ts b/studio/frontend/tests/sole-quant-row-state.test.ts
new file mode 100644
index 00000000000..1c03b0ecf74
--- /dev/null
+++ b/studio/frontend/tests/sole-quant-row-state.test.ts
@@ -0,0 +1,77 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { soleQuantRowState } from "../src/features/model-picker/components/model-selector/row-identity.ts";
+
+const REPO = "unsloth/Qwen3-8B-GGUF";
+const OTHER_REPO = "unsloth/Llama-3.1-8B-Instruct-GGUF";
+const QUANT = "Q4_K_M";
+
+/** The row shown for a repo holding only Q4_K_M on disk. */
+const rowFor = (state: {
+ pickerValue?: string | null;
+ loadedModelId?: string | null;
+ activeGgufVariant?: string | null;
+}) =>
+ soleQuantRowState({
+ pickerValue: state.pickerValue ?? REPO,
+ repoId: REPO,
+ quant: QUANT,
+ loadedModelId: state.loadedModelId ?? null,
+ activeGgufVariant: state.activeGgufVariant ?? null,
+ });
+
+test("this quant running: selected and loaded", () => {
+ assert.deepEqual(rowFor({ loadedModelId: REPO, activeGgufVariant: QUANT }), {
+ selected: true,
+ loaded: true,
+ });
+});
+
+test("quant casing and padding still count as running", () => {
+ assert.deepEqual(
+ rowFor({ loadedModelId: REPO, activeGgufVariant: " q4_k_m " }),
+ { selected: true, loaded: true },
+ );
+});
+
+test("repo running a different quant: neither selected nor loaded", () => {
+ // Q8 stayed resident while the active cache now holds only Q4_K_M.
+ assert.deepEqual(rowFor({ loadedModelId: REPO, activeGgufVariant: "Q8_0" }), {
+ selected: false,
+ loaded: false,
+ });
+});
+
+test("repo resident with no quant reported: not this row", () => {
+ assert.deepEqual(rowFor({ loadedModelId: REPO }), {
+ selected: false,
+ loaded: false,
+ });
+});
+
+test("another model resident: the picker's value still selects the row", () => {
+ // Compare panes stage one model per pane while a single model is resident.
+ assert.deepEqual(
+ rowFor({ loadedModelId: OTHER_REPO, activeGgufVariant: "Q8_0" }),
+ { selected: true, loaded: false },
+ );
+});
+
+test("nothing resident: the picker's value still selects the row", () => {
+ assert.deepEqual(rowFor({}), { selected: true, loaded: false });
+});
+
+test("the picker points elsewhere: not selected, even while running", () => {
+ assert.deepEqual(
+ rowFor({
+ pickerValue: OTHER_REPO,
+ loadedModelId: REPO,
+ activeGgufVariant: QUANT,
+ }),
+ { selected: false, loaded: true },
+ );
+});
diff --git a/studio/frontend/tests/variant-visibility.test.ts b/studio/frontend/tests/variant-visibility.test.ts
new file mode 100644
index 00000000000..7492d776846
--- /dev/null
+++ b/studio/frontend/tests/variant-visibility.test.ts
@@ -0,0 +1,162 @@
+// 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 {
+ shouldMountVariantExpander,
+ toggleAutoExpandedRow,
+ visibleGgufVariants,
+} from "../src/features/model-picker/components/model-selector/variant-visibility.ts";
+
+/** A repo holding one complete quant, one torn download, and one quant that
+ * only exists on the Hub. */
+const COMPLETE = { quant: "Q4_K_M", downloaded: true, partial: false };
+const TORN = { quant: "Q8_0", downloaded: false, partial: true };
+const REMOTE_ONLY = { quant: "F16", downloaded: false, partial: false };
+const VARIANTS = [COMPLETE, TORN, REMOTE_ONLY];
+
+const quants = (rows: readonly { quant: string }[]) =>
+ rows.map((row) => row.quant);
+
+test("On Device with the setting off lists what is on disk", () => {
+ const shown = visibleGgufVariants(VARIANTS, {
+ onDevice: true,
+ showAll: false,
+ });
+ // The torn quant stays: it occupies space and needs a resume.
+ assert.deepEqual(quants(shown), ["Q4_K_M", "Q8_0"]);
+});
+
+test("On Device with the setting on lists every quant", () => {
+ const shown = visibleGgufVariants(VARIANTS, {
+ onDevice: true,
+ showAll: true,
+ });
+ assert.deepEqual(quants(shown), ["Q4_K_M", "Q8_0", "F16"]);
+});
+
+test("browse lists are never filtered", () => {
+ const shown = visibleGgufVariants(VARIANTS, {
+ onDevice: false,
+ showAll: false,
+ });
+ assert.deepEqual(quants(shown), ["Q4_K_M", "Q8_0", "F16"]);
+});
+
+test("a torn-only repo does not empty its list", () => {
+ const shown = visibleGgufVariants([TORN], {
+ onDevice: true,
+ showAll: false,
+ });
+ // An empty list renders "No GGUF variants found", stranding the download.
+ assert.deepEqual(quants(shown), ["Q8_0"]);
+});
+
+test("a repo with nothing on disk lists nothing", () => {
+ const shown = visibleGgufVariants([REMOTE_ONLY], {
+ onDevice: true,
+ showAll: false,
+ });
+ assert.deepEqual(quants(shown), []);
+});
+
+test("variants missing the flags count as not on disk", () => {
+ // A backend that reports neither flag, as the older ones do.
+ const unflagged: { quant: string; downloaded?: boolean; partial?: boolean } =
+ { quant: "Q2_K" };
+ const shown = visibleGgufVariants([unflagged], {
+ onDevice: true,
+ showAll: false,
+ });
+ assert.deepEqual(quants(shown), []);
+});
+
+test("auto-expansion waits for the sole-quant probe", () => {
+ // Every row would otherwise open an expander, and its remote listing,
+ // moments before collapsing into a single row.
+ assert.equal(
+ shouldMountVariantExpander({
+ expanded: true,
+ autoExpand: true,
+ soleQuantsPending: true,
+ }),
+ false,
+ );
+});
+
+test("auto-expansion resumes once the probe settles", () => {
+ assert.equal(
+ shouldMountVariantExpander({
+ expanded: true,
+ autoExpand: true,
+ soleQuantsPending: false,
+ }),
+ true,
+ );
+});
+
+test("a row the user opened is not held back", () => {
+ assert.equal(
+ shouldMountVariantExpander({
+ expanded: true,
+ autoExpand: false,
+ soleQuantsPending: true,
+ }),
+ true,
+ );
+});
+
+test("a collapsed row never mounts an expander", () => {
+ for (const soleQuantsPending of [true, false]) {
+ for (const autoExpand of [true, false]) {
+ assert.equal(
+ shouldMountVariantExpander({
+ expanded: false,
+ autoExpand,
+ soleQuantsPending,
+ }),
+ false,
+ );
+ }
+ }
+});
+
+test("clicking a row held back by its probe opens it", () => {
+ // Auto-expand is on, so the row is not in the collapsed set, but its
+ // pending probe means it renders nothing.
+ const next = toggleAutoExpandedRow(
+ { collapsed: new Set(), reopened: new Set() },
+ { repoId: "unsloth/Qwen3-8B-GGUF", showing: false },
+ );
+ assert.deepEqual([...next.collapsed], []);
+ assert.deepEqual([...next.reopened], ["unsloth/Qwen3-8B-GGUF"]);
+ // Reopened rows stop following the preference, so the wait no longer applies.
+ assert.equal(
+ shouldMountVariantExpander({
+ expanded: true,
+ autoExpand: false,
+ soleQuantsPending: true,
+ }),
+ true,
+ );
+});
+
+test("clicking a showing row collapses it and clears the reopen mark", () => {
+ const next = toggleAutoExpandedRow(
+ { collapsed: new Set(), reopened: new Set(["unsloth/Qwen3-8B-GGUF"]) },
+ { repoId: "unsloth/Qwen3-8B-GGUF", showing: true },
+ );
+ assert.deepEqual([...next.collapsed], ["unsloth/Qwen3-8B-GGUF"]);
+ assert.deepEqual([...next.reopened], []);
+});
+
+test("reopening a collapsed row leaves other rows alone", () => {
+ const next = toggleAutoExpandedRow(
+ { collapsed: new Set(["a", "b"]), reopened: new Set() },
+ { repoId: "a", showing: false },
+ );
+ assert.deepEqual([...next.collapsed], ["b"]);
+ assert.deepEqual([...next.reopened], ["a"]);
+});