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.

studio: GGUF unlimited context, auto-load, wait-for-load, UX fixes

Daniel Han991a2bfc3564
diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.py
index 33a024b26ea..42cce3c4d8a 100644
--- a/studio/backend/core/inference/llama_cpp.py
+++ b/studio/backend/core/inference/llama_cpp.py
@@ -676,7 +676,7 @@ class LlamaCppBackend:
"--port",
str(self._port),
"-c",
- str(n_ctx),
+ "0", # 0 = use model's native context size
"--parallel",
"1", # Single-user studio, saves VRAM
"--flash-attn",
diff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.py
index dd23bcc5c7f..3570ab52e65 100644
--- a/studio/backend/core/inference/orchestrator.py
+++ b/studio/backend/core/inference/orchestrator.py
@@ -78,7 +78,8 @@ class InferenceOrchestrator:
self._static_models = get_default_models()
self._top_gguf_cache: Optional[list[str]] = None
- self._top_gguf_fetched = False
+ self._top_hub_cache: Optional[list[str]] = None
+ self._top_models_ready = threading.Event()
# Version tracking for subprocess reuse
self._current_transformers_major: Optional[str] = None # "4" or "5"
@@ -86,9 +87,9 @@ class InferenceOrchestrator:
atexit.register(self._cleanup)
logger.info("InferenceOrchestrator initialized (subprocess mode)")
- # Kick off background fetch of top GGUF models
+ # Kick off background fetch of top models from HF
threading.Thread(
- target = self._fetch_top_gguf, daemon = True, name = "top-gguf"
+ target = self._fetch_top_models, daemon = True, name = "top-models"
).start()
# ------------------------------------------------------------------
@@ -97,12 +98,23 @@ class InferenceOrchestrator:
@property
def default_models(self) -> list[str]:
- top = self._top_gguf_cache or []
- seen = set(top)
- return top + [m for m in self._static_models if m not in seen]
-
- def _fetch_top_gguf(self) -> None:
- """Fetch top 4 GGUF repos from unsloth by downloads (background)."""
+ # Wait up to 5s for background HF fetch to finish
+ self._top_models_ready.wait(timeout = 5)
+ top_gguf = self._top_gguf_cache or []
+ top_hub = self._top_hub_cache or []
+ # GGUFs first, then hub models, then static fallbacks.
+ # Send extras so the frontend still has 4 per category
+ # after removing already-downloaded models.
+ result: list[str] = []
+ seen: set[str] = set()
+ for m in top_gguf + top_hub + self._static_models:
+ if m not in seen:
+ result.append(m)
+ seen.add(m)
+ return result
+
+ def _fetch_top_models(self) -> None:
+ """Fetch top GGUF and non-GGUF repos from unsloth by downloads."""
try:
import httpx
@@ -112,22 +124,33 @@ class InferenceOrchestrator:
"author": "unsloth",
"sort": "downloads",
"direction": "-1",
- "limit": "40",
+ "limit": "80",
},
timeout = 15,
)
if resp.status_code == 200:
models = resp.json()
+ # Top 8 GGUFs (frontend deduplicates against downloaded,
+ # so we fetch extra to always fill 4 slots)
gguf_ids = [
- m["id"] for m in models if m.get("id", "").upper().endswith("-GGUF")
- ][:4]
+ m["id"] for m in models
+ if m.get("id", "").upper().endswith("-GGUF")
+ ][:8]
+ # Top 8 non-GGUF hub models
+ hub_ids = [
+ m["id"] for m in models
+ if not m.get("id", "").upper().endswith("-GGUF")
+ ][:8]
if gguf_ids:
self._top_gguf_cache = gguf_ids
logger.info("Top GGUF models: %s", gguf_ids)
+ if hub_ids:
+ self._top_hub_cache = hub_ids
+ logger.info("Top hub models: %s", hub_ids)
except Exception as e:
- logger.warning("Failed to fetch top GGUF models: %s", e)
+ logger.warning("Failed to fetch top models: %s", e)
finally:
- self._top_gguf_fetched = True
+ self._top_models_ready.set()
# ------------------------------------------------------------------
# Subprocess lifecycle
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 1b2ee91785f..55bd9710a5a 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -238,8 +238,10 @@ async def load_model(
except Exception as e:
logger.warning(f"Could not read adapter_config.json: {e}")
- # Load the model
- success = backend.load_model(
+ # Load the model in a thread so the event loop stays free
+ # for download progress polling and other requests.
+ success = await asyncio.to_thread(
+ backend.load_model,
config = config,
max_seq_length = request.max_seq_length,
load_in_4bit = load_in_4bit,
diff --git a/studio/frontend/src/components/assistant-ui/model-selector/pickers.tsx b/studio/frontend/src/components/assistant-ui/model-selector/pickers.tsx
index 6baeb9b55ba..c8f88818087 100644
--- a/studio/frontend/src/components/assistant-ui/model-selector/pickers.tsx
+++ b/studio/frontend/src/components/assistant-ui/model-selector/pickers.tsx
@@ -369,24 +369,37 @@ export function HubModelPicker({
// re-mounting the popover does not flash an empty "Downloaded" section.
const [cachedGguf, setCachedGguf] = useState<CachedGgufRepo[]>(_cachedGgufCache);
const [cachedModels, setCachedModels] = useState<CachedModelRepo[]>(_cachedModelsCache);
+ const alreadyCached = _cachedGgufCache.length > 0 || _cachedModelsCache.length > 0;
+ const [cachedReady, setCachedReady] = useState(alreadyCached);
useEffect(() => {
- listCachedGguf().then((v) => { _cachedGgufCache = v; setCachedGguf(v); }).catch(() => {});
- listCachedModels().then((v) => { _cachedModelsCache = v; setCachedModels(v); }).catch(() => {});
- }, []);
-
- // Deduplicate: don't show downloaded models in the recommended list
+ if (alreadyCached) return;
+ let done = 0;
+ const check = () => { if (++done >= 2) setCachedReady(true); };
+ listCachedGguf().then((v) => { _cachedGgufCache = v; setCachedGguf(v); }).catch(() => {}).finally(check);
+ listCachedModels().then((v) => { _cachedModelsCache = v; setCachedModels(v); }).catch(() => {}).finally(check);
+ }, [alreadyCached]);
+
+ // Deduplicate: don't show downloaded models in the recommended list.
+ // Compare case-insensitively since HF cache lowercases repo IDs.
const downloadedSet = useMemo(() => {
const s = new Set<string>();
- for (const c of cachedGguf) s.add(c.repo_id);
- for (const c of cachedModels) s.add(c.repo_id);
+ for (const c of cachedGguf) s.add(c.repo_id.toLowerCase());
+ for (const c of cachedModels) s.add(c.repo_id.toLowerCase());
return s;
}, [cachedGguf, cachedModels]);
- const recommendedIds = useMemo(
- () => dedupe([...models.map((model) => model.id), value ?? ""])
- .filter((id) => !downloadedSet.has(id)),
- [models, value, downloadedSet],
- );
+ const recommendedIds = useMemo(() => {
+ const all = dedupe([...models.map((model) => model.id), value ?? ""])
+ .filter((id) => !downloadedSet.has(id.toLowerCase()));
+ // Cap at 4 GGUFs + 4 non-GGUFs so the list stays manageable
+ const gguf: string[] = [];
+ const hub: string[] = [];
+ for (const id of all) {
+ if (isGgufRepo(id) && gguf.length < 4) gguf.push(id);
+ else if (!isGgufRepo(id) && hub.length < 4) hub.push(id);
+ }
+ return [...gguf, ...hub];
+ }, [models, value, downloadedSet]);
const { paramCountById: recommendedParamCountById } =
useRecommendedModelVram(recommendedIds);
@@ -493,7 +506,12 @@ export function HubModelPicker({
<div ref={scrollRef} className="max-h-64 overflow-y-auto">
<div className="p-1">
- {!showHfSection && (cachedGguf.length > 0 || cachedModels.length > 0) ? (
+ {!cachedReady && !showHfSection ? (
+ <div className="flex items-center gap-2 px-5 py-3">
+ <Spinner className="size-3 text-muted-foreground" />
+ <span className="text-xs text-muted-foreground">Loading models…</span>
+ </div>
+ ) : !showHfSection && (cachedGguf.length > 0 || cachedModels.length > 0) ? (
<>
<ListLabel>{"\uD83E\uDDA5"} Downloaded</ListLabel>
{cachedGguf.map((c) => (
@@ -523,7 +541,7 @@ export function HubModelPicker({
</>
) : null}
- {!showHfSection ? (
+ {!showHfSection && cachedReady ? (
<>
<ListLabel>{"\uD83E\uDDA5"} Recommended</ListLabel>
{recommendedIds.length === 0 ? (
diff --git a/studio/frontend/src/components/ui/sonner.tsx b/studio/frontend/src/components/ui/sonner.tsx
index f211c4acd0c..11dca18213a 100644
--- a/studio/frontend/src/components/ui/sonner.tsx
+++ b/studio/frontend/src/components/ui/sonner.tsx
@@ -16,11 +16,11 @@ const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme();
return (
- <Sonner
- theme={theme as ToasterProps["theme"]}
- className="toaster group"
- duration={5000}
- icons={{
+ <Sonner
+ theme={theme as ToasterProps["theme"]}
+ className="toaster group"
+ duration={5000}
+ icons={{
success: (
<HugeiconsIcon
icon={CheckmarkCircle02Icon}
@@ -68,6 +68,7 @@ const Toaster = ({ ...props }: ToasterProps) => {
toastOptions={{
classNames: {
toast: "cn-toast",
+ closeButton: "!top-1.5 !translate-y-0",
},
}}
{...props}
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 0935728e891..30a8d97461b 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -4,7 +4,14 @@
import type { ChatModelAdapter } from "@assistant-ui/react";
import type { MessageTiming } from "@assistant-ui/core";
import { toast } from "sonner";
-import { generateAudio, streamChatCompletions } from "./chat-api";
+import {
+ generateAudio,
+ listCachedGguf,
+ listCachedModels,
+ listGgufVariants,
+ loadModel,
+ streamChatCompletions,
+} from "./chat-api";
import { db } from "../db";
import { useChatRuntimeStore } from "../stores/chat-runtime-store";
import {
@@ -167,17 +174,117 @@ async function resolveUseAdapter(
}
}
+/** Wait for an in-progress model load to finish (polls store every 500ms). */
+function waitForModelReady(abortSignal?: AbortSignal): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const check = () => {
+ if (abortSignal?.aborted) { reject(new Error("Aborted")); return; }
+ if (!useChatRuntimeStore.getState().modelLoading) { resolve(); return; }
+ setTimeout(check, 500);
+ };
+ check();
+ });
+}
+
+/**
+ * Auto-load the smallest downloaded model when the user tries to chat
+ * without selecting one. Prefers GGUF (picks smallest cached variant),
+ * falls back to smallest cached safetensors model.
+ */
+async function autoLoadSmallestModel(): Promise<boolean> {
+ const toastId = toast("Loading a model…", {
+ description: "Auto-selecting the smallest downloaded model.",
+ duration: Infinity,
+ });
+ try {
+ const [ggufRepos, modelRepos] = await Promise.all([
+ listCachedGguf().catch(() => []),
+ listCachedModels().catch(() => []),
+ ]);
+
+ // Try GGUF first: pick the repo with the smallest total size,
+ // then pick its smallest downloaded variant.
+ if (ggufRepos.length > 0) {
+ const sorted = [...ggufRepos].sort((a, b) => a.size_bytes - b.size_bytes);
+ for (const repo of sorted) {
+ try {
+ const variants = await listGgufVariants(repo.repo_id);
+ const downloaded = variants.variants
+ .filter((v) => v.downloaded)
+ .sort((a, b) => a.size_bytes - b.size_bytes);
+ if (downloaded.length > 0) {
+ const variant = downloaded[0];
+ await loadModel({
+ model_path: repo.repo_id,
+ hf_token: null,
+ max_seq_length: 4096,
+ load_in_4bit: true,
+ is_lora: false,
+ gguf_variant: variant.quant,
+ trust_remote_code: false,
+ });
+ useChatRuntimeStore.getState().setCheckpoint(repo.repo_id, variant.quant);
+ toast.success(`Loaded ${repo.repo_id} (${variant.quant})`, { id: toastId });
+ return true;
+ }
+ } catch {
+ continue;
+ }
+ }
+ }
+
+ // Fall back to safetensors models
+ if (modelRepos.length > 0) {
+ const sorted = [...modelRepos].sort((a, b) => a.size_bytes - b.size_bytes);
+ for (const repo of sorted) {
+ try {
+ await loadModel({
+ model_path: repo.repo_id,
+ hf_token: null,
+ max_seq_length: 4096,
+ load_in_4bit: true,
+ is_lora: false,
+ gguf_variant: null,
+ trust_remote_code: false,
+ });
+ useChatRuntimeStore.getState().setCheckpoint(repo.repo_id);
+ toast.success(`Loaded ${repo.repo_id}`, { id: toastId });
+ return true;
+ } catch {
+ continue;
+ }
+ }
+ }
+
+ toast.dismiss(toastId);
+ return false;
+ } catch {
+ toast.dismiss(toastId);
+ return false;
+ }
+}
+
export function createOpenAIStreamAdapter(): ChatModelAdapter {
return {
async *run({ messages, abortSignal, unstable_threadId }) {
const runtime = useChatRuntimeStore.getState();
const { params } = runtime;
- if (!params.checkpoint) {
- toast.error("No model loaded", {
- description: "Pick model in top bar, then retry.",
- });
- throw new Error("Load a model first.");
+ // Wait for in-progress model load to finish before inferring
+ if (runtime.modelLoading) {
+ toast.info("Waiting for model to finish loading…");
+ await waitForModelReady(abortSignal);
+ }
+
+ if (!useChatRuntimeStore.getState().params.checkpoint) {
+ // Auto-load the smallest downloaded model
+ const loaded = await autoLoadSmallestModel();
+ if (!loaded) {
+ toast.error("No model loaded", {
+ description: "Pick a model in the top bar, then retry.",
+ });
+ throw new Error("Load a model first.");
+ }
}
const outboundMessages = messages
diff --git a/studio/frontend/src/features/chat/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
index 9e033ab8215..b0032eb0cd7 100644
--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx
+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
@@ -279,7 +279,7 @@ export function ChatSettingsPanel({
<CollapsibleSection
icon={SlidersHorizontalIcon}
label="Sampling"
- defaultOpen={false}
+ defaultOpen={true}
>
<div className="flex flex-col gap-5">
<ParamSlider
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
index e5c58c7be7f..b29161f7731 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
@@ -38,7 +38,7 @@ const MODEL_LOAD_TOAST_CLASSNAMES = {
title: "leading-5",
description: "mt-0",
closeButton:
- "!left-auto !right-1 !top-2 !translate-x-0 !translate-y-0 !border-transparent !bg-transparent !shadow-none hover:!bg-transparent hover:opacity-70",
+ "!left-auto !right-1.5 !top-1.5 !translate-x-0 !translate-y-0 !border-transparent !bg-transparent !shadow-none hover:!bg-transparent hover:opacity-70",
} as const;
const LORA_SUFFIX_RE = /_(\d{9,})$/;
@@ -186,6 +186,7 @@ export function useChatModelRuntime() {
loadAbortRef.current = null;
loadToastIdRef.current = null;
setLoadToastDismissedState(false);
+ useChatRuntimeStore.getState().setModelLoading(false);
}, [setLoadToastDismissedState]);
const renderLoadDescription = useCallback(
@@ -258,6 +259,8 @@ export function useChatModelRuntime() {
if (!modelId || (params.checkpoint === modelId && (ggufVariant ?? null) === (currentVariant ?? null))) {
return;
}
+ // Prevent duplicate loads if already loading this model
+ if (loadingModelRef.current?.id === modelId) return;
const explicitIsLora =
typeof selection === "string" ? undefined : selection.isLora;
@@ -294,6 +297,7 @@ export function useChatModelRuntime() {
setLoadToastDismissedState(false);
const loadInfo = { id: modelId, displayName, isDownloaded };
setLoadingModel(loadInfo);
+ useChatRuntimeStore.getState().setModelLoading(true);
setLoadProgress(
isDownloaded
? { percent: null, label: null, phase: "starting" }
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 07d3aecc367..c9f1753f822 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -46,6 +46,8 @@ type ChatRuntimeStore = {
activeThreadId: string | null;
pendingAudioBase64: string | null;
pendingAudioName: string | null;
+ modelLoading: boolean;
+ setModelLoading: (loading: boolean) => void;
setParams: (params: InferenceParams) => void;
setModels: (models: ChatModelSummary[]) => void;
setLoras: (loras: ChatLoraSummary[]) => void;
@@ -70,6 +72,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set) => ({
activeThreadId: null,
pendingAudioBase64: null,
pendingAudioName: null,
+ modelLoading: false,
+ setModelLoading: (loading) => set({ modelLoading: loading }),
setParams: (params) => set({ params }),
setModels: (models) => set({ models }),
setLoras: (loras) => set({ loras }),