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: resync model state after a llama.cpp update unloads it (#6998)

oobabooga85f529209763
diff --git a/studio/frontend/src/components/llama-update-banner.tsx b/studio/frontend/src/components/llama-update-banner.tsx
index 840383de906..3db15ffe30f 100644
--- a/studio/frontend/src/components/llama-update-banner.tsx
+++ b/studio/frontend/src/components/llama-update-banner.tsx
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { Button } from "@/components/ui/button";
+import { resyncInferenceStatusAfterServerModelChange } from "@/features/chat";
import { useLlamaUpdateCheck } from "@/hooks/use-llama-update-check";
import { useShowLlamaUpdateBanner } from "@/hooks/use-llama-update-pref";
import { toast } from "@/lib/toast";
@@ -81,9 +82,14 @@ export function LlamaUpdateBanner({
positioned = true,
}: LlamaUpdateBannerProps): ReactElement | null {
const showBannerPref = useShowLlamaUpdateBanner();
+ // Not gated on showBannerPref: this hook instance is the app-wide listener
+ // for a cross-tab reload_required resync (the settings-sheet's own instance
+ // only runs during an MTP-fallback rebuild), so muting the banner must not
+ // also silence that resync -- it only suppresses the UI below.
const { status, visible, applying, apply, dismiss, snooze } =
useLlamaUpdateCheck({
- enabled: enabled && showBannerPref,
+ enabled,
+ onReloadRequired: resyncInferenceStatusAfterServerModelChange,
});
async function handleUpdate() {
@@ -102,7 +108,10 @@ export function LlamaUpdateBanner({
}
const show =
- visible && status != null && (status.update_available || applying);
+ showBannerPref &&
+ visible &&
+ status != null &&
+ (status.update_available || applying);
const sizeBytes = status?.update_size_bytes ?? null;
const sizeLabel =
sizeBytes && sizeBytes > 0
diff --git a/studio/frontend/src/features/chat/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
index ea6c409b40b..a547b88e57a 100644
--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx
+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
@@ -80,6 +80,7 @@ import { Fragment, type ReactNode } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { toast } from "@/lib/toast";
import { OpenAICodeExecSection } from "./components/openai-code-exec-section";
+import { resyncInferenceStatusAfterServerModelChange } from "./hooks/use-chat-model-runtime";
import {
type ExternalProviderConfig,
getExternalProviderApiKey,
@@ -573,7 +574,10 @@ export function ChatSettingsPanel({
status: llamaUpdateStatus,
applying: llamaUpdating,
apply: applyLlamaUpdate,
- } = useLlamaUpdateCheck({ enabled: mtpUpdatable });
+ } = useLlamaUpdateCheck({
+ enabled: mtpUpdatable,
+ onReloadRequired: resyncInferenceStatusAfterServerModelChange,
+ });
const handleMtpUpdate = useCallback(async () => {
const result = await applyLlamaUpdate();
if (result.ok) {
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 0a4342f2083..a659b7f83e9 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
@@ -245,18 +245,98 @@ function getTrustRemoteCodeRequiredMessage(modelName: string): string {
return `${modelName} was not loaded because its custom code was not approved. Load it again to review the code and approve it.`;
}
+/**
+ * Reconcile the chat runtime store against `/api/inference/status`: refresh the
+ * models/loras catalogs and either re-pin the active checkpoint or clear the
+ * loaded-model flags when nothing is loaded. Module-level so it can run outside
+ * a React render (e.g. the imperative resync below); `useChatModelRuntime.refresh`
+ * is a thin wrapper over it. External selections are left untouched since they
+ * have no backend mirror.
+ */
+async function syncInferenceStatusToStore(options?: {
+ signal?: AbortSignal;
+ includeLoras?: boolean;
+}): Promise<void> {
+ const signal = options?.signal;
+ const includeLoras = options?.includeLoras ?? true;
+ const { setModels, setLoras, setCheckpoint, setModelsError } =
+ useChatRuntimeStore.getState();
+ setModelsError(null);
+ try {
+ const [listRes, statusRes, lorasRes] = await Promise.all([
+ listModels(),
+ getInferenceStatus(),
+ includeLoras ? listLoras() : Promise.resolve(null),
+ ]);
+
+ // Cancellation can land while the requests above are in flight. Bail
+ // before writing backend state back -- cancelLoading already cleared it.
+ if (signal?.aborted) return;
+
+ setModels(listRes.models.map(toChatModelSummary));
+ if (lorasRes) {
+ setLoras(lorasRes.loras.map(toLoraSummary));
+ }
+
+ const selectedCheckpoint = useChatRuntimeStore.getState().params.checkpoint;
+ const isExternalSelectionActive = isExternalModelId(selectedCheckpoint);
+ if (statusRes.active_model && !isExternalSelectionActive) {
+ const checkpointId = resolveInferenceCheckpointId(statusRes);
+ if (checkpointId) {
+ setCheckpoint(checkpointId, statusRes.gguf_variant);
+ applyActiveModelStatusToStore(statusRes, {
+ previousCheckpoint: selectedCheckpoint,
+ });
+ // setModels(listRes...) above used catalog data, which omits audio
+ // capability. Re-apply live status so attach gates survive a refresh.
+ syncModelCapabilities(checkpointId, statusRes);
+ }
+ } else if (!statusRes.active_model && !isExternalSelectionActive) {
+ useChatRuntimeStore.setState({
+ modelRequiresTrustRemoteCode: false,
+ loadedIsMultimodal: false,
+ loadedIsDiffusion: false,
+ });
+ }
+ } catch (error) {
+ if (signal?.aborted) return;
+ const message =
+ error instanceof Error ? error.message : "Failed to load models";
+ setModelsError(message);
+ toast.error("Failed to refresh models", {
+ description: message,
+ });
+ }
+}
+
+/**
+ * Reconcile the UI after the SERVER unloaded the active model out from under it
+ * (e.g. a llama.cpp update unloads the running model to swap the binary): the
+ * model selector drops to "select model" instead of pointing at a model that now
+ * 400s on send. Imperative so the global llama-update banner (which has no
+ * chat-runtime handle) can call it.
+ *
+ * Only a LOCAL selection points at the unloaded model. An external-provider
+ * selection has no llama.cpp mirror and still works, so clearing it (which also
+ * wipes its persisted id) would drop a valid, unrelated model; skip the clear so
+ * the refresh below leaves it intact.
+ */
+export async function resyncInferenceStatusAfterServerModelChange(): Promise<void> {
+ if (!isExternalModelId(useChatRuntimeStore.getState().params.checkpoint)) {
+ useChatRuntimeStore.getState().clearCheckpoint();
+ }
+ await syncInferenceStatusToStore();
+}
+
export function useChatModelRuntime() {
const params = useChatRuntimeStore((state) => state.params);
const models = useChatRuntimeStore((state) => state.models);
const loras = useChatRuntimeStore((state) => state.loras);
- const setModels = useChatRuntimeStore((state) => state.setModels);
- const setLoras = useChatRuntimeStore((state) => state.setLoras);
const setParams = useChatRuntimeStore((state) => state.setParams);
const setModelsError = useChatRuntimeStore((state) => state.setModelsError);
const setLastModelLoadError = useChatRuntimeStore(
(state) => state.setLastModelLoadError,
);
- const setCheckpoint = useChatRuntimeStore((state) => state.setCheckpoint);
const clearCheckpoint = useChatRuntimeStore((state) => state.clearCheckpoint);
const [loadingModel, setLoadingModel] = useState<{
@@ -313,59 +393,11 @@ export function useChatModelRuntime() {
[],
);
- const refresh = useCallback(async (options?: {
- signal?: AbortSignal;
- includeLoras?: boolean;
- }) => {
- const signal = options?.signal;
- const includeLoras = options?.includeLoras ?? true;
- setModelsError(null);
- try {
- const [listRes, statusRes, lorasRes] = await Promise.all([
- listModels(),
- getInferenceStatus(),
- includeLoras ? listLoras() : Promise.resolve(null),
- ]);
-
- // Cancellation can land while the requests above are in flight. Bail
- // before writing backend state back -- cancelLoading already cleared it.
- if (signal?.aborted) return;
-
- setModels(listRes.models.map(toChatModelSummary));
- if (lorasRes) {
- setLoras(lorasRes.loras.map(toLoraSummary));
- }
-
- const selectedCheckpoint = useChatRuntimeStore.getState().params.checkpoint;
- const isExternalSelectionActive = isExternalModelId(selectedCheckpoint);
- if (statusRes.active_model && !isExternalSelectionActive) {
- const checkpointId = resolveInferenceCheckpointId(statusRes);
- if (checkpointId) {
- setCheckpoint(checkpointId, statusRes.gguf_variant);
- applyActiveModelStatusToStore(statusRes, {
- previousCheckpoint: selectedCheckpoint,
- });
- // setModels(listRes...) above used catalog data, which omits audio
- // capability. Re-apply live status so attach gates survive a refresh.
- syncModelCapabilities(checkpointId, statusRes);
- }
- } else if (!statusRes.active_model && !isExternalSelectionActive) {
- useChatRuntimeStore.setState({
- modelRequiresTrustRemoteCode: false,
- loadedIsMultimodal: false,
- loadedIsDiffusion: false,
- });
- }
- } catch (error) {
- if (signal?.aborted) return;
- const message =
- error instanceof Error ? error.message : "Failed to load models";
- setModelsError(message);
- toast.error("Failed to refresh models", {
- description: message,
- });
- }
- }, [setCheckpoint, setLoras, setModels, setModelsError, setParams]);
+ const refresh = useCallback(
+ (options?: { signal?: AbortSignal; includeLoras?: boolean }) =>
+ syncInferenceStatusToStore(options),
+ [],
+ );
const cancelLoading = useCallback(() => {
const model = loadingModelRef.current;
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index d070ed15de4..30998846458 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -25,7 +25,10 @@ export {
usePlusMenuPrefsStore,
type PlusMenuItemId,
} from "./stores/plus-menu-prefs-store";
-export { useChatModelRuntime } from "./hooks/use-chat-model-runtime";
+export {
+ useChatModelRuntime,
+ resyncInferenceStatusAfterServerModelChange,
+} from "./hooks/use-chat-model-runtime";
export {
customProviderDisplayName,
isExternalModelId,
diff --git a/studio/frontend/src/hooks/use-llama-update-check.ts b/studio/frontend/src/hooks/use-llama-update-check.ts
index d8f894b1b12..e3a735ffde1 100644
--- a/studio/frontend/src/hooks/use-llama-update-check.ts
+++ b/studio/frontend/src/hooks/use-llama-update-check.ts
@@ -22,6 +22,9 @@ export interface LlamaUpdateJob {
error: string | null;
// Download fraction while running, 1 on success.
progress: number | null;
+ // Set once the job leaves "running"; identifies a completed job so a
+ // repeated fetch of the same success can be told apart from the next one.
+ finished_at: string | null;
}
export interface LlamaUpdateStatus {
@@ -34,10 +37,24 @@ export interface LlamaUpdateStatus {
job: LlamaUpdateJob;
}
+function parseJob(value: unknown): LlamaUpdateJob {
+ const job = (value ?? {}) as Record<string, unknown>;
+ return {
+ state: (job.state as LlamaUpdateJob["state"]) ?? "idle",
+ message: typeof job.message === "string" ? job.message : "",
+ from_tag: typeof job.from_tag === "string" ? job.from_tag : null,
+ to_tag: typeof job.to_tag === "string" ? job.to_tag : null,
+ reload_required:
+ typeof job.reload_required === "boolean" ? job.reload_required : null,
+ error: typeof job.error === "string" ? job.error : null,
+ progress: typeof job.progress === "number" ? job.progress : null,
+ finished_at: typeof job.finished_at === "string" ? job.finished_at : null,
+ };
+}
+
function parseStatus(value: unknown): LlamaUpdateStatus | null {
if (!value || typeof value !== "object") return null;
const s = value as Record<string, unknown>;
- const job = (s.job ?? {}) as Record<string, unknown>;
return {
supported: s.supported === true,
update_available: s.update_available === true,
@@ -45,19 +62,34 @@ function parseStatus(value: unknown): LlamaUpdateStatus | null {
latest_tag: typeof s.latest_tag === "string" ? s.latest_tag : null,
update_size_bytes:
typeof s.update_size_bytes === "number" ? s.update_size_bytes : null,
- job: {
- state: (job.state as LlamaUpdateJob["state"]) ?? "idle",
- message: typeof job.message === "string" ? job.message : "",
- from_tag: typeof job.from_tag === "string" ? job.from_tag : null,
- to_tag: typeof job.to_tag === "string" ? job.to_tag : null,
- reload_required:
- typeof job.reload_required === "boolean" ? job.reload_required : null,
- error: typeof job.error === "string" ? job.error : null,
- progress: typeof job.progress === "number" ? job.progress : null,
- },
+ job: parseJob(s.job),
};
}
+// The backend job persists as "success" until the next update starts (it's a
+// single in-memory record, not per-tab), so a fresh mount -- a new tab, or a
+// page reload of a tab that already resynced -- would otherwise replay the
+// same completed job forever. Persist the handled marker outside React state
+// so it survives both, and is shared across tabs in this browser.
+const HANDLED_RELOAD_STORAGE_KEY = "unsloth_llama_update_reload_handled_at";
+
+function getHandledReloadAt(): string | null {
+ try {
+ return localStorage.getItem(HANDLED_RELOAD_STORAGE_KEY);
+ } catch {
+ return null;
+ }
+}
+
+function setHandledReloadAt(finishedAt: string | null): void {
+ if (!finishedAt) return;
+ try {
+ localStorage.setItem(HANDLED_RELOAD_STORAGE_KEY, finishedAt);
+ } catch {
+ // storage unavailable
+ }
+}
+
async function fetchStatus(
forceRefresh = false,
): Promise<LlamaUpdateStatus | null> {
@@ -78,6 +110,14 @@ const recheckStatus = () => fetchStatus(true);
interface UseLlamaUpdateCheckOptions {
enabled?: boolean;
+ /**
+ * Called when a completed update reports `reload_required` (i.e. it unloaded
+ * the active model server-side). Consumers use it to resync the chat runtime
+ * so the model selector drops to "select model" instead of pointing at a
+ * model that now 400s on send. Fires for both this tab's own apply() and a
+ * cross-tab update mirrored through the background poll.
+ */
+ onReloadRequired?: () => void;
}
export interface LlamaApplyResult {
@@ -90,12 +130,25 @@ export interface LlamaApplyResult {
/** Tracks llama.cpp update visibility and apply progress. */
export function useLlamaUpdateCheck({
enabled = true,
+ onReloadRequired,
}: UseLlamaUpdateCheckOptions = {}) {
const [status, setStatus] = useState<LlamaUpdateStatus | null>(null);
const [visible, setVisible] = useState(false);
const [applying, setApplying] = useState(false);
const pollTimer = useRef<ReturnType<typeof setInterval> | null>(null);
const snoozeTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ // Read through a ref so startJobPoll stays stable (apply/surfaceIfAvailable
+ // depend on it) while still calling the latest callback.
+ const onReloadRequiredRef = useRef(onReloadRequired);
+ useEffect(() => {
+ onReloadRequiredRef.current = onReloadRequired;
+ }, [onReloadRequired]);
+ // Fires the callback once per completed job, whether this tab watched it run
+ // or only saw the persisted "success" after the fact (e.g. another tab
+ // applied it). Keyed by finished_at and seeded from localStorage so a fresh
+ // mount (new tab, or a page reload of a tab that already resynced) doesn't
+ // replay a job some tab already handled.
+ const reloadNotifiedForRef = useRef<string | null>(getHandledReloadAt());
const clearPollTimer = useCallback(() => {
if (pollTimer.current) {
@@ -104,6 +157,25 @@ export function useLlamaUpdateCheck({
}
}, []);
+ // Shared by the poll path (this tab watched the job run), the surface path
+ // (this tab only saw the persisted success), and apply()'s stale-click path
+ // (the job came back embedded in a "not started" response) so none of them
+ // can drop or double-fire the notification.
+ const notifyReloadIfNeeded = useCallback(
+ (job: Pick<LlamaUpdateJob, "state" | "reload_required" | "finished_at">) => {
+ if (
+ job.state === "success" &&
+ job.reload_required &&
+ job.finished_at !== reloadNotifiedForRef.current
+ ) {
+ reloadNotifiedForRef.current = job.finished_at;
+ setHandledReloadAt(job.finished_at);
+ onReloadRequiredRef.current?.();
+ }
+ },
+ [],
+ );
+
// Used by apply() and another-tab job tracking.
const startJobPoll = useCallback(
(onDone?: (result: LlamaApplyResult) => void) => {
@@ -118,6 +190,12 @@ export function useLlamaUpdateCheck({
if (s.job.state === "success") {
setVisible(false);
void refreshHardwareInfo();
+ // The update unloads the running model server-side, so the chat
+ // runtime still points at a model that now 400s on send. Let the
+ // consumer drop the selector to "select model" instead of waiting for
+ // a page reload. Fires here (not just from apply's onDone) so a
+ // cross-tab update mirrored through this poll is covered too.
+ notifyReloadIfNeeded(s.job);
onDone?.({
ok: true,
tag: s.job.to_tag,
@@ -131,7 +209,7 @@ export function useLlamaUpdateCheck({
}
}, JOB_POLL_INTERVAL_MS);
},
- [clearPollTimer],
+ [clearPollTimer, notifyReloadIfNeeded],
);
const surfaceIfAvailable = useCallback(
@@ -145,11 +223,16 @@ export function useLlamaUpdateCheck({
if (!pollTimer.current) startJobPoll();
return;
}
+ // A completed job persists as "success" until the next update starts, so
+ // a tab that missed the running window entirely (mounted, or only checks
+ // hourly and misses both the running and just-finished moments) still
+ // needs to resync here, not just from the poll path above.
+ notifyReloadIfNeeded(next.job);
if (next.update_available) {
setVisible(true);
}
},
- [startJobPoll],
+ [startJobPoll, notifyReloadIfNeeded],
);
useEffect(() => {
@@ -185,6 +268,26 @@ export function useLlamaUpdateCheck({
};
}, [enabled, surfaceIfAvailable, clearPollTimer]);
+ // Cross-tab nudge: a tab that only checks hourly would otherwise stay
+ // pointed at a server-unloaded model for up to an hour after a DIFFERENT
+ // open tab applies an update. The storage event only fires in other tabs
+ // (never the one that wrote it), so this recheck fires promptly there
+ // without this tab redundantly re-triggering itself.
+ useEffect(() => {
+ if (!enabled) return;
+ const onStorage = (event: StorageEvent) => {
+ if (
+ event.key === HANDLED_RELOAD_STORAGE_KEY &&
+ event.newValue &&
+ event.newValue !== reloadNotifiedForRef.current
+ ) {
+ recheckStatus().then(surfaceIfAvailable);
+ }
+ };
+ window.addEventListener("storage", onStorage);
+ return () => window.removeEventListener("storage", onStorage);
+ }, [enabled, surfaceIfAvailable]);
+
const dismiss = useCallback(() => {
setVisible(false);
}, []);
@@ -206,6 +309,7 @@ export function useLlamaUpdateCheck({
started?: boolean;
reason?: string | null;
message?: string | null;
+ job?: unknown;
} | null = null;
try {
const res = await authFetch("/api/llama/update", { method: "POST" });
@@ -229,6 +333,11 @@ export function useLlamaUpdateCheck({
action.started === false &&
action.reason !== "already_running"
) {
+ // A stale banner's click can land after another tab already applied the
+ // update (e.g. "up_to_date"): the response still carries that tab's
+ // completed job, so process reload_required here too, not just from the
+ // poll path -- otherwise this rejection silently drops it.
+ notifyReloadIfNeeded(parseJob(action.job));
setApplying(false);
return {
ok: false,
@@ -239,7 +348,7 @@ export function useLlamaUpdateCheck({
return await new Promise<LlamaApplyResult>((resolve) =>
startJobPoll(resolve),
);
- }, [applying, startJobPoll]);
+ }, [applying, startJobPoll, notifyReloadIfNeeded]);
return {
status: enabled ? status : null,