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: picking a preset no longer overwrites a model's remembered sampling (#14128)
Daniel Hanc1aef2f45526
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.pyindex 437a4a90fb2..bf050b9e152 100644--- a/studio/backend/routes/chat_history.py+++ b/studio/backend/routes/chat_history.py@@ -549,6 +549,10 @@ class ChatSettingsPayload(BaseModel):# Last-used params per checkpoint id. Deep-merged per key, so patching one# model cannot drop another's.inferenceParamsByModel: Optional[dict[str, ChatInferenceSettings]] = None+ # Per model id, keys of the entry above removed before this patch merges; never stored.+ forgetInferenceParamsByModel: Optional[+ dict[str, Annotated[list[str], Field(max_length = 64)]]+ ] = Field(default = None, max_length = 1_000)rememberParamsPerModel: Optional[bool] = NonecustomPresets: Optional[list[ChatPreset]] = NoneactivePreset: Optional[str] = Nonediff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex 28452d19a6c..1183553587a 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -5616,6 +5616,31 @@ def _deep_merge_settings(current: dict[str, Any], updates: dict[str, Any]) -> direturn merged+# A command, not a setting: per model id, the remembered keys dropped before the rest of the patch+# merges, since a deep merge can only add or overwrite (#14068). Keys, not rows, so a concurrent edit+# to a key the command does not name survives.+_FORGET_PARAMS_KEY = "forgetInferenceParamsByModel"+++def _merge_settings_updates(current: dict[str, Any], updates: dict[str, Any]) -> dict[str, Any]:+ updates = dict(updates)+ forget = updates.pop(_FORGET_PARAMS_KEY, None) or {}+ by_model = current.get("inferenceParamsByModel")+ if forget and isinstance(by_model, dict):+ pruned = dict(by_model)+ for model_id, keys in forget.items():+ entry = pruned.get(model_id)+ if not isinstance(entry, dict):+ continue+ rest = {k: v for k, v in entry.items() if k not in keys}+ if rest:+ pruned[model_id] = rest+ else:+ del pruned[model_id]+ current = {**current, "inferenceParamsByModel": pruned}+ return _deep_merge_settings(current, updates)++def upsert_chat_settings_merge(updates: dict[str, Any]) -> dict[str, Any]:"""Atomic read-merge-write under BEGIN IMMEDIATE so concurrent writerscannot drop each other's updates."""@@ -5638,7 +5663,7 @@ def upsert_chat_settings_merge(updates: dict[str, Any]) -> dict[str, Any]:raise CorruptSettingsError(f"Cannot apply partial settings patch to corrupt key(s): {keys}")- merged = _deep_merge_settings(current, updates)+ merged = _merge_settings_updates(current, updates)now = datetime.now(timezone.utc).isoformat()conn.executemany("""@@ -5724,7 +5749,7 @@ def upsert_chat_settings_merge_if_current(# those timestamps reads as a settings change.conn.commit()return current, True- merged = _deep_merge_settings(current, updates)+ merged = _merge_settings_updates(current, updates)now = datetime.now(timezone.utc).isoformat()conn.executemany("""diff --git a/studio/backend/tests/test_chat_history_storage.py b/studio/backend/tests/test_chat_history_storage.pyindex 74a7f0f8f51..cb9c15538e1 100644--- a/studio/backend/tests/test_chat_history_storage.py+++ b/studio/backend/tests/test_chat_history_storage.py@@ -639,6 +639,41 @@ def test_settings_merge_keeps_each_model_s_remembered_params(tmp_path, monkeypatassert by_model == {"qwen": {"temperature": 0.4, "topP": 0.8}, "llama": {"temperature": 0.9}}+def test_picking_a_preset_can_forget_one_model_s_params(tmp_path, monkeypatch):+ """A preset pick drops the loaded model's preset-owned keys (#14068); a merge alone cannot+ remove a key. The forget runs first, so an edit in the same debounced patch starts fresh, and+ a key it does not name (a Fast mode another tab just set) survives."""+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_settings_merge(+ {+ "inferenceParamsByModel": {+ "qwen": {"temperature": 0.3, "systemPrompt": "Pirate", "fastMode": True},+ "llama": {"temperature": 0.9},+ }+ }+ )+ studio_db.upsert_chat_settings_merge(+ {+ "forgetInferenceParamsByModel": {"qwen": ["temperature", "systemPrompt", "topP"]},+ "inferenceParamsByModel": {"qwen": {"topP": 0.5}},+ }+ )+ settings = studio_db.list_chat_settings()+ assert settings["inferenceParamsByModel"] == {+ "qwen": {"fastMode": True, "topP": 0.5},+ "llama": {"temperature": 0.9},+ }+ assert "forgetInferenceParamsByModel" not in settings++ _, applied = studio_db.upsert_chat_settings_merge_if_current(+ {}, {"forgetInferenceParamsByModel": {"qwen": ["fastMode", "topP"], "missing": ["x"]}}+ )+ assert applied is True+ settings = studio_db.list_chat_settings()+ assert settings["inferenceParamsByModel"] == {"llama": {"temperature": 0.9}}+ assert "forgetInferenceParamsByModel" not in settings++def test_settings_merge_quarantines_corrupt_json_and_rejects_partial_patch(tmp_path, monkeypatch):_reset_studio_db(tmp_path, monkeypatch)studio_db.upsert_chat_settings_merge({"inferenceParams": {"temperature": 0.5, "topP": 0.8}})diff --git a/studio/backend/tests/test_chat_settings_payload.py b/studio/backend/tests/test_chat_settings_payload.pyindex 1ecb6c3b042..7e177973e8f 100644--- a/studio/backend/tests/test_chat_settings_payload.py+++ b/studio/backend/tests/test_chat_settings_payload.py@@ -303,3 +303,14 @@ def test_out_of_range_seeds_are_refused(seed):def test_the_whole_uint32_pin_range_is_accepted(seed):payload = ChatSettingsPayload.model_validate({"inferenceParams": {"seed": seed}})assert payload.model_dump(exclude_unset = True) == {"inferenceParams": {"seed": seed}}+++def test_forgetting_a_model_s_params_names_its_keys():+ payload = ChatSettingsPayload.model_validate(+ {"forgetInferenceParamsByModel": {"qwen": ["temperature", "systemPrompt"]}}+ )+ assert payload.model_dump(exclude_unset = True) == {+ "forgetInferenceParamsByModel": {"qwen": ["temperature", "systemPrompt"]}+ }+ with pytest.raises(ValidationError):+ ChatSettingsPayload.model_validate({"forgetInferenceParamsByModel": ["qwen"]})diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.tsindex 8438eb91f34..76d80b88eda 100644--- a/studio/frontend/scripts/check-bundle-budget.ts+++ b/studio/frontend/scripts/check-bundle-budget.ts@@ -330,8 +330,11 @@ export const BUDGET = {// The runtime update card's skip and Undo (#14436) add 1,706 B raw / 424 B transfer against 444f63275c.// Finished chat replies render lone markdown markers as written, cut ones keep the repair (#14391): +179 B raw /// +52 B transfer measured against main (6,870,298 -> 6,870,477 B raw, one machine and build). Raised by that.- transferBytes: 2_070_261,- rawBytes: 6_874_370,+ // Picking a preset forgetting a model's remembered sampling (#14128) keeps its preset marks in the eager chat+ // runtime store, about 1,860 B raw / 440 B transfer: merged with main at acb31d909b the build measures+ // 6,876,062 B raw / 2,070,545 B transfer (Node 24, 97 chunks). Raised to that plus the same margin.+ transferBytes: 2_070_734,+ rawBytes: 6_876_222,};// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering thediff --git a/studio/frontend/src/features/chat/api/chat-settings-api.ts b/studio/frontend/src/features/chat/api/chat-settings-api.tsindex 101d7e4dee6..8eb6eecfca6 100644--- a/studio/frontend/src/features/chat/api/chat-settings-api.ts+++ b/studio/frontend/src/features/chat/api/chat-settings-api.ts@@ -36,6 +36,8 @@ export interface PersistedChatSettings {inferenceParams?: PersistedInferenceParams;/** Last-used params per checkpoint id, replayed on model switch. */inferenceParamsByModel?: Record<string, PersistedInferenceParams>;+ /** Outgoing only: per model id, keys of the entry above the server drops before merging the rest. */+ forgetInferenceParamsByModel?: Record<string, string[]>;rememberParamsPerModel?: boolean;customPresets?: PersistedChatPreset[];activePreset?: string;diff --git a/studio/frontend/src/features/chat/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsxindex b94ad5b1aae..98fc396f2cf 100644--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx@@ -958,6 +958,7 @@ export function ChatSettingsPanel({if (p) {setParams(applyPresetParamsWithinCurrentLimits(p), {minPChoiceEdited: true,+ fromPreset: true,});if (p.loadConfig) {applyPresetLoadConfig(p.loadConfig);@@ -1020,7 +1021,7 @@ export function ChatSettingsPanel({if (fallbackPreset) {setParams(applyPresetParamsWithinCurrentLimits(fallbackPreset),- { minPChoiceEdited: true },+ { minPChoiceEdited: true, fromPreset: true },);if (fallbackPreset.loadConfig) {applyPresetLoadConfig(fallbackPreset.loadConfig);diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.tsindex 0c67f771d6c..7788edde1c1 100644--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts@@ -42,6 +42,7 @@ import { isOllamaManifestRef } from "../utils/qwen-sampling-table";import {type ChatPresetSource,type Preset,+ getPresetOwnedParams,getPresetSource,} from "../presets/preset-policy";import { normalizeModelIdentity } from "../../hub/lib/model-identity";@@ -482,7 +483,26 @@ const ATOMIC_SETTING_KEYS = new Set<string>(["ragSource"]);const NESTED_MAP_SETTING_KEYS = new Set<string>(["inferenceParamsByModel"]);function mergePatch(into: SettingsPatch, more: SettingsPatch): void {+ // The server forgets before it merges, so an older queued edit to a forgotten key goes too.+ const forget = more.forgetInferenceParamsByModel;+ if (forget) {+ const byModel = into.inferenceParamsByModel;+ const merged = { ...into.forgetInferenceParamsByModel };+ for (const [id, keys] of Object.entries(forget)) {+ merged[id] = [...new Set([...(merged[id] ?? []), ...keys])];+ const queued = byModel?.[id];+ if (byModel && queued) {+ byModel[id] = Object.fromEntries(+ Object.entries(queued).filter(([key]) => !keys.includes(key)),+ );+ }+ }+ into.forgetInferenceParamsByModel = merged;+ }for (const [key, value] of Object.entries(more)) {+ if (key === "forgetInferenceParamsByModel") {+ continue;+ }const intoAny = into as Record<string, unknown>;const prev = intoAny[key];if (ATOMIC_SETTING_KEYS.has(key)) {@@ -1927,6 +1947,15 @@ function isHeldThreadScopedField(field: string): boolean {}// Reports whether the edit was taken; with no chat open the caller persists globally as before.+/** Whether a sampling edit made now goes to the open chat, as captureThreadScopedEdit decides it. */+function threadCapturesSampling(): boolean {+ const threadId = useChatRuntimeStore.getState().activeThreadId;+ return (+ threadId !== null &&+ (threadId === threadScopedSettingsThreadId || threadId === pendingPairingThreadId)+ );+}+function captureThreadScopedEdit(field: string,writeGlobal: (() => void) | null = null,@@ -2786,6 +2815,9 @@ type ChatRuntimeStore = {/** Defaults came from the server-resident model at startup, so a legacy* global snapshot can be attributed to it. */migrateOwnedGlobalQwenDefaults?: boolean;+ /** A preset pick: not an edit of the loaded model, so its remembered params are dropped+ * instead of overwritten, and its recommendation applies again on the next load. */+ fromPreset?: boolean;},) => void;setCustomPresets: (presets: Preset[]) => void;@@ -3055,6 +3087,8 @@ const SCALAR_SETTING_KEYS = [// Ids this browser holds a local answer for. Hydration keeps these and merges the rest, so a// pre-hydration edit cannot drop other models.const locallyRememberedModels = new Set<string>();+// Models showing a preset's values: their edits are filed as deltas and they are not snapshotted on leave.+const modelsShowingPresetPick = new Set<string>();// Per-model edits made before the settings response landed, held as PATCHES rather than rows.// The set above is overlaid wholesale, which is right for a row built from a hydrated entry but// not for one typed before there was an entry: that row names only the keys the user touched, so@@ -3274,6 +3308,19 @@ function getParamsByModelAfterEdit(if (!persist) {return outgoing;}+ // After a preset pick the server holds only what was edited since, so this browser does too:+ // a whole snapshot would file the preset's values and replay them on the next load.+ if (modelsShowingPresetPick.has(nextParams.checkpoint)) {+ const base = outgoing ?? state.paramsByModel;+ const delta = recordMaxTokensAsMax(+ pickRememberedChanges(changedParams),+ rememberedWindow(nextParams.checkpoint),+ );+ const partial = state.rememberParamsPerModel && hasKeys(delta)+ ? { ...base, [nextParams.checkpoint]: { ...base[nextParams.checkpoint], ...delta } }+ : null;+ return trackParamsByModel(state, partial, nextParams.checkpoint) ?? outgoing;+ }const recorded = trackParamsByModel(state,getRememberedParamsPatch(@@ -3296,6 +3343,70 @@ function getParamsByModelAfterEdit(return recorded ?? outgoing;}+/** The map with the preset-owned keys of `modelId`'s entry dropped, keeping what presets do not+ * set (Fast mode, trust remote code) and, with a chat open, the sampling that chat captures. The+ * server is told which keys to drop, since its merge cannot remove one. */+function forgetModelParams(+ state: ChatRuntimeStore,+ outgoing: Record<string, PersistedInferenceParams> | null,+ modelId: string,+): Record<string, PersistedInferenceParams> | null {+ if (!(state.rememberParamsPerModel && modelId && state.settingsHydrated)) {+ return outgoing;+ }+ const current = outgoing ?? state.paramsByModel;+ const chatOwnsSampling = threadCapturesSampling();+ const forgotten = Object.keys(getPresetOwnedParams(state.params)).filter(+ (key) => !(chatOwnsSampling && isThreadScopedParamKey(key)),+ );+ if (!chatOwnsSampling) {+ modelsShowingPresetPick.add(modelId);+ }+ saveSettingsPatch({ forgetInferenceParamsByModel: { [modelId]: forgotten } });+ const entry = current[modelId];+ if (entry === undefined) {+ return outgoing;+ }+ const kept = Object.fromEntries(+ Object.entries(entry).filter(([key]) => !forgotten.includes(key)),+ ) as PersistedInferenceParams;+ const rest = Object.fromEntries(+ Object.entries(current).filter(([id]) => id !== modelId),+ );+ return hasKeys(kept) ? { ...rest, [modelId]: kept } : rest;+}++/** Every preset-owned value the installation keeps, minus the sampling an open chat captures. */+function persistPresetDefaults(params: InferenceParams): void {+ const chatOwnsSampling = threadCapturesSampling();+ const owned = getPresetOwnedParams(params) as Record<string, unknown>;+ const defaults = Object.fromEntries(+ Object.entries(owned).filter(+ ([key]) => !(chatOwnsSampling && isThreadScopedParamKey(key)),+ ),+ ) as PersistedInferenceParams;+ if (hasKeys(defaults)) {+ saveSettingsPatch({ inferenceParams: defaults });+ }+}++/** A model reaching the screen under a custom preset shows that preset's values, so its later edits+ * file only themselves; reaching it under Default or the user's own edits ends that. */+function notePresetOnLoad(+ state: ChatRuntimeStore,+ modelId: string,+ switched: boolean,+ fromModelDefaults = false,+): void {+ if (!modelId || !(switched || fromModelDefaults)) return;+ if (state.activePresetSource === "custom") {+ modelsShowingPresetPick.add(modelId);+ } else if (switched || state.activePresetSource === "builtin-default") {+ // A same-model poll under edited values replaces nothing, so it keeps the mark.+ modelsShowingPresetPick.delete(modelId);+ }+}+/** Snapshot the model being switched away from, so a model that was never edited still keeps what it ran with. */function rememberOutgoingModel(state: ChatRuntimeStore,@@ -3304,6 +3415,14 @@ function rememberOutgoingModel(if (!state.settingsHydrated && outgoing.checkpoint) {modelLeftBeforeHydration = outgoing.checkpoint;}+ // A custom preset's values, or Default's fixed ones before a status lands, are not this model's+ // own: filed, they outranked its recommendation on every later load (#14068).+ if (+ state.activePresetSource === "custom" ||+ modelsShowingPresetPick.has(outgoing.checkpoint)+ ) {+ return null;+ }const picked = pickRememberedParams(withoutActiveThreadParams(state, outgoing),);@@ -3405,6 +3524,13 @@ function getHydratedPresetState(nextState.activePresetSource =settings.activePresetSource ?? getPresetSource(activePreset);}+ // A model resident before hydration loaded under the placeholder source, so restoring a custom+ // preset here is its load under that preset.+ notePresetOnLoad(+ { ...state, ...nextState } as ChatRuntimeStore,+ state.params.checkpoint,+ nextState.activePresetSource !== undefined,+ );return nextState;}@@ -4801,6 +4927,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({const outgoing = checkpointChanged? rememberOutgoingModel(state, state.params): null;+ notePresetOnLoad(state, params.checkpoint, checkpointChanged, fromModelDefaults);// An interactive local load arrives with the destination checkpoint and recommended params, reaching// setCheckpoint only later, so replay here or the switch never restores the model's own settings.noteLoadedContext(params.checkpoint, options?.maxTokensCap);@@ -4848,21 +4975,28 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({: changedParams;// An edit belongs to the model the params now describe, so a call moving checkpoint and// sliders at once files them under the destination.- const paramsByModel = getParamsByModelAfterEdit(- state,- outgoing,- nextParams,- sharedParams,- options?.persist !== false && !fromModelDefaults,- );+ const fromPreset = options?.fromPreset === true;+ const paramsByModel = fromPreset+ ? forgetModelParams(state, outgoing, nextParams.checkpoint)+ : getParamsByModelAfterEdit(+ state,+ outgoing,+ nextParams,+ sharedParams,+ options?.persist !== false && !fromModelDefaults,+ );if (persistingGlobally) {// A switch replays the destination's entry over the params, so writing it back says nothing// new and, merged per key, would overwrite another tab's copy.persistParamEdit(sharedParams,- checkpointChanged ? null : paramsByModel,+ checkpointChanged || fromPreset ? null : paramsByModel,nextParams.checkpoint,);+ // The row is forgotten and an unmoved value sends nothing, so the defaults need the whole preset.+ if (fromPreset) {+ persistPresetDefaults(nextParams);+ }// Level with what was just written, or a chat opened later this session falls back to the// sampling from before this model loaded.noteThreadScopedDefaults(sharedParams);@@ -5080,6 +5214,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({checkpointChanged && options?.persist !== false? rememberOutgoingModel(state, state.params): null;+ notePresetOnLoad(state, modelId, checkpointChanged);// A compare pane's load reaches the store only here.const previousWindow = rememberedWindow(modelId);noteLoadedContext(modelId, options?.maxTokensCap);diff --git a/studio/frontend/src/features/chat/utils/chat-settings-storage.ts b/studio/frontend/src/features/chat/utils/chat-settings-storage.tsindex 304eea60c90..679c8f2ff23 100644--- a/studio/frontend/src/features/chat/utils/chat-settings-storage.ts+++ b/studio/frontend/src/features/chat/utils/chat-settings-storage.ts@@ -308,6 +308,15 @@ export function sanitizeChatSettings(value: unknown): PersistedChatSettings {if (inferenceParamsByModel) {settings.inferenceParamsByModel = inferenceParamsByModel;}+ if (isRecord(value.forgetInferenceParamsByModel)) {+ const forget: Record<string, string[]> = {};+ for (const [id, keys] of Object.entries(value.forgetInferenceParamsByModel)) {+ if (!id || !Array.isArray(keys)) continue;+ const named = keys.filter((key): key is string => typeof key === "string");+ if (named.length > 0) forget[id] = named;+ }+ if (hasKeys(forget)) settings.forgetInferenceParamsByModel = forget;+ }if (rememberParamsPerModel !== undefined) {settings.rememberParamsPerModel = rememberParamsPerModel;}diff --git a/studio/frontend/tests/helpers/store-stubs/settings-http.ts b/studio/frontend/tests/helpers/store-stubs/settings-http.tsindex f43a377d86f..7031d38e097 100644--- a/studio/frontend/tests/helpers/store-stubs/settings-http.ts+++ b/studio/frontend/tests/helpers/store-stubs/settings-http.ts@@ -59,10 +59,26 @@ function pathExists(current: unknown, path: string[]): boolean {return true;}-function deepMerge(+export function deepMerge(current: Record<string, unknown>,patch: Record<string, unknown>,): Record<string, unknown> {+ // The backend's forget command: drop those keys first, never store the command.+ const { forgetInferenceParamsByModel: forget, ...rest } = patch;+ if (forget && typeof forget === "object") {+ const byModel = { ...(current.inferenceParamsByModel as Record<string, Record<string, unknown>>) };+ for (const [id, keys] of Object.entries(forget as Record<string, string[]>)) {+ const entry = byModel[id];+ if (!entry) continue;+ const kept = Object.fromEntries(+ Object.entries(entry).filter(([key]) => !keys.includes(key)),+ );+ if (Object.keys(kept).length > 0) byModel[id] = kept;+ else delete byModel[id];+ }+ current = { ...current, inferenceParamsByModel: byModel };+ patch = rest;+ }const merged = { ...current };for (const [key, value] of Object.entries(patch)) {const existing = merged[key];diff --git a/studio/frontend/tests/preset-model-memory-hydration.test.ts b/studio/frontend/tests/preset-model-memory-hydration.test.tsnew file mode 100644index 00000000000..32cba86e6cd--- /dev/null+++ b/studio/frontend/tests/preset-model-memory-hydration.test.ts@@ -0,0 +1,70 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Startup order for #14068: the resident model's defaults can land before the settings response+// restores a custom preset, so that model loaded under the placeholder Default. Hydration has to+// treat it as loaded under the preset, or its first edit files the preset as the model's tuning.++import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";++import { installLocalStorageFake } from "./helpers/kit.ts";++const { store: localStorageFake } = installLocalStorageFake();+localStorageFake.set("unsloth_chat_settings_imported_to_studio_db", "true");+register("./store-settings-resolver.mjs", import.meta.url);++const { settingsHttp } = await import("./helpers/store-stubs/settings-http.ts");+const { useChatRuntimeStore } = await import(+ "../src/features/chat/stores/chat-runtime-store.ts"+);+const { mergeBackendRecommendedInference } = await import(+ "../src/features/chat/presets/preset-policy.ts"+);+const { DEFAULT_INFERENCE_PARAMS } = await import(+ "../src/features/chat/types/runtime.ts"+);++const QWEN = "unsloth/Qwen3.6-35B-A3B-GGUF";+const PIRATE = {+ temperature: 0.3,+ topP: 0.7,+ topK: 10,+ systemPrompt: "Talk like a pirate.",+};++test("a model resident before hydration restores a custom preset as a preset load", async () => {+ settingsHttp.settings = {+ rememberParamsPerModel: true,+ inferenceParams: PIRATE,+ customPresets: [{ name: "Pirate", params: { ...DEFAULT_INFERENCE_PARAMS, ...PIRATE } }],+ activePreset: "Pirate",+ activePresetSource: "custom",+ };+ settingsHttp.hold();+ const hydrating = useChatRuntimeStore.getState().hydratePersistedSettings();++ const store = useChatRuntimeStore.getState();+ store.setParams(+ mergeBackendRecommendedInference({+ current: store.params,+ response: { inference: { temperature: 1, top_p: 0.9, top_k: 64 }, is_gguf: true, context_length: 8192 },+ modelId: QWEN,+ presetSource: store.activePresetSource,+ loadedContextLength: 8192,+ }),+ { fromModelDefaults: true, maxTokensCap: 8192 },+ );+ settingsHttp.release?.();+ await hydrating;++ const hydrated = useChatRuntimeStore.getState();+ assert.equal(hydrated.activePresetSource, "custom");+ hydrated.setActivePresetSource("modified");+ hydrated.setParams({ ...useChatRuntimeStore.getState().params, topK: 5 });+ const entry = useChatRuntimeStore.getState().paramsByModel[QWEN] ?? {};+ assert.equal(entry.topK, 5);+ assert.equal(entry.systemPrompt, undefined, "the preset's prompt is not filed as the model's");+ assert.equal(entry.temperature, undefined);+});diff --git a/studio/frontend/tests/preset-model-memory.test.ts b/studio/frontend/tests/preset-model-memory.test.tsnew file mode 100644index 00000000000..84e16a2ceeb--- /dev/null+++ b/studio/frontend/tests/preset-model-memory.test.ts@@ -0,0 +1,362 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Picking a preset is not a per-model edit (#14068). Default fell back to fixed sampling for every+// model, and a custom preset's values came back on the next load after switching to Default. These+// drive the real store the way the settings sheet, a model load and a status poll do.++import assert from "node:assert/strict";+import { register } from "node:module";+import test from "node:test";++import { installLocalStorageFake } from "./helpers/kit.ts";++const { store: localStorageFake } = installLocalStorageFake();+localStorageFake.set("unsloth_chat_settings_imported_to_studio_db", "true");+register("./store-settings-resolver.mjs", import.meta.url);++const { settingsHttp, deepMerge } = await import(+ "./helpers/store-stubs/settings-http.ts"+);+const { useChatRuntimeStore, beginThreadScopedPairing } = await import(+ "../src/features/chat/stores/chat-runtime-store.ts"+);+const {+ BUILTIN_PRESETS,+ applyPresetForProvider,+ getPresetSource,+ mergeBackendRecommendedInference,+} = await import("../src/features/chat/presets/preset-policy.ts");+const { DEFAULT_INFERENCE_PARAMS } = await import(+ "../src/features/chat/types/runtime.ts"+);++type Preset = (typeof BUILTIN_PRESETS)[number];++const GEMMA = "HauhauCS/Gemma-4-E4B-Uncensored-HauhauCS-Aggressive";+const QWEN = "unsloth/Qwen3.6-35B-A3B-GGUF";+const CONTEXT = 131072;+/** What the backend recommends for every model here. */+const RECOMMENDED = { temperature: 1, top_p: 0.9, top_k: 64 };+const DEFAULT = BUILTIN_PRESETS[0];+const CUSTOM: Preset = {+ name: "Pirate",+ params: {+ ...DEFAULT_INFERENCE_PARAMS,+ temperature: 0.3,+ topP: 0.7,+ topK: 10,+ systemPrompt: "Talk like a pirate.",+ },+};++/** A model load, or a status poll when the checkpoint is already the one loaded. */+function loadOrPoll(modelId: string): void {+ const store = useChatRuntimeStore.getState();+ store.setParams(+ mergeBackendRecommendedInference({+ current: store.params,+ response: { inference: RECOMMENDED, is_gguf: true, context_length: CONTEXT },+ modelId,+ presetSource: store.activePresetSource,+ loadedContextLength: CONTEXT,+ }),+ { fromModelDefaults: true, maxTokensCap: CONTEXT },+ );+}++/** chat-settings-sheet's applyPreset. */+function pickPreset(preset: Preset): void {+ const store = useChatRuntimeStore.getState();+ store.setParams(applyPresetForProvider(store.params, preset, null), {+ minPChoiceEdited: true,+ fromPreset: true,+ } as never);+ store.setActivePreset(preset.name);+ store.setActivePresetSource(getPresetSource(preset.name));+}++function sampling() {+ const { temperature, topP, topK, systemPrompt } =+ useChatRuntimeStore.getState().params;+ return { temperature, topP, topK, systemPrompt };+}++const AUTOMATIC = { temperature: 1, topP: 0.9, topK: 64, systemPrompt: "" };++async function settled(): Promise<void> {+ await new Promise((resolve) => setTimeout(resolve, 600));+}++test.before(async () => {+ settingsHttp.settings = {};+ await useChatRuntimeStore.getState().hydratePersistedSettings();+ assert.equal(useChatRuntimeStore.getState().settingsHydrated, true);+ assert.equal(useChatRuntimeStore.getState().rememberParamsPerModel, true);+});++test.beforeEach(() => {+ useChatRuntimeStore.getState().clearCheckpoint();+ useChatRuntimeStore.setState({ paramsByModel: {} });+ pickPreset(DEFAULT);+});++const NOT_PRESET_OWNED = ["checkpoint", "maxSeqLength", "trustRemoteCode", "fastMode"];+const PRESET_OWNED = new Set(+ Object.keys(DEFAULT.params).filter((key) => !NOT_PRESET_OWNED.includes(key)),+);++function presetOwnedKeys(entry: Record<string, unknown> | undefined): string[] {+ return Object.keys(entry ?? {}).filter((key) => PRESET_OWNED.has(key));+}++/** What the server holds after every write so far, through the backend's merge. */+function stored(): Record<string, unknown> {+ return settingsHttp.puts.reduce(+ (settings, put) => deepMerge(settings, put),+ settingsHttp.settings,+ );+}++test("picking Default with a model loaded goes back to that model's recommendation", async () => {+ loadOrPoll(GEMMA);+ const store = useChatRuntimeStore.getState();+ store.setActivePresetSource("modified");+ store.setParams({ ...store.params, temperature: 0.2 });+ await settled();+ assert.equal(+ (stored().inferenceParamsByModel as Record<string, { temperature?: number }>)[GEMMA]+ ?.temperature,+ 0.2,+ "a slider edit is stored for the model",+ );+ pickPreset(CUSTOM);+ pickPreset(DEFAULT);+ loadOrPoll(GEMMA);+ assert.deepEqual(+ sampling(),+ AUTOMATIC,+ "Default's fixed sampling is not filed as the model's own",+ );+ await settled();+ const byModel = stored().inferenceParamsByModel as Record<string, Record<string, unknown>>;+ assert.deepEqual(+ presetOwnedKeys(byModel[GEMMA]),+ [],+ "no sampling is left for the next launch",+ );+ assert.equal(stored().forgetInferenceParamsByModel, undefined);+});++test("a custom preset does not come back after ejecting and picking Default", () => {+ loadOrPoll(GEMMA);+ pickPreset(CUSTOM);+ loadOrPoll(GEMMA);+ assert.deepEqual(sampling(), {+ temperature: 0.3,+ topP: 0.7,+ topK: 10,+ systemPrompt: "Talk like a pirate.",+ });+ useChatRuntimeStore.getState().clearCheckpoint();+ pickPreset(DEFAULT);+ loadOrPoll(GEMMA);+ assert.deepEqual(sampling(), AUTOMATIC);+});++test("a model first loaded under a custom preset does not keep it", () => {+ pickPreset(CUSTOM);+ loadOrPoll(QWEN);+ assert.equal(sampling().systemPrompt, "Talk like a pirate.");+ useChatRuntimeStore.getState().clearCheckpoint();+ pickPreset(DEFAULT);+ loadOrPoll(GEMMA);+ assert.deepEqual(sampling(), AUTOMATIC);+ loadOrPoll(QWEN);+ assert.deepEqual(sampling(), AUTOMATIC);+});++test("ejecting right after picking Default does not file its fixed sampling", () => {+ loadOrPoll(GEMMA);+ pickPreset(DEFAULT);+ assert.equal(sampling().temperature, DEFAULT_INFERENCE_PARAMS.temperature);+ useChatRuntimeStore.getState().clearCheckpoint();+ loadOrPoll(GEMMA);+ assert.deepEqual(sampling(), AUTOMATIC);+});++// Edits and picks share one debounced write, so the forget has to order against the edits queued+// beside it.+test("a pick and a slider edit in one write window land in the order they were made", async () => {+ loadOrPoll(GEMMA);+ const store = useChatRuntimeStore.getState();+ store.setActivePresetSource("modified");+ store.setParams({ ...store.params, temperature: 0.2, systemPrompt: "Old" });+ pickPreset(DEFAULT);+ await settled();+ const byModel = () =>+ stored().inferenceParamsByModel as Record<string, Record<string, unknown>>;+ assert.deepEqual(+ presetOwnedKeys(byModel()[GEMMA]),+ [],+ "an edit queued before the pick is forgotten",+ );++ loadOrPoll(GEMMA);+ pickPreset(CUSTOM);+ const live = useChatRuntimeStore.getState();+ live.setActivePresetSource("modified");+ live.setParams({ ...live.params, topK: 5 });+ await settled();+ assert.deepEqual(+ presetOwnedKeys(byModel()[GEMMA]),+ ["topK"],+ "an edit after the pick starts a fresh entry, without the preset or the older one",+ );+ assert.equal(byModel()[GEMMA].topK, 5);+});++// Presets do not set these, so a pick keeps them for the model.+test("a preset pick keeps the model's remembered Fast mode", async () => {+ loadOrPoll(GEMMA);+ const store = useChatRuntimeStore.getState();+ store.setActivePresetSource("modified");+ store.setParams({ ...store.params, fastMode: true, temperature: 0.2 });+ pickPreset(CUSTOM);+ await settled();+ const local = useChatRuntimeStore.getState().paramsByModel[GEMMA];+ assert.equal(local?.fastMode, true);+ assert.deepEqual(presetOwnedKeys(local), []);+ const byModel = stored().inferenceParamsByModel as Record<string, Record<string, unknown>>;+ assert.equal(byModel[GEMMA].fastMode, true);+ assert.deepEqual(presetOwnedKeys(byModel[GEMMA]), []);+});++// The edit is filed as itself, not as a snapshot carrying the preset's sampling and prompt.+test("an edit after a preset pick does not file the preset for the model", () => {+ loadOrPoll(GEMMA);+ pickPreset(CUSTOM);+ const store = useChatRuntimeStore.getState();+ store.setActivePresetSource("modified");+ store.setParams({ ...store.params, topK: 5 });+ store.setParams({ ...useChatRuntimeStore.getState().params, fastMode: true });+ useChatRuntimeStore.getState().clearCheckpoint();+ pickPreset(DEFAULT);+ loadOrPoll(GEMMA);+ assert.deepEqual(sampling(), { ...AUTOMATIC, topK: 5 });+ assert.equal(useChatRuntimeStore.getState().params.fastMode, true);+});++// The memory itself still works: a slider moved on a model is that model's and outlasts a switch.+test("a slider edit is still remembered per model over its recommendation", () => {+ loadOrPoll(GEMMA);+ const store = useChatRuntimeStore.getState();+ store.setActivePresetSource("modified");+ store.setParams({ ...store.params, temperature: 0.2 });+ loadOrPoll(QWEN);+ assert.equal(sampling().temperature, 0.2, "an unremembered model keeps what is on screen");+ useChatRuntimeStore.getState().setParams({+ ...useChatRuntimeStore.getState().params,+ temperature: 0.5,+ });+ loadOrPoll(GEMMA);+ assert.equal(sampling().temperature, 0.2);+ loadOrPoll(QWEN);+ assert.equal(sampling().temperature, 0.5);+});++// The model was not on screen when the preset was picked, so the pick could not mark it.+test("a model first loaded under a custom preset files later edits as themselves", () => {+ pickPreset(CUSTOM);+ loadOrPoll(QWEN);+ const store = useChatRuntimeStore.getState();+ store.setParams({ ...store.params, fastMode: true });+ useChatRuntimeStore.getState().setActivePresetSource("modified");+ useChatRuntimeStore.getState().setParams({ ...useChatRuntimeStore.getState().params, topK: 5 });+ assert.deepEqual(presetOwnedKeys(useChatRuntimeStore.getState().paramsByModel[QWEN]), ["topK"]);+ useChatRuntimeStore.getState().clearCheckpoint();+ pickPreset(DEFAULT);+ loadOrPoll(QWEN);+ assert.deepEqual(sampling(), { ...AUTOMATIC, topK: 5 });+});++// Another tab may have set a key the pick does not own, so the pick names keys, not the row.+test("a preset pick asks the server to drop only the preset's keys", async () => {+ loadOrPoll(GEMMA);+ settingsHttp.puts.length = 0;+ pickPreset(DEFAULT);+ await settled();+ const forget = settingsHttp.puts.find((put) => put.forgetInferenceParamsByModel)+ ?.forgetInferenceParamsByModel as Record<string, string[]>;+ assert.deepEqual(new Set(forget[GEMMA]), PRESET_OWNED);+});++// An edit made while nothing was loaded is the user's, so reloading under it ends the preset mark.+test("a model reloaded under the user's own edits is remembered whole again", () => {+ loadOrPoll(GEMMA);+ pickPreset(DEFAULT);+ useChatRuntimeStore.getState().clearCheckpoint();+ const store = useChatRuntimeStore.getState();+ store.setActivePresetSource("modified");+ store.setParams({ ...store.params, temperature: 0.4 });+ loadOrPoll(GEMMA);+ const loaded = useChatRuntimeStore.getState();+ loaded.setParams({ ...loaded.params, topK: 7 });+ const entry = useChatRuntimeStore.getState().paramsByModel[GEMMA];+ assert.equal(entry?.topK, 7);+ assert.equal(entry?.temperature, 0.4, "the whole snapshot, not just the moved key");+});++// A status poll for the model already on screen replaces none of the preset's values.+test("a same-model status poll keeps later edits filed as themselves", () => {+ loadOrPoll(GEMMA);+ pickPreset(CUSTOM);+ const store = useChatRuntimeStore.getState();+ store.setActivePresetSource("modified");+ store.setParams({ ...store.params, topK: 5 });+ loadOrPoll(GEMMA);+ useChatRuntimeStore.getState().setParams({ ...useChatRuntimeStore.getState().params, topP: 0.5 });+ assert.deepEqual(+ presetOwnedKeys(useChatRuntimeStore.getState().paramsByModel[GEMMA]).sort(),+ ["topK", "topP"],+ );+});++// The model's row is forgotten, so a preset value that already matched the screen must still reach+// the defaults the model falls back to after a restart.+test("a preset pick writes the whole preset to the installation defaults", async () => {+ loadOrPoll(GEMMA);+ pickPreset(CUSTOM);+ await settled();+ settingsHttp.puts.length = 0;+ pickPreset(CUSTOM);+ await settled();+ const written = Object.assign(+ {},+ ...settingsHttp.puts.map((put) => (put.inferenceParams ?? {}) as Record<string, unknown>),+ );+ assert.equal(written.temperature, 0.3);+ assert.equal(written.topK, 10);+ assert.equal(written.systemPrompt, "Talk like a pirate.");+});++// Last: the open chat's pairing stays for the rest of the module.+// With a saved chat open the preset's sampling belongs to that chat, so the model's own stays.+test("a preset picked inside a chat leaves the model's remembered sampling alone", () => {+ loadOrPoll(GEMMA);+ const store = useChatRuntimeStore.getState();+ store.setActivePresetSource("modified");+ store.setParams({ ...store.params, temperature: 0.2 });+ store.setActiveThreadId("chat-1" as never);+ beginThreadScopedPairing("chat-1");+ pickPreset(CUSTOM);+ assert.equal(useChatRuntimeStore.getState().paramsByModel[GEMMA]?.temperature, 0.2);+ // The chat kept the sampling, so the model is not marked: a later edit it owns files whole.+ useChatRuntimeStore.setState({ paramsByModel: {} });+ const inChat = useChatRuntimeStore.getState();+ const fastMode = !inChat.params.fastMode;+ inChat.setParams({ ...inChat.params, fastMode });+ const entry = useChatRuntimeStore.getState().paramsByModel[GEMMA] ?? {};+ assert.equal(entry.fastMode, fastMode);+ assert.ok("maxTokens" in entry, "a whole snapshot, not only the moved key");+});diff --git a/studio/frontend/tests/provider-max-output-tokens.test.ts b/studio/frontend/tests/provider-max-output-tokens.test.tsindex 6d94eb83135..821cb2de760 100644--- a/studio/frontend/tests/provider-max-output-tokens.test.ts+++ b/studio/frontend/tests/provider-max-output-tokens.test.ts@@ -97,11 +97,11 @@ test("preset application clamps live Max Tokens to the active external cap", ());assert.match(settings,- /setParams\(applyPresetParamsWithinCurrentLimits\(p\),\s*\{\s*minPChoiceEdited: true,\s*\}\)/,+ /setParams\(applyPresetParamsWithinCurrentLimits\(p\),\s*\{\s*minPChoiceEdited: true,\s*fromPreset: true,\s*\}\)/,);assert.match(settings,- /setParams\(\s*applyPresetParamsWithinCurrentLimits\(fallbackPreset\),\s*\{ minPChoiceEdited: true \},\s*\)/,+ /setParams\(\s*applyPresetParamsWithinCurrentLimits\(fallbackPreset\),\s*\{ minPChoiceEdited: true, fromPreset: true \},\s*\)/,);});