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
fix(studio): honor run settings on initial model load (#7346) (#7351)
Souravrajvi0dffea2af27b9
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex 7452cf34477..a439a912397 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -2676,7 +2676,7 @@ export function ChatPage({config: meta?.config,nativePathToken: meta?.nativePathToken,nativePathExpiresAtMs: meta?.nativePathExpiresAtMs,- forceReload: isSameLoadedModel || undefined,+ forceReload: meta?.forceReload ?? (isSameLoadedModel || undefined),};await stageOrLoad(selection);})();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.tsindex bb19223a6a0..48a6168555f 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@@ -62,6 +62,7 @@ import {import { isExternalModelId } from "../external-providers";import {applyPerModelConfigToRuntime,+ normalizeMaxSeqLength,type PerModelConfig,} from "@/features/model-picker";import type {@@ -604,12 +605,19 @@ export function useChatModelRuntime() {async function performLoad(): Promise<void> {if (abortCtrl.signal.aborted) throw new Error("Cancelled");let previousWasUnloaded = false;+ const pendingLoadConfig =+ typeof selection !== "string" ? selection.config : undefined;+ if (pendingLoadConfig) {+ applyPerModelConfigToRuntime(pendingLoadConfig);+ }const currentCheckpoint =useChatRuntimeStore.getState().params.checkpoint;const stateBeforeUnload = useChatRuntimeStore.getState();let trustRemoteCode = stateBeforeUnload.params.trustRemoteCode ?? false;let approvedRemoteCodeFingerprint: string | null = null;- const maxSeqLength = stateBeforeUnload.params.maxSeqLength;+ const maxSeqLength =+ normalizeMaxSeqLength(pendingLoadConfig?.maxSeqLength) ??+ stateBeforeUnload.params.maxSeqLength;const previousActiveNativePathToken =stateBeforeUnload.activeNativePathToken;const previousIsGguf =@@ -643,34 +651,54 @@ export function useChatModelRuntime() {const previousActiveNativePathExpiresAtMs =stateBeforeUnload.activeNativePathExpiresAtMs;// Snapshot the load settings at click time, before the awaits below- // (validation, the trust dialog, unload).- const loadChatTemplateOverride = stateBeforeUnload.chatTemplateOverride;- const loadKvCacheDtype = stateBeforeUnload.kvCacheDtype;+ // (validation, the trust dialog, unload). When the picker staged a+ // config payload, prefer it over the store: React may not have+ // flushed NumericValueInput's blur commit into state yet.+ const loadChatTemplateOverride =+ pendingLoadConfig?.chatTemplateOverride?.trim()+ ? pendingLoadConfig.chatTemplateOverride+ : stateBeforeUnload.chatTemplateOverride;+ const loadKvCacheDtype =+ pendingLoadConfig?.kvCacheDtype ?? stateBeforeUnload.kvCacheDtype;// gpuMemoryMode is a standing preference (kept across a model switch);// the rest are per-model knobs the reset below clears, so they are// re-baselined there in lock-step with the store.- let loadCustomContextLength = stateBeforeUnload.customContextLength;+ let loadCustomContextLength =+ pendingLoadConfig?.customContextLength ??+ stateBeforeUnload.customContextLength;const loadGgufContextLength = stateBeforeUnload.ggufContextLength;- const loadTensorParallel = stateBeforeUnload.tensorParallel;+ const loadTensorParallel =+ pendingLoadConfig?.tensorParallel ?? stateBeforeUnload.tensorParallel;const loadActivePresetSource = stateBeforeUnload.activePresetSource;const loadActiveGgufVariant = stateBeforeUnload.activeGgufVariant;- const loadGpuMemoryMode = stateBeforeUnload.gpuMemoryMode;- let loadGpuLayers = stateBeforeUnload.gpuLayers;- let loadNCpuMoe = stateBeforeUnload.nCpuMoe;+ const loadGpuMemoryMode =+ pendingLoadConfig?.gpuMemoryMode ?? stateBeforeUnload.gpuMemoryMode;+ let loadGpuLayers =+ pendingLoadConfig?.gpuLayers ?? stateBeforeUnload.gpuLayers;+ let loadNCpuMoe =+ pendingLoadConfig?.nCpuMoe ?? stateBeforeUnload.nCpuMoe;let loadSplitRatio = stateBeforeUnload.splitRatio;// Reconcile the persisted pick against the GPUs present now, so a stale// cross-host / now-hidden pick is dropped before /load rather than// rejected there. Warm the device cache first: load-on-selection can// run before any GPU hook mounted, and a cold cache would pass the// pick through unvalidated. validateGpuIds derives from this too.- if (stateBeforeUnload.selectedGpuIds != null) {+ if (+ pendingLoadConfig?.selectedGpuIds !== undefined ||+ stateBeforeUnload.selectedGpuIds != null+ ) {await ensureGpuDeviceCache();}- let loadSelectedGpuIds = reconcilePersistedGpuIds(- stateBeforeUnload.selectedGpuIds,- );- let loadSpeculativeType = stateBeforeUnload.speculativeType;- let loadSpecDraftNMax = stateBeforeUnload.specDraftNMax;+ let loadSelectedGpuIds =+ pendingLoadConfig?.selectedGpuIds !== undefined+ ? reconcilePersistedGpuIds(pendingLoadConfig.selectedGpuIds)+ : reconcilePersistedGpuIds(stateBeforeUnload.selectedGpuIds);+ let loadSpeculativeType =+ pendingLoadConfig?.speculativeType != null+ ? normalizeSpeculativeType(pendingLoadConfig.speculativeType)+ : stateBeforeUnload.speculativeType;+ let loadSpecDraftNMax =+ pendingLoadConfig?.specDraftNMax ?? stateBeforeUnload.specDraftNMax;try {// Lightweight pre-flight validation: avoid unloading a working model// if the new identifier is clearly invalid (e.g. bad HF id / path).@@ -810,15 +838,23 @@ export function useChatModelRuntime() {// model loads at Auto/native, not the previous model's pin.customContextLength: null,});- loadSpeculativeType = persistedSpeculativeType;- loadSpecDraftNMax = null;+ loadSpeculativeType =+ pendingLoadConfig?.speculativeType != null+ ? normalizeSpeculativeType(pendingLoadConfig.speculativeType)+ : persistedSpeculativeType;+ loadSpecDraftNMax = pendingLoadConfig?.specDraftNMax ?? null;// Keep the click-time snapshot in lock-step with the store reset so// the load below sizes against the cleared per-model knobs, not the// previous model's (gpuMemoryMode is standing, so left as captured).- loadCustomContextLength = null;- loadSelectedGpuIds = null;- loadGpuLayers = GPU_LAYERS_AUTO;- loadNCpuMoe = 0;+ // An explicit staged config from run-settings still wins.+ loadCustomContextLength =+ pendingLoadConfig?.customContextLength ?? null;+ loadSelectedGpuIds =+ pendingLoadConfig?.selectedGpuIds !== undefined+ ? reconcilePersistedGpuIds(pendingLoadConfig.selectedGpuIds)+ : null;+ loadGpuLayers = pendingLoadConfig?.gpuLayers ?? GPU_LAYERS_AUTO;+ loadNCpuMoe = pendingLoadConfig?.nCpuMoe ?? 0;loadSplitRatio = null;}diff --git a/studio/frontend/src/features/model-picker/components/model-config-page.tsx b/studio/frontend/src/features/model-picker/components/model-config-page.tsxindex afbd33af7cb..90202a2bcf0 100644--- a/studio/frontend/src/features/model-picker/components/model-config-page.tsx+++ b/studio/frontend/src/features/model-picker/components/model-config-page.tsx@@ -24,7 +24,14 @@ import { ChevronDownStandardIcon } from "@/lib/chevron-icons";import { toast } from "@/lib/toast";import { ArrowLeft01Icon } from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";-import { type ReactNode, useEffect, useId, useState } from "react";+import {+ type ReactNode,+ type Ref,+ useEffect,+ useId,+ useRef,+ useState,+} from "react";import {useDefaultChatTemplate,useModelMaxPositionEmbeddings,@@ -50,7 +57,10 @@ import {} from "../model-config/per-model-config";import { ChatTemplateEditorDialog } from "./chat-template-editor-dialog";import type { ModelPickTarget } from "./model-selector/types";-import { NumericValueInput } from "./numeric-value-input";+import {+ NumericValueInput,+ type NumericValueInputHandle,+} from "./numeric-value-input";const ROW_CLASS = "flex min-h-8 items-center justify-between gap-3";const LABEL_CLASS =@@ -130,11 +140,13 @@ function MaxSeqLengthSetting({max,inputMax,onChange,+ inputRef,}: {value: number;max: number;inputMax: number;onChange: (value: number) => void;+ inputRef?: Ref<NumericValueInputHandle>;}) {return (<div className="space-y-3">@@ -146,6 +158,7 @@ function MaxSeqLengthSetting({</InfoHint></div><NumericValueInput+ ref={inputRef}value={value}min={MAX_SEQ_LENGTH_MIN}max={inputMax}@@ -182,6 +195,7 @@ function AdvancedGpuSlider({onChange,displayValue,info,+ inputRef,}: {label: string;value: number;@@ -190,6 +204,7 @@ function AdvancedGpuSlider({onChange: (value: number) => void;displayValue?: string;info?: ReactNode;+ inputRef?: Ref<NumericValueInputHandle>;}) {return (<div className="space-y-3">@@ -199,6 +214,7 @@ function AdvancedGpuSlider({{info && <InfoHint>{info}</InfoHint>}</div><NumericValueInput+ ref={inputRef}value={value}min={min}max={max}@@ -231,11 +247,15 @@ function GpuMemorySettings({update,layerCount,moeLayerCount,+ gpuLayersInputRef,+ moeLayersInputRef,}: {config: PerModelConfig;update: (patch: Partial<PerModelConfig>) => void;layerCount: number | null;moeLayerCount: number | null;+ gpuLayersInputRef?: Ref<NumericValueInputHandle>;+ moeLayersInputRef?: Ref<NumericValueInputHandle>;}) {const gpuDevices = useGpuDevices();const mode = config.gpuMemoryMode ?? "auto";@@ -322,6 +342,7 @@ function GpuMemorySettings({<><AdvancedGpuSliderlabel="GPU Layers"+ inputRef={gpuLayersInputRef}value={Math.max(GPU_LAYERS_AUTO, Math.min(gpuLayers, gpuLayersMax))}min={GPU_LAYERS_AUTO}max={gpuLayersMax}@@ -338,6 +359,7 @@ function GpuMemorySettings({{showMoeSlider && (<AdvancedGpuSliderlabel="MoE Layers on CPU"+ inputRef={moeLayersInputRef}value={Math.min(nCpuMoe, moeLayersMax)}min={0}max={moeLayersMax}@@ -399,6 +421,8 @@ function GgufAdvancedSettings({onEditTemplate,layerCount,moeLayerCount,+ gpuLayersInputRef,+ moeLayersInputRef,}: {config: PerModelConfig;update: (patch: Partial<PerModelConfig>) => void;@@ -407,6 +431,8 @@ function GgufAdvancedSettings({onEditTemplate: () => void;layerCount: number | null;moeLayerCount: number | null;+ gpuLayersInputRef?: Ref<NumericValueInputHandle>;+ moeLayersInputRef?: Ref<NumericValueInputHandle>;}) {return (<>@@ -535,6 +561,8 @@ function GgufAdvancedSettings({update={update}layerCount={layerCount}moeLayerCount={moeLayerCount}+ gpuLayersInputRef={gpuLayersInputRef}+ moeLayersInputRef={moeLayersInputRef}/><ChatTemplateSetting config={config} onEditTemplate={onEditTemplate} />@@ -597,6 +625,10 @@ export function ModelConfigPage({const [showAdvanced, setShowAdvanced] = useState(() =>hasNonDefaultAdvanced(config),);+ const contextInputRef = useRef<NumericValueInputHandle>(null);+ const maxSeqLengthInputRef = useRef<NumericValueInputHandle>(null);+ const gpuLayersInputRef = useRef<NumericValueInputHandle>(null);+ const moeLayersInputRef = useRef<NumericValueInputHandle>(null);const nativePathToken =target.meta.nativePathToken ??(isActiveModel ? activeNativePathToken : null);@@ -744,11 +776,6 @@ export function ModelConfigPage({? { ...config, customContextLength: activeLoadedContext }: config: config;- // Load request needs a concrete max length; substitute the fallback here only,- // never in the persisted runtimeConfig.- const loadConfig = target.isGguf- ? runtimeConfig- : { ...runtimeConfig, maxSeqLength: maxSeqLengthValue };const rememberChanged = remember !== savedRemember;const persistenceOnly = isActiveModel && atBaseline && rememberChanged;const primaryActionLabel = persistenceOnly@@ -760,18 +787,90 @@ export function ModelConfigPage({: "Load model";const handleRun = () => {- const defaultConfig = isDefaultConfig(runtimeConfig);+ // Same-click Load/Reload: a numeric draft the user just typed is flushed only+ // by that input's blur handler, which updates the parent config after this+ // click closure already captured the stale value. Commit every numeric input+ // imperatively so the staged load honors what the user just typed, not just+ // the Context field.+ const committedContext = target.isGguf+ ? contextInputRef.current?.commit()+ : undefined;+ const committedMaxSeqLength = target.isGguf+ ? undefined+ : maxSeqLengthInputRef.current?.commit();+ const committedGpuLayers = target.isGguf+ ? gpuLayersInputRef.current?.commit()+ : undefined;+ const committedMoeLayers = target.isGguf+ ? moeLayersInputRef.current?.commit()+ : undefined;++ const pendingPatch: Partial<PerModelConfig> = {};+ if (committedContext != null) {+ pendingPatch.customContextLength = committedContext;+ }+ if (committedMaxSeqLength != null) {+ pendingPatch.maxSeqLength = clampMaxSeqLength(+ committedMaxSeqLength,+ MAX_SEQ_LENGTH_MAX,+ );+ }+ if (committedGpuLayers != null) {+ pendingPatch.gpuLayers = committedGpuLayers;+ }+ if (committedMoeLayers != null) {+ pendingPatch.nCpuMoe = committedMoeLayers;+ }+ const hasPending =+ committedContext != null ||+ committedMaxSeqLength != null ||+ committedGpuLayers != null ||+ committedMoeLayers != null;++ const effectiveConfig = hasPending+ ? { ...config, ...pendingPatch }+ : config;+ // pinFixedLayerContext above was computed from the render-time config, before+ // the same-click GPU Layers draft was committed. Recompute it from+ // effectiveConfig so committing a positive fixed-layer value still pins the+ // fitted context; otherwise the saved config carries customContextLength: null+ // and a later fresh load sends the native context with fixed layers (the OOM+ // the pin exists to avoid).+ const effectivePinFixedLayerContext =+ target.isGguf &&+ effectiveConfig.gpuMemoryMode === "manual" &&+ effectiveConfig.gpuLayers != null &&+ effectiveConfig.gpuLayers >= 0 &&+ effectiveConfig.customContextLength == null &&+ activeLoadedContext != null;+ const effectiveRuntimeConfig = hasPending+ ? effectivePinFixedLayerContext+ ? { ...effectiveConfig, customContextLength: activeLoadedContext }+ : effectiveConfig+ : runtimeConfig;+ // Non-GGUF load substitutes the resolved max sequence length; recompute it+ // from the committed draft so a same-click Max Seq Length edit is not lost.+ const effectiveMaxSeqLengthValue =+ committedMaxSeqLength == null+ ? maxSeqLengthValue+ : (normalizeMaxSeqLength(effectiveConfig.maxSeqLength) ??+ clampMaxSeqLength(DEFAULT_MAX_SEQ_LENGTH, nativeMaxSeqLength));+ // Recheck the committed draft so Save/Forget reloads when needed.+ const effectiveAtBaseline = perModelConfigsEqual(effectiveConfig, baseline);+ const effectivePersistenceOnly =+ isActiveModel && effectiveAtBaseline && rememberChanged;+ const defaultConfig = isDefaultConfig(effectiveRuntimeConfig);let saveFailed = false;if (remember) {saveFailed = !savePerModelConfig(target.id,target.ggufVariant,- runtimeConfig,+ effectiveRuntimeConfig,);} else {saveFailed = !deletePerModelConfig(target.id, target.ggufVariant);}- if (persistenceOnly) {+ if (effectivePersistenceOnly) {if (saveFailed) {toast.error("Couldn't save settings for this model.");return;@@ -791,7 +890,10 @@ export function ModelConfigPage({if (saveFailed) {toast.error("Couldn't save these settings, loading with them anyway.");}- onRun(loadConfig);+ const effectiveLoadConfig = target.isGguf+ ? effectiveRuntimeConfig+ : { ...effectiveRuntimeConfig, maxSeqLength: effectiveMaxSeqLengthValue };+ onRun(effectiveLoadConfig);};return (@@ -838,6 +940,7 @@ export function ModelConfigPage({</InfoHint></div><NumericValueInput+ ref={contextInputRef}value={contextValue}min={minContext}max={maxContext}@@ -886,6 +989,8 @@ export function ModelConfigPage({onEditTemplate={() => setTemplateOpen(true)}layerCount={stagedDims?.layerCount ?? null}moeLayerCount={stagedDims?.moeLayerCount ?? null}+ gpuLayersInputRef={gpuLayersInputRef}+ moeLayersInputRef={moeLayersInputRef}/>)}@@ -914,6 +1019,7 @@ export function ModelConfigPage({value={maxSeqLengthValue}max={maxSeqLengthMax}inputMax={MAX_SEQ_LENGTH_MAX}+ inputRef={maxSeqLengthInputRef}onChange={(value) =>update({maxSeqLength: clampMaxSeqLength(value, MAX_SEQ_LENGTH_MAX),diff --git a/studio/frontend/src/features/model-picker/components/numeric-value-input.tsx b/studio/frontend/src/features/model-picker/components/numeric-value-input.tsxindex 2489927fc27..be9aa7745c1 100644--- a/studio/frontend/src/features/model-picker/components/numeric-value-input.tsx+++ b/studio/frontend/src/features/model-picker/components/numeric-value-input.tsx@@ -2,7 +2,13 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { cn } from "@/lib/utils";-import { useRef, useState } from "react";+import {+ forwardRef,+ useEffect,+ useImperativeHandle,+ useRef,+ useState,+} from "react";export function snapToStep(value: number,@@ -28,44 +34,109 @@ function sanitizeNumeric(raw: string, allowNegative: boolean): string {return `${sign}${head}${tail}`;}-export function NumericValueInput({- value,- min,- max,- step,- onChange,- displayValue,- className,- ariaLabel,- size: sizeAttr,- disabled = false,-}: {- value: number;- min?: number;- max?: number;- step: number;- onChange: (v: number) => void;- displayValue?: string;- className?: string;- ariaLabel?: string;- size?: number;- disabled?: boolean;-}) {+export type NumericValueInputHandle = {+ /** Commit a valid focused/same-click draft; null when none is pending. */+ commit: () => number | null;+};++export const NumericValueInput = forwardRef<+ NumericValueInputHandle,+ {+ value: number;+ min?: number;+ max?: number;+ step: number;+ onChange: (v: number) => void;+ displayValue?: string;+ className?: string;+ ariaLabel?: string;+ size?: number;+ disabled?: boolean;+ }+>(function NumericValueInput(+ {+ value,+ min,+ max,+ step,+ onChange,+ displayValue,+ className,+ ariaLabel,+ size: sizeAttr,+ disabled = false,+ },+ ref,+) {const [focused, setFocused] = useState(false);const [draft, setDraft] = useState("");const cancelBlurCommitRef = useRef(false);+ const draftRef = useRef("");+ const dirtyRef = useRef(false);+ // Same-click Load: blur commits via onChange and clears dirtyRef before the+ // button onClick runs, while parent `value` is still stale. Keep the blur+ // result for one imperative commit(); clear when `value` catches up or on+ // focus / external edits (Reset, slider).+ const lastBlurCommittedRef = useRef<number | null>(null);++ // The blur bridge is only valid across the single synchronous gesture that set+ // it: blur commits during a button's mousedown and that button's onClick+ // consumes it via commit() before React re-renders. Any settled render means the+ // gesture is over, so drop the cache on every commit. Keying this on [value]+ // alone missed a Reset (or other external edit) that restores the shown value+ // unchanged when the blur did dispatch onChange (final !== value): value nets+ // back to its prior number, so the effect never re-ran, the stale pin survived,+ // and the next Load/Save replayed the override Reset had removed.+ useEffect(() => {+ lastBlurCommittedRef.current = null;+ });- const commit = (raw: string) => {+ const commitDraft = (raw: string): number | null => {const parsed = Number.parseFloat(raw);if (!Number.isFinite(parsed)) {- return;+ return null;}const final = snapToStep(parsed, step, min, max);if (final !== value) {onChange(final);}+ return final;};+ useImperativeHandle(+ ref,+ () => ({+ commit: () => {+ if (dirtyRef.current) {+ const raw = draftRef.current;+ const final = commitDraft(raw);+ dirtyRef.current = false;+ lastBlurCommittedRef.current = null;+ if (final == null) {+ draftRef.current = String(value);+ }+ if (focused) {+ setFocused(false);+ }+ return final;+ }+ const blurCommitted = lastBlurCommittedRef.current;+ if (blurCommitted != null) {+ lastBlurCommittedRef.current = null;+ if (focused) {+ setFocused(false);+ }+ return blurCommitted;+ }+ if (focused) {+ setFocused(false);+ }+ return null;+ },+ }),+ [draft, focused, max, min, onChange, step, value],+ );+const displayed = focused ? draft : (displayValue ?? String(value));return (@@ -82,7 +153,11 @@ export function NumericValueInput({aria-label={ariaLabel}onFocus={(e) => {cancelBlurCommitRef.current = false;- setDraft(String(value));+ dirtyRef.current = false;+ lastBlurCommittedRef.current = null;+ const next = String(value);+ draftRef.current = next;+ setDraft(next);setFocused(true);const target = e.currentTarget;requestAnimationFrame(() => target.select());@@ -90,24 +165,47 @@ export function NumericValueInput({onBlur={() => {if (cancelBlurCommitRef.current) {cancelBlurCommitRef.current = false;- } else {- commit(draft);+ lastBlurCommittedRef.current = null;+ } else if (dirtyRef.current) {+ const final = commitDraft(draftRef.current);+ dirtyRef.current = false;+ if (final == null) {+ draftRef.current = String(value);+ lastBlurCommittedRef.current = null;+ } else {+ draftRef.current = String(final);+ // Only bridge the still-stale parent value when the blur actually+ // dispatched onChange (final !== value). When final === value the+ // parent is already current, so there is nothing to bridge; caching+ // here would leave a stale pin that a later Reset or external edit+ // (which doesn't change the displayed value) can never clear, so a+ // following Load/Save would recreate the override Reset removed.+ lastBlurCommittedRef.current = final !== value ? final : null;+ }}setFocused(false);}}- onChange={(e) =>- setDraft(sanitizeNumeric(e.target.value, (min ?? 0) < 0))- }+ onChange={(e) => {+ dirtyRef.current = true;+ lastBlurCommittedRef.current = null;+ const next = sanitizeNumeric(e.target.value, (min ?? 0) < 0);+ draftRef.current = next;+ setDraft(next);+ }}onKeyDown={(e) => {if (e.key === "Enter") {e.currentTarget.blur();} else if (e.key === "Escape") {cancelBlurCommitRef.current = true;- setDraft(String(value));+ dirtyRef.current = false;+ lastBlurCommittedRef.current = null;+ const next = String(value);+ draftRef.current = next;+ setDraft(next);e.currentTarget.blur();}}}className={cn(className)}/>);-}+});diff --git a/studio/frontend/src/features/model-picker/index.ts b/studio/frontend/src/features/model-picker/index.tsindex d2b4785ec36..383d441f09d 100644--- a/studio/frontend/src/features/model-picker/index.ts+++ b/studio/frontend/src/features/model-picker/index.ts@@ -12,6 +12,7 @@ export {export { hfModelFitsDevice } from "./components/model-selector/recommended-fit";export {NumericValueInput,+ type NumericValueInputHandle,snapToStep,} from "./components/numeric-value-input";export { SidebarModelConfig } from "./components/sidebar-model-config";diff --git a/tests/studio/playwright_model_config.py b/tests/studio/playwright_model_config.pyindex a8d143a253a..d72dc379551 100644--- a/tests/studio/playwright_model_config.py+++ b/tests/studio/playwright_model_config.py@@ -70,6 +70,8 @@ ART_DIR = os.environ.get("PW_ART_DIR", "logs/playwright_modelcfg")ART = Path(ART_DIR)ART.mkdir(parents = True, exist_ok = True)STRICT = os.environ.get("STUDIO_UI_STRICT", "0") == "1"+PLAYWRIGHT_BROWSER = os.environ.get("STUDIO_PLAYWRIGHT_BROWSER", "chromium").lower()+PLAYWRIGHT_CHANNEL = os.environ.get("STUDIO_PLAYWRIGHT_CHANNEL") or NoneTURN_TIMEOUT_MS = int(os.environ.get("STUDIO_UI_TURN_TIMEOUT_MS", "180000"))WALL_TIMEOUT_S = float(os.environ.get("STUDIO_UI_WALL_TIMEOUT_S", "720"))FETCH_TIMEOUT_MS = int(os.environ.get("STUDIO_UI_FETCH_TIMEOUT_MS", "30000"))@@ -145,10 +147,19 @@ with sync_playwright() as p:)# Health pre-flight: bash-side health wait can pass before the auth DB migrates.wait_for_health(BASE, timeout = 30.0, info = info)- browser = p.chromium.launch(- headless = True,- args = chromium_launch_args(),- )+ if PLAYWRIGHT_BROWSER not in ("chromium", "firefox", "webkit"):+ fail(f"unsupported STUDIO_PLAYWRIGHT_BROWSER={PLAYWRIGHT_BROWSER!r}")+ sys.exit(1)+ browser_type = getattr(p, PLAYWRIGHT_BROWSER)+ launch_kwargs = {"headless": True}+ if PLAYWRIGHT_BROWSER == "chromium":+ launch_kwargs["args"] = chromium_launch_args()+ if PLAYWRIGHT_CHANNEL:+ launch_kwargs["channel"] = PLAYWRIGHT_CHANNEL+ elif PLAYWRIGHT_CHANNEL:+ fail("STUDIO_PLAYWRIGHT_CHANNEL requires chromium")+ sys.exit(1)+ browser = browser_type.launch(**launch_kwargs)ctx = browser.new_context(viewport = {"width": 1280, "height": 900},reduced_motion = "reduce",@@ -464,11 +475,6 @@ with sync_playwright() as p:else:default_ctx = ctx_in.input_value()info(f"default Context Length shown: {default_ctx!r}")- ctx_in.click()- ctx_in.fill(str(DISTINCT_CTX))- page.wait_for_timeout(300)- page.keyboard.press("Tab") # blur to commit- page.wait_for_timeout(300)remember = popover.get_by_label("Remember for this model").firstif _count(remember):try:@@ -477,12 +483,16 @@ with sync_playwright() as p:remember.click()else:fail("'Remember for this model' checkbox not found")+ ctx_in.click()+ ctx_in.fill(str(DISTINCT_CTX))page.wait_for_timeout(300)shoot("05-ctx-set")btn = primary_button(popover)if btn is None:fail("primary Load/Save button not found in run-settings")else:+ # Keep the input focused. The button click must commit the draft+ # and use it in the same load request.btn.click()page.wait_for_timeout(2500)shoot("06-after-load")@@ -570,6 +580,47 @@ with sync_playwright() as p:else:info("OK reset: distinctive context cleared from unsloth_model_configs")shoot("08-after-reset")++ # ─────────────────────────────────────────────────────+ # 3b. Re-typing the value already shown must not pin an override (HARD).+ # Entering the currently displayed native/default context commits no+ # onChange (the value is unchanged), so the cached blur value must not be+ # replayed into a stored override on Load. Otherwise re-typing the shown+ # number, or doing so before a Reset, recreates a phantom context pin.+ # ─────────────────────────────────────────────────────+ step("re-typing the shown context does not pin an override")+ ctx_in = context_input(popover)+ native_default = _as_int(ctx_in.input_value()) if ctx_in else None+ if ctx_in is None or native_default is None:+ info("skip re-type-shown: Context Length input has no numeric default")+ else:+ remember = popover.get_by_label("Remember for this model").first+ if _count(remember):+ try:+ remember.check()+ except Exception:+ remember.click()+ ctx_in.click()+ ctx_in.fill(str(native_default))+ page.wait_for_timeout(200)+ btn = primary_button(popover)+ if btn is not None and btn.is_enabled():+ # Same-click Load: the button click must commit the draft, but a draft+ # equal to the shown value carries no override.+ btn.click()+ page.wait_for_timeout(1500)+ cfg = read_configs()+ pinned = any(+ _as_int(e.get("customContextLength")) == native_default for e in config_entries(cfg)+ )+ if pinned:+ fail(+ "re-typing the shown context pinned it as an override "+ f"(customContextLength={native_default})"+ )+ else:+ info("OK re-type-shown: shown context not stored as an override")+ shoot("08b-after-retype-shown")close_picker()# ─────────────────────────────────────────────────────diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.pyindex 3934b72d831..815f68e010b 100644--- a/tests/studio/test_model_picker_contracts.py+++ b/tests/studio/test_model_picker_contracts.py@@ -346,6 +346,36 @@ def test_fixed_layer_gguf_pins_displayed_context():assert "customContextLength: activeLoadedContext" in src+def test_fixed_layer_pin_recomputed_after_committing_gpu_layers():+ """pinFixedLayerContext is computed from the render-time config, before a+ same-click GPU Layers draft is committed. handleRun must recompute it from the+ committed effectiveConfig; otherwise typing a positive GPU Layers value on an+ auto-fit GGUF and clicking Reload saves customContextLength: null, so a later+ fresh load sends the native context with fixed layers (the OOM the pin avoids)."""+ src = _read("features/model-picker/components/model-config-page.tsx")+ assert "const effectivePinFixedLayerContext =" in src+ assert 'effectiveConfig.gpuMemoryMode === "manual"' in src+ assert "effectiveConfig.gpuLayers != null" in src+ assert "effectiveConfig.customContextLength == null" in src+ assert "{ ...effectiveConfig, customContextLength: activeLoadedContext }" in src+++def test_blur_cache_cleared_on_every_settled_render():+ """The lastBlurCommittedRef bridge is valid only across the single synchronous+ same-click gesture that set it. Keying its clear on [value] missed a Reset (or+ external edit) that restores the shown value unchanged after the blur dispatched+ onChange: value nets back to its prior number, the effect never re-ran, and a+ later Load/Save replayed the override Reset removed. Clear it on every settled+ render instead."""+ src = _read("features/model-picker/components/numeric-value-input.tsx")+ # The clearing effect must run on every commit, not be gated on [value] alone.+ assert not re.search(r"lastBlurCommittedRef\.current = null;\s*\}, \[value\]\);", src)+ assert re.search(+ r"useEffect\(\(\) => \{\s*lastBlurCommittedRef\.current = null;\s*\}\);",+ src,+ )++def test_auto_defaults_not_persisted_as_overrides():"""Auto GPU memory mode and Auto/default speculative type are follow-globaldefaults; normalization must not persist them as per-model overrides, else a@@ -382,15 +412,90 @@ def test_reset_persists_null_max_length_and_substitutes_only_for_load():Reset) so isDefaultConfig can clear a remembered override; the concretefallback is substituted only into the load request, not the saved record."""src = _read("features/model-picker/components/model-config-page.tsx")- # Load-only substitution of the resolved value.- assert "maxSeqLength: maxSeqLengthValue" in src- assert "const loadConfig" in src- # The persisted record is loaded via onRun(loadConfig), and save uses the- # untouched runtimeConfig (so a reset/default config stays default).- assert "onRun(loadConfig)" in src+ # Load-only substitution of the resolved value (recomputed from any committed+ # same-click Max Seq Length draft, so it is never dropped).+ assert "maxSeqLength: effectiveMaxSeqLengthValue" in src+ assert "const effectiveLoadConfig" in src+ # The persisted record is saved from effectiveRuntimeConfig; the load request+ # carries effectiveLoadConfig (with any committed context input).+ assert "onRun(effectiveLoadConfig)" in srcassert "savePerModelConfig(" in src+def test_initial_load_uses_staged_config_payload():+ """Run-settings Load must pass the staged config through to /load even when+ React has not flushed NumericValueInput blur commits into the store yet."""+ runtime = _read("features/chat/hooks/use-chat-model-runtime.ts")+ assert "const pendingLoadConfig =" in runtime+ assert "pendingLoadConfig?.kvCacheDtype" in runtime+ assert "pendingLoadConfig?.customContextLength" in runtime+ page = _read("features/model-picker/components/model-config-page.tsx")+ assert "contextInputRef" in page+ assert "contextInputRef.current?.commit()" in page+ numeric = _read("features/model-picker/components/numeric-value-input.tsx")+ assert "export type NumericValueInputHandle" in numeric+ assert "commit:" in numeric+ # P1: commit returns null unless the user actually edited the field,+ # so Load/Save with untouched Auto does not pin native context.+ assert "dirtyRef.current" in numeric+ assert "return null;" in numeric+ # P2: blur clears dirtyRef after commit so Reset/slider cannot be+ # overwritten by a stale draft on a later Load.+ assert "dirtyRef.current = false;" in numeric+ assert "draftRef.current = String(final);" in numeric+ # Same-click Load after blur still sees the committed draft.+ assert "lastBlurCommittedRef" in numeric+ # Invalid drafts must not turn Auto into an explicit pin.+ assert "const commitDraft = (raw: string): number | null" in numeric+ assert re.search(r"if \(!Number\.isFinite\(parsed\)\) \{\s*return null;", numeric)+ assert re.search(+ r"if \(final == null\) \{\s*"+ r"draftRef\.current = String\(value\);\s*"+ r"lastBlurCommittedRef\.current = null;",+ numeric,+ )+ # handleRun only promotes commit() when non-null.+ assert "committedContext != null" in page+ assert "pendingPatch.customContextLength = committedContext;" in page+++def test_same_click_commit_covers_all_numeric_inputs():+ """The same-click blur bridge must flush every NumericValueInput-backed+ setting, not just Context Length. Max Seq Length (non-GGUF), GPU Layers and+ MoE Layers (GGUF) also stage their draft only on blur, so handleRun must+ imperatively commit each and fold the value into the staged load config;+ otherwise a value the user typed right before clicking Load/Reload is lost."""+ page = _read("features/model-picker/components/model-config-page.tsx")+ # Each numeric input owns an imperative handle that handleRun commits, and the+ # handle is forwarded down to the actual NumericValueInput.+ for ref in ("maxSeqLengthInputRef", "gpuLayersInputRef", "moeLayersInputRef"):+ assert f"const {ref} = useRef<NumericValueInputHandle>(null);" in page+ assert f"{ref}.current?.commit()" in page+ assert f"inputRef={{{ref}}}" in page+ # The leaf sub-components accept and forward the handle as a ref.+ assert page.count("inputRef?: Ref<NumericValueInputHandle>;") >= 2+ assert "ref={inputRef}" in page+ # Committed drafts are folded into the staged config, gated on non-null so an+ # untouched field never fabricates an override.+ assert "committedMaxSeqLength != null" in page+ assert "committedGpuLayers != null" in page+ assert "committedMoeLayers != null" in page+ assert "pendingPatch.gpuLayers = committedGpuLayers;" in page+ assert "pendingPatch.nCpuMoe = committedMoeLayers;" in page+ # The non-GGUF load path substitutes the committed Max Seq Length draft.+ assert "const effectiveMaxSeqLengthValue =" in page+ assert "maxSeqLength: effectiveMaxSeqLengthValue" in page+++def test_context_commit_rechecks_persistence_only_shortcut():+ """Committed context changes must bypass persistence-only saves."""+ src = _read("features/model-picker/components/model-config-page.tsx")+ assert "const effectiveConfig =" in src+ assert "perModelConfigsEqual(effectiveConfig, baseline)" in src+ assert "const effectivePersistenceOnly =" in src+ assert "if (effectivePersistenceOnly)" in src++def test_reset_enabled_for_explicit_context_pin_at_native():"""An explicit customContextLength that equals the native ceiling is still auser override, so contextAtDefault must require customContextLength == null.