Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: remember chat parameters per model (#8757)

Michael Han2819e29474a5
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.py
index a5bf80490c5..cf4eba4fd87 100644
--- a/studio/backend/routes/chat_history.py
+++ b/studio/backend/routes/chat_history.py
@@ -399,6 +399,10 @@ class ChatSettingsPayload(BaseModel):
model_config = ConfigDict(extra = "forbid", allow_inf_nan = False)
inferenceParams: Optional[ChatInferenceSettings] = None
+ # Last-used params per checkpoint id. Deep-merged per key, so patching one
+ # model cannot drop another's.
+ inferenceParamsByModel: Optional[dict[str, ChatInferenceSettings]] = None
+ rememberParamsPerModel: Optional[bool] = None
customPresets: Optional[list[ChatPreset]] = None
activePreset: Optional[str] = None
activePresetSource: Optional[Literal["builtin-default", "custom", "modified"]] = None
diff --git a/studio/backend/tests/test_chat_history_routes.py b/studio/backend/tests/test_chat_history_routes.py
index 8766a308747..0398f41e9c1 100644
--- a/studio/backend/tests/test_chat_history_routes.py
+++ b/studio/backend/tests/test_chat_history_routes.py
@@ -295,6 +295,37 @@ def test_chat_settings_payload_accepts_fast_mode_presets():
assert dumped["customPresets"][0]["params"]["fastMode"] is True
+def test_chat_settings_payload_carries_per_model_params():
+ """The payload is extra="forbid", so per-model memory only reaches the DB if the
+ schema names both keys. A patch also has to survive exclude_unset with just the
+ one model it touched, since that is what keeps other models' settings intact."""
+ payload = chat_history.ChatSettingsPayload.model_validate(
+ {
+ "rememberParamsPerModel": True,
+ "inferenceParamsByModel": {
+ "unsloth/Qwen3.5-9B-GGUF": {"temperature": 0.2, "maxTokens": 4096},
+ },
+ }
+ )
+
+ dumped = payload.model_dump(exclude_unset = True)
+ assert dumped["rememberParamsPerModel"] is True
+ assert dumped["inferenceParamsByModel"] == {
+ "unsloth/Qwen3.5-9B-GGUF": {"temperature": 0.2, "maxTokens": 4096},
+ }
+ # Nothing else is implied by the patch, so the merge cannot clobber it.
+ assert "inferenceParams" not in dumped
+
+
+def test_chat_settings_payload_rejects_junk_per_model_params():
+ """Provider-qualified ids are opaque keys, but the values are still real
+ inference settings -- an unknown field must 400 rather than reach the DB."""
+ with pytest.raises(ValidationError):
+ chat_history.ChatSettingsPayload.model_validate(
+ {"inferenceParamsByModel": {"openai:gpt-x": {"notAParam": 1}}}
+ )
+
+
def test_chat_settings_payload_accepts_preset_load_config():
payload = chat_history.ChatSettingsPayload.model_validate(
{
diff --git a/studio/backend/tests/test_chat_history_storage.py b/studio/backend/tests/test_chat_history_storage.py
index 136d817b653..5092198ce5e 100644
--- a/studio/backend/tests/test_chat_history_storage.py
+++ b/studio/backend/tests/test_chat_history_storage.py
@@ -471,6 +471,24 @@ def test_settings_merge_preserves_nested_keys(tmp_path, monkeypatch):
assert params == {"temperature": 0.9, "topP": 0.8}
+def test_settings_merge_keeps_each_model_s_remembered_params(tmp_path, monkeypatch):
+ """Per-model memory patches one model at a time, so the merge has to keep the
+ others. Without this, tuning a second model would wipe the first one's settings
+ and the switch back would land on whatever the last edit happened to be."""
+ _reset_studio_db(tmp_path, monkeypatch)
+ studio_db.upsert_chat_settings_merge(
+ {"inferenceParamsByModel": {"qwen": {"temperature": 0.2, "topP": 0.8}}}
+ )
+ studio_db.upsert_chat_settings_merge(
+ {"inferenceParamsByModel": {"llama": {"temperature": 0.9}}}
+ )
+ # A second edit to the first model merges into its own entry.
+ studio_db.upsert_chat_settings_merge({"inferenceParamsByModel": {"qwen": {"temperature": 0.4}}})
+
+ by_model = studio_db.list_chat_settings()["inferenceParamsByModel"]
+ assert by_model == {"qwen": {"temperature": 0.4, "topP": 0.8}, "llama": {"temperature": 0.9}}
+
+
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/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 10b4cd9d0c1..f9dbbdcd212 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -1993,6 +1993,8 @@ function restoreVisibleModelState(snapshot: VisibleModelStateSnapshot): void {
liveUsage
.setCheckpoint(snapshot.settings.params.checkpoint, undefined, {
trackQueuedSettings: false,
+ // The model being stepped off is the one the background load put there.
+ persist: false,
});
useChatRuntimeStore.setState({
...snapshot.runtime,
@@ -2949,6 +2951,12 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
{
persist: !options?.preserveVisibleSettings,
trackQueuedSettings: !options?.preserveVisibleSettings,
+ fromModelDefaults: true,
+ // A budget remembered from a larger context does not fit this load.
+ maxTokensCap:
+ candidate.kind === "gguf"
+ ? (loadResp.context_length ?? undefined)
+ : effectiveMaxSeqLength,
},
);
// Upsert: a pre-load catalog entry has no backend-derived audio
@@ -3329,6 +3337,8 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
{
persist: !options?.preserveVisibleSettings,
trackQueuedSettings: !options?.preserveVisibleSettings,
+ fromModelDefaults: true,
+ maxTokensCap: loadResp.context_length ?? undefined,
},
);
const defaultModel: ChatModelSummary = {
diff --git a/studio/frontend/src/features/chat/api/chat-settings-api.ts b/studio/frontend/src/features/chat/api/chat-settings-api.ts
index 87bf1129f36..45ad8d363e6 100644
--- a/studio/frontend/src/features/chat/api/chat-settings-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-settings-api.ts
@@ -11,15 +11,16 @@ import type {
ReasoningEffort,
} from "../stores/chat-runtime-store";
import type { ResearchWebsitePolicy } from "../types/research";
-import type { InferenceParams } from "../types/runtime";
+import type {
+ InferenceParams,
+ PersistedInferenceParams,
+} from "../types/runtime";
import {
ChatSettingsRequestError,
isUnderKeepaliveBudget,
} from "../utils/settings-retry";
-export type PersistedInferenceParams = Partial<
- Omit<InferenceParams, "checkpoint">
->;
+export type { PersistedInferenceParams };
export interface PersistedChatPreset {
name: string;
@@ -29,6 +30,9 @@ export interface PersistedChatPreset {
export interface PersistedChatSettings {
inferenceParams?: PersistedInferenceParams;
+ /** Last-used params per checkpoint id, replayed on model switch. */
+ inferenceParamsByModel?: Record<string, PersistedInferenceParams>;
+ rememberParamsPerModel?: boolean;
customPresets?: PersistedChatPreset[];
activePreset?: string;
activePresetSource?: ChatPresetSource;
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
index 4b5476a724f..963b5ed0ebf 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
@@ -1544,6 +1544,11 @@ export function useChatModelRuntime() {
persistGpuMemoryModeOnLoad(loadResponse, loadGpuMemoryMode);
const currentParams = useChatRuntimeStore.getState().params;
+ // The context this load actually has: the server's for a GGUF, the
+ // sequence length the load was invoked with otherwise.
+ const loadedContextCap = loadResponse.is_gguf
+ ? (loadResponse.context_length ?? undefined)
+ : effectiveMaxSeqLength;
setParams(
mergeBackendRecommendedInference({
current: currentParams,
@@ -1551,6 +1556,12 @@ export function useChatModelRuntime() {
modelId,
presetSource: useChatRuntimeStore.getState().activePresetSource,
}),
+ // Lay this model's remembered settings back over its defaults,
+ // but not a budget larger than the context it just loaded with.
+ {
+ fromModelDefaults: true,
+ maxTokensCap: loadedContextCap,
+ },
);
// Qwen3.5/3.6 small models (0.8B, 2B, 4B, 9B) disable thinking by default.
// Anchored regex: first "Xb" / "X.Xb" after start-of-string or
@@ -1757,7 +1768,12 @@ export function useChatModelRuntime() {
? { presencePenalty: 1.5 }
: {}),
};
- store.setParams({ ...store.params, ...p });
+ // Same rule as the load response: defaults first, this model's
+ // remembered settings over them.
+ store.setParams({ ...store.params, ...p }, {
+ fromModelDefaults: true,
+ maxTokensCap: loadedContextCap,
+ });
}
}
await refresh({ signal: abortCtrl.signal });
diff --git a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
index 014d02f2932..702616fab00 100644
--- a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
+++ b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
@@ -157,6 +157,14 @@ export function applyActiveModelStatusToStore(
modelId: checkpointId,
presetSource: store.activePresetSource,
}),
+ // The model's own remembered settings outrank the recommendation, or
+ // every poll would undo them, but not past the context it loaded with.
+ // context_length is reported for a safetensors load too, so this is not
+ // narrowed to GGUF; absent, there is nothing to cap against.
+ {
+ fromModelDefaults: true,
+ maxTokensCap: status.context_length ?? undefined,
+ },
);
}
diff --git a/studio/frontend/src/features/chat/lib/per-model-params.ts b/studio/frontend/src/features/chat/lib/per-model-params.ts
new file mode 100644
index 00000000000..990c87639b6
--- /dev/null
+++ b/studio/frontend/src/features/chat/lib/per-model-params.ts
@@ -0,0 +1,137 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Per-model parameter memory: a per-checkpoint record alongside the global set,
+// so a switch no longer hands the next model the previous one's settings. No
+// store or network imports, so the rules stay unit-testable.
+
+import type {
+ InferenceParams,
+ PersistedInferenceParams,
+} from "../types/runtime";
+
+export type PersistedInferenceParamKey = keyof PersistedInferenceParams;
+
+/** Params that persist across a reload. `checkpoint` is the key, not a value. */
+export const PERSISTED_INFERENCE_PARAM_KEYS = [
+ "temperature",
+ "topP",
+ "topK",
+ "minP",
+ "repetitionPenalty",
+ "presencePenalty",
+ "maxSeqLength",
+ "maxTokens",
+ "systemPrompt",
+ "systemVariables",
+ "trustRemoteCode",
+ "fastMode",
+] as const satisfies readonly PersistedInferenceParamKey[];
+
+/** What the memory records. `maxSeqLength` is left out: the context belongs to
+ * the load config, and a second copy would advertise one never loaded. */
+export const REMEMBERED_INFERENCE_PARAM_KEYS =
+ PERSISTED_INFERENCE_PARAM_KEYS.filter(
+ (key): key is PersistedInferenceParamKey => key !== "maxSeqLength",
+ );
+
+export function setInferenceParam(
+ params: InferenceParams,
+ key: PersistedInferenceParamKey,
+ value: PersistedInferenceParams[PersistedInferenceParamKey],
+): void {
+ (params as Record<PersistedInferenceParamKey, unknown>)[key] = value;
+}
+
+/** The remembered subset. No version bump, unlike getChangedInferenceParams. */
+export function pickRememberedParams(
+ params: InferenceParams,
+): PersistedInferenceParams {
+ const picked: PersistedInferenceParams = {};
+ for (const key of REMEMBERED_INFERENCE_PARAM_KEYS) {
+ const value = params[key];
+ if (value !== undefined) {
+ setInferenceParam(picked as InferenceParams, key, value);
+ }
+ }
+ return picked;
+}
+
+/** Whether an edit moved anything the memory keeps. */
+function movedRememberedParam(changed: PersistedInferenceParams): boolean {
+ return REMEMBERED_INFERENCE_PARAM_KEYS.some(
+ (key) => changed[key] !== undefined,
+ );
+}
+
+/** Just the keys an edit moved. What goes to the server for a model that already
+ * has an entry: it merges per key, so a whole snapshot would put this browser's
+ * copy of every other key over another tab's. */
+export function pickRememberedChanges(
+ changed: PersistedInferenceParams,
+): PersistedInferenceParams {
+ const picked: PersistedInferenceParams = {};
+ for (const key of REMEMBERED_INFERENCE_PARAM_KEYS) {
+ const value = changed[key];
+ if (value !== undefined) {
+ setInferenceParam(picked as InferenceParams, key, value);
+ }
+ }
+ return picked;
+}
+
+/** The map after an edit, or null when there is nothing to record (off, no model,
+ * no persisted param moved), which leaves the map and its version untouched. */
+export function getRememberedParamsPatch(
+ enabled: boolean,
+ paramsByModel: Record<string, PersistedInferenceParams>,
+ modelId: string | undefined,
+ changedParams: PersistedInferenceParams,
+ snapshot: PersistedInferenceParams,
+): Record<string, PersistedInferenceParams> | null {
+ if (!(enabled && modelId && movedRememberedParam(changedParams))) {
+ return null;
+ }
+ // The whole snapshot: replay overlays the entry, so a partial one would leave
+ // the gaps filled by whichever model was on screen last.
+ return { ...paramsByModel, [modelId]: snapshot };
+}
+
+/** The params a switch should land on. A model with nothing remembered keeps what
+ * is on screen, and `current` comes back by identity so callers can tell that
+ * apart. `maxTokensCap` is the context the model just loaded with. */
+export function getReplayedParams(
+ enabled: boolean,
+ paramsByModel: Record<string, PersistedInferenceParams>,
+ current: InferenceParams,
+ modelId: string,
+ checkpointChanged: boolean,
+ maxTokensCap?: number,
+): InferenceParams {
+ // The cap describes the load, not the memory, so it applies even when nothing
+ // replays. Identity survives when the budget already fits.
+ const capped = (params: InferenceParams): InferenceParams =>
+ maxTokensCap !== undefined && params.maxTokens > maxTokensCap
+ ? { ...params, maxTokens: maxTokensCap }
+ : params;
+ if (!(enabled && checkpointChanged)) {
+ return capped(current);
+ }
+ const remembered = paramsByModel[modelId];
+ if (!remembered) {
+ return capped(current);
+ }
+ // Key by key, not a spread: the row accepts every persisted key from any
+ // writer, and a spread would carry maxSeqLength and stale keys into params.
+ const replayed = { ...current };
+ for (const key of REMEMBERED_INFERENCE_PARAM_KEYS) {
+ const value = remembered[key];
+ if (value !== undefined) {
+ setInferenceParam(replayed, key, value);
+ }
+ }
+ if (maxTokensCap !== undefined && replayed.maxTokens > maxTokensCap) {
+ replayed.maxTokens = maxTokensCap;
+ }
+ return replayed;
+}
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index 201041a5b3b..480b2ef4d94 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -1544,6 +1544,14 @@ export function SharedComposer({
store.setCheckpoint(
resp.model,
resp.is_gguf ? (sel.ggufVariant ?? undefined) : null,
+ // Same cap as the interactive load: this replays the model's
+ // remembered settings, and a budget kept from a larger context does
+ // not fit the one it just loaded with.
+ {
+ maxTokensCap: resp.is_gguf
+ ? (resp.context_length ?? undefined)
+ : effectiveMaxSeqLength,
+ },
);
store.setModelRequiresTrustRemoteCode(
resp.requires_trust_remote_code ?? false,
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index 277e1ad9061..2c84fbf6724 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -29,6 +29,16 @@ import {
} from "../presets/preset-policy";
import { normalizePresetLoadConfig } from "../presets/preset-load-config";
import { getExternalMaxOutputTokens } from "../provider-capabilities";
+import {
+ PERSISTED_INFERENCE_PARAM_KEYS,
+ REMEMBERED_INFERENCE_PARAM_KEYS,
+ type PersistedInferenceParamKey,
+ getRememberedParamsPatch,
+ getReplayedParams,
+ pickRememberedChanges,
+ pickRememberedParams,
+ setInferenceParam,
+} from "../lib/per-model-params";
import {
type ChatLoraSummary,
type ChatModelSummary,
@@ -335,19 +345,35 @@ function isPlainObject(value: unknown): value is Record<string, unknown> {
// stored `kb` one keeps `kbId`, which the backend's thread variant forbids.
const ATOMIC_SETTING_KEYS = new Set<string>(["ragSource"]);
+// Maps of per-model objects, merged a level further in: two edits to different
+// fields inside one debounce window must not replace each other.
+const NESTED_MAP_SETTING_KEYS = new Set<string>(["inferenceParamsByModel"]);
+
function mergePatch(into: SettingsPatch, more: SettingsPatch): void {
for (const [key, value] of Object.entries(more)) {
const intoAny = into as Record<string, unknown>;
const prev = intoAny[key];
- if (
- !ATOMIC_SETTING_KEYS.has(key) &&
- isPlainObject(prev) &&
- isPlainObject(value)
- ) {
- intoAny[key] = { ...prev, ...value };
- } else {
+ if (ATOMIC_SETTING_KEYS.has(key)) {
intoAny[key] = value;
+ continue;
+ }
+ if (!isPlainObject(prev) || !isPlainObject(value)) {
+ intoAny[key] = value;
+ continue;
}
+ if (!NESTED_MAP_SETTING_KEYS.has(key)) {
+ intoAny[key] = { ...prev, ...value };
+ continue;
+ }
+ const merged: Record<string, unknown> = { ...prev };
+ for (const [id, entry] of Object.entries(value)) {
+ const existing = merged[id];
+ merged[id] =
+ isPlainObject(existing) && isPlainObject(entry)
+ ? { ...existing, ...entry }
+ : entry;
+ }
+ intoAny[key] = merged;
}
}
@@ -2053,6 +2079,9 @@ type ChatRuntimeStore = {
*/
threadScopedSettingsPending: boolean;
params: InferenceParams;
+ /** Last-used sampling params per checkpoint id, replayed on model switch. */
+ paramsByModel: Record<string, PersistedInferenceParams>;
+ rememberParamsPerModel: boolean;
customPresets: Preset[];
activePreset: string;
activePresetSource: ChatPresetSource;
@@ -2381,7 +2410,15 @@ type ChatRuntimeStore = {
setModelRequiresTrustRemoteCode: (required: boolean) => void;
setParams: (
params: InferenceParams,
- options?: { persist?: boolean; trackQueuedSettings?: boolean },
+ options?: {
+ persist?: boolean;
+ trackQueuedSettings?: boolean;
+ /** These params are the model's defaults, so its remembered settings are
+ * laid back over them even though the checkpoint did not change. */
+ fromModelDefaults?: boolean;
+ /** The context the model just loaded with. */
+ maxTokensCap?: number;
+ },
) => void;
setCustomPresets: (presets: Preset[]) => void;
setActivePreset: (name: string) => void;
@@ -2424,7 +2461,14 @@ type ChatRuntimeStore = {
setCheckpoint: (
modelId: string,
ggufVariant?: string | null,
- options?: { trackQueuedSettings?: boolean },
+ options?: {
+ trackQueuedSettings?: boolean;
+ /** False when the switch only puts back what was on screen before a
+ * hidden load, so the model it steps off was never the user's. */
+ persist?: boolean;
+ /** The context the model just loaded with, when the caller knows it. */
+ maxTokensCap?: number;
+ },
) => void;
setActiveThreadId: (threadId: string | null) => void;
/** show `threadId`'s own settings; a null threadId or snapshot restores the global ones. */
@@ -2472,6 +2516,7 @@ type ChatRuntimeStore = {
clearToolConfirmation: (toolCallId: string) => void;
setWebFetchToolsEnabled: (enabled: boolean) => void;
setRagEnabled: (enabled: boolean) => void;
+ setRememberParamsPerModel: (enabled: boolean) => void;
setRagSource: (source: RagSource) => void;
setRagMode: (mode: RagMode) => void;
setRagTopK: (topK: number) => void;
@@ -2538,9 +2583,9 @@ type PersistedChatSettings = Awaited<
type PersistedInferenceParams = NonNullable<
PersistedChatSettings["inferenceParams"]
>;
-type PersistedInferenceParamKey = keyof PersistedInferenceParams;
type ScalarSettingKey =
| "autoTitle"
+ | "rememberParamsPerModel"
| "reasoningEffort"
| "preserveThinking"
| "collapseHtmlArtifacts"
@@ -2586,23 +2631,9 @@ type SettingsHydrationVersions = {
presets: PresetHydrationVersions;
};
-const PERSISTED_INFERENCE_PARAM_KEYS = [
- "temperature",
- "topP",
- "topK",
- "minP",
- "repetitionPenalty",
- "presencePenalty",
- "maxSeqLength",
- "maxTokens",
- "systemPrompt",
- "systemVariables",
- "trustRemoteCode",
- "fastMode",
-] as const satisfies readonly PersistedInferenceParamKey[];
-
const SCALAR_SETTING_KEYS = [
"autoTitle",
+ "rememberParamsPerModel",
"reasoningEffort",
"preserveThinking",
"collapseHtmlArtifacts",
@@ -2637,6 +2668,9 @@ const SCALAR_SETTING_KEYS = [
"gpuMemoryMode",
] as const satisfies readonly ScalarSettingKey[];
+// 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>();
const inferenceParamMutationVersions = Object.fromEntries(
PERSISTED_INFERENCE_PARAM_KEYS.map((key) => [key, 0]),
) as Record<PersistedInferenceParamKey, number>;
@@ -2704,17 +2738,13 @@ function backfillMirroredSettings(settings: PersistedChatSettings): void {
if (hasKeys(patch)) saveSettingsPatch(patch);
}
-function setInferenceParam(
- params: InferenceParams,
- key: PersistedInferenceParamKey,
- value: PersistedInferenceParams[PersistedInferenceParamKey],
-): void {
- (params as Record<PersistedInferenceParamKey, unknown>)[key] = value;
-}
-
+/** `bumpVersions` fences the moved keys against a hydration response in flight.
+ * A model's own defaults do not get that: they must not outrank the settings the
+ * user saved for it. */
function getChangedInferenceParams(
nextParams: InferenceParams,
currentParams: InferenceParams,
+ bumpVersions = true,
): PersistedInferenceParams {
const changedParams: PersistedInferenceParams = {};
for (const key of PERSISTED_INFERENCE_PARAM_KEYS) {
@@ -2722,7 +2752,9 @@ function getChangedInferenceParams(
if (Object.is(nextValue, currentParams[key])) {
continue;
}
- inferenceParamMutationVersions[key] += 1;
+ if (bumpVersions) {
+ inferenceParamMutationVersions[key] += 1;
+ }
if (nextValue !== undefined) {
setInferenceParam(changedParams as InferenceParams, key, nextValue);
}
@@ -2730,6 +2762,135 @@ function getChangedInferenceParams(
return changedParams;
}
+/** Bump the hydration versions for the replayed keys and mirror them into the
+ * global set, so a reload lands on this model's settings. */
+function persistReplayedParams(
+ state: ChatRuntimeStore,
+ nextParams: InferenceParams,
+ replayed: boolean,
+): void {
+ if (!replayed) {
+ return;
+ }
+ const changed = getChangedInferenceParams(nextParams, state.params);
+ if (state.settingsHydrated && hasKeys(changed)) {
+ saveSettingsPatch({ inferenceParams: changed });
+ }
+}
+
+/** Same fence as the inference-param versions, recorded per model so only the
+ * edited one is protected. Before hydration the params are placeholders, so
+ * nothing is recorded. */
+function trackParamsByModel(
+ state: ChatRuntimeStore,
+ paramsByModel: Record<string, PersistedInferenceParams> | null,
+ modelId: string | undefined,
+): Record<string, PersistedInferenceParams> | null {
+ if (!state.settingsHydrated) {
+ return null;
+ }
+ if (paramsByModel && modelId) {
+ locallyRememberedModels.add(modelId);
+ }
+ return paramsByModel;
+}
+
+/** State a model switch owes to the memory: the outgoing model's snapshot. */
+function getReplayStatePatch(
+ state: ChatRuntimeStore,
+ nextParams: InferenceParams,
+ outgoing: Record<string, PersistedInferenceParams> | null,
+ baseParams: InferenceParams,
+): Partial<ChatRuntimeStore> {
+ persistReplayedParams(state, nextParams, baseParams !== state.params);
+ return outgoing ? { paramsByModel: outgoing } : {};
+}
+
+/** The map after a setParams call, falling back to the outgoing snapshot. A
+ * non-persisting update (a background load) must not rewrite durable memory.
+ *
+ * Only an edit is recorded: defaults are not settings the model was used with,
+ * and staged load params describe the model about to load. Both are picked up
+ * by the snapshot taken when the model is left. */
+function getParamsByModelAfterEdit(
+ state: ChatRuntimeStore,
+ outgoing: Record<string, PersistedInferenceParams> | null,
+ nextParams: InferenceParams,
+ changedParams: PersistedInferenceParams,
+ persist: boolean,
+): Record<string, PersistedInferenceParams> | null {
+ if (!persist) {
+ return outgoing;
+ }
+ const recorded = trackParamsByModel(
+ state,
+ getRememberedParamsPatch(
+ state.rememberParamsPerModel,
+ outgoing ?? state.paramsByModel,
+ nextParams.checkpoint,
+ changedParams,
+ pickRememberedParams(nextParams),
+ ),
+ nextParams.checkpoint,
+ );
+ return recorded ?? outgoing;
+}
+
+/** Snapshot the model being switched away from, so a model that was never edited
+ * still keeps what it ran with. */
+function rememberOutgoingModel(
+ state: ChatRuntimeStore,
+ outgoing: InferenceParams,
+): Record<string, PersistedInferenceParams> | null {
+ if (!state.settingsHydrated && outgoing.checkpoint) {
+ modelLeftBeforeHydration = outgoing.checkpoint;
+ }
+ const snapshot = pickRememberedParams(outgoing);
+ // Only to seed a model with no entry: later changes are written key by key by
+ // the edit that made them, and a full snapshot would put this browser's copy
+ // of untouched keys over another tab's.
+ const seeding = state.paramsByModel[outgoing.checkpoint] === undefined;
+ const next = trackParamsByModel(
+ state,
+ getRememberedParamsPatch(
+ state.rememberParamsPerModel,
+ state.paramsByModel,
+ outgoing.checkpoint,
+ snapshot,
+ snapshot,
+ ),
+ outgoing.checkpoint,
+ );
+ // A full snapshot rewrites every field, so send one only when this browser has
+ // something to say: an edit made here, or an entry that does not exist yet.
+ if (next && state.settingsHydrated && outgoing.checkpoint && seeding) {
+ saveSettingsPatch({
+ inferenceParamsByModel: { [outgoing.checkpoint]: snapshot },
+ });
+ }
+ return next;
+}
+
+/** Write an edit to the global set, and to the selected model's own set. */
+function persistParamEdit(
+ changedParams: PersistedInferenceParams,
+ paramsByModel: Record<string, PersistedInferenceParams> | null,
+ modelId: string | undefined,
+): void {
+ if (!hasKeys(changedParams)) {
+ return;
+ }
+ // Only what moved: the server merges per key, so sending the rest would put
+ // this browser's copy of every other key over another tab's.
+ const rememberedChanges = pickRememberedChanges(changedParams);
+ saveSettingsPatch({
+ inferenceParams: changedParams,
+ ...(paramsByModel && modelId && hasKeys(rememberedChanges)
+ ? { inferenceParamsByModel: { [modelId]: rememberedChanges } }
+ : {}),
+ });
+}
+
function getHydratedCustomPresets(
settings: PersistedChatSettings,
state: ChatRuntimeStore,
@@ -2779,6 +2940,61 @@ function getHydratedPresetState(
return nextState;
}
+/** Keys the user moved while the request was in flight: the same fence, read the
+ * other way round. */
+function pickLocallyEditedParams(
+ params: InferenceParams,
+ versions: SettingsHydrationVersions,
+): PersistedInferenceParams {
+ const edited: PersistedInferenceParams = {};
+ for (const key of REMEMBERED_INFERENCE_PARAM_KEYS) {
+ if (inferenceParamMutationVersions[key] !== versions.inferenceParams[key]) {
+ setInferenceParam(edited as InferenceParams, key, params[key]);
+ }
+ }
+ return edited;
+}
+
+/** The context the last load or status published for the model on screen.
+ * ggufContextLength covers only GGUF, so without this a safetensors model has
+ * nothing to clamp the hydration replay against. Keyed by checkpoint. */
+let loadedContext: { checkpoint: string; cap: number } | null = null;
+
+function noteLoadedContext(checkpoint: string, cap: number | undefined): void {
+ if (cap !== undefined) {
+ loadedContext = { checkpoint, cap };
+ }
+}
+
+function loadedContextFor(checkpoint: string): number | null {
+ return loadedContext?.checkpoint === checkpoint ? loadedContext.cap : null;
+}
+
+/** A model that took over from another while the request was in flight. Its
+ * defaults lose to its own entry but outrank the global set, which belongs to
+ * whichever model was used last. Not narrowed to the keys that moved. */
+let modelLoadedBeforeHydration: string | null = null;
+
+/** A model stepped off before hydration. Nothing can be filed for it yet, but the
+ * global set the response will deliver is what it ran with, so this says which
+ * model to file that under. */
+let modelLeftBeforeHydration: string | null = null;
+
+function noteModelDefaultsBeforeHydration(
+ checkpoint: string,
+ replacedAnotherModel: boolean,
+): void {
+ if (replacedAnotherModel) {
+ modelLoadedBeforeHydration = checkpoint;
+ return;
+ }
+ // The model already resident at startup is the one the saved global set
+ // describes, so its defaults must not stand in front of it.
+ if (modelLoadedBeforeHydration !== checkpoint) {
+ modelLoadedBeforeHydration = null;
+ }
+}
+
/**
* Whether the active checkpoint is an external model that cannot run deep
* research, matching the composer's own rule. An unresolved provider is left
@@ -2818,17 +3034,94 @@ function getHydratedSettingsState(
versions: SettingsHydrationVersions,
): Partial<ChatRuntimeStore> {
const nextState: Partial<ChatRuntimeStore> = {};
+ const checkpoint = state.params.checkpoint;
+ const loadedBeforeHydration = modelLoadedBeforeHydration === checkpoint;
+ modelLoadedBeforeHydration = null;
+ // The toggle as it will read once this response lands, under the same fence
+ // the scalar loop below applies.
+ const remembersPerModel =
+ settings.rememberParamsPerModel !== undefined &&
+ scalarSettingMutationVersions.rememberParamsPerModel ===
+ versions.scalarSettings.rememberParamsPerModel
+ ? settings.rememberParamsPerModel
+ : state.rememberParamsPerModel;
+ // A model loaded mid-flight has no entry to restore its defaults from, so the
+ // global set would overwrite them with the last model's. Only while the memory
+ // is on: with it off that global set IS this model's settings.
+ const keepModelDefaults =
+ remembersPerModel &&
+ loadedBeforeHydration &&
+ settings.inferenceParamsByModel?.[checkpoint] === undefined;
const params = { ...state.params };
for (const key of PERSISTED_INFERENCE_PARAM_KEYS) {
const value = settings.inferenceParams?.[key];
if (
value !== undefined &&
+ !keepModelDefaults &&
+ // The context belongs to the load, not to the previous model's global set,
+ // and no entry carries one for the replay below to put back.
+ !(loadedBeforeHydration && key === "maxSeqLength") &&
inferenceParamMutationVersions[key] === versions.inferenceParams[key]
) {
setInferenceParam(params, key, value);
}
}
nextState.params = params;
+ if (settings.inferenceParamsByModel !== undefined) {
+ const hydrated: Record<string, PersistedInferenceParams> = {};
+ for (const [modelId, entry] of Object.entries(
+ settings.inferenceParamsByModel,
+ )) {
+ // Stored as written: a gap is a key this model never pinned, and there is
+ // no honest value to invent. The replay lays the entry over what a load
+ // just published, which is where a gap belongs.
+ hydrated[modelId] = entry;
+ }
+ for (const modelId of locallyRememberedModels) {
+ const local = state.paramsByModel[modelId];
+ if (local) {
+ hydrated[modelId] = local;
+ }
+ }
+ // The entry arriving for this model predates the fenced edit, so lay the
+ // edit over it or the next defaults update replays the stale one.
+ if (checkpoint) {
+ const edited = pickLocallyEditedParams(params, versions);
+ if (hasKeys(edited)) {
+ hydrated[checkpoint] = { ...hydrated[checkpoint], ...edited };
+ }
+ }
+ nextState.paramsByModel = hydrated;
+ } else if (checkpoint) {
+ // No map in the response: an install upgraded from before this feature. With
+ // no entry the next defaults update has nothing to replay and puts the
+ // recommendation back over the fenced edit.
+ const edited = pickLocallyEditedParams(params, versions);
+ if (hasKeys(edited)) {
+ nextState.paramsByModel = {
+ ...state.paramsByModel,
+ [checkpoint]: { ...state.paramsByModel[checkpoint], ...edited },
+ };
+ }
+ }
+ // A model stepped off before this response landed could not be filed then, and
+ // the global set it ran with is only now known. Without this it has no entry,
+ // so switching back inherits whatever replaced it.
+ const left = modelLeftBeforeHydration;
+ modelLeftBeforeHydration = null;
+ const byModel = nextState.paramsByModel ?? state.paramsByModel;
+ if (remembersPerModel && left && left !== checkpoint && !byModel[left]) {
+ const inherited: PersistedInferenceParams = {};
+ for (const key of REMEMBERED_INFERENCE_PARAM_KEYS) {
+ const value = settings.inferenceParams?.[key];
+ if (value !== undefined) {
+ setInferenceParam(inherited as InferenceParams, key, value);
+ }
+ }
+ if (hasKeys(inherited)) {
+ nextState.paramsByModel = { ...byModel, [left]: inherited };
+ }
+ }
for (const key of SCALAR_SETTING_KEYS) {
const value = settings[key];
// Full access is session-only, so a stored level must not silently drop the
@@ -2889,6 +3182,44 @@ function getHydratedSettingsState(
(nextState as Record<ScalarSettingKey, unknown>)[key] = value;
}
}
+ // The model already selected when this lands never crossed a checkpoint
+ // transition, so nothing replayed its memory and it would run on the global
+ // set, which belongs to whichever model was used last.
+ const remembered = (nextState.paramsByModel ?? state.paramsByModel)[
+ params.checkpoint
+ ];
+ if (
+ (nextState.rememberParamsPerModel ?? state.rememberParamsPerModel) &&
+ remembered
+ ) {
+ // Same fence as the global set above: a key the user moved mid-flight is
+ // their edit. REMEMBERED, not PERSISTED, as in getReplayedParams: a
+ // maxSeqLength the row carries must not replace the loaded context.
+ const replayed = { ...params };
+ for (const key of REMEMBERED_INFERENCE_PARAM_KEYS) {
+ const value = remembered[key];
+ if (
+ value !== undefined &&
+ inferenceParamMutationVersions[key] === versions.inferenceParams[key]
+ ) {
+ setInferenceParam(replayed, key, value);
+ }
+ }
+ // The same cap the load and status replays apply.
+ nextState.params = replayed;
+ }
+ // Outside the replay: an install with only a global set has no entry, and the
+ // budget restored from it does not fit the load either.
+ const capped = nextState.params ?? params;
+ // ggufContextLength describes whatever is resident, which an external pick
+ // leaves loaded, so it is not this checkpoint's context to clamp against.
+ const residentGgufCap = isExternalModelId(checkpoint)
+ ? null
+ : state.ggufContextLength;
+ const cap = loadedContextFor(checkpoint) ?? residentGgufCap;
+ if (cap !== null && capped.maxTokens > cap) {
+ nextState.params = { ...capped, maxTokens: cap };
+ }
return nextState;
}
@@ -2920,6 +3251,9 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
? { ...DEFAULT_INFERENCE_PARAMS, checkpoint: persistedExternal }
: DEFAULT_INFERENCE_PARAMS;
})(),
+ paramsByModel: {},
+ // On by default; a model with nothing remembered keeps the current settings.
+ rememberParamsPerModel: true,
customPresets: [],
activePreset: "Default",
activePresetSource: getPresetSource("Default"),
@@ -3159,27 +3493,69 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
set({ modelRequiresTrustRemoteCode }),
setParams: (params, options) =>
set((state) => {
- // Bump version unconditionally so a late hydration response won't clobber
- // a pre-hydrate user edit; only the HTTP write is gated on settingsHydrated.
- const changedParams = getChangedInferenceParams(params, state.params);
+ // Mirror setCheckpoint: the local load path can mutate params.checkpoint
+ // via setParams() before setCheckpoint runs, leaving stale per-turn
+ // counters under the new checkpoint.
+ const checkpointChanged = state.params.checkpoint !== params.checkpoint;
+ const fromModelDefaults = options?.fromModelDefaults === true;
+ // Remember what the outgoing model was running with before replacing it.
+ const outgoing = checkpointChanged
+ ? rememberOutgoingModel(state, state.params)
+ : null;
+ // An interactive local load lands here with the destination checkpoint and
+ // the backend's recommended params, and only reaches setCheckpoint later,
+ // once params.checkpoint already matches. Replay here or that switch, the
+ // common one, never restores the model's own settings. fromModelDefaults
+ // marks the updates that re-apply model defaults after a load or a status
+ // poll: they overwrite remembered values, so memory goes back over them.
+ noteLoadedContext(params.checkpoint, options?.maxTokensCap);
+ const nextParams = getReplayedParams(
+ state.rememberParamsPerModel,
+ outgoing ?? state.paramsByModel,
+ params,
+ params.checkpoint,
+ checkpointChanged || fromModelDefaults,
+ options?.maxTokensCap,
+ );
+ // A user edit fences the keys it moved against a hydration response still
+ // in flight; only the HTTP write is gated on settingsHydrated.
+ const changedParams = getChangedInferenceParams(
+ nextParams,
+ state.params,
+ !fromModelDefaults,
+ );
const queuedSettingsChanged = shouldAdvanceQueuedSettingsEpoch(
state.params,
- params,
+ nextParams,
options?.trackQueuedSettings !== false,
);
- if (
- options?.persist !== false &&
- state.settingsHydrated &&
- hasKeys(changedParams)
- ) {
- saveSettingsPatch({ inferenceParams: changedParams });
+ // An edit belongs to the model the params now describe, so a call that moves
+ // checkpoint and sliders at once files them under the destination.
+ const paramsByModel = getParamsByModelAfterEdit(
+ state,
+ outgoing,
+ nextParams,
+ changedParams,
+ options?.persist !== false && !fromModelDefaults,
+ );
+ if (options?.persist !== false && state.settingsHydrated) {
+ // A switch replays the destination's entry over the params, so writing
+ // it back says nothing new and, merged per key on the server, would put
+ // this browser's copy over one another tab has since changed.
+ persistParamEdit(
+ changedParams,
+ checkpointChanged ? null : paramsByModel,
+ nextParams.checkpoint,
+ );
+ } else if (fromModelDefaults && !state.settingsHydrated) {
+ noteModelDefaultsBeforeHydration(
+ nextParams.checkpoint,
+ checkpointChanged && state.params.checkpoint !== "",
+ );
}
- // Mirror setCheckpoint: the local load path can mutate params.checkpoint
- // via setParams() before setCheckpoint runs, leaving stale per-turn
- // counters under the new checkpoint.
- const checkpointChanged = state.params.checkpoint !== params.checkpoint;
return {
- params,
+ params: nextParams,
+ ...(paramsByModel ? { paramsByModel } : {}),
...(queuedSettingsChanged
? { queuedSettingsEpoch: state.queuedSettingsEpoch + 1 }
: {}),
@@ -3360,10 +3736,25 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
// Clear stale per-turn usage on model change; the relaxed external-provider
// render gate would otherwise show old counters until the next completion.
const checkpointChanged = state.params.checkpoint !== modelId;
+ // Remember what the outgoing model was running with before replacing it.
+ // Not for a restore: the model it steps off is the one a background load
+ // put there, and its load defaults are not settings the user chose.
+ const outgoing =
+ checkpointChanged && options?.persist !== false
+ ? rememberOutgoingModel(state, state.params)
+ : null;
+ const baseParams = getReplayedParams(
+ state.rememberParamsPerModel,
+ outgoing ?? state.paramsByModel,
+ state.params,
+ modelId,
+ checkpointChanged,
+ options?.maxTokensCap,
+ );
// Clamp maxTokens to the new model's cap when switching into an external
// model so a value carried over from a local session doesn't exceed the
// slider's max.
- let nextMaxTokens = state.params.maxTokens;
+ let nextMaxTokens = baseParams.maxTokens;
if (checkpointChanged && isExternalModelId(modelId)) {
const parsed = parseExternalModelId(modelId);
const provider = parsed
@@ -3404,12 +3795,14 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
},
options?.trackQueuedSettings !== false,
);
+ const nextParams = {
+ ...baseParams,
+ checkpoint: modelId,
+ maxTokens: nextMaxTokens,
+ };
return {
- params: {
- ...state.params,
- checkpoint: modelId,
- maxTokens: nextMaxTokens,
- },
+ params: nextParams,
+ ...getReplayStatePatch(state, nextParams, outgoing, baseParams),
activeGgufVariant: nextGgufVariant,
...(queuedSettingsChanged
? { queuedSettingsEpoch: state.queuedSettingsEpoch + 1 }
@@ -3607,6 +4000,12 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
saveBool(CHAT_DEEP_RESEARCH_ENABLED_KEY, false);
return set((state) => ({
queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
+ // An unload leaves the model the same way a switch does, so record what it
+ // was running with.
+ ...(() => {
+ const outgoing = rememberOutgoingModel(state, state.params);
+ return outgoing ? { paramsByModel: outgoing } : {};
+ })(),
params: {
...state.params,
checkpoint: "",
@@ -3985,6 +4384,46 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
queuedSettingsEpoch: state.queuedSettingsEpoch + 1,
};
}),
+ setRememberParamsPerModel: (rememberParamsPerModel) =>
+ set((state) => {
+ setScalarSettingVersion(
+ "rememberParamsPerModel",
+ rememberParamsPerModel,
+ state.rememberParamsPerModel,
+ );
+ // Turning it on adopts the settings on screen for the active model.
+ const snapshot = pickRememberedParams(state.params);
+ const paramsByModel = trackParamsByModel(
+ state,
+ getRememberedParamsPatch(
+ rememberParamsPerModel,
+ state.paramsByModel,
+ state.params.checkpoint,
+ snapshot,
+ snapshot,
+ ),
+ state.params.checkpoint,
+ );
+ // Turning it on is an explicit statement about the model on screen, so the
+ // whole snapshot is what it means, not a key-by-key patch.
+ if (paramsByModel && state.settingsHydrated && state.params.checkpoint) {
+ saveSettingsPatch({
+ inferenceParamsByModel: {
+ [state.params.checkpoint]: paramsByModel[state.params.checkpoint],
+ },
+ });
+ }
+ // Turning it off makes the settings on screen the one shared set. The
+ // global set can still be the last model's, so write it or the next launch
+ // restores that instead.
+ if (!rememberParamsPerModel && state.settingsHydrated) {
+ saveSettingsPatch({ inferenceParams: snapshot });
+ }
+ return {
+ rememberParamsPerModel,
+ ...(paramsByModel ? { paramsByModel } : {}),
+ };
+ }),
setRagSource: (ragSource) =>
set((state) => {
saveRagSource(ragSource);
diff --git a/studio/frontend/src/features/chat/types/runtime.ts b/studio/frontend/src/features/chat/types/runtime.ts
index 1021e461b6e..76f67e370c0 100644
--- a/studio/frontend/src/features/chat/types/runtime.ts
+++ b/studio/frontend/src/features/chat/types/runtime.ts
@@ -23,6 +23,12 @@ export interface InferenceParams {
fastMode?: boolean;
}
+/** The params that survive a reload. `checkpoint` names the model rather than
+ * being one of its settings, so it is not one of them. */
+export type PersistedInferenceParams = Partial<
+ Omit<InferenceParams, "checkpoint">
+>;
+
export const DEFAULT_INFERENCE_PARAMS: InferenceParams = {
temperature: 0.6,
topP: 0.95,
diff --git a/studio/frontend/src/features/chat/utils/chat-settings-storage.ts b/studio/frontend/src/features/chat/utils/chat-settings-storage.ts
index c157db9f37f..09c43beb035 100644
--- a/studio/frontend/src/features/chat/utils/chat-settings-storage.ts
+++ b/studio/frontend/src/features/chat/utils/chat-settings-storage.ts
@@ -156,6 +156,23 @@ function sanitizeInferenceParams(
return hasKeys(params) ? params : undefined;
}
+// Not capped. The server merge never removes keys and keeps an existing key in
+// its original position, so a load-time trim would permanently hide the oldest
+// entries: editing one of those models would write an update that the next
+// reload silently drops again. Entries are a dozen numbers each.
+function sanitizeInferenceParamsByModel(
+ value: unknown,
+): Record<string, PersistedInferenceParams> | undefined {
+ if (!isRecord(value)) return undefined;
+ const byModel: Record<string, PersistedInferenceParams> = {};
+ for (const [modelId, params] of Object.entries(value)) {
+ if (!modelId) continue;
+ const sanitized = sanitizeInferenceParams(params);
+ if (sanitized) byModel[modelId] = sanitized;
+ }
+ return hasKeys(byModel) ? byModel : undefined;
+}
+
function toFullPreset(preset: PersistedChatPreset): Preset {
const loadConfig = normalizePresetLoadConfig(preset.loadConfig);
return {
@@ -227,6 +244,10 @@ function sanitizeChatSettings(value: unknown): PersistedChatSettings {
const settings: PersistedChatSettings = {};
const inferenceParams = sanitizeInferenceParams(value.inferenceParams);
+ const inferenceParamsByModel = sanitizeInferenceParamsByModel(
+ value.inferenceParamsByModel,
+ );
+ const rememberParamsPerModel = sanitizeBool(value.rememberParamsPerModel);
const customPresets = sanitizeCustomPresets(value.customPresets);
const activePresetSource = sanitizePresetSource(value.activePresetSource);
const reasoningEffort = sanitizeReasoningEffort(value.reasoningEffort);
@@ -242,6 +263,12 @@ function sanitizeChatSettings(value: unknown): PersistedChatSettings {
const toolCallTimeout = sanitizeInt(value.toolCallTimeout, 1);
if (inferenceParams) settings.inferenceParams = inferenceParams;
+ if (inferenceParamsByModel) {
+ settings.inferenceParamsByModel = inferenceParamsByModel;
+ }
+ if (rememberParamsPerModel !== undefined) {
+ settings.rememberParamsPerModel = rememberParamsPerModel;
+ }
if (customPresets !== undefined) settings.customPresets = customPresets;
if (typeof value.activePreset === "string" && value.activePreset.trim()) {
settings.activePreset = value.activePreset.trim();
@@ -315,6 +342,8 @@ function loadLegacySystemPromptPresets(
export function isEmptyChatSettings(settings: PersistedChatSettings): boolean {
return (
(!settings.inferenceParams || !hasKeys(settings.inferenceParams)) &&
+ settings.inferenceParamsByModel === undefined &&
+ settings.rememberParamsPerModel === undefined &&
settings.customPresets === undefined &&
settings.activePreset === undefined &&
settings.activePresetSource === undefined &&
diff --git a/studio/frontend/src/features/settings/settings-search.ts b/studio/frontend/src/features/settings/settings-search.ts
index 40035a1b7ed..cc4d46c0a2a 100644
--- a/studio/frontend/src/features/settings/settings-search.ts
+++ b/studio/frontend/src/features/settings/settings-search.ts
@@ -91,6 +91,7 @@ export const SETTINGS_SEARCH_INDEX: Record<SettingsTab, TranslationKey[]> = {
chat: [
"settings.general.chatDefaults",
"settings.general.autoTitleNewChats",
+ "settings.chat.rememberParamsPerModel",
"settings.profile.greetingSloth",
"settings.chat.thinking.collapseByDefault",
"settings.chat.artifacts.title",
diff --git a/studio/frontend/src/features/settings/tabs/chat-tab.tsx b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
index 8fd1b7da53c..2ca0f1f5a8e 100644
--- a/studio/frontend/src/features/settings/tabs/chat-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/chat-tab.tsx
@@ -133,6 +133,12 @@ export function ChatTab() {
const togglePlusPin = usePlusMenuPrefsStore((state) => state.togglePin);
const autoTitle = useChatRuntimeStore((state) => state.autoTitle);
const setAutoTitle = useChatRuntimeStore((state) => state.setAutoTitle);
+ const rememberParamsPerModel = useChatRuntimeStore(
+ (state) => state.rememberParamsPerModel,
+ );
+ const setRememberParamsPerModel = useChatRuntimeStore(
+ (state) => state.setRememberParamsPerModel,
+ );
const showGreetingSloth = useUserProfileStore((s) => s.showGreetingSloth);
const setShowGreetingSloth = useUserProfileStore(
(s) => s.setShowGreetingSloth,
@@ -303,6 +309,15 @@ export function ChatTab() {
>
<Switch checked={autoTitle} onCheckedChange={setAutoTitle} />
</SettingsRow>
+ <SettingsRow
+ label={t("settings.chat.rememberParamsPerModel")}
+ description={t("settings.chat.rememberParamsPerModelDescription")}
+ >
+ <Switch
+ checked={rememberParamsPerModel}
+ onCheckedChange={setRememberParamsPerModel}
+ />
+ </SettingsRow>
<SettingsRow
label={t("settings.chat.pastedTextThreshold")}
description={t("settings.chat.pastedTextThresholdDescription")}
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index 683a4b882d6..1ab0d104b9b 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -1012,6 +1012,9 @@ export const ar = {
modelDisclaimer: "إظهار إخلاء مسؤولية النموذج",
modelDisclaimerDescription:
'إظهار عبارة "LLMs can make mistakes" أسفل مربع المحادثة.',
+ rememberParamsPerModel: "تذكر الإعدادات لكل نموذج",
+ rememberParamsPerModelDescription:
+ "عند تبديل النموذج تُستعاد درجة الحرارة والموجّه وبقية الإعدادات التي استخدمتها آخر مرة مع ذلك النموذج. عند الإيقاف تبقى مجموعة إعدادات واحدة لكل النماذج.",
thinking: {
collapseByDefault: "طيّ التفكير افتراضيًا",
collapseByDefaultDescription:
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 5ab914f8646..098f65ff92f 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -1047,6 +1047,9 @@ export const de = {
modelDisclaimer: "Modell-Hinweis anzeigen",
modelDisclaimerDescription:
"Zeigt „LLMs können Fehler machen“ unter dem Chatfeld an.",
+ rememberParamsPerModel: "Einstellungen pro Modell merken",
+ rememberParamsPerModelDescription:
+ "Beim Modellwechsel werden Temperatur, Prompt und die weiteren Einstellungen wiederhergestellt, die Sie zuletzt mit diesem Modell verwendet haben. Aus: ein Satz Einstellungen für alle Modelle.",
thinking: {
collapseByDefault: "Denken standardmäßig einklappen",
collapseByDefaultDescription:
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index 69f06b71a95..ad0c49f32ac 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -1008,6 +1008,9 @@ export const en = {
modelDisclaimer: "Show model disclaimer",
modelDisclaimerDescription:
'Show "LLMs can make mistakes" under the chat box.',
+ rememberParamsPerModel: "Remember settings per model",
+ rememberParamsPerModelDescription:
+ "Switching models restores the temperature, prompt and other settings you last used with that model. Off keeps one set of settings for every model.",
thinking: {
collapseByDefault: "Collapse Thinking by default",
collapseByDefaultDescription:
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 3c6e9592a7a..d4124030c46 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -1038,6 +1038,9 @@ export const es = {
modelDisclaimer: "Mostrar aviso del modelo",
modelDisclaimerDescription:
'Muestra "Los LLM pueden cometer errores" bajo el cuadro de chat.',
+ rememberParamsPerModel: "Recordar los ajustes por modelo",
+ rememberParamsPerModelDescription:
+ "Al cambiar de modelo se restauran la temperatura, el prompt y los demás ajustes que usaste por última vez con ese modelo. Desactivado, se mantiene un único conjunto de ajustes para todos los modelos.",
thinking: {
collapseByDefault: "Contraer el razonamiento de forma predeterminada",
collapseByDefaultDescription:
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 1ae1d4dde1a..452c9588fa5 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -1044,6 +1044,9 @@ export const fr = {
modelDisclaimer: "Afficher l'avertissement du modèle",
modelDisclaimerDescription:
'Afficher "Les LLM peuvent faire des erreurs" sous la zone de discussion.',
+ rememberParamsPerModel: "Mémoriser les réglages par modèle",
+ rememberParamsPerModelDescription:
+ "Changer de modèle restaure la température, le prompt et les autres réglages utilisés en dernier avec ce modèle. Désactivé, un seul jeu de réglages s'applique à tous les modèles.",
thinking: {
collapseByDefault: "Replier la réflexion par défaut",
collapseByDefaultDescription:
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index fa0d0a805a5..846374ed1d1 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -1018,6 +1018,9 @@ export const hi = {
modelDisclaimer: "मॉडल अस्वीकरण दिखाएं",
modelDisclaimerDescription:
'चैट बॉक्स के नीचे "LLMs can make mistakes" दिखाएं।',
+ rememberParamsPerModel: "हर मॉडल के लिए सेटिंग्स याद रखें",
+ rememberParamsPerModelDescription:
+ "मॉडल बदलने पर उस मॉडल के साथ आपने आखिरी बार जो तापमान, प्रॉम्प्ट और अन्य सेटिंग्स इस्तेमाल की थीं, वे वापस आ जाती हैं। बंद होने पर सभी मॉडलों के लिए एक ही सेट रहता है।",
thinking: {
collapseByDefault: "थिंकिंग को डिफ़ॉल्ट रूप से संक्षिप्त रखें",
collapseByDefaultDescription:
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 690eec2afda..d1d9dde222e 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -1012,6 +1012,9 @@ export const it = {
modelDisclaimer: "Mostra l'avviso sul modello",
modelDisclaimerDescription:
"Mostra «Gli LLM possono commettere errori» sotto il campo della chat.",
+ rememberParamsPerModel: "Ricorda le impostazioni per modello",
+ rememberParamsPerModelDescription:
+ "Cambiando modello vengono ripristinati temperatura, prompt e le altre impostazioni usate l'ultima volta con quel modello. Disattivato, resta un unico set di impostazioni per tutti i modelli.",
thinking: {
collapseByDefault: "Comprimi il ragionamento per impostazione predefinita",
collapseByDefaultDescription:
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index 2db819fb98b..d251ac0af82 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -1000,6 +1000,9 @@ export const ja = {
"アシスタントの応答にモデルのメタデータを表示します。",
modelDisclaimer: "モデルの免責事項を表示",
modelDisclaimerDescription: 'チャットボックスの下に "LLMs can make mistakes" と表示します。',
+ rememberParamsPerModel: "モデルごとに設定を記憶",
+ rememberParamsPerModelDescription:
+ "モデルを切り替えると、そのモデルで最後に使った温度やプロンプトなどの設定が復元されます。オフの場合は、すべてのモデルで同じ設定を使います。",
thinking: {
collapseByDefault: "思考をデフォルトで折りたたむ",
collapseByDefaultDescription:
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 1013b257955..c215d0c1761 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -1010,6 +1010,9 @@ export const ko = {
modelDisclaimer: "모델 고지 표시",
modelDisclaimerDescription:
'채팅 상자 아래에 "LLMs can make mistakes" 문구를 표시합니다.',
+ rememberParamsPerModel: "모델별로 설정 기억",
+ rememberParamsPerModelDescription:
+ "모델을 전환하면 해당 모델에서 마지막으로 사용한 온도, 프롬프트 등의 설정이 복원됩니다. 끄면 모든 모델이 하나의 설정을 공유합니다.",
thinking: {
collapseByDefault: "기본적으로 사고 과정 접기",
collapseByDefaultDescription:
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index ba95cdb1592..1e08e0b5fc6 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -1026,6 +1026,9 @@ export const ptBR = {
modelDisclaimer: "Mostrar aviso do modelo",
modelDisclaimerDescription:
'Mostra "LLMs podem cometer erros" abaixo da caixa de chat.',
+ rememberParamsPerModel: "Lembrar as configurações por modelo",
+ rememberParamsPerModelDescription:
+ "Ao trocar de modelo, a temperatura, o prompt e as demais configurações usadas por último com aquele modelo são restauradas. Desativado, um único conjunto de configurações vale para todos os modelos.",
thinking: {
collapseByDefault: "Recolher o raciocínio por padrão",
collapseByDefaultDescription:
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index 39729fed76b..9cfd9defec9 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -1023,6 +1023,9 @@ export const ru = {
modelDisclaimer: "Показывать предупреждение о модели",
modelDisclaimerDescription:
"Показывать сообщение «LLM могут ошибаться» под полем ввода.",
+ rememberParamsPerModel: "Запоминать настройки для каждой модели",
+ rememberParamsPerModelDescription:
+ "При переключении модели восстанавливаются температура, промпт и другие настройки, которые вы использовали с ней в последний раз. Если выключено, для всех моделей действует один набор настроек.",
thinking: {
collapseByDefault: "Сворачивать размышления по умолчанию",
collapseByDefaultDescription:
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 7431ca26f4e..11db3e73a25 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -987,6 +987,9 @@ export const zhCN = {
modelDisclaimer: "显示模型免责声明",
modelDisclaimerDescription:
"在聊天框下方显示“LLM 可能会出错”。",
+ rememberParamsPerModel: "按模型记住设置",
+ rememberParamsPerModelDescription:
+ "切换模型时会恢复你上次在该模型上使用的温度、提示词等设置。关闭后,所有模型共用一套设置。",
thinking: {
collapseByDefault: "默认折叠思考过程",
collapseByDefaultDescription:
diff --git a/studio/frontend/tests/helpers/kit.ts b/studio/frontend/tests/helpers/kit.ts
index 2892266e76d..f1174c9de90 100644
--- a/studio/frontend/tests/helpers/kit.ts
+++ b/studio/frontend/tests/helpers/kit.ts
@@ -63,6 +63,13 @@ export function installLocalStorageFake(): {
listeners.get(type)?.delete(fn);
},
},
+ // A window implies a document: code guarded on `typeof window` reaches for
+ // one, and a fake without it is a browser no browser ever is.
+ document: {
+ visibilityState: "visible",
+ addEventListener: () => undefined,
+ removeEventListener: () => undefined,
+ },
localStorage: storage,
});
return {
diff --git a/studio/frontend/tests/helpers/store-stubs/model-picker.ts b/studio/frontend/tests/helpers/store-stubs/model-picker.ts
new file mode 100644
index 00000000000..a53900604b4
--- /dev/null
+++ b/studio/frontend/tests/helpers/store-stubs/model-picker.ts
@@ -0,0 +1,14 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The picker barrel reaches the whole chat UI; the store only needs these three.
+
+export function applyPerModelConfigToRuntime(): void {}
+
+export function currentRuntimePerModelConfig(): Record<string, unknown> {
+ return {};
+}
+
+export function perModelConfigsEqual(): boolean {
+ return true;
+}
diff --git a/studio/frontend/tests/helpers/store-stubs/settings-http.ts b/studio/frontend/tests/helpers/store-stubs/settings-http.ts
new file mode 100644
index 00000000000..f2ce1267f97
--- /dev/null
+++ b/studio/frontend/tests/helpers/store-stubs/settings-http.ts
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// A chat-settings endpoint a test can hold open, so it can act while hydration
+// is still in flight. `puts` records what the store wrote back.
+
+export const settingsHttp = {
+ settings: {} as Record<string, unknown>,
+ puts: [] as Record<string, unknown>[],
+ /** Resolve to let a held GET complete. */
+ release: null as (() => void) | null,
+ hold(): void {
+ settingsHttp.gate = new Promise<void>((resolve) => {
+ settingsHttp.release = resolve;
+ });
+ },
+ gate: null as Promise<void> | null,
+};
+
+export async function authFetch(
+ _url: string,
+ init?: { method?: string; body?: string },
+): Promise<Response> {
+ if (init?.method === "PUT") {
+ settingsHttp.puts.push(JSON.parse(init.body ?? "{}"));
+ } else if (settingsHttp.gate) {
+ await settingsHttp.gate;
+ }
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({ settings: settingsHttp.settings }),
+ } as Response;
+}
diff --git a/studio/frontend/tests/per-model-params-hydration-max-seq-length.test.ts b/studio/frontend/tests/per-model-params-hydration-max-seq-length.test.ts
new file mode 100644
index 00000000000..51bbf3346dc
--- /dev/null
+++ b/studio/frontend/tests/per-model-params-hydration-max-seq-length.test.ts
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The hydration replay is a second copy of the replay rules, so it needs its own
+// guard. Its own file: per-model-params-hydration.test.ts shares store state
+// across its tests, and an appended case picks up an earlier one's temperature.
+
+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 QWEN = "unsloth/Qwen3.5-9B-GGUF";
+
+test("hydration does not replay a maxSeqLength an entry happens to carry", async () => {
+ // maxSeqLength is persisted but never remembered: the context belongs to the
+ // load config. This app writes none into an entry, but the row accepts one.
+ settingsHttp.settings = {
+ inferenceParamsByModel: {
+ [QWEN]: { temperature: 0.2, maxSeqLength: 131072 },
+ },
+ };
+ useChatRuntimeStore.setState({
+ params: {
+ ...useChatRuntimeStore.getState().params,
+ checkpoint: QWEN,
+ maxSeqLength: 4096,
+ },
+ });
+
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ const { params } = useChatRuntimeStore.getState();
+ assert.equal(
+ params.temperature,
+ 0.2,
+ "the remembered temperature should still replay",
+ );
+ assert.equal(
+ params.maxSeqLength,
+ 4096,
+ "the loaded context must survive the hydration replay",
+ );
+});
diff --git a/studio/frontend/tests/per-model-params-hydration-races.test.ts b/studio/frontend/tests/per-model-params-hydration-races.test.ts
new file mode 100644
index 00000000000..8fd3eb2f289
--- /dev/null
+++ b/studio/frontend/tests/per-model-params-hydration-races.test.ts
@@ -0,0 +1,213 @@
+// 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 races where the settings GET is still in flight. Own file: the other
+// hydration suite shares store state across its tests, so an appended case picks
+// up an earlier one's params.
+
+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 A = "unsloth/model-a";
+const B = "unsloth/model-b";
+const STATUS = {
+ inference: { temperature: 0.9 },
+ is_gguf: true,
+ context_length: 131072,
+} as never;
+
+/** Every field this file varies is set explicitly: the store is a module
+ * singleton, so a value left behind by an earlier test silently changes the
+ * next one's meaning. */
+function reset(
+ params: Record<string, unknown>,
+ rest: Record<string, unknown> = {},
+) {
+ useChatRuntimeStore.setState({
+ params: { ...useChatRuntimeStore.getState().params, ...params },
+ rememberParamsPerModel: true,
+ paramsByModel: {},
+ settingsHydrated: false,
+ ...rest,
+ });
+}
+
+test("with the memory off, the saved shared settings still reach a new model", async () => {
+ // keepModelDefaults exists so a model that loaded mid-flight is not handed the
+ // previous model's globals. With the memory OFF there is no previous model:
+ // the global set is the one set the user keeps for everything, and suppressing
+ // it strands the model on whatever the load happened to recommend.
+ settingsHttp.settings = {
+ rememberParamsPerModel: false,
+ inferenceParams: { temperature: 0.22, systemPrompt: "shared" },
+ };
+ reset({ checkpoint: A }, { rememberParamsPerModel: false });
+ settingsHttp.hold();
+ const hydrating = useChatRuntimeStore.getState().hydratePersistedSettings();
+ const s = useChatRuntimeStore.getState();
+ s.setParams(
+ mergeBackendRecommendedInference({
+ current: { ...s.params, checkpoint: B },
+ response: STATUS,
+ modelId: B,
+ presetSource: s.activePresetSource,
+ }),
+ { fromModelDefaults: true },
+ );
+ settingsHttp.release?.();
+ await hydrating;
+
+ const { params } = useChatRuntimeStore.getState();
+ assert.equal(params.temperature, 0.22);
+ assert.equal(params.systemPrompt, "shared");
+});
+
+test("a model that loaded mid-flight keeps its own context", async () => {
+ // The global maxSeqLength belongs to whichever model was used last. No entry
+ // ever carries one, so the replay cannot put the right value back after the
+ // global loop has overwritten it.
+ settingsHttp.settings = {
+ inferenceParams: { maxSeqLength: 131072, temperature: 0.9 },
+ inferenceParamsByModel: { [B]: { temperature: 0.2 } },
+ };
+ reset({ checkpoint: A, maxSeqLength: 131072 });
+ settingsHttp.hold();
+ const hydrating = useChatRuntimeStore.getState().hydratePersistedSettings();
+ const s = useChatRuntimeStore.getState();
+ s.setParams(
+ { ...s.params, checkpoint: B, maxSeqLength: 4096 },
+ { fromModelDefaults: true, maxTokensCap: 4096 },
+ );
+ settingsHttp.release?.();
+ await hydrating;
+
+ const { params } = useChatRuntimeStore.getState();
+ assert.equal(
+ params.maxSeqLength,
+ 4096,
+ "the loaded context survives hydration",
+ );
+ assert.equal(params.temperature, 0.2, "the entry still replays");
+});
+
+test("a pre-hydration edit survives on an install that has no model map", async () => {
+ // The upgrade path: settings written before this feature carry only
+ // inferenceParams. The edit is fenced out of the global set either way, but
+ // without an entry the next defaults update has nothing to replay and puts the
+ // backend recommendation back over it.
+ settingsHttp.settings = { inferenceParams: { temperature: 0.55 } };
+ reset({ checkpoint: A });
+ settingsHttp.hold();
+ const hydrating = useChatRuntimeStore.getState().hydratePersistedSettings();
+ const s = useChatRuntimeStore.getState();
+ s.setParams({ ...s.params, temperature: 0.11 });
+ settingsHttp.release?.();
+ await hydrating;
+ assert.equal(useChatRuntimeStore.getState().params.temperature, 0.11);
+
+ const s2 = useChatRuntimeStore.getState();
+ s2.setParams(
+ mergeBackendRecommendedInference({
+ current: s2.params,
+ response: STATUS,
+ modelId: A,
+ presetSource: s2.activePresetSource,
+ }),
+ { fromModelDefaults: true },
+ );
+ assert.equal(
+ useChatRuntimeStore.getState().params.temperature,
+ 0.11,
+ "the edit is not replaced by the backend recommendation",
+ );
+});
+
+test("setCheckpoint clamps a replayed budget to the context it is given", () => {
+ // Compare's ensureModelLoaded reaches the replay through setCheckpoint, which
+ // is the one switch path that had no way to pass the context it just loaded.
+ reset(
+ { checkpoint: "small", maxTokens: 2048 },
+ {
+ settingsHydrated: true,
+ rememberParamsPerModel: true,
+ paramsByModel: { big: { maxTokens: 131072 } },
+ },
+ );
+ useChatRuntimeStore
+ .getState()
+ .setCheckpoint("big", null, { maxTokensCap: 4096 });
+ assert.equal(useChatRuntimeStore.getState().params.maxTokens, 4096);
+});
+
+test("the loaded context caps the budget even with nothing remembered", () => {
+ // The cap describes the load, so it cannot be conditional on a replay: compare
+ // loading a fresh 8K model after a 32K one has no entry to replay and would
+ // otherwise send the 32K budget.
+ reset(
+ { checkpoint: "small", maxTokens: 32768 },
+ { settingsHydrated: true, paramsByModel: {} },
+ );
+ useChatRuntimeStore
+ .getState()
+ .setCheckpoint("fresh", null, { maxTokensCap: 8192 });
+ assert.equal(useChatRuntimeStore.getState().params.maxTokens, 8192);
+});
+
+test("the memory being off does not disable the loaded-context cap", () => {
+ reset(
+ { checkpoint: "small", maxTokens: 32768 },
+ {
+ settingsHydrated: true,
+ rememberParamsPerModel: false,
+ paramsByModel: {},
+ },
+ );
+ useChatRuntimeStore
+ .getState()
+ .setCheckpoint("fresh", null, { maxTokensCap: 8192 });
+ assert.equal(useChatRuntimeStore.getState().params.maxTokens, 8192);
+});
+
+test("a model left before hydration keeps the globals it was running with", async () => {
+ // The upgrade path again, from the other side: A is resident with only the
+ // legacy global set to its name, and B replaces it before the GET returns.
+ // Nothing could be filed for A at the time, so without this A ends up with no
+ // entry and switching back inherits B's settings.
+ settingsHttp.settings = {
+ inferenceParams: { temperature: 0.33, systemPrompt: "A's prompt" },
+ };
+ reset({ checkpoint: A });
+ settingsHttp.hold();
+ const hydrating = useChatRuntimeStore.getState().hydratePersistedSettings();
+ useChatRuntimeStore.getState().setParams(
+ {
+ ...useChatRuntimeStore.getState().params,
+ checkpoint: B,
+ temperature: 0.95,
+ systemPrompt: "B's prompt",
+ },
+ { fromModelDefaults: true },
+ );
+ settingsHttp.release?.();
+ await hydrating;
+
+ useChatRuntimeStore.getState().setCheckpoint(A, null);
+ const { params } = useChatRuntimeStore.getState();
+ assert.equal(params.temperature, 0.33);
+ assert.equal(params.systemPrompt, "A's prompt");
+});
diff --git a/studio/frontend/tests/per-model-params-hydration.test.ts b/studio/frontend/tests/per-model-params-hydration.test.ts
new file mode 100644
index 00000000000..419bb798eb6
--- /dev/null
+++ b/studio/frontend/tests/per-model-params-hydration.test.ts
@@ -0,0 +1,955 @@
+// 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 decides whether the per-model memory survives. The inference
+// status can land before the settings response, and the model it reports was
+// never switched to, so nothing replays its memory on its own. These drive the
+// real store through that order and through a steady-state poll.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import { register } from "node:module";
+import test from "node:test";
+
+import { installLocalStorageFake } from "./helpers/kit.ts";
+
+const { store: localStorageFake } = installLocalStorageFake();
+// Skip the legacy import path: it would look for settings this test never wrote.
+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.5-9B-GGUF";
+const LLAMA = "unsloth/Llama-4-8B";
+const EXTERNAL = "external::anthropic::claude-opus-5";
+const TUNED = { temperature: 0.2, maxTokens: 4096, systemPrompt: "Be terse." };
+
+/** A status response for a resident GGUF, recommending its own sampling. */
+const STATUS = {
+ inference: { temperature: 0.9, top_p: 0.5 },
+ is_gguf: true,
+ context_length: 131072,
+} as never;
+
+/** applyActiveModelStatusToStore's update, which the last test pins. */
+function applyStatus(modelId: string) {
+ const store = useChatRuntimeStore.getState();
+ store.setParams(
+ mergeBackendRecommendedInference({
+ current: store.params,
+ response: STATUS,
+ modelId,
+ presetSource: store.activePresetSource,
+ }),
+ { fromModelDefaults: true },
+ );
+}
+
+/** The debounced settings writer, flushed. */
+async function settled(): Promise<void> {
+ await new Promise((resolve) => setTimeout(resolve, 600));
+}
+
+test("a status response that beats hydration keeps the model's settings", async () => {
+ settingsHttp.settings = {
+ inferenceParams: TUNED,
+ inferenceParamsByModel: { [QWEN]: TUNED },
+ };
+ settingsHttp.hold();
+ const hydrating = useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ applyStatus(QWEN);
+ // Nothing is recorded before hydration: these params are the recommendation
+ // the backend just sent, not settings this model was used with.
+ assert.deepEqual(useChatRuntimeStore.getState().paramsByModel, {});
+
+ settingsHttp.release?.();
+ await hydrating;
+
+ const hydrated = useChatRuntimeStore.getState();
+ assert.deepEqual(
+ hydrated.paramsByModel[QWEN],
+ TUNED,
+ "the persisted entry is not fenced out by the status update",
+ );
+ // The status set the global params, and a model that was already resident
+ // never crosses a checkpoint transition, so hydration is the only replay.
+ assert.equal(hydrated.params.temperature, 0.2);
+ assert.equal(hydrated.params.maxTokens, 4096);
+ assert.equal(hydrated.params.systemPrompt, "Be terse.");
+ // Params this model never pinned still take the recommendation.
+ assert.equal(hydrated.params.topP, 0.5);
+
+ // The reported failure was durable: switching away wrote the recommendation
+ // over the tuning, so it was gone on the next launch too. Nothing is written
+ // now, this browser having only read the entry, so the stored tuning stands.
+ settingsHttp.puts.length = 0;
+ useChatRuntimeStore
+ .getState()
+ .setParams({ ...useChatRuntimeStore.getState().params, checkpoint: LLAMA });
+ await settled();
+ for (const put of settingsHttp.puts) {
+ assert.equal(
+ (put.inferenceParamsByModel as Record<string, unknown>)?.[QWEN],
+ undefined,
+ "the recommendation is not written over the tuning",
+ );
+ }
+ const held = useChatRuntimeStore.getState().paramsByModel[QWEN];
+ assert.equal(held?.temperature, 0.2, "the tuning this browser still holds");
+ assert.equal(held?.maxTokens, 4096);
+ assert.equal(held?.systemPrompt, "Be terse.");
+});
+
+// A status poll re-applies the recommendation on every refresh, so without
+// laying the memory back over it the tuning lasts only until the next poll.
+test("a status poll does not undo the model's remembered settings", () => {
+ useChatRuntimeStore.setState({
+ params: {
+ ...useChatRuntimeStore.getState().params,
+ checkpoint: QWEN,
+ temperature: 0.2,
+ },
+ paramsByModel: { [QWEN]: TUNED },
+ });
+
+ applyStatus(QWEN);
+
+ const after = useChatRuntimeStore.getState();
+ assert.equal(after.params.temperature, 0.2);
+ assert.equal(after.params.maxTokens, 4096);
+});
+
+// A model with nothing remembered must still take the recommendation, or the
+// memory would just be the old global set under a new name.
+test("a model with nothing remembered still takes the recommendation", () => {
+ useChatRuntimeStore.setState({
+ params: { ...useChatRuntimeStore.getState().params, checkpoint: LLAMA },
+ paramsByModel: {},
+ });
+
+ applyStatus(LLAMA);
+
+ assert.equal(useChatRuntimeStore.getState().params.temperature, 0.9);
+});
+
+// A pre-hydration edit is the user's, and the fence that protects it from the
+// hydrated global set has to protect it from the replay too.
+test("a pre-hydration edit outranks the replay", async () => {
+ settingsHttp.settings = {
+ inferenceParams: { temperature: 0.2, systemPrompt: "Be terse." },
+ inferenceParamsByModel: { [QWEN]: TUNED },
+ };
+ settingsHttp.hold();
+ useChatRuntimeStore.setState({
+ params: { ...useChatRuntimeStore.getState().params, checkpoint: QWEN },
+ paramsByModel: {},
+ // Hydration runs once per store, so re-arm it for a second startup.
+ settingsHydrated: false,
+ });
+ const hydrating = useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ const store = useChatRuntimeStore.getState();
+ store.setParams({ ...store.params, temperature: 0.85 });
+
+ settingsHttp.release?.();
+ await hydrating;
+
+ const params = useChatRuntimeStore.getState().params;
+ assert.equal(params.temperature, 0.85, "the slider the user just moved");
+ assert.equal(
+ params.systemPrompt,
+ "Be terse.",
+ "a key the user did not touch still replays",
+ );
+});
+
+// A stored entry can be partial: an older write, or a field that did not
+// survive sanitising. It is kept as written and the replay lays it over what
+// the load just published, which is where a gap belongs.
+test("a partial stored entry is neither filled nor borrowed from", async () => {
+ settingsHttp.settings = {
+ inferenceParams: { temperature: 0.5, topP: 0.9, systemPrompt: "saved" },
+ // Only one field, as an older client or a hand-written payload would leave it.
+ inferenceParamsByModel: { [QWEN]: { temperature: 0.15 } },
+ };
+ useChatRuntimeStore.setState({
+ params: {
+ ...useChatRuntimeStore.getState().params,
+ checkpoint: LLAMA,
+ topP: 0.11,
+ systemPrompt: "the other model's",
+ },
+ paramsByModel: {},
+ settingsHydrated: false,
+ });
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ assert.deepEqual(
+ useChatRuntimeStore.getState().paramsByModel[QWEN],
+ { temperature: 0.15 },
+ "stored as written, not grown with another model's settings",
+ );
+
+ // The load that follows publishes this model's own defaults, and the replay
+ // lays the entry over them.
+ const store = useChatRuntimeStore.getState();
+ store.setParams(
+ { ...store.params, checkpoint: QWEN, topP: 0.8, systemPrompt: "" },
+ { fromModelDefaults: true },
+ );
+
+ const params = useChatRuntimeStore.getState().params;
+ assert.equal(params.temperature, 0.15, "what the entry does hold");
+ assert.equal(params.topP, 0.8, "the gap takes this model's own default");
+ assert.equal(
+ params.systemPrompt,
+ "",
+ "not the prompt the previous model was using",
+ );
+});
+
+// The context belongs to the load config. A second copy recorded here is what
+// would later replay over the context the backend actually loaded.
+test("the context length is not part of what a model remembers", () => {
+ useChatRuntimeStore.setState({
+ params: {
+ ...useChatRuntimeStore.getState().params,
+ checkpoint: LLAMA,
+ maxSeqLength: 4096,
+ temperature: 0.33,
+ },
+ paramsByModel: {},
+ });
+
+ // applyPerModelConfigToRuntime, staging the context of the model about to
+ // load while the previous one is still current.
+ const staging = useChatRuntimeStore.getState();
+ staging.setParams({ ...staging.params, maxSeqLength: 32768 });
+ assert.deepEqual(
+ useChatRuntimeStore.getState().paramsByModel,
+ {},
+ "a context on its own is not an edit this remembers",
+ );
+
+ // The load lands and the checkpoint moves.
+ const switching = useChatRuntimeStore.getState();
+ switching.setParams(
+ { ...switching.params, checkpoint: QWEN },
+ { fromModelDefaults: true },
+ );
+
+ const remembered = useChatRuntimeStore.getState().paramsByModel[LLAMA];
+ assert.equal(remembered?.temperature, 0.33, "its sampling is remembered");
+ assert.equal(
+ "maxSeqLength" in (remembered ?? {}),
+ false,
+ "its context is not, so nothing replays over the loaded one",
+ );
+});
+
+// A model loaded mid-flight has no entry, so the hydrated global set would hand
+// it the previous model's sampling.
+test("a model loaded before hydration keeps its own defaults", async () => {
+ settingsHttp.settings = {
+ inferenceParams: { temperature: 0.42, systemPrompt: "the last model's" },
+ inferenceParamsByModel: {},
+ };
+ settingsHttp.hold();
+ useChatRuntimeStore.setState({
+ params: { ...useChatRuntimeStore.getState().params, checkpoint: LLAMA },
+ paramsByModel: {},
+ settingsHydrated: false,
+ });
+ const hydrating = useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ applyStatus(QWEN);
+
+ settingsHttp.release?.();
+ await hydrating;
+
+ const params = useChatRuntimeStore.getState().params;
+ assert.equal(
+ params.temperature,
+ 0.9,
+ "the recommendation it loaded with, not the saved global set",
+ );
+ assert.equal(params.topP, 0.5);
+});
+
+// The resident model is the one the saved global set describes, so its
+// recommendation must not stand in front of those settings.
+test("the resident model keeps the settings saved for it", async () => {
+ settingsHttp.settings = {
+ inferenceParams: { temperature: 0.2, systemPrompt: "tuned" },
+ };
+ settingsHttp.hold();
+ useChatRuntimeStore.setState({
+ // Nothing selected yet: a local checkpoint is not persisted, the first
+ // status publishes it. The starting sampling differs from the status, so
+ // the recommendation really does move it.
+ params: {
+ ...useChatRuntimeStore.getState().params,
+ checkpoint: "",
+ temperature: 0.5,
+ },
+ paramsByModel: {},
+ settingsHydrated: false,
+ });
+ const hydrating = useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ applyStatus(QWEN);
+
+ settingsHttp.release?.();
+ await hydrating;
+
+ const params = useChatRuntimeStore.getState().params;
+ assert.equal(
+ params.temperature,
+ 0.2,
+ "the saved value, not the recommendation",
+ );
+ assert.equal(params.systemPrompt, "tuned");
+});
+
+// A restore after a hidden auto-load steps off the model that load put there.
+test("a restore does not remember the model a hidden load left", () => {
+ useChatRuntimeStore.setState({
+ params: {
+ ...useChatRuntimeStore.getState().params,
+ checkpoint: QWEN,
+ temperature: 0.77,
+ },
+ paramsByModel: {},
+ });
+
+ useChatRuntimeStore.getState().setCheckpoint(LLAMA, undefined, {
+ trackQueuedSettings: false,
+ persist: false,
+ });
+
+ assert.deepEqual(useChatRuntimeStore.getState().paramsByModel, {});
+});
+
+// A visible switch still records it.
+test("a visible switch remembers the model being left", () => {
+ useChatRuntimeStore.setState({
+ params: {
+ ...useChatRuntimeStore.getState().params,
+ checkpoint: QWEN,
+ temperature: 0.77,
+ },
+ paramsByModel: {},
+ });
+
+ useChatRuntimeStore.getState().setCheckpoint(LLAMA);
+
+ assert.equal(
+ useChatRuntimeStore.getState().paramsByModel[QWEN]?.temperature,
+ 0.77,
+ );
+});
+
+// A default equal to the outgoing model's value never moved, so it is not
+// covered by the changed keys, but it is still this model's default.
+test("a default equal to the previous model's value is still kept", async () => {
+ settingsHttp.settings = {
+ inferenceParams: { temperature: 0.2 },
+ inferenceParamsByModel: {},
+ };
+ settingsHttp.hold();
+ useChatRuntimeStore.setState({
+ // Both models recommend 0.9, so the load moves nothing.
+ params: {
+ ...useChatRuntimeStore.getState().params,
+ checkpoint: LLAMA,
+ temperature: 0.9,
+ },
+ paramsByModel: {},
+ settingsHydrated: false,
+ });
+ const hydrating = useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ applyStatus(QWEN);
+
+ settingsHttp.release?.();
+ await hydrating;
+
+ assert.equal(
+ useChatRuntimeStore.getState().params.temperature,
+ 0.9,
+ "the model's own default, not the other model's saved value",
+ );
+});
+
+// A status that beat the settings response has already published the context
+// the model loaded with, so the replay has to fit it too.
+test("the replay at hydration fits the context already published", async () => {
+ settingsHttp.settings = {
+ inferenceParams: {},
+ inferenceParamsByModel: { [QWEN]: { maxTokens: 131072 } },
+ };
+ settingsHttp.hold();
+ useChatRuntimeStore.setState({
+ params: {
+ ...useChatRuntimeStore.getState().params,
+ checkpoint: QWEN,
+ maxTokens: 8192,
+ },
+ paramsByModel: {},
+ // What the status published for the reduced context it loaded with.
+ ggufContextLength: 8192,
+ settingsHydrated: false,
+ });
+ const hydrating = useChatRuntimeStore.getState().hydratePersistedSettings();
+ settingsHttp.release?.();
+ await hydrating;
+
+ assert.equal(useChatRuntimeStore.getState().params.maxTokens, 8192);
+});
+
+// A model's defaults are not settings it was used with: recording them makes
+// the next defaults hook replay them over itself.
+test("model defaults are replayed over, not recorded", () => {
+ useChatRuntimeStore.setState({
+ params: { ...useChatRuntimeStore.getState().params, checkpoint: LLAMA },
+ paramsByModel: {},
+ });
+
+ applyStatus(QWEN);
+ assert.equal(
+ useChatRuntimeStore.getState().paramsByModel[QWEN],
+ undefined,
+ "the recommendation is not memory",
+ );
+
+ // The Qwen3 thinking params, applied straight after the load response.
+ const store = useChatRuntimeStore.getState();
+ store.setParams(
+ { ...store.params, temperature: 0.6, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ const params = useChatRuntimeStore.getState().params;
+ assert.equal(params.temperature, 0.6);
+ assert.equal(params.minP, 0);
+ assert.equal(params.presencePenalty, 1.5);
+});
+// Unloading or evicting leaves a model the same way switching does.
+test("clearing the checkpoint remembers the model being dropped", () => {
+ useChatRuntimeStore.setState({
+ params: {
+ ...useChatRuntimeStore.getState().params,
+ checkpoint: LLAMA,
+ temperature: 0.11,
+ },
+ paramsByModel: {},
+ });
+
+ useChatRuntimeStore.getState().clearCheckpoint();
+
+ assert.equal(
+ useChatRuntimeStore.getState().paramsByModel[LLAMA]?.temperature,
+ 0.11,
+ );
+});
+
+// Lowering a GGUF's context and reloading: the remembered budget no longer fits.
+test("a remembered budget is clamped to the context just loaded", () => {
+ useChatRuntimeStore.setState({
+ params: {
+ ...useChatRuntimeStore.getState().params,
+ checkpoint: QWEN,
+ maxTokens: 8192,
+ },
+ paramsByModel: { [QWEN]: { maxTokens: 131072 } },
+ });
+
+ const store = useChatRuntimeStore.getState();
+ store.setParams(
+ { ...store.params, maxTokens: 8192 },
+ { fromModelDefaults: true, maxTokensCap: 8192 },
+ );
+
+ assert.equal(useChatRuntimeStore.getState().params.maxTokens, 8192);
+});
+
+// The three places that re-apply a model's defaults. Each overwrites remembered
+// values without changing the checkpoint, so each has to ask for the replay;
+// they pull in the chat UI, so this reads them rather than importing them.
+test("every site that re-applies model defaults asks for the replay", () => {
+ const sites: [string, RegExp][] = [
+ [
+ "../src/features/chat/lib/apply-inference-status-to-store.ts",
+ /mergeBackendRecommendedInference\([\s\S]{0,500}?fromModelDefaults: true/,
+ ],
+ [
+ "../src/features/chat/hooks/use-chat-model-runtime.ts",
+ /mergeBackendRecommendedInference\([\s\S]{0,500}?fromModelDefaults: true/,
+ ],
+ [
+ // The Qwen3 thinking-mode params applied after a load.
+ "../src/features/chat/hooks/use-chat-model-runtime.ts",
+ /setParams\(\{ \.\.\.store\.params, \.\.\.p \}, \{\s*fromModelDefaults: true,/,
+ ],
+ ];
+ for (const [path, pattern] of sites) {
+ const source = readFileSync(new URL(path, import.meta.url), "utf8");
+ assert.match(source, pattern, path);
+ }
+});
+
+// The user drags a slider while the GET is still out. The fence keeps the
+// server's value off it, but the entry arriving for the model predates it.
+test("an edit made before hydration is kept by the model's entry", async () => {
+ useChatRuntimeStore.setState({
+ settingsHydrated: false,
+ rememberParamsPerModel: true,
+ paramsByModel: {},
+ params: { ...useChatRuntimeStore.getState().params, checkpoint: QWEN },
+ });
+ settingsHttp.settings = {
+ inferenceParams: { temperature: 0.9 },
+ inferenceParamsByModel: {
+ [QWEN]: { temperature: 0.9, systemPrompt: "stale" },
+ },
+ };
+ settingsHttp.hold();
+ const hydrating = useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ const editing = useChatRuntimeStore.getState();
+ editing.setParams({ ...editing.params, temperature: 0.33 });
+
+ settingsHttp.release?.();
+ await hydrating;
+
+ const hydrated = useChatRuntimeStore.getState();
+ assert.equal(hydrated.params.temperature, 0.33, "the fence held");
+ assert.equal(
+ hydrated.paramsByModel[QWEN]?.temperature,
+ 0.33,
+ "and the entry took the edit rather than the value it was written before",
+ );
+ // Keys the user did not touch still come from the server.
+ assert.equal(hydrated.paramsByModel[QWEN]?.systemPrompt, "stale");
+
+ applyStatus(QWEN);
+ assert.equal(
+ useChatRuntimeStore.getState().params.temperature,
+ 0.33,
+ "so a poll that re-applies defaults replays the edit, not the old value",
+ );
+});
+
+// A safetensors reload at a smaller sequence length: the load sets the budget
+// to that context and the memory would replay a larger one over it.
+test("a remembered budget is capped by a non-GGUF load", () => {
+ const runtime = readFileSync(
+ new URL(
+ "../src/features/chat/hooks/use-chat-model-runtime.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ // One cap for both sites: the load response and the Qwen3 thinking defaults.
+ assert.match(
+ runtime,
+ /const loadedContextCap = loadResponse\.is_gguf\s*\?\s*\(loadResponse\.context_length \?\? undefined\)\s*:\s*effectiveMaxSeqLength;/,
+ );
+ assert.equal(
+ runtime.match(/maxTokensCap: loadedContextCap/g)?.length,
+ 2,
+ "the thinking-defaults replay is capped too",
+ );
+
+ const adapter = readFileSync(
+ new URL("../src/features/chat/api/chat-adapter.ts", import.meta.url),
+ "utf8",
+ );
+ assert.match(
+ adapter,
+ /\? \(loadResp\.context_length \?\? undefined\)\s*: effectiveMaxSeqLength,/,
+ );
+
+ const status = readFileSync(
+ new URL(
+ "../src/features/chat/lib/apply-inference-status-to-store.ts",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ // Reported for a safetensors load too, so the cap is not narrowed to GGUF.
+ assert.match(status, /maxTokensCap: status\.context_length \?\? undefined,/);
+});
+
+// The clamp itself, through the store: the memory holds a budget from a larger
+// context and the load reports a smaller one.
+test("the cap wins over the remembered budget", () => {
+ useChatRuntimeStore.setState({
+ settingsHydrated: true,
+ rememberParamsPerModel: true,
+ paramsByModel: { [LLAMA]: { maxTokens: 32768 } },
+ params: { ...useChatRuntimeStore.getState().params, checkpoint: LLAMA },
+ });
+ const store = useChatRuntimeStore.getState();
+ store.setParams(
+ { ...store.params, maxSeqLength: 8192, maxTokens: 8192 },
+ { fromModelDefaults: true, maxTokensCap: 8192 },
+ );
+ assert.equal(useChatRuntimeStore.getState().params.maxTokens, 8192);
+
+ // Without a cap the older, larger budget is what comes back.
+ const uncapped = useChatRuntimeStore.getState();
+ uncapped.setParams(
+ { ...uncapped.params, maxTokens: 8192 },
+ { fromModelDefaults: true },
+ );
+ assert.equal(useChatRuntimeStore.getState().params.maxTokens, 32768);
+});
+
+// The toggle is a mirrored scalar setting, so the write goes through
+// setScalarSettingVersion rather than an explicit saveSettingsPatch beside it.
+// Turning it off has to survive a reload, or the memory comes back on.
+test("turning the memory off is persisted and hydrated back", async () => {
+ useChatRuntimeStore.setState({
+ settingsHydrated: true,
+ rememberParamsPerModel: true,
+ });
+ settingsHttp.puts.length = 0;
+ useChatRuntimeStore.getState().setRememberParamsPerModel(false);
+ await settled();
+ // The writer debounces and coalesces, so this is the patch the toggle joined.
+ assert.equal(
+ settingsHttp.puts.at(-1)?.rememberParamsPerModel,
+ false,
+ "the choice is written, not just held in the store",
+ );
+
+ // The next launch reads it back rather than falling to the default.
+ useChatRuntimeStore.setState({
+ settingsHydrated: false,
+ rememberParamsPerModel: true,
+ });
+ settingsHttp.settings = { rememberParamsPerModel: false };
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+ assert.equal(useChatRuntimeStore.getState().rememberParamsPerModel, false);
+});
+
+// A safetensors load publishes its context through the cap, not through
+// ggufContextLength, which is null for everything that is not a GGUF.
+test("a safetensors context also caps the hydration replay", async () => {
+ useChatRuntimeStore.setState({
+ settingsHydrated: false,
+ rememberParamsPerModel: true,
+ ggufContextLength: null,
+ paramsByModel: {},
+ params: { ...useChatRuntimeStore.getState().params, checkpoint: LLAMA },
+ });
+ settingsHttp.settings = {
+ inferenceParams: { maxTokens: 32768 },
+ inferenceParamsByModel: { [LLAMA]: { maxTokens: 32768 } },
+ };
+ settingsHttp.hold();
+ const hydrating = useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ // The status beats the settings response and reports the smaller context.
+ const store = useChatRuntimeStore.getState();
+ store.setParams(
+ { ...store.params, maxSeqLength: 8192, maxTokens: 8192 },
+ { fromModelDefaults: true, maxTokensCap: 8192 },
+ );
+ assert.equal(useChatRuntimeStore.getState().params.maxTokens, 8192);
+
+ settingsHttp.release?.();
+ await hydrating;
+ assert.equal(
+ useChatRuntimeStore.getState().params.maxTokens,
+ 8192,
+ "the replay fits the context the load actually has",
+ );
+});
+
+// The cap belongs to the model it was reported for: a switch away from it must
+// not carry it onto the next one.
+test("a kept context does not follow the next model", async () => {
+ useChatRuntimeStore.setState({
+ settingsHydrated: false,
+ rememberParamsPerModel: true,
+ ggufContextLength: null,
+ paramsByModel: {},
+ params: { ...useChatRuntimeStore.getState().params, checkpoint: LLAMA },
+ });
+ settingsHttp.settings = {
+ inferenceParams: { maxTokens: 32768 },
+ inferenceParamsByModel: { [QWEN]: { maxTokens: 32768 } },
+ };
+ settingsHttp.hold();
+ const hydrating = useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ const store = useChatRuntimeStore.getState();
+ store.setParams(
+ { ...store.params, maxTokens: 8192 },
+ { fromModelDefaults: true, maxTokensCap: 8192 },
+ );
+ // A different model takes over, with no context reported for it.
+ const switched = useChatRuntimeStore.getState();
+ switched.setParams({ ...switched.params, checkpoint: QWEN });
+
+ settingsHttp.release?.();
+ await hydrating;
+ assert.equal(
+ useChatRuntimeStore.getState().params.maxTokens,
+ 32768,
+ "the other model's smaller context does not clamp this one",
+ );
+});
+
+// The settings on screen got there by replay and a hidden load replays without
+// persisting, so the global set can still be the previous model's.
+test("turning the memory off keeps the settings on screen", async () => {
+ useChatRuntimeStore.setState({
+ settingsHydrated: true,
+ rememberParamsPerModel: true,
+ paramsByModel: { [LLAMA]: { temperature: 0.11, systemPrompt: "B" } },
+ params: {
+ ...useChatRuntimeStore.getState().params,
+ checkpoint: QWEN,
+ temperature: 0.9,
+ systemPrompt: "A",
+ },
+ });
+ await settled();
+ settingsHttp.puts.length = 0;
+
+ // A hidden restore: B's settings reach the screen, nothing is written.
+ const store = useChatRuntimeStore.getState();
+ store.setParams(
+ { ...store.params, checkpoint: LLAMA },
+ { fromModelDefaults: true, persist: false },
+ );
+ assert.equal(useChatRuntimeStore.getState().params.temperature, 0.11);
+ assert.equal(
+ settingsHttp.puts.length,
+ 0,
+ "the hidden restore wrote nothing, which is the point",
+ );
+
+ useChatRuntimeStore.getState().setRememberParamsPerModel(false);
+ await settled();
+ const written: Record<string, unknown> = {};
+ for (const put of settingsHttp.puts) Object.assign(written, put);
+ const globals = written.inferenceParams as Record<string, unknown>;
+ assert.equal(globals?.temperature, 0.11);
+ assert.equal(globals?.systemPrompt, "B");
+});
+
+// An install upgraded from before the memory has no entries at all, so the
+// replay never runs and the cap that rides with it never applies.
+test("the loaded context caps a global budget with no entry to replay", async () => {
+ useChatRuntimeStore.setState({
+ settingsHydrated: false,
+ rememberParamsPerModel: true,
+ ggufContextLength: null,
+ paramsByModel: {},
+ params: { ...useChatRuntimeStore.getState().params, checkpoint: LLAMA },
+ });
+ settingsHttp.settings = { inferenceParams: { maxTokens: 32768 } };
+ settingsHttp.hold();
+ const hydrating = useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ const store = useChatRuntimeStore.getState();
+ store.setParams(
+ { ...store.params, maxSeqLength: 8192, maxTokens: 8192 },
+ { fromModelDefaults: true, maxTokensCap: 8192 },
+ );
+
+ settingsHttp.release?.();
+ await hydrating;
+ assert.equal(useChatRuntimeStore.getState().params.maxTokens, 8192);
+});
+
+// The server merges per key, so a full snapshot rewrites every field of a
+// model's entry. A second tab that has only read an entry has nothing to say
+// about it, and switching models is not an edit.
+test("a browser that only read an entry does not write it back", async () => {
+ useChatRuntimeStore.setState({
+ settingsHydrated: false,
+ rememberParamsPerModel: true,
+ paramsByModel: {},
+ });
+ settingsHttp.settings = {
+ inferenceParamsByModel: {
+ [QWEN]: { temperature: 0.6 },
+ [LLAMA]: { temperature: 0.7 },
+ },
+ };
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+ useChatRuntimeStore.setState({
+ params: {
+ ...useChatRuntimeStore.getState().params,
+ checkpoint: QWEN,
+ temperature: 0.6,
+ },
+ });
+ await settled();
+
+ const perModelWrites = async (): Promise<string[]> => {
+ await settled();
+ const keys = new Set<string>();
+ for (const put of settingsHttp.puts) {
+ for (const id of Object.keys(
+ (put.inferenceParamsByModel ?? {}) as object,
+ )) {
+ keys.add(id);
+ }
+ }
+ settingsHttp.puts.length = 0;
+ return [...keys];
+ };
+ await perModelWrites();
+
+ // Switching back and forth, touching nothing.
+ for (const checkpoint of [LLAMA, QWEN, LLAMA]) {
+ const store = useChatRuntimeStore.getState();
+ store.setParams({ ...store.params, checkpoint });
+ assert.deepEqual(
+ await perModelWrites(),
+ [],
+ "a switch reads the entries, it does not rewrite them",
+ );
+ }
+ // The replay still happens, it is only the write that is withheld.
+ assert.equal(useChatRuntimeStore.getState().params.temperature, 0.7);
+
+ // An edit here is this browser's own, and is written -- but only the key it
+ // moved. The server merges per key, so sending the rest would put this
+ // browser's copy of the prompt over one the other tab has since changed.
+ settingsHttp.puts.length = 0;
+ const editing = useChatRuntimeStore.getState();
+ editing.setParams({ ...editing.params, temperature: 0.42 });
+ await settled();
+ const patch: Record<string, Record<string, unknown>> = {};
+ for (const put of settingsHttp.puts) {
+ Object.assign(
+ patch,
+ (put.inferenceParamsByModel ?? {}) as Record<
+ string,
+ Record<string, unknown>
+ >,
+ );
+ }
+ settingsHttp.puts.length = 0;
+ assert.deepEqual(patch, { [LLAMA]: { temperature: 0.42 } });
+
+ // And switching away from it writes nothing more: the edit already said it,
+ // and the rest of the entry is not this browser's to restate.
+ const leaving = useChatRuntimeStore.getState();
+ leaving.setParams({ ...leaving.params, checkpoint: QWEN });
+ assert.deepEqual(await perModelWrites(), []);
+});
+
+// The case the outgoing snapshot exists for: a model with no entry at all,
+// switched away from without ever being edited, still has to be seeded.
+test("a model with no entry is still seeded when it is left", async () => {
+ useChatRuntimeStore.setState({
+ settingsHydrated: true,
+ rememberParamsPerModel: true,
+ paramsByModel: {},
+ params: {
+ ...useChatRuntimeStore.getState().params,
+ checkpoint: QWEN,
+ temperature: 0.31,
+ },
+ });
+ await settled();
+ settingsHttp.puts.length = 0;
+
+ const store = useChatRuntimeStore.getState();
+ store.setParams({ ...store.params, checkpoint: LLAMA });
+ await settled();
+ const written: Record<string, Record<string, unknown>> = {};
+ for (const put of settingsHttp.puts) {
+ Object.assign(
+ written,
+ (put.inferenceParamsByModel ?? {}) as Record<
+ string,
+ Record<string, unknown>
+ >,
+ );
+ }
+ assert.equal(written[QWEN]?.temperature, 0.31);
+});
+
+// Two fields of one model changed inside the debounce window each send a
+// one-field object, and one level of merging would drop the first.
+test("two edits to one model inside a debounce window both survive", async () => {
+ useChatRuntimeStore.setState({
+ settingsHydrated: false,
+ rememberParamsPerModel: true,
+ paramsByModel: {},
+ });
+ settingsHttp.settings = {
+ inferenceParamsByModel: { [QWEN]: { temperature: 0.6, topP: 0.9 } },
+ };
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+ useChatRuntimeStore.setState({
+ params: {
+ ...useChatRuntimeStore.getState().params,
+ checkpoint: QWEN,
+ temperature: 0.6,
+ topP: 0.9,
+ },
+ });
+ await settled();
+ settingsHttp.puts.length = 0;
+
+ const first = useChatRuntimeStore.getState();
+ first.setParams({ ...first.params, temperature: 0.42 });
+ const second = useChatRuntimeStore.getState();
+ second.setParams({ ...second.params, topP: 0.11 });
+ await settled();
+
+ assert.deepEqual(
+ settingsHttp.puts.map((put) => put.inferenceParamsByModel),
+ [{ [QWEN]: { temperature: 0.42, topP: 0.11 } }],
+ "one PUT carrying both edits, not the last one alone",
+ );
+});
+
+// Picking an external model leaves the local one resident, so ggufContextLength
+// goes on describing a model that has nothing to do with the pick.
+test("a resident GGUF context does not cap an external model", async () => {
+ useChatRuntimeStore.setState({
+ settingsHydrated: false,
+ rememberParamsPerModel: true,
+ ggufContextLength: 8192,
+ paramsByModel: {},
+ params: {
+ ...useChatRuntimeStore.getState().params,
+ checkpoint: EXTERNAL,
+ },
+ });
+ settingsHttp.settings = { inferenceParams: { maxTokens: 32768 } };
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+ assert.equal(useChatRuntimeStore.getState().params.maxTokens, 32768);
+
+ // A local checkpoint with the same resident context is still capped.
+ useChatRuntimeStore.setState({
+ settingsHydrated: false,
+ ggufContextLength: 8192,
+ paramsByModel: {},
+ params: { ...useChatRuntimeStore.getState().params, checkpoint: QWEN },
+ });
+ settingsHttp.settings = { inferenceParams: { maxTokens: 32768 } };
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+ assert.equal(useChatRuntimeStore.getState().params.maxTokens, 8192);
+});
diff --git a/studio/frontend/tests/per-model-params.test.ts b/studio/frontend/tests/per-model-params.test.ts
new file mode 100644
index 00000000000..c3424b31632
--- /dev/null
+++ b/studio/frontend/tests/per-model-params.test.ts
@@ -0,0 +1,421 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The rules the per-model memory follows, including where it must NOT act: a
+// model with nothing remembered keeps what is on screen, and an edit that moved
+// nothing must not mark the map dirty.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+// preset-policy imports extensionless, the way vite resolves.
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+import {
+ REMEMBERED_INFERENCE_PARAM_KEYS,
+ getRememberedParamsPatch,
+ getReplayedParams,
+ pickRememberedParams,
+} from "../src/features/chat/lib/per-model-params.ts";
+import type { InferenceParams } from "../src/features/chat/types/runtime.ts";
+
+const QWEN = "unsloth/Qwen3.5-9B-GGUF";
+const LLAMA = "unsloth/Llama-4-8B";
+
+function params(overrides: Partial<InferenceParams> = {}): InferenceParams {
+ return {
+ checkpoint: QWEN,
+ temperature: 0.7,
+ topP: 0.95,
+ topK: 40,
+ minP: 0.05,
+ repetitionPenalty: 1,
+ presencePenalty: 0,
+ maxSeqLength: 4096,
+ maxTokens: 2048,
+ systemPrompt: "",
+ systemVariables: "",
+ ...overrides,
+ } as InferenceParams;
+}
+
+/** What the store passes: the edit that moved, plus the full resulting params. */
+function record(
+ paramsByModel: Record<string, Record<string, unknown>>,
+ modelId: string | undefined,
+ changed: Record<string, unknown>,
+ full: InferenceParams,
+) {
+ return getRememberedParamsPatch(
+ true,
+ paramsByModel as never,
+ modelId,
+ changed as never,
+ pickRememberedParams(full),
+ );
+}
+
+test("an edit is filed against the model it was made for", () => {
+ const next = record(
+ {},
+ QWEN,
+ { temperature: 0.2 },
+ params({ temperature: 0.2 }),
+ );
+ assert.equal(next?.[QWEN].temperature, 0.2);
+});
+
+// The entry has to be the whole snapshot. Replay overlays it onto the outgoing
+// model's params, so anything missing would silently keep the other model's value.
+test("an entry records every param, not only the one that moved", () => {
+ const next = record(
+ {},
+ QWEN,
+ { temperature: 0.2 },
+ params({ temperature: 0.2, systemPrompt: "Be terse." }),
+ );
+ assert.equal(next?.[QWEN].systemPrompt, "Be terse.");
+ assert.equal(next?.[QWEN].topP, 0.95);
+});
+
+test("editing one model leaves every other model's memory alone", () => {
+ const before = { [LLAMA]: { temperature: 0.9 } };
+ const after = record(
+ before,
+ QWEN,
+ { temperature: 0.2 },
+ params({ temperature: 0.2 }),
+ );
+ assert.deepEqual(after?.[LLAMA], { temperature: 0.9 });
+ assert.equal(after?.[QWEN].temperature, 0.2);
+ // The input map is not mutated: the store compares by identity to decide
+ // whether anything has to be persisted.
+ assert.deepEqual(before, { [LLAMA]: { temperature: 0.9 } });
+});
+
+// The reported failure: A remembered only its temperature, so switching back
+// overlaid it onto B's prompt and A ran under settings it was never given.
+test("a model returns to the prompt it was last used with", () => {
+ const aParams = params({
+ checkpoint: QWEN,
+ temperature: 0.2,
+ systemPrompt: "A",
+ });
+ const memory = record({}, QWEN, { temperature: 0.2 }, aParams);
+ assert.ok(memory);
+
+ // Switch to B, which has no memory, then change only B's prompt.
+ const onB = getReplayedParams(true, memory, aParams, LLAMA, true);
+ const bParams = { ...onB, checkpoint: LLAMA, systemPrompt: "B" };
+ const afterB = record(memory, LLAMA, { systemPrompt: "B" }, bParams);
+ assert.ok(afterB);
+
+ const backOnA = getReplayedParams(true, afterB, bParams, QWEN, true);
+ assert.equal(backOnA.systemPrompt, "A");
+ assert.equal(backOnA.temperature, 0.2);
+});
+
+// The interactive local load calls setParams with the destination checkpoint,
+// not setCheckpoint, so replaying only there left the common switch dead.
+test("a local model load replays memory over the backend's recommendation", () => {
+ let memory: Record<string, ReturnType<typeof pickRememberedParams>> = {};
+ let live = params({ checkpoint: QWEN });
+
+ function loadModel(modelId: string, recommended: Partial<InferenceParams>) {
+ const merged = { ...live, ...recommended, checkpoint: modelId };
+ const replayed = getReplayedParams(true, memory, merged, modelId, true);
+ memory = record(memory, modelId, { temperature: 1 }, replayed) ?? memory;
+ live = replayed;
+ }
+
+ function edit(overrides: Partial<InferenceParams>) {
+ live = { ...live, ...overrides };
+ memory = record(memory, live.checkpoint, overrides, live) ?? memory;
+ }
+
+ loadModel(QWEN, { temperature: 0.7 });
+ edit({ temperature: 0.2 });
+ loadModel(LLAMA, { temperature: 0.6 });
+ assert.equal(
+ live.temperature,
+ 0.6,
+ "a model with no memory takes its recommendation",
+ );
+
+ loadModel(QWEN, { temperature: 0.7 });
+ assert.equal(
+ live.temperature,
+ 0.2,
+ "the tuned value beats the recommendation",
+ );
+});
+
+// Without snapshotting the model being left, an install upgrading from the
+// single global set loses whatever the resident model ran with.
+test("the model being switched away from is remembered", () => {
+ // Startup after an upgrade: global params hydrated, nothing remembered yet.
+ const onA = params({ checkpoint: QWEN, temperature: 0.2, systemPrompt: "A" });
+ const memory = record({}, QWEN, pickRememberedParams(onA), onA);
+ assert.ok(memory, "leaving A records what A was running with");
+
+ const onB = getReplayedParams(true, memory, onA, LLAMA, true);
+ const editedB = { ...onB, checkpoint: LLAMA, systemPrompt: "B" };
+ const afterB =
+ record(memory, LLAMA, { systemPrompt: "B" }, editedB) ?? memory;
+
+ const backOnA = getReplayedParams(true, afterB, editedB, QWEN, true);
+ assert.equal(backOnA.systemPrompt, "A");
+ assert.equal(backOnA.temperature, 0.2);
+});
+
+// The auto-load follows setCheckpoint with setParams carrying the load
+// response, so replay must run there too or the load's budget wins.
+test("a load response does not overwrite a remembered token budget", () => {
+ const memory = {
+ [QWEN]: { ...pickRememberedParams(params()), maxTokens: 4096 },
+ };
+ const afterCheckpoint = getReplayedParams(true, memory, params(), QWEN, true);
+ assert.equal(afterCheckpoint.maxTokens, 4096);
+
+ // setParams(fromModelLoad) with the load response: checkpoint unchanged, so
+ // only the forced replay keeps the remembered budget.
+ const loadResponse = { ...afterCheckpoint, maxTokens: 131072 };
+ const withoutForcedReplay = getReplayedParams(
+ true,
+ memory,
+ loadResponse,
+ QWEN,
+ false,
+ );
+ assert.equal(
+ withoutForcedReplay.maxTokens,
+ 131072,
+ "this is the reported bug",
+ );
+
+ const withForcedReplay = getReplayedParams(
+ true,
+ memory,
+ loadResponse,
+ QWEN,
+ true,
+ );
+ assert.equal(withForcedReplay.maxTokens, 4096);
+});
+
+// A load or status re-applies the model's defaults, so replaying afterwards is
+// what keeps its own settings while leaving an unremembered model its default.
+test("a model's defaults do not outrank what it is remembered with", async () => {
+ const { mergeBackendRecommendedInference } = await import(
+ "../src/features/chat/presets/preset-policy.ts"
+ );
+ const response = {
+ inference: { temperature: 0.9, top_p: 0.5 },
+ is_gguf: true,
+ context_length: 131072,
+ };
+ const applyDefaults = (current: InferenceParams, modelId: string) =>
+ mergeBackendRecommendedInference({
+ current,
+ response: response as never,
+ modelId,
+ presetSource: "builtin-default",
+ });
+ const memory = { [QWEN]: { temperature: 0.2, maxTokens: 4096 } };
+
+ const tuned = applyDefaults(
+ params({ temperature: 0.2, maxTokens: 4096 }),
+ QWEN,
+ );
+ assert.equal(tuned.temperature, 0.9, "this is the reported clobber");
+ // setParams(fromModelDefaults) forces the replay even though the checkpoint
+ // did not change.
+ const replayed = getReplayedParams(true, memory, tuned, QWEN, true);
+ assert.equal(replayed.temperature, 0.2);
+ assert.equal(replayed.maxTokens, 4096);
+
+ const fresh = getReplayedParams(
+ true,
+ memory,
+ applyDefaults(params(), LLAMA),
+ LLAMA,
+ true,
+ );
+ assert.equal(
+ fresh.temperature,
+ 0.9,
+ "a model with no memory keeps its own defaults",
+ );
+});
+
+// Null is how the store leaves the map and its hydration version untouched.
+test("nothing is recorded when there is nothing to record", () => {
+ const snapshot = pickRememberedParams(params());
+ assert.equal(
+ getRememberedParamsPatch(false, {}, QWEN, { temperature: 0.2 }, snapshot),
+ null,
+ "the feature being off records nothing",
+ );
+ assert.equal(
+ getRememberedParamsPatch(
+ true,
+ {},
+ undefined,
+ { temperature: 0.2 },
+ snapshot,
+ ),
+ null,
+ "no model selected records nothing",
+ );
+ assert.equal(
+ getRememberedParamsPatch(true, {}, "", { temperature: 0.2 }, snapshot),
+ null,
+ "an empty checkpoint is not a model id",
+ );
+ assert.equal(
+ getRememberedParamsPatch(true, {}, QWEN, {}, snapshot),
+ null,
+ "an edit that moved no persisted param records nothing",
+ );
+});
+
+test("switching models replays that model's own settings", () => {
+ const current = params({ temperature: 0.7, systemPrompt: "" });
+ const replayed = getReplayedParams(
+ true,
+ { [LLAMA]: { temperature: 0.1, systemPrompt: "Be terse." } },
+ current,
+ LLAMA,
+ true,
+ );
+ assert.equal(replayed.temperature, 0.1);
+ assert.equal(replayed.systemPrompt, "Be terse.");
+ // Params the model never pinned carry over rather than snapping to defaults.
+ assert.equal(replayed.topP, current.topP);
+});
+
+test("a model with nothing remembered keeps the settings on screen", () => {
+ const current = params({ temperature: 0.33 });
+ const replayed = getReplayedParams(true, {}, current, LLAMA, true);
+ assert.equal(replayed, current, "returned by identity, so nothing persists");
+});
+
+test("re-selecting the same model does not replay over a live edit", () => {
+ const current = params({ temperature: 0.33 });
+ // checkpointChanged=false: the user just nudged a slider, and replaying the
+ // stored value here would undo the edit they are making.
+ const replayed = getReplayedParams(
+ true,
+ { [QWEN]: { temperature: 0.9 } },
+ current,
+ QWEN,
+ false,
+ );
+ assert.equal(replayed, current);
+});
+
+test("the feature being off leaves a model switch alone", () => {
+ const current = params({ temperature: 0.33 });
+ const replayed = getReplayedParams(
+ false,
+ { [LLAMA]: { temperature: 0.9 } },
+ current,
+ LLAMA,
+ true,
+ );
+ assert.equal(replayed, current);
+});
+
+// Turning the setting on adopts what is on screen for the active model, so the
+// first switch away and back returns to it rather than to nothing.
+test("the snapshot covers every remembered key and excludes the checkpoint", () => {
+ const picked = pickRememberedParams(params());
+ assert.equal(
+ "checkpoint" in picked,
+ false,
+ "the checkpoint names the model, it is not one of the values",
+ );
+ // The context a model loads with is already kept per model by its load
+ // config, and that is the copy the load uses.
+ assert.equal("maxSeqLength" in picked, false);
+ for (const key of REMEMBERED_INFERENCE_PARAM_KEYS) {
+ if (params()[key] !== undefined) {
+ assert.ok(key in picked, `${key} should be captured`);
+ }
+ }
+});
+
+test("the snapshot drops params the current model never set", () => {
+ const picked = pickRememberedParams(
+ params({ topK: undefined as unknown as number }),
+ );
+ assert.equal("topK" in picked, false);
+});
+
+// The row accepts every persisted key from any writer, so the read side has to
+// hold the write side's rules rather than trust the entry's shape.
+test("a maxSeqLength in a stored entry is not replayed over the loaded context", () => {
+ const replayed = getReplayedParams(
+ true,
+ { [QWEN]: { temperature: 0.2, maxSeqLength: 131072 } },
+ params({ checkpoint: QWEN, maxSeqLength: 4096 }),
+ QWEN,
+ true,
+ );
+ assert.equal(replayed.temperature, 0.2, "the remembered value still replays");
+ // A second copy of the context would advertise one the backend never loaded.
+ assert.equal(replayed.maxSeqLength, 4096);
+});
+
+test("a key that is not an inference param cannot reach the live params", () => {
+ const replayed = getReplayedParams(
+ true,
+ { [QWEN]: { temperature: 0.2, notAParam: 9 } as never },
+ params({ checkpoint: QWEN }),
+ QWEN,
+ true,
+ );
+ assert.equal(replayed.temperature, 0.2);
+ // params flows on into request bodies and into an extra="forbid" settings write.
+ assert.equal("notAParam" in replayed, false);
+});
+
+// Model ids are opaque keys: a Hub repo, an absolute path on any OS, or a
+// provider-qualified external id. One that did not round trip would mean that
+// platform silently cannot remember settings.
+for (const [label, id] of [
+ ["a Windows drive path", "C:\\Users\\Daniel\\models\\Qwen3-8B"],
+ ["a UNC share path", "\\\\fileserver\\models\\gemma-3-270m-it"],
+ ["a WSL UNC path", "\\\\wsl$\\Ubuntu\\home\\d\\models\\llama"],
+ [
+ "a macOS path with spaces",
+ "/Users/d/Library/Application Support/unsloth/gemma",
+ ],
+ [
+ "a Linux cache path",
+ "/home/d/.cache/huggingface/hub/models--unsloth--Qwen3-0.6B",
+ ],
+ ["a provider-qualified id", "external::anthropic::claude-opus-5"],
+ ["a non-ASCII repo id", "unsloth/通義千問-7B"],
+] as const) {
+ test(`${label} is remembered and replayed unchanged`, () => {
+ const recorded = record(
+ {},
+ id,
+ { temperature: 0.2 },
+ params({ checkpoint: id, temperature: 0.2 }),
+ );
+ assert.ok(recorded, "nothing was recorded");
+ assert.equal(recorded[id].temperature, 0.2);
+ const replayed = getReplayedParams(
+ true,
+ recorded,
+ params({ temperature: 1 }),
+ id,
+ true,
+ );
+ assert.equal(replayed.temperature, 0.2);
+ });
+}
diff --git a/studio/frontend/tests/store-settings-resolver.mjs b/studio/frontend/tests/store-settings-resolver.mjs
new file mode 100644
index 00000000000..d5387c5b639
--- /dev/null
+++ b/studio/frontend/tests/store-settings-resolver.mjs
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The store stubs, plus a chat-settings endpoint a test can drive. Register
+// this to exercise the real chat-runtime store against hydration.
+import { resolve as resolveBundler } from "./bundler-resolver.mjs";
+
+const STUBS = new Map([
+ ["@/features/auth", "./helpers/store-stubs/settings-http.ts"],
+ ["@/features/hub", "./helpers/store-stubs/hub.ts"],
+ ["@/features/model-picker", "./helpers/store-stubs/model-picker.ts"],
+ ["@/config/env", "./helpers/store-stubs/env.ts"],
+ ["@/lib/toast", "./helpers/store-stubs/toast.ts"],
+]);
+
+export function resolve(specifier, context, next) {
+ const stub = STUBS.get(specifier);
+ if (stub) {
+ return next(new URL(stub, import.meta.url).href, context);
+ }
+ return resolveBundler(specifier, context, next);
+}
diff --git a/tests/studio/test_new_chat_context_recount.py b/tests/studio/test_new_chat_context_recount.py
index 26871e50bcf..ab34a78f89d 100644
--- a/tests/studio/test_new_chat_context_recount.py
+++ b/tests/studio/test_new_chat_context_recount.py
@@ -161,6 +161,10 @@ const state: any = {
// Deep Research sends a research run instead of this history, so the count would price
// a request that is never made.
deepResearchEnabled: false,
+ // Per-model parameter memory, off and empty: the recount is about the window, not
+ // about which model last set the temperature.
+ rememberParamsPerModel: false,
+ paramsByModel: {},
};
function set(updater: any): void {
@@ -171,6 +175,27 @@ function set(updater: any): void {
// What the sliced setCheckpoint reducer reads through: nothing is persisted here, and
// no external provider is configured, so its output-cap clamp is a no-op.
const CHAT_DEEP_RESEARCH_ENABLED_KEY = "unsloth_deep_research_enabled";
+// The per-model memory, with the toggle off above: nothing is snapshotted, no map is
+// written back, and a switch keeps the params on screen. Only the loaded-context cap
+// is kept real, since that one clamps a value the recount prices.
+function rememberOutgoingModel(_state: any, _outgoing: any): any {
+ return null;
+}
+function getReplayedParams(
+ _enabled: any,
+ _byModel: any,
+ current: any,
+ _modelId: string,
+ _checkpointChanged: boolean,
+ maxTokensCap?: number,
+): any {
+ return maxTokensCap !== undefined && current.maxTokens > maxTokensCap
+ ? { ...current, maxTokens: maxTokensCap }
+ : current;
+}
+function getReplayStatePatch(): any {
+ return {};
+}
function saveLastExternalCheckpoint(_id: string | null): void {}
function saveBool(_key: string, _value: boolean): void {}
function parseExternalModelId(id: string): any {