Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
studio: persist the settings dialog picks that reset on every tab switch (#7991)
Maheswar Kumarcf30f02533d3
diff --git a/studio/frontend/src/features/settings/components/usage-examples.tsx b/studio/frontend/src/features/settings/components/usage-examples.tsxindex 7902170a37a..f89ce969eeb 100644--- a/studio/frontend/src/features/settings/components/usage-examples.tsx+++ b/studio/frontend/src/features/settings/components/usage-examples.tsx@@ -31,6 +31,7 @@ import { Streamdown } from "streamdown";import { loadCodingAgents } from "../api/coding-agents";import { loadOpenAIAutoSwitchSettings } from "../api/openai-auto-switch";import { type OpenAIModel, listOpenAIModels } from "../api/openai-models";+import { useSettingsPanelPrefsStore } from "../stores/settings-panel-prefs-store";import { buildAgentCommand, isLoopbackHost, normalizeHost } from "./agent-command";type ExampleType =@@ -58,6 +59,9 @@ const TYPE_TABS: { id: ExampleType; label: string }[] = [{ id: "javascriptAdvanced", label: "JavaScript + advanced" },];+// guards a restored tab against a snippet type dropped in a later release.+const EXAMPLE_TYPE_IDS = new Set<string>(TYPE_TABS.map((tab) => tab.id));+const TYPE_LABEL_KEY: Partial<Record<ExampleType, TranslationKey>> = {curlTools: "settings.apiKeys.exampleCurlTools",pythonTools: "settings.apiKeys.examplePythonTools",@@ -509,20 +513,41 @@ export function UsageExamples({ apiKey }: { apiKey?: string | null }) {const cloudflareUrl = usePlatformStore((s) => s.cloudflareUrl);const serverUrl = usePlatformStore((s) => s.serverUrl);const secure = usePlatformStore((s) => s.secure);- const [lang, setLang] = useState<ExampleType>("curl");+ const setStoredLang = useSettingsPanelPrefsStore((s) => s.setApiExampleLang);+ const setStoredOs = useSettingsPanelPrefsStore((s) => s.setApiExampleOs);+ const setStoredAgent = useSettingsPanelPrefsStore(+ (s) => s.setApiExampleAgent,+ );+ // read once: these seed the controls, which write back through the handlers.+ const [storedPrefs] = useState(() => useSettingsPanelPrefsStore.getState());+ const [lang, setLang] = useState<ExampleType>(+ storedPrefs.apiExampleLang && EXAMPLE_TYPE_IDS.has(storedPrefs.apiExampleLang)+ ? (storedPrefs.apiExampleLang as ExampleType)+ : "curl",+ );+ // an explicit pick wins, since the snippet may target another machine.const [os, setOs] = useState<Os>(- deviceType === "windows" ? "windows" : "unix",+ storedPrefs.apiExampleOs === "windows" ||+ storedPrefs.apiExampleOs === "unix"+ ? storedPrefs.apiExampleOs+ : deviceType === "windows"+ ? "windows"+ : "unix",);const [copied, setCopied] = useState(false);const [copiedUrl, setCopiedUrl] = useState(false);const [copiedAgent, setCopiedAgent] = useState(false);- const [agent, setAgent] = useState<string>(DEFAULT_AGENT);+ const [agent, setAgent] = useState<string>(+ storedPrefs.apiExampleAgent ?? DEFAULT_AGENT,+ );const [availableAgents, setAvailableAgents] =useState<string[]>(DEFAULT_AGENTS);const [detectedAgents, setDetectedAgents] = useState<string[]>([]);+ // set on answer, so a restored agent never validates against the defaults.+ const [agentsLoaded, setAgentsLoaded] = useState(false);// True once the user has picked an agent themselves; guards the detection// effect below from clobbering that choice if it resolves afterward.- const agentPickedByUserRef = useRef(false);+ const agentPickedByUserRef = useRef(storedPrefs.apiExampleAgent != null);const [useTunnel, setUseTunnel] = useState<boolean>(readUseTunnelPref);const origin = typeof window !== "undefined" ? window.location.origin : "";const base =@@ -561,12 +586,25 @@ export function UsageExamples({ apiKey }: { apiKey?: string | null }) {}).catch(() => {// Best-effort: keep the default agent list and let the user pick manually.+ })+ .finally(() => {+ if (!cancelled) setAgentsLoaded(true);});return () => {cancelled = true;};}, [localAgentDetection]);+ // a restored agent this build no longer offers cannot build a command.+ useEffect(() => {+ if (!agentPickedByUserRef.current) return;+ if (localAgentDetection && !agentsLoaded) return;+ if (availableAgents.includes(agent)) return;+ agentPickedByUserRef.current = false;+ setStoredAgent(null);+ setAgent(DEFAULT_AGENT);+ }, [agent, agentsLoaded, availableAgents, localAgentDetection, setStoredAgent]);+// Single source of truth for the auto-picked agent, re-derived whenever// the detected list or the loaded model's GGUF-ness changes -- in either// direction. `codex` needs a GGUF model (unsloth_cli's@@ -726,7 +764,10 @@ export function UsageExamples({ apiKey }: { apiKey?: string | null }) {<buttonkey={tab.id}type="button"- onClick={() => setLang(tab.id)}+ onClick={() => {+ setLang(tab.id);+ setStoredLang(tab.id);+ }}aria-pressed={active}className={cn("rounded-full px-2.5 py-1 text-ui-11 font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",@@ -745,7 +786,10 @@ export function UsageExamples({ apiKey }: { apiKey?: string | null }) {<div className="flex min-w-0 items-center gap-0.5 border-b border-border px-2 py-1.5"><buttontype="button"- onClick={() => setOs("unix")}+ onClick={() => {+ setOs("unix");+ setStoredOs("unix");+ }}aria-pressed={os === "unix"}className={cn("rounded-full px-2.5 py-1 text-ui-11 font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",@@ -758,7 +802,10 @@ export function UsageExamples({ apiKey }: { apiKey?: string | null }) {</button><buttontype="button"- onClick={() => setOs("windows")}+ onClick={() => {+ setOs("windows");+ setStoredOs("windows");+ }}aria-pressed={os === "windows"}className={cn("rounded-full px-2.5 py-1 text-ui-11 font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",@@ -816,6 +863,7 @@ export function UsageExamples({ apiKey }: { apiKey?: string | null }) {onClick={() => {agentPickedByUserRef.current = true;setAgent(id);+ setStoredAgent(id);}}aria-pressed={active}title={diff --git a/studio/frontend/src/features/settings/stores/settings-panel-prefs-store.ts b/studio/frontend/src/features/settings/stores/settings-panel-prefs-store.tsnew file mode 100644index 00000000000..1727829625e--- /dev/null+++ b/studio/frontend/src/features/settings/stores/settings-panel-prefs-store.ts@@ -0,0 +1,127 @@+// 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 { create } from "zustand";+import { persist } from "zustand/middleware";++export type ExampleOs = "unix" | "windows";+export type FineTuneAction = "train" | "recipes" | "export";++export const SETTINGS_PANEL_PREFS_STORAGE_KEY = "unsloth_settings_panel_prefs";++// settings dialog picks that renderTab() used to drop on every tab switch.+export interface SettingsPanelPrefsState {+ // null model means "follow whichever model the server has resident".+ agentsAgent: string | null;+ agentsModel: string | null;+ // the quant carries the model it was picked for, so remembering a quant alone+ // never pins a model the tab would otherwise keep following.+ agentsVariant: string | null;+ agentsVariantModel: string | null;+ setAgentsAgent: (agent: string | null) => void;+ setAgentsModel: (model: string | null, variant: string | null) => void;+ setAgentsVariant: (model: string, variant: string) => void;++ // null os means "follow the detected device type".+ apiExampleLang: string | null;+ apiExampleOs: ExampleOs | null;+ apiExampleAgent: string | null;+ setApiExampleLang: (lang: string) => void;+ setApiExampleOs: (os: ExampleOs) => void;+ setApiExampleAgent: (agent: string | null) => void;++ resourcesLiveUpdates: boolean;+ setResourcesLiveUpdates: (enabled: boolean) => void;++ fineTuneAction: FineTuneAction;+ setFineTuneAction: (action: FineTuneAction) => void;+}++const EXAMPLE_OS_VALUES: ExampleOs[] = ["unix", "windows"];+const FINE_TUNE_VALUES: FineTuneAction[] = ["train", "recipes", "export"];++// localStorage is untyped at runtime and these reach `.toLowerCase()` and the+// path checks in agents-tab, so a bad record would take the app down. The+// default merge also spreads the blob over the actions themselves. Whitelist.+function text(value: unknown): string | null {+ return typeof value === "string" && value.length > 0 ? value : null;+}++function oneOf<T extends string>(value: unknown, allowed: T[], fallback: T): T {+ return typeof value === "string" && (allowed as string[]).includes(value)+ ? (value as T)+ : fallback;+}++function sanitize(+ persisted: unknown,+ current: SettingsPanelPrefsState,+): SettingsPanelPrefsState {+ const raw = (+ persisted && typeof persisted === "object" ? persisted : {}+ ) as Record<string, unknown>;+ const agentsModel = text(raw.agentsModel);+ const agentsVariantModel = text(raw.agentsVariantModel);+ const agentsVariant = text(raw.agentsVariant);+ return {+ ...current,+ agentsAgent: text(raw.agentsAgent),+ agentsModel,+ // A quant with no model to scope it to can never be applied.+ agentsVariant: agentsVariantModel ? agentsVariant : null,+ agentsVariantModel: agentsVariant ? agentsVariantModel : null,+ apiExampleLang: text(raw.apiExampleLang),+ apiExampleOs:+ typeof raw.apiExampleOs === "string" &&+ (EXAMPLE_OS_VALUES as string[]).includes(raw.apiExampleOs)+ ? (raw.apiExampleOs as ExampleOs)+ : null,+ apiExampleAgent: text(raw.apiExampleAgent),+ resourcesLiveUpdates:+ typeof raw.resourcesLiveUpdates === "boolean"+ ? raw.resourcesLiveUpdates+ : true,+ fineTuneAction: oneOf(raw.fineTuneAction, FINE_TUNE_VALUES, "train"),+ };+}++export const useSettingsPanelPrefsStore = create<SettingsPanelPrefsState>()(+ persist(+ (set) => ({+ agentsAgent: null,+ agentsModel: null,+ agentsVariant: null,+ agentsVariantModel: null,+ setAgentsAgent: (agentsAgent) => set({ agentsAgent }),+ // picking a model carries its quant, and clearing it clears that quant.+ setAgentsModel: (agentsModel, agentsVariant) =>+ set({ agentsModel, agentsVariant, agentsVariantModel: agentsModel }),+ setAgentsVariant: (agentsVariantModel, agentsVariant) =>+ set({ agentsVariant, agentsVariantModel }),++ apiExampleLang: null,+ apiExampleOs: null,+ apiExampleAgent: null,+ setApiExampleLang: (apiExampleLang) => set({ apiExampleLang }),+ setApiExampleOs: (apiExampleOs) => set({ apiExampleOs }),+ setApiExampleAgent: (apiExampleAgent) => set({ apiExampleAgent }),++ resourcesLiveUpdates: true,+ setResourcesLiveUpdates: (resourcesLiveUpdates) =>+ set({ resourcesLiveUpdates }),++ fineTuneAction: "train",+ setFineTuneAction: (fineTuneAction) => set({ fineTuneAction }),+ }),+ {+ name: SETTINGS_PANEL_PREFS_STORAGE_KEY,+ // Pinned so a later shape change has somewhere to migrate from.+ version: 1,+ // Older records share these field names, so the sanitiser is enough. A+ // newer one is dropped: it may reuse the names with different meaning.+ migrate: (persisted, version) =>+ (version < 1 ? persisted : {}) as SettingsPanelPrefsState,+ merge: (persisted, current) => sanitize(persisted, current),+ },+ ),+);diff --git a/studio/frontend/src/features/settings/tabs/agents-tab.tsx b/studio/frontend/src/features/settings/tabs/agents-tab.tsxindex a8ef07234be..00eb87146f2 100644--- a/studio/frontend/src/features/settings/tabs/agents-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/agents-tab.tsx@@ -53,6 +53,7 @@ import {} from "../components/agent-command";import { SettingsSection } from "../components/settings-section";import { psSingle, shSingle } from "../components/usage-examples";+import { useSettingsPanelPrefsStore } from "../stores/settings-panel-prefs-store";const DOCS_URL = "https://unsloth.ai/docs/integrations/unsloth-start";const EXAMPLE_MODEL_REPO = "unsloth/gemma-4-E4B-it-GGUF";@@ -214,6 +215,11 @@ function looksLikePath(value: string): boolean {);}+// hugging face ids fold case; a path does not, since Linux paths are sensitive.+function modelKey(model: string): string {+ return looksLikePath(model) ? model : model.toLowerCase();+}+function isHuggingFaceRepo(model: string): boolean {return HUGGING_FACE_REPO_PATTERN.test(model);}@@ -242,11 +248,9 @@ function discoverGgufModels(const variants: Record<string, string> = {};// Hugging Face ids are case-insensitive, and the catalog and cache endpoints can// disagree on spelling; two rows for one repo would leave the load id on only one.- const seen = new Set(models.map((model) => model.toLowerCase()));+ const seen = new Set(models.map(modelKey));const add = (model: string) => {- // Local entries arrive here as absolute paths, and a path is case-sensitive on- // Linux: folding those would collapse two distinct models into one.- const key = looksLikePath(model) ? model : model.toLowerCase();+ const key = modelKey(model);if (seen.has(key)) {return;}@@ -635,14 +639,29 @@ export function AgentsTab() {? deviceType === "windows": isWindowsClient;const localDetection = canUseLocalAgentDetection(serverUrl ?? origin);+ const setStoredAgent = useSettingsPanelPrefsStore((s) => s.setAgentsAgent);+ const setStoredModel = useSettingsPanelPrefsStore((s) => s.setAgentsModel);+ const setStoredVariant = useSettingsPanelPrefsStore(+ (s) => s.setAgentsVariant,+ );+ // read once: these seed the controls, which write back through the handlers.+ const [storedPrefs] = useState(() => useSettingsPanelPrefsStore.getState());const [agents, setAgents] = useState<string[]>(SUPPORTED_AGENTS.map((agent) => agent.id),);- const [selectedAgent, setSelectedAgent] = useState(FALLBACK_AGENT.id);- const agentSelectionChanged = useRef(false);+ const [selectedAgent, setSelectedAgent] = useState(+ storedPrefs.agentsAgent ?? FALLBACK_AGENT.id,+ );+ // a restored pick counts as explicit, or detection would overwrite it.+ const agentSelectionChanged = useRef(storedPrefs.agentsAgent != null);const [detectedAgents, setDetectedAgents] = useState<Set<string>>(new Set());const [loaded, setLoaded] = useState(false);- const [models, setModels] = useState<string[]>([EXAMPLE_MODEL_REPO]);+ // list the restored model until the discovery scan confirms or retires it.+ const [models, setModels] = useState<string[]>(+ storedPrefs.agentsModel && storedPrefs.agentsModel !== EXAMPLE_MODEL_REPO+ ? [storedPrefs.agentsModel, EXAMPLE_MODEL_REPO]+ : [EXAMPLE_MODEL_REPO],+ );const [cachedLoadIds, setCachedLoadIds] = useState<Record<string, string>>({},);@@ -658,20 +677,43 @@ export function AgentsTab() {const [knownVariants, setKnownVariants] = useState<Record<string, string>>({[EXAMPLE_MODEL_REPO]: EXAMPLE_MODEL_VARIANT,});- const [selectedModel, setSelectedModel] = useState(EXAMPLE_MODEL_REPO);- const modelSelectionChanged = useRef(false);+ const initialModel = storedPrefs.agentsModel ?? EXAMPLE_MODEL_REPO;+ const [selectedModel, setSelectedModel] = useState(initialModel);+ const modelSelectionChanged = useRef(storedPrefs.agentsModel != null);+ // held until discovery and the first status can confirm the restored model.+ const restoredModel = useRef<string | null>(storedPrefs.agentsModel);+ const [discoveredKeys, setDiscoveredKeys] = useState<Set<string> | null>(+ null,+ );+ const [statusSettled, setStatusSettled] = useState(false);// The model status last reported, for the discovery scan to preserve.- const activeModelRef = useRef<string | null>(null);+ const activeModelRef = useRef<{+ model: string;+ variant: string | null;+ } | null>(null);// Only the newest status request may apply; a slow earlier one must not win.const statusSeq = useRef(0);// A quant picked by hand, scoped to its repo: polling and refetches must not// overwrite it, but it must not follow the selection onto a different repo.- const chosenVariant = useRef<{ model: string; variant: string } | null>(null);+ // a restored quant is scoped the same way, so it applies when its model does.+ const chosenVariant = useRef<{ model: string; variant: string } | null>(+ storedPrefs.agentsVariantModel && storedPrefs.agentsVariant+ ? {+ model: storedPrefs.agentsVariantModel,+ variant: storedPrefs.agentsVariant,+ }+ : null,+ );const [modelSearch, setModelSearch] = useState("");const [modelPickerOpen, setModelPickerOpen] = useState(false);const [variants, setVariants] = useState<GgufVariantDetail[]>([]);const [selectedVariant, setSelectedVariant] = useState<string | null>(- EXAMPLE_MODEL_VARIANT,+ chosenVariant.current &&+ modelKey(chosenVariant.current.model) === modelKey(initialModel)+ ? chosenVariant.current.variant+ : initialModel === EXAMPLE_MODEL_REPO+ ? EXAMPLE_MODEL_VARIANT+ : null,);const [variantsLoading, setVariantsLoading] = useState(true);const [variantsFailed, setVariantsFailed] = useState(false);@@ -796,12 +838,40 @@ export function AgentsTab() {};}, [localDetection]);+ // a restored agent the backend no longer lists cannot build a command.+ useEffect(() => {+ if (!agentSelectionChanged.current) return;+ if (localDetection && !loaded) return;+ if (agents.includes(selectedAgent)) return;+ agentSelectionChanged.current = false;+ setStoredAgent(null);+ setSelectedAgent(+ agents.find((agent) => detectedAgents.has(agent)) ??+ agents[0] ??+ FALLBACK_AGENT.id,+ );+ }, [+ agents,+ detectedAgents,+ loaded,+ localDetection,+ selectedAgent,+ setStoredAgent,+ ]);+useEffect(() => {let cancelled = false;+ // An endpoint that could not answer has not proved a model absent, and the+ // retire treats discoveredKeys as exactly that proof.+ let discoveryComplete = true;+ const note = <T,>(fallback: T) => (): T => {+ discoveryComplete = false;+ return fallback;+ };Promise.all([- listModels().catch(() => null),- listCachedGguf().catch(() => []),- listLocalModels().catch(() => null),+ listModels().catch(note(null)),+ listCachedGguf().catch(note([])),+ listLocalModels().catch(note(null)),]).then(([info, cachedGgufs, local]) => {if (cancelled) {@@ -828,10 +898,14 @@ export function AgentsTab() {labels[entry.id] = entry.label;}}+ // Left null when a source failed; null already means "cannot retire".+ if (discoveryComplete) {+ setDiscoveredKeys(new Set(discovered.models.map(modelKey)));+ }// Status is applied on its own schedule now, so keep whatever model it has// already adopted rather than dropping it when this slower scan lands.setModels(() => {- const active = activeModelRef.current;+ const active = activeModelRef.current?.model;return active && !discovered.models.includes(active)? [active, ...discovered.models]: discovered.models;@@ -851,6 +925,16 @@ export function AgentsTab() {};}, []);+ // The remembered quant for `model`, matched through modelKey: the catalog,+ // cache and status endpoints can disagree on repo-id casing, and an exact+ // compare would silently drop the user's quant.+ const rememberedVariant = useCallback((model: string): string | null => {+ const chosen = chosenVariant.current;+ return chosen && modelKey(chosen.model) === modelKey(model)+ ? chosen.variant+ : null;+ }, []);+// List the resident model and follow it, unless the user picked one explicitly.const adoptActiveModel = useCallback((active: { model: string; variant: string | null }) => {@@ -865,12 +949,12 @@ export function AgentsTab() {}if (!modelSelectionChanged.current) {setSelectedModel(active.model);- if (chosenVariant.current?.model !== active.model) {- setSelectedVariant(active.variant);- }+ // a remembered quant for this model wins, since it may be adopted here+ // before the variants fetch below has had a chance to apply it.+ setSelectedVariant(rememberedVariant(active.model) ?? active.variant);}},- [],+ [rememberedVariant],);// A native-grant label only stands for whatever was resident at the time, so once@@ -920,7 +1004,9 @@ export function AgentsTab() {const applyStatus = useCallback((status: InferenceStatusResponse) => {const active = activeGgufSelection(status);- activeModelRef.current = active?.model ?? null;+ activeModelRef.current = active+ ? { model: active.model, variant: active.variant }+ : null;const wasAttachOnly = attachOnlyModel;setActiveStatusModel(active?.model ?? null);setAttachOnlyModel(active && !active.named ? active.model : null);@@ -954,10 +1040,14 @@ export function AgentsTab() {.then((status) => {if (!cancelled && seq === statusSeq.current) {applyStatus(status);+ // Only a current, answered poll is evidence: settling a superseded+ // one would let the retire run with activeModelRef unset.+ setStatusSettled(true);}}).catch(() => {- // A failed poll just leaves the last known selection in place.+ // Not settled: a request that never answered proves nothing about+ // what is resident, so the retire below must keep waiting.});};sync();@@ -968,6 +1058,40 @@ export function AgentsTab() {};}, [applyStatus]);+ // retiring a restored pick needs both reads: either alone can miss a model+ // the other knows about, and a wrong retire drops the user's choice.+ useEffect(() => {+ const restored = restoredModel.current;+ if (!(restored && discoveredKeys && statusSettled)) return;+ const active = activeModelRef.current;+ restoredModel.current = null;+ // modelKey both sides: discovery folds repo-id case, so an exact match+ // would retire a valid pick just for a different spelling.+ // A path is never in discoveredKeys (the catalog drops path ids and a scan+ // root may not cover it), but `unsloth start --model <path>` is valid, so+ // absence there is not evidence.+ if (+ looksLikePath(restored) ||+ discoveredKeys.has(modelKey(restored)) ||+ (active && modelKey(active.model) === modelKey(restored))+ ) {+ return;+ }+ // an uncached pick would pin the builder to a model the CLI cannot load.+ modelSelectionChanged.current = false;+ chosenVariant.current = null;+ setStoredModel(null, null);+ // adopt straight away rather than parking on the example model: the next+ // poll is STATUS_POLL_MS away, and a command copied meanwhile would switch+ // a shared server off whatever is loaded.+ if (active) {+ adoptActiveModel(active);+ return;+ }+ setSelectedModel(EXAMPLE_MODEL_REPO);+ setSelectedVariant(EXAMPLE_MODEL_VARIANT);+ }, [adoptActiveModel, discoveredKeys, statusSettled, setStoredModel]);+useEffect(() => {let cancelled = false;@@ -1028,11 +1152,19 @@ export function AgentsTab() {const available = new Set(uniqueVariants.map((variant) => variant.quant),);+ // Authoritative for this repo: drop a remembered quant it no longer+ // offers, or adoptActiveModel re-imposes it on the next poll.+ // Stop adoptActiveModel re-imposing a quant this repo will not serve.+ // In-memory only: `partial` here means "still downloading", and an+ // offline reply lists just the cache, so neither is grounds to delete+ // the user's saved quant. Dropping the ref re-runs this next mount.+ const remembered = rememberedVariant(selectedModel);+ if (remembered && !available.has(remembered)) {+ chosenVariant.current = null;+ }const nextVariant =pickVariant(available, [- chosenVariant.current?.model === selectedModel- ? chosenVariant.current.variant- : null,+ rememberedVariant(selectedModel),preferredVariant,info.default_variant,]) ??@@ -1067,7 +1199,13 @@ export function AgentsTab() {return () => {cancelled = true;};- }, [cachedLoadId, hfToken, preferredVariant, selectedModel]);+ }, [+ cachedLoadId,+ hfToken,+ preferredVariant,+ rememberedVariant,+ selectedModel,+ ]);// No GGUF warning for `codex` (unsloth_cli's _require_gguf_for_codex): the// picker only ever offers GGUF models.@@ -1146,6 +1284,7 @@ export function AgentsTab() {onValueChange={(agent) => {agentSelectionChanged.current = true;setSelectedAgent(agent);+ setStoredAgent(agent);resetCopied();}}>@@ -1262,8 +1401,16 @@ export function AgentsTab() {data-checked={model === selectedModel}onSelect={() => {modelSelectionChanged.current = true;+ restoredModel.current = null;+ const variant =+ rememberedVariant(model) ?? knownVariants[model] ?? null;setSelectedModel(model);- setSelectedVariant(knownVariants[model] ?? null);+ setSelectedVariant(variant);+ // a native-grant label names no path to reuse.+ setStoredModel(+ model === attachOnlyModel ? null : model,+ model === attachOnlyModel ? null : variant,+ );setVariants([]);setVariantsFailed(false);setVariantsLoading(isHuggingFaceRepo(model));@@ -1306,6 +1453,11 @@ export function AgentsTab() {onValueChange={(variant) => {chosenVariant.current = { model: selectedModel, variant };setSelectedVariant(variant);+ // stored against its model, so a quant picked while following+ // the resident model is remembered without pinning it.+ if (selectedModel !== attachOnlyModel) {+ setStoredVariant(selectedModel, variant);+ }resetCopied();}}disabled={variantsLoading || variants.length === 0}diff --git a/studio/frontend/src/features/settings/tabs/data-tab.tsx b/studio/frontend/src/features/settings/tabs/data-tab.tsxindex 200b443f391..58571660a2b 100644--- a/studio/frontend/src/features/settings/tabs/data-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/data-tab.tsx@@ -67,6 +67,13 @@ import { SettingsRow } from "../components/settings-row";import { SettingsSection } from "../components/settings-section";import { UploadedFilesView } from "../components/uploaded-files-dialog";import { useSettingsDialogStore } from "../stores/settings-dialog-store";+import {+ type FineTuneAction,+ useSettingsPanelPrefsStore,+} from "../stores/settings-panel-prefs-store";++// display order, and the guard against a persisted action this build dropped.+const FINE_TUNE_ACTIONS: FineTuneAction[] = ["export", "train", "recipes"];export function DataTab() {const t = useT();@@ -97,18 +104,20 @@ export function DataTab() {// the Train tab would upload it and then strand the user; gate the action// the same way the sidebar gates Train.const chatOnly = usePlatformStore((s) => s.isChatOnly());- const [fineTuneAction, setFineTuneAction] = useState<- "train" | "recipes" | "export"- >(chatOnly ? "export" : "train");+ const storedFineTuneAction = useSettingsPanelPrefsStore(+ (s) => s.fineTuneAction,+ );+ const setFineTuneAction = useSettingsPanelPrefsStore(+ (s) => s.setFineTuneAction,+ );+ const restoredAction = FINE_TUNE_ACTIONS.includes(storedFineTuneAction)+ ? storedFineTuneAction+ : "export";+ // derived, not corrected: a stored "train" returns when chat-only flips off.+ const fineTuneAction =+ chatOnly && restoredAction === "train" ? "export" : restoredAction;// Chat Completions (OpenAI messages) is the only export format we ship.const fineTuneFormat: FineTuneFormat = "openai";-- // The MLX self-heal can flip chat-only while the dialog is open.- useEffect(() => {- if (chatOnly) {- setFineTuneAction((a) => (a === "train" ? "export" : a));- }- }, [chatOnly]);// Requests can arrive after Data is already mounted (for example from the// archive-all toast), so always switch before consuming the flag.useEffect(() => {@@ -480,7 +489,7 @@ export function DataTab() {</Button></DropdownMenuTrigger><DropdownMenuContent align="end" className="w-56">- {(["export", "train", "recipes"] as const).map((action) => (+ {FINE_TUNE_ACTIONS.map((action) => (<DropdownMenuItemkey={action}disabled={action === "train" && chatOnly}diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsxindex b53e0de4669..0b360639880 100644--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx@@ -64,6 +64,7 @@ import { SettingsRow } from "../components/settings-row";import { SettingsSection } from "../components/settings-section";import { StudioVersionSection } from "../components/studio-version-section";import { useSettingsDialogStore } from "../stores/settings-dialog-store";+import { SETTINGS_PANEL_PREFS_STORAGE_KEY } from "../stores/settings-panel-prefs-store";// Keys cleared by "Reset all local preferences".// NEVER include auth/session keys here — clearing them would log the user out@@ -82,6 +83,7 @@ const PREFS_KEYS: string[] = ["chat_settings_width","unsloth_sidebar_navigate_open","unsloth_settings_active_tab",+ SETTINGS_PANEL_PREFS_STORAGE_KEY,// Chat runtime prefs"unsloth_chat_auto_title","unsloth_chat_permission_mode",diff --git a/studio/frontend/src/features/settings/tabs/resources-tab.tsx b/studio/frontend/src/features/settings/tabs/resources-tab.tsxindex fc95d22c46c..ddefdadec46 100644--- a/studio/frontend/src/features/settings/tabs/resources-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/resources-tab.tsx@@ -29,6 +29,7 @@ import {import { SettingsRow } from "../components/settings-row";import { SettingsSection } from "../components/settings-section";import { useMonitorOverlayStore } from "../stores/monitor-overlay-store";+import { useSettingsPanelPrefsStore } from "../stores/settings-panel-prefs-store";import { CopyIcon, FolderOpenIcon, LayersIcon } from "lucide-react";const POLL_MS = 3000;@@ -183,10 +184,14 @@ function deviceOrdinal(device: GpuDevice): number | undefined {export function ResourcesTab() {const t = useT();- const [liveUpdates, setLiveUpdates] = useState(true);+ const liveUpdates = useSettingsPanelPrefsStore((s) => s.resourcesLiveUpdates);+ const setLiveUpdates = useSettingsPanelPrefsStore(+ (s) => s.setResourcesLiveUpdates,+ );const { isOpen, setIsOpen } = useMonitorOverlayStore();+ // always fetch once: the switch is persisted now, so gating the hook on it+ // would leave a session that opens with it off reading zeros forever.const systemInfo = useSystemInfo({- enabled: liveUpdates,pollMs: liveUpdates ? POLL_MS : undefined,});const [hfCache, setHfCache] = useState<HuggingFaceCacheSettings | null>(null);diff --git a/studio/frontend/tests/settings-panel-prefs.test.ts b/studio/frontend/tests/settings-panel-prefs.test.tsnew file mode 100644index 00000000000..26edbad8a3e--- /dev/null+++ b/studio/frontend/tests/settings-panel-prefs.test.ts@@ -0,0 +1,219 @@+// 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 { readFile } from "node:fs/promises";+import test from "node:test";+import { installLocalStorageFake, registerBundlerResolver } from "./helpers/kit.ts";++registerBundlerResolver();+const { store } = installLocalStorageFake();++const KEY = "unsloth_settings_panel_prefs";++// A record written before the sanitiser existed, holding every field.+store.set(+ KEY,+ JSON.stringify({+ state: {+ agentsAgent: "codex",+ agentsModel: "unsloth/Foo-GGUF",+ agentsVariant: "UD-Q4_K_XL",+ agentsVariantModel: "unsloth/Foo-GGUF",+ apiExampleLang: "pythonTools",+ apiExampleOs: "windows",+ apiExampleAgent: "codex",+ resourcesLiveUpdates: false,+ fineTuneAction: "recipes",+ },+ version: 0,+ }),+);++const { useSettingsPanelPrefsStore, SETTINGS_PANEL_PREFS_STORAGE_KEY } =+ await import("../src/features/settings/stores/settings-panel-prefs-store.ts");++test("a version 0 record hydrates every field", () => {+ const s = useSettingsPanelPrefsStore.getState();+ assert.equal(s.agentsAgent, "codex");+ assert.equal(s.agentsModel, "unsloth/Foo-GGUF");+ assert.equal(s.agentsVariant, "UD-Q4_K_XL");+ assert.equal(s.apiExampleOs, "windows");+ assert.equal(s.resourcesLiveUpdates, false);+ assert.equal(s.fineTuneAction, "recipes");+});++test("picking a model carries its quant, and clearing it clears the quant", () => {+ const s = useSettingsPanelPrefsStore.getState();+ s.setAgentsModel("unsloth/Bar-GGUF", "Q4_K_M");+ let next = useSettingsPanelPrefsStore.getState();+ assert.equal(next.agentsModel, "unsloth/Bar-GGUF");+ assert.equal(next.agentsVariantModel, "unsloth/Bar-GGUF");+ next.setAgentsModel(null, null);+ next = useSettingsPanelPrefsStore.getState();+ assert.equal(next.agentsModel, null);+ assert.equal(next.agentsVariant, null);+ assert.equal(next.agentsVariantModel, null);+});++test("a quant remembered for one model does not follow onto another", () => {+ const s = useSettingsPanelPrefsStore.getState();+ s.setAgentsVariant("unsloth/Baz-GGUF", "Q4_K_M");+ const next = useSettingsPanelPrefsStore.getState();+ assert.equal(next.agentsVariant, "Q4_K_M");+ assert.equal(next.agentsVariantModel, "unsloth/Baz-GGUF");+ assert.equal(next.agentsModel, null, "a quant pick must not pin the model");+});++test("a setter write round-trips through localStorage", () => {+ useSettingsPanelPrefsStore.getState().setFineTuneAction("export");+ const raw = store.get(KEY);+ assert.ok(raw, "nothing was written");+ assert.equal(JSON.parse(raw as string).state.fineTuneAction, "export");+});++// The reason the sanitiser exists: agentsModel reaches `.toLowerCase()` and the+// path checks in agents-tab, so a non-string takes the whole app down.+test("a non-string model is refused rather than handed to the tab", () => {+ const merged = useSettingsPanelPrefsStore.persist.getOptions().merge;+ assert.ok(merged, "merge must be supplied, or untrusted JSON reaches the UI");+ const out = merged(+ { agentsModel: 42, agentsVariant: [], fineTuneAction: "obliterate" },+ useSettingsPanelPrefsStore.getState(),+ ) as { agentsModel: unknown; fineTuneAction: string };+ assert.equal(out.agentsModel, null);+ assert.equal(out.fineTuneAction, "train");+});++test("a persisted blob cannot replace the store actions", () => {+ const merged = useSettingsPanelPrefsStore.persist.getOptions().merge;+ assert.ok(merged);+ const out = merged(+ { setFineTuneAction: 5 },+ useSettingsPanelPrefsStore.getState(),+ ) as { setFineTuneAction: unknown };+ assert.equal(typeof out.setFineTuneAction, "function");+});++// The case agentsVariantModel exists for: the tab keeps following the resident+// model, but the quant picked against it still survives the unmount.+test("a quant picked while following the resident model does not pin a model", () => {+ const s = useSettingsPanelPrefsStore.getState();+ s.setAgentsModel(null, null);+ s.setAgentsVariant("unsloth/Qux-GGUF", "Q6_K");+ const next = useSettingsPanelPrefsStore.getState();+ assert.equal(next.agentsModel, null);+ assert.equal(next.agentsVariant, "Q6_K");+ assert.equal(next.agentsVariantModel, "unsloth/Qux-GGUF");+});++// Half a pair is unusable: a quant with no model can never be scoped to one.+test("a quant with no model to scope it to is dropped", () => {+ const merged = useSettingsPanelPrefsStore.persist.getOptions().merge;+ assert.ok(merged);+ const out = merged(+ { agentsVariant: "Q6_K" },+ useSettingsPanelPrefsStore.getState(),+ ) as { agentsVariant: unknown; agentsVariantModel: unknown };+ assert.equal(out.agentsVariant, null);+ assert.equal(out.agentsVariantModel, null);+});++// A downgrade must not read a newer record: the field names may have been+// reused with different meaning.+test("a record from a newer build falls back to defaults", () => {+ const { migrate, version } = useSettingsPanelPrefsStore.persist.getOptions();+ assert.ok(migrate);+ assert.equal(version, 1);+ assert.deepEqual(migrate({ agentsModel: "unsloth/Foo-GGUF" }, 2), {});+ assert.deepEqual(migrate({ agentsModel: "unsloth/Foo-GGUF" }, 0), {+ agentsModel: "unsloth/Foo-GGUF",+ });+});++// Settling in a .finally let a superseded or failed poll release the retire+// with no resident model recorded, which erased the saved model and quant.+test("the status poll settles only on the read that applied", async () => {+ const source = await readFile(+ new URL("../src/features/settings/tabs/agents-tab.tsx", import.meta.url),+ "utf8",+ );+ const sync = source.slice(+ source.indexOf("const sync = ()"),+ source.indexOf("const timer = window.setInterval"),+ );+ assert.ok(sync, "the status poll moved; this contract needs updating");+ assert.ok(+ !sync.includes(".finally("),+ "a stale or failed poll must not settle",+ );+ const applied = sync.slice(+ sync.indexOf("seq === statusSeq.current"),+ sync.indexOf(".catch("),+ );+ assert.match(applied, /setStatusSettled\(true\)/);+});++// Reset-all is the only in-app escape hatch from a bad pinned model.+test("Reset all local preferences clears this key", async () => {+ const source = await readFile(+ new URL("../src/features/settings/tabs/general-tab.tsx", import.meta.url),+ "utf8",+ );+ const keys = source.slice(+ source.indexOf("const PREFS_KEYS"),+ source.indexOf("];", source.indexOf("const PREFS_KEYS")),+ );+ assert.ok(+ keys.includes("SETTINGS_PANEL_PREFS_STORAGE_KEY") ||+ keys.includes(`"${SETTINGS_PANEL_PREFS_STORAGE_KEY}"`),+ `${SETTINGS_PANEL_PREFS_STORAGE_KEY} missing from PREFS_KEYS`,+ );+});++// A quant is scoped to the repo it was picked for, and the catalog, cache and+// status endpoints can disagree on repo-id casing, so that scope check has to+// normalize or the user's quant is dropped when the spelling differs.+test("the remembered quant is scoped through modelKey, not an exact compare", async () => {+ const source = await readFile(+ new URL("../src/features/settings/tabs/agents-tab.tsx", import.meta.url),+ "utf8",+ );+ assert.match(+ source,+ /modelKey\(chosen\.model\) === modelKey\(model\)/,+ "rememberedVariant must compare through modelKey",+ );+ const exact = source+ .split("\n")+ .filter((line) => line.includes("chosenVariant.current?.model ==="));+ assert.deepEqual(+ exact,+ [],+ "an exact repo-id compare on chosenVariant drops the quant on a casing difference",+ );+});++// An unreadable record leaves the pre-PR defaults, so a mangled blob never+// changes how the tabs behave.+test("an unreadable record leaves the defaults", () => {+ const merged = useSettingsPanelPrefsStore.persist.getOptions().merge;+ assert.ok(merged);+ const out = merged(null, useSettingsPanelPrefsStore.getState());+ assert.equal(out.agentsModel, null);+ assert.equal(out.agentsVariant, null);+ assert.equal(out.resourcesLiveUpdates, true);+ assert.equal(out.fineTuneAction, "train");+});++// Last: it rehydrates the store. Corrupt JSON must not take settings down.+test("corrupt JSON does not break the store", async () => {+ store.set(KEY, "{not json");+ await assert.doesNotReject(async () => {+ await useSettingsPanelPrefsStore.persist.rehydrate();+ });+ assert.equal(+ typeof useSettingsPanelPrefsStore.getState().setAgentsModel,+ "function",+ );+});