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: keep each chat's sampling params and system prompt with the chat (#9055)

Michael Handc470257b6d2
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.py
index ee5d40b5665..86ce24b140b 100644
--- a/studio/backend/routes/chat_history.py
+++ b/studio/backend/routes/chat_history.py
@@ -80,7 +80,9 @@ class ChatRagKnowledgeBaseSource(BaseModel):
class ChatThreadSettings(BaseModel):
"""The chat settings captured per thread; a thread storing none uses the global ones."""
- model_config = ConfigDict(extra = "forbid")
+ # allow_inf_nan as in ChatInferenceSettings: json.loads and pydantic both take
+ # a bare NaN, which is then stored as a token no strict reader can parse back.
+ model_config = ConfigDict(extra = "forbid", allow_inf_nan = False)
reasoningEnabled: Optional[bool] = None
reasoningEffort: Optional[
@@ -107,6 +109,18 @@ class ChatThreadSettings(BaseModel):
ragTopK: Optional[int] = Field(default = None, ge = 1, le = 50)
ragAutoInject: Optional[Literal["auto", "on", "off"]] = None
ragAutoInjectMinScore: Optional[float] = Field(default = None, ge = 0, le = 1)
+ # The sampling params a chat runs with. Ranges match the sliders that set them.
+ temperature: Optional[float] = Field(default = None, ge = 0, le = 2)
+ topP: Optional[float] = Field(default = None, ge = 0, le = 1)
+ # -1 disables top-k, matching ChatCompletionRequest and the default.yaml fallback.
+ topK: Optional[int] = Field(default = None, ge = -1, le = 100)
+ minP: Optional[float] = Field(default = None, ge = 0, le = 1)
+ repetitionPenalty: Optional[float] = Field(default = None, ge = 1, le = 2)
+ presencePenalty: Optional[float] = Field(default = None, ge = 0, le = 2)
+ # Not length-capped, like the installation-wide copy: truncating here would
+ # silently change what the chat runs with.
+ systemPrompt: Optional[str] = None
+ systemVariables: Optional[str] = None
class ChatThread(BaseModel):
diff --git a/studio/backend/tests/test_chat_thread_settings.py b/studio/backend/tests/test_chat_thread_settings.py
index 6d4ef46b314..f10d767e980 100644
--- a/studio/backend/tests/test_chat_thread_settings.py
+++ b/studio/backend/tests/test_chat_thread_settings.py
@@ -597,3 +597,74 @@ def test_the_newest_writer_is_not_the_first_evicted(tmp_path, monkeypatch):
got = thread_from_row(studio_db.get_chat_thread("thread-1")).settings
assert got.toolsEnabled is False
+
+
+def test_sampling_params_are_part_of_the_snapshot():
+ """The reported gap: a chat's system prompt and sampling did not travel with it."""
+ settings = ChatThreadSettings.model_validate(
+ {
+ "temperature": 0.2,
+ "topP": 0.85,
+ "topK": 40,
+ "minP": 0.02,
+ "repetitionPenalty": 1.1,
+ "presencePenalty": 0.5,
+ "systemPrompt": "You are a terse reviewer.",
+ "systemVariables": "name=Ada",
+ }
+ )
+ assert settings.temperature == 0.2
+ assert settings.systemPrompt == "You are a terse reviewer."
+ assert settings.systemVariables == "name=Ada"
+
+
+ "field, inside, outside",
+ [
+ ("temperature", 2, 2.5),
+ ("temperature", 0, -0.1),
+ ("topP", 1, 1.5),
+ ("topK", 100, 101),
+ # -1 disables top-k; the floor is below it, not at zero.
+ ("topK", -1, -2),
+ ("minP", 0, -1),
+ ("repetitionPenalty", 1, 0.5),
+ ("presencePenalty", 2, 3),
+ ],
+)
+def test_sampling_params_take_the_slider_range_and_no_more(field, inside, outside):
+ """Both halves: extra="forbid" alone would refuse the out-of-range value too."""
+ assert getattr(ChatThreadSettings.model_validate({field: inside}), field) == inside
+ with pytest.raises(ValidationError):
+ ChatThreadSettings.model_validate({field: outside})
+
+
+def test_the_disabled_top_k_value_round_trips():
+ """ChatCompletionRequest allows -1 and default.yaml falls back to it, so a chat
+ running with top-k off has to be able to store that."""
+ assert ChatThreadSettings.model_validate({"topK": -1}).topK == -1
+
+
[email protected]("bad", [float("nan"), float("inf"), float("-inf")])
+def test_sampling_params_refuse_nan_and_infinity(bad):
+ """Stored bare, these parse back in Python but are not valid JSON for anything else."""
+ assert ChatThreadSettings.model_validate({"temperature": 0.5}).temperature == 0.5
+ with pytest.raises(ValidationError):
+ ChatThreadSettings.model_validate({"temperature": bad})
+
+
+def test_a_long_system_prompt_is_stored_whole():
+ """Truncating would silently change what the chat runs with."""
+ prompt = "x" * 20_000
+ settings = ChatThreadSettings.model_validate({"systemPrompt": prompt})
+ assert settings.systemPrompt == prompt
+
+
+def test_an_older_build_drops_only_the_sampling_it_cannot_read():
+ """readable_thread_settings keeps the rest of a snapshot a newer build wrote."""
+ from routes.chat_history import readable_thread_settings
+
+ kept = readable_thread_settings(
+ {"toolsEnabled": True, "temperature": 0.3, "somethingNewer": "?"}
+ )
+ assert kept == {"toolsEnabled": True, "temperature": 0.3}
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 aa883e3c347..74691a39326 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -64,11 +64,13 @@ import {
} from "../utils/mirrored-chat-settings";
import { retryablePatchAfterFailure } from "../utils/settings-retry";
import {
+ THREAD_SCOPED_PARAM_KEYS,
THREAD_SCOPED_SETTING_KEYS,
type ThreadScopedSettingKey,
type ThreadScopedSettings,
hasThreadScopedSettings,
isThreadOwnedSettingKey,
+ isThreadScopedParamKey,
sanitizeThreadScopedSettings,
} from "../utils/thread-scoped-settings";
import {
@@ -781,12 +783,22 @@ let threadSettingsWriteThreadId: string | null = null;
// leaves in the store by the time the debounce fires.
let threadSettingsWriteSnapshot: ThreadScopedSettings | null = null;
+/** Where a thread-scoped key's live value is: sampling under `params`, the rest fields. */
+function readThreadScopedValue(
+ state: ChatRuntimeStore,
+ key: ThreadScopedSettingKey,
+): unknown {
+ return isThreadScopedParamKey(key)
+ ? state.params[key]
+ : (state as Record<string, unknown>)[key];
+}
+
function readThreadScopedSettings(
state: ChatRuntimeStore,
): ThreadScopedSettings {
const source: Record<string, unknown> = {};
for (const key of THREAD_SCOPED_SETTING_KEYS) {
- source[key] = state[key];
+ source[key] = readThreadScopedValue(state, key);
}
// drops "full" with it: a stored bypass would come back without the warning dialog.
return sanitizeThreadScopedSettings(source);
@@ -874,6 +886,129 @@ const CLAMPED_PILL_KEYS = [
] as const;
type ClampedPillKey = (typeof CLAMPED_PILL_KEYS)[number];
+/**
+ * The value of a sampling edit still waiting on its chat's read, if there is one.
+ *
+ * Pills can be read back off the store when the window closes, but the sampling keys
+ * share `params` with the model's recommendation, so a load landing in the same window
+ * would overwrite the edit first, pinning the model's value onto the chat as if the user
+ * had chosen it. Captured at the edit instead; last entry wins, as the read-back did.
+ */
+function heldThreadScopedParamValue(key: string): unknown {
+ for (let i = heldThreadScopedEdits.length - 1; i >= 0; i -= 1) {
+ if (heldThreadScopedEdits[i].field === key) {
+ return heldThreadScopedEdits[i].value;
+ }
+ }
+ return undefined;
+}
+
+/**
+ * Put back the sampling keys the open chat owns, so a model load or status poll applying
+ * that model's recommendation leaves the chat running on what it stored. Only an unpinned
+ * chat falls through to the model's values.
+ */
+function restoreThreadScopedParams(params: InferenceParams): InferenceParams {
+ const kept: Record<string, unknown> = {};
+ for (const key of THREAD_SCOPED_PARAM_KEYS) {
+ // ?? and not ||: 0, "" and -1 are all values a user sets on purpose here.
+ const held = heldThreadScopedParamValue(key) ?? threadScopedOverride(key);
+ if (held === undefined || isSameThreadScopedValue(held, params[key])) {
+ continue;
+ }
+ kept[key] = held;
+ }
+ return hasKeys(kept) ? { ...params, ...kept } : params;
+}
+
+/**
+ * Take the open chat's own values back out of a snapshot about to be remembered against
+ * a model: they belong to the chat, so leaving them in replays one chat's prompt and
+ * sampling into the next chat opened on that model. What the model already remembered
+ * wins over the installation values, so stepping off a model inside a chat does not
+ * flatten a preference it was given outside one.
+ *
+ * A chat whose read is still out owns its keys just as much as an applied one (the edit
+ * sits in heldThreadScopedEdits, not a snapshot); gating on the applied id alone let a
+ * model switch in that window snapshot the chat's sampling into the outgoing model's
+ * memory, which every other chat on that model then replays.
+ */
+function withoutActiveThreadParams(
+ state: ChatRuntimeStore,
+ params: InferenceParams,
+): InferenceParams {
+ if (threadScopedSettingsThreadId === null && pendingPairingThreadId === null) {
+ return params;
+ }
+ const remembered = params.checkpoint
+ ? state.paramsByModel[params.checkpoint]
+ : undefined;
+ const restored: Record<string, unknown> = {};
+ for (const key of THREAD_SCOPED_PARAM_KEYS) {
+ // Only a key this chat actually owns; the rest are already the model's.
+ const held = heldThreadScopedParamValue(key);
+ if (held === undefined && threadScopedOverride(key) === undefined) continue;
+ // For a held key the installation copy can still be null and the store no longer
+ // holds the pre-edit value; the sample taken when the window opened is that value.
+ const own =
+ remembered?.[key] ??
+ globalThreadScopedDefaults?.[key] ??
+ (held !== undefined ? pairingWindowDefaults?.[key] : undefined);
+ if (own === undefined || isSameThreadScopedValue(own, params[key])) {
+ continue;
+ }
+ restored[key] = own;
+ }
+ return hasKeys(restored) ? { ...params, ...restored } : params;
+}
+
+/**
+ * Drop the sampling keys the open chat just took, so they reach neither the installation
+ * defaults nor this model's memory: both are shared with every other chat. A model's own
+ * values are never taken and pass straight through.
+ */
+function withoutCapturedThreadEdits(
+ changedParams: PersistedInferenceParams,
+ fromModelDefaults: boolean,
+): PersistedInferenceParams {
+ const shared: PersistedInferenceParams = {};
+ for (const [key, value] of Object.entries(changedParams)) {
+ if (
+ isThreadScopedParamKey(key) &&
+ !fromModelDefaults &&
+ // By value: this runs inside the updater, so the store still holds the pre-edit
+ // value, and a load in the same pairing window is what a read-back would find.
+ captureThreadScopedEdit(key, null, value)
+ ) {
+ continue;
+ }
+ (shared as Record<string, unknown>)[key] = value;
+ }
+ return shared;
+}
+
+/**
+ * Move the in-memory copy of the installation defaults to what was just written.
+ * `applyThreadScopedSettings` falls back to it for a chat with no snapshot, so leaving it
+ * stale means such a chat runs the sampling of whichever model was loaded before it.
+ */
+function noteThreadScopedDefaults(shared: PersistedInferenceParams): void {
+ let next: Record<string, unknown> | null = null;
+ for (const [key, value] of Object.entries(shared)) {
+ if (!isThreadScopedParamKey(key)) continue;
+ // Held field: the pairing capture restores it from the sample taken when the window
+ // opened, so without this the pre-window value goes back and the in-memory defaults
+ // stay behind the server's for the session, pinning onto the next snapshot-less chat.
+ if (isHeldThreadScopedField(key)) {
+ hydratedDefaultsByHeldField.set(key, value);
+ }
+ if (globalThreadScopedDefaults === null) continue;
+ next ??= { ...globalThreadScopedDefaults };
+ next[key] = value;
+ }
+ if (next !== null) globalThreadScopedDefaults = next as ThreadScopedSettings;
+}
+
function isSameThreadScopedValue(next: unknown, current: unknown): boolean {
if (Object.is(next, current)) return true;
// ragSource is the only object among these, and its variants carry at most a kb id.
@@ -1371,6 +1506,8 @@ let pairingWindowDefaultsThreadId: string | null = null;
let heldThreadScopedEdits: {
field: string;
writeGlobal: (() => void) | null;
+ /** Sampling keys only, captured by value; see heldThreadScopedParamValue. */
+ value?: unknown;
}[] = [];
/** Start of the window: the read for `threadId` is out but its snapshot has not landed. */
@@ -1515,6 +1652,8 @@ export function commitHeldThreadScopedEditsToTheirThread(
closeThreadScopedPairingGate(null);
if (threadId === null || held.length === 0) return Promise.resolve();
const changes = heldThreadScopedChanges(held);
+ // Read off the store above, so only now that the values are safely captured.
+ restoreDefaultsOverCommittedEdits(threadId, held);
if (keepalive) {
sendThreadScopedSettingsBeacon(threadId, changes, true);
return Promise.resolve();
@@ -1524,13 +1663,66 @@ export function commitHeldThreadScopedEditsToTheirThread(
return mergeThreadScopedSettingsIntoRow(threadId, changes);
}
+/**
+ * Put the installation values back over the edits just written to the chat the user left.
+ * Without this the store keeps showing that chat's temperature and system prompt, and the
+ * next chat opened takes them: a snapshot-less one captures the store as the installation
+ * defaults and is pinned with them, a brand new one simply runs on them.
+ *
+ * Only when the chat is actually being left. A failed read about to be retried commits the
+ * same way while the chat stays open, as does a fork; putting the defaults back there
+ * would undo an edit the user is looking at.
+ */
+function restoreDefaultsOverCommittedEdits(
+ threadId: string,
+ held: { field: string }[],
+): void {
+ if (useChatRuntimeStore.getState().activeThreadId === threadId) return;
+ const before = (pairingWindowDefaults ?? globalThreadScopedDefaults) as Record<
+ string,
+ unknown
+ > | null;
+ const fields: Record<string, unknown> = {};
+ const params: Record<string, unknown> = {};
+ for (const edit of held) {
+ // The server answered for this field while the window was open, so that value is
+ // the installation's; the pre-window sample is only what this browser had cached.
+ const value = hydratedDefaultsByHeldField.has(edit.field)
+ ? hydratedDefaultsByHeldField.get(edit.field)
+ : before?.[edit.field];
+ hydratedDefaultsByHeldField.delete(edit.field);
+ // Nothing known to go back to: leaving the edit up is no worse than blanking it.
+ if (value === undefined) continue;
+ if (isThreadScopedParamKey(edit.field)) {
+ params[edit.field] = value;
+ } else {
+ fields[edit.field] = value;
+ }
+ }
+ if (!hasKeys(fields) && !hasKeys(params)) return;
+ // setState and not setParams: these values are already the installation's, and going
+ // through the setter would persist them back to it and to the loaded model's memory.
+ useChatRuntimeStore.setState((state) =>
+ hasKeys(params)
+ ? ({ ...fields, params: { ...state.params, ...params } } as Partial<ChatRuntimeStore>)
+ : (fields as Partial<ChatRuntimeStore>),
+ );
+}
+
/** What the user actually touched, read off the store, which still holds their edits. */
function heldThreadScopedChanges(
held: { field: string }[],
): ThreadScopedSettings {
const edited: Record<string, unknown> = {};
- const live = useChatRuntimeStore.getState() as Record<string, unknown>;
- for (const edit of held) edited[edit.field] = live[edit.field];
+ const live = useChatRuntimeStore.getState();
+ // Same reader the snapshot path uses: sampling keys sit under `params`, so a direct
+ // field read returns undefined and the sanitizer drops them.
+ for (const edit of held) {
+ edited[edit.field] = readThreadScopedValue(
+ live,
+ edit.field as ThreadScopedSettingKey,
+ );
+ }
return sanitizeThreadScopedSettings(edited);
}
@@ -1591,6 +1783,10 @@ async function mergeThreadScopedSettingsIntoRow(
* belong to the chat, so when its pairing window closes the default goes back to the
* value from before the window, which is this browser's pre-hydration copy. The server's
* is the authoritative one and lands nowhere else.
+ *
+ * A default published by a model that loaded inside the window is recorded here for the
+ * same reason: setParams already sent it to the installation, so restoring the pre-window
+ * sample over it would leave this session's copy behind the server's.
*/
const hydratedDefaultsByHeldField = new Map<string, unknown>();
@@ -1603,6 +1799,7 @@ function isHeldThreadScopedField(field: string): boolean {
function captureThreadScopedEdit(
field: string,
writeGlobal: (() => void) | null = null,
+ value?: unknown,
): boolean {
if (!isThreadOwnedSettingKey(field)) return false;
const threadId = useChatRuntimeStore.getState().activeThreadId;
@@ -1617,7 +1814,7 @@ function captureThreadScopedEdit(
return true;
}
if (threadId === pendingPairingThreadId) {
- heldThreadScopedEdits.push({ field, writeGlobal });
+ heldThreadScopedEdits.push({ field, writeGlobal, value });
return true;
}
return false;
@@ -2478,8 +2675,9 @@ type ChatRuntimeStore = {
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. */
+ /** These params are the model's defaults, so its remembered settings are laid back
+ * over them even though the checkpoint did not change. Being the model's and not
+ * the user's, they also move the installation defaults, never the chat's. */
fromModelDefaults?: boolean;
/** The context the model just loaded with. */
maxTokensCap?: number;
@@ -2855,6 +3053,9 @@ function persistReplayedParams(
const changed = getChangedInferenceParams(nextParams, state.params);
if (state.settingsHydrated && hasKeys(changed)) {
saveSettingsPatch({ inferenceParams: changed });
+ // Same reason as the setParams write: the in-memory copy is what a chat with
+ // no snapshot falls back to, so it has to move with what was just stored.
+ noteThreadScopedDefaults(changed);
}
}
@@ -2909,7 +3110,10 @@ function getParamsByModelAfterEdit(
outgoing ?? state.paramsByModel,
nextParams.checkpoint,
changedParams,
- pickRememberedParams(nextParams),
+ // Same filter as the outgoing snapshot: an edit to a key the memory keeps but the
+ // chat does not (maxTokens, fastMode) still records the WHOLE snapshot, so the open
+ // chat's sampling would ride into the model's entry and replay into the next chat.
+ pickRememberedParams(withoutActiveThreadParams(state, nextParams)),
),
nextParams.checkpoint,
);
@@ -2925,7 +3129,9 @@ function rememberOutgoingModel(
if (!state.settingsHydrated && outgoing.checkpoint) {
modelLeftBeforeHydration = outgoing.checkpoint;
}
- const snapshot = pickRememberedParams(outgoing);
+ const snapshot = pickRememberedParams(
+ withoutActiveThreadParams(state, 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.
@@ -3135,6 +3341,15 @@ function getHydratedSettingsState(
const params = { ...state.params };
for (const key of PERSISTED_INFERENCE_PARAM_KEYS) {
const value = settings.inferenceParams?.[key];
+ // A slider moved before this response landed is held for the open chat, like a pill
+ // clicked in the same window. The edit wins in the store, but it is the chat's, so
+ // keep the server's value for the restore that runs when the pairing window closes:
+ // without it the default falls back to this browser's pre-hydration copy and is
+ // pinned onto the next snapshot-less chat. The edit already moved the version below.
+ if (value !== undefined && isHeldThreadScopedField(key)) {
+ hydratedDefaultsByHeldField.set(key, value);
+ continue;
+ }
if (
value !== undefined &&
!keepModelDefaults &&
@@ -3593,14 +3808,21 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
// 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 replayed = checkpointChanged || fromModelDefaults;
const nextParams = getReplayedParams(
state.rememberParamsPerModel,
outgoing ?? state.paramsByModel,
params,
params.checkpoint,
- checkpointChanged || fromModelDefaults,
+ replayed,
options?.maxTokensCap,
);
+ // A chat outranks both the model's memory and its defaults, so the sampling it
+ // pinned goes back on top of the replay. Live store only: persistence is decided
+ // from nextParams below, so a pinning chat does not withhold the model's value.
+ const effective = replayed
+ ? restoreThreadScopedParams(nextParams)
+ : nextParams;
// 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(
@@ -3610,27 +3832,45 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
);
const queuedSettingsChanged = shouldAdvanceQueuedSettingsEpoch(
state.params,
- nextParams,
+ effective,
options?.trackQueuedSettings !== false,
);
+ const persistingGlobally =
+ options?.persist !== false && state.settingsHydrated;
+ // A sampling key moved with a chat open belongs to that chat, so it reaches neither
+ // the installation defaults nor this model's memory, both shared with every other
+ // chat. What is left over is still the installation's.
+ //
+ // Capture is NOT gated on hydration, unlike the global write: the composer and the
+ // settings sheet are live while the initial /api/chat/settings request is still out,
+ // and this chat's pairing has already begun. Leaving such an edit uncaptured let the
+ // arriving snapshot apply over it and let the pairing capture take it for an
+ // installation default, pinning it onto the next snapshot-less chat.
+ const sharedParams =
+ options?.persist !== false
+ ? withoutCapturedThreadEdits(changedParams, fromModelDefaults)
+ : 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,
+ sharedParams,
options?.persist !== false && !fromModelDefaults,
);
- if (options?.persist !== false && state.settingsHydrated) {
+ if (persistingGlobally) {
// 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,
+ sharedParams,
checkpointChanged ? null : paramsByModel,
nextParams.checkpoint,
);
+ // Level with what was just written, or a chat opened later in the same
+ // session falls back to the sampling from before this model loaded.
+ noteThreadScopedDefaults(sharedParams);
} else if (fromModelDefaults && !state.settingsHydrated) {
noteModelDefaultsBeforeHydration(
nextParams.checkpoint,
@@ -3638,7 +3878,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
);
}
return {
- params: nextParams,
+ params: effective,
...(paramsByModel ? { paramsByModel } : {}),
...(queuedSettingsChanged
? { queuedSettingsEpoch: state.queuedSettingsEpoch + 1 }
@@ -3884,8 +4124,15 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
checkpoint: modelId,
maxTokens: nextMaxTokens,
};
+ // The chat outranks the model it switches to, so its pinned sampling and prompt go
+ // back over the replay; an external switch has no load after it to do that. Live
+ // store only: getReplayStatePatch still persists from the unrestored object, so the
+ // model's own values reach the installation defaults.
+ const restoredParams = checkpointChanged
+ ? restoreThreadScopedParams(nextParams)
+ : nextParams;
return {
- params: nextParams,
+ params: restoredParams,
...getReplayStatePatch(state, nextParams, outgoing, baseParams),
activeGgufVariant: nextGgufVariant,
...(queuedSettingsChanged
@@ -3995,10 +4242,11 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
const nextState: Partial<ChatRuntimeStore> = {};
const target = nextState as Record<string, unknown>;
const applied: Record<string, unknown> = {};
+ const paramsPatch: Record<string, unknown> = {};
for (const key of THREAD_SCOPED_SETTING_KEYS) {
// the user set this one while the read was in flight, so it wins over what came back.
if (heldFields.has(key)) {
- applied[key] = state[key];
+ applied[key] = readThreadScopedValue(state, key);
continue;
}
// full access was accepted through a warning dialog: a switch must not drop it.
@@ -4028,7 +4276,18 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
const value = stored?.[key] ?? globalThreadScopedDefaults?.[key];
if (value === undefined) continue;
applied[key] = value;
- if (!isSameThreadScopedValue(value, state[key])) target[key] = value;
+ if (isSameThreadScopedValue(value, readThreadScopedValue(state, key))) {
+ continue;
+ }
+ // The sampling ones are one object, gathered and applied together below.
+ if (isThreadScopedParamKey(key)) {
+ paramsPatch[key] = value;
+ } else {
+ target[key] = value;
+ }
+ }
+ if (hasKeys(paramsPatch)) {
+ nextState.params = { ...state.params, ...paramsPatch };
}
// Search and Thinking are mutually exclusive on Kimi, and the model-selection effect
// that enforces it does not rerun on a thread switch. Restoring both, which a chat
@@ -4542,7 +4801,11 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
state.rememberParamsPerModel,
);
// Turning it on adopts the settings on screen for the active model.
- const snapshot = pickRememberedParams(state.params);
+ // Inside a chat the sampling on screen is that chat's and both writes below are
+ // shared, so the outgoing snapshot's filter takes those keys back out first.
+ const snapshot = pickRememberedParams(
+ withoutActiveThreadParams(state, state.params),
+ );
const paramsByModel = trackParamsByModel(
state,
getRememberedParamsPatch(
@@ -4568,6 +4831,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
// restores that instead.
if (!rememberParamsPerModel && state.settingsHydrated) {
saveSettingsPatch({ inferenceParams: snapshot });
+ // Third write of the installation-wide sampling; level the copy as the others do.
+ noteThreadScopedDefaults(snapshot);
}
return {
rememberParamsPerModel,
diff --git a/studio/frontend/src/features/chat/utils/qwen-params.ts b/studio/frontend/src/features/chat/utils/qwen-params.ts
index c6e55b7f4c6..b4d48d8df43 100644
--- a/studio/frontend/src/features/chat/utils/qwen-params.ts
+++ b/studio/frontend/src/features/chat/utils/qwen-params.ts
@@ -28,5 +28,7 @@ export function applyQwenThinkingParams(thinkingOn: boolean): void {
const params = needsPresencePenalty
? { ...base, presencePenalty: 1.5 }
: base;
+ // Deliberately unmarked, unlike the post-load path applying the same table: the
+ // user asked for this mode here, so it must land even on a chat pinning sampling.
store.setParams({ ...store.params, ...params });
}
diff --git a/studio/frontend/src/features/chat/utils/thread-scoped-settings.ts b/studio/frontend/src/features/chat/utils/thread-scoped-settings.ts
index 7b993573abb..79943442deb 100644
--- a/studio/frontend/src/features/chat/utils/thread-scoped-settings.ts
+++ b/studio/frontend/src/features/chat/utils/thread-scoped-settings.ts
@@ -2,8 +2,8 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
// The chat settings that describe one conversation rather than the installation: the composer
-// pills, the permission level and the retrieval controls. Editing one with a chat open writes
-// this snapshot onto the thread, and reopening that thread applies it back.
+// pills, the permission level, the retrieval controls and the sampling params. Editing one with
+// a chat open writes this snapshot onto the thread, and reopening that thread applies it back.
import type {
PermissionMode,
@@ -38,6 +38,38 @@ export interface ThreadScopedSettings {
ragTopK?: number;
ragAutoInject?: RagAutoInject;
ragAutoInjectMinScore?: number;
+ temperature?: number;
+ topP?: number;
+ topK?: number;
+ minP?: number;
+ repetitionPenalty?: number;
+ presencePenalty?: number;
+ systemPrompt?: string;
+ systemVariables?: string;
+}
+
+/** The subset living under `params` rather than as a store field of its own. */
+export const THREAD_SCOPED_PARAM_KEYS = [
+ "temperature",
+ "topP",
+ "topK",
+ "minP",
+ "repetitionPenalty",
+ "presencePenalty",
+ "systemPrompt",
+ "systemVariables",
+] as const satisfies readonly (keyof ThreadScopedSettings)[];
+
+export type ThreadScopedParamKey = (typeof THREAD_SCOPED_PARAM_KEYS)[number];
+
+const THREAD_SCOPED_PARAM_KEY_SET: ReadonlySet<string> = new Set(
+ THREAD_SCOPED_PARAM_KEYS,
+);
+
+export function isThreadScopedParamKey(
+ key: string,
+): key is ThreadScopedParamKey {
+ return THREAD_SCOPED_PARAM_KEY_SET.has(key);
}
const THREAD_SCOPED_BOOLEAN_KEYS = [
@@ -65,6 +97,14 @@ const THREAD_SCOPED_ENUM_VALUES = {
const THREAD_SCOPED_NUMBER_BOUNDS = {
ragTopK: { min: 1, max: 50, integer: true },
ragAutoInjectMinScore: { min: 0, max: 1, integer: false },
+ // Same ranges as the sampling sliders, and as the ge/le on the same fields.
+ temperature: { min: 0, max: 2, integer: false },
+ topP: { min: 0, max: 1, integer: false },
+ // -1 disables top-k and is what default.yaml resolves to, so the floor is -1, not 0.
+ topK: { min: -1, max: 100, integer: true },
+ minP: { min: 0, max: 1, integer: false },
+ repetitionPenalty: { min: 1, max: 2, integer: false },
+ presencePenalty: { min: 0, max: 2, integer: false },
} as const satisfies Partial<
Record<
keyof ThreadScopedSettings,
@@ -72,7 +112,14 @@ const THREAD_SCOPED_NUMBER_BOUNDS = {
>
>;
+// Not length-capped: truncating a prompt would silently change what the chat runs with.
+const THREAD_SCOPED_STRING_KEYS = [
+ "systemPrompt",
+ "systemVariables",
+] as const satisfies readonly (keyof ThreadScopedSettings)[];
+
export const THREAD_SCOPED_SETTING_KEYS = [
+ ...THREAD_SCOPED_STRING_KEYS,
...THREAD_SCOPED_BOOLEAN_KEYS,
...(Object.keys(
THREAD_SCOPED_ENUM_VALUES,
@@ -133,6 +180,9 @@ export function sanitizeThreadScopedSettings(
const sanitized = sanitizeBoundedNumber(value[key], bounds);
if (sanitized !== undefined) target[key] = sanitized;
}
+ for (const key of THREAD_SCOPED_STRING_KEYS) {
+ if (typeof value[key] === "string") target[key] = value[key];
+ }
const ragSource = sanitizeRagSource(value.ragSource);
if (ragSource) settings.ragSource = ragSource;
return settings;
diff --git a/studio/frontend/tests/helpers/store-stubs/chat-history-storage.ts b/studio/frontend/tests/helpers/store-stubs/chat-history-storage.ts
new file mode 100644
index 00000000000..fc1c48cb345
--- /dev/null
+++ b/studio/frontend/tests/helpers/store-stubs/chat-history-storage.ts
@@ -0,0 +1,66 @@
+// 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 thread row, in memory. Recorded writes are how a test sees what a chat was saved
+// as, and `rows` is what a reopen would read back.
+
+export interface RecordedThreadWrite {
+ threadId: string;
+ /** A replacement write: the whole snapshot. */
+ settings?: Record<string, unknown>;
+ /** A merge write: only the fields the user touched. */
+ settingsPatch?: Record<string, unknown>;
+ settingsSeq?: number;
+ settingsWriter?: string;
+}
+
+export const threadRows = {
+ writes: [] as RecordedThreadWrite[],
+ /** The row as the last write left it, per thread. */
+ rows: new Map<string, Record<string, unknown>>(),
+ /** Reject the next write, to exercise the failure arm. */
+ failNext: false,
+ reset(): void {
+ threadRows.writes.length = 0;
+ threadRows.rows.clear();
+ threadRows.failNext = false;
+ },
+ /** Oldest first. */
+ writesFor(threadId: string): RecordedThreadWrite[] {
+ return threadRows.writes.filter((write) => write.threadId === threadId);
+ },
+};
+
+export async function updateStoredChatThread(
+ threadId: string,
+ update: {
+ settings?: Record<string, unknown>;
+ settingsPatch?: Record<string, unknown>;
+ settingsSeq?: number;
+ settingsWriter?: string;
+ },
+ _options?: { signal?: AbortSignal },
+): Promise<void> {
+ if (threadRows.failNext) {
+ threadRows.failNext = false;
+ throw new Error("stubbed thread write failure");
+ }
+ threadRows.writes.push({ threadId, ...update });
+ const row = threadRows.rows.get(threadId) ?? {};
+ // Replacement replaces settings_json, patch merges into it, as the server's PATCH does.
+ threadRows.rows.set(
+ threadId,
+ update.settings !== undefined
+ ? { ...update.settings }
+ : { ...row, ...update.settingsPatch },
+ );
+}
+
+export async function ensureStoredChatThread(): Promise<void> {}
+
+export async function getStoredChatThread(
+ threadId: string,
+): Promise<{ settings: Record<string, unknown> } | null> {
+ const row = threadRows.rows.get(threadId);
+ return row ? { settings: row } : null;
+}
diff --git a/studio/frontend/tests/helpers/thread-sampling-world.ts b/studio/frontend/tests/helpers/thread-sampling-world.ts
new file mode 100644
index 00000000000..57de89f3d1d
--- /dev/null
+++ b/studio/frontend/tests/helpers/thread-sampling-world.ts
@@ -0,0 +1,424 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// One scenario of the per-chat sampling state machine: a fresh copy of the store, the
+// twelve things a user can do to it, a shadow model of what each chat is owed, and the
+// invariants that have to hold after every single one of them.
+//
+// The store keeps the whole feature in module state, so a scenario gets its own module
+// instance through the "?scenario=" query thread-sampling-resolver.mjs understands.
+// Register that resolver and install the localStorage fake before importing this.
+
+import { threadRows } from "./store-stubs/chat-history-storage.ts";
+import { settingsHttp } from "./store-stubs/settings-http.ts";
+
+const STORE_URL = new URL(
+ "../../src/features/chat/stores/chat-runtime-store.ts",
+ import.meta.url,
+).href;
+const QWEN_URL = new URL(
+ "../../src/features/chat/utils/qwen-params.ts",
+ import.meta.url,
+).href;
+const SETTINGS_URL = new URL(
+ "../../src/features/chat/utils/thread-scoped-settings.ts",
+ import.meta.url,
+).href;
+
+export const SAMPLING_KEYS = [
+ "temperature",
+ "topP",
+ "topK",
+ "minP",
+ "repetitionPenalty",
+ "presencePenalty",
+ "systemPrompt",
+ "systemVariables",
+] as const;
+
+export type SamplingKey = (typeof SAMPLING_KEYS)[number];
+
+/** The ranges PATCH /api/chat/threads/{id} enforces, which the sanitizer mirrors. A live
+ * value outside one of these cannot be stored, so the chat loses it on the next reopen. */
+const BOUNDS: Record<string, { min: number; max: number }> = {
+ temperature: { min: 0, max: 2 },
+ topP: { min: 0, max: 1 },
+ topK: { min: -1, max: 100 },
+ minP: { min: 0, max: 1 },
+ repetitionPenalty: { min: 1, max: 2 },
+ presencePenalty: { min: 0, max: 2 },
+};
+
+export const QWEN = "unsloth/Qwen3.5-9B-GGUF";
+export const LLAMA = "unsloth/Llama-4-8B";
+export const EXTERNAL = "external::anthropic::claude-opus-5";
+
+/** What the installation is holding before anything happens. */
+export const INSTALLATION = {
+ temperature: 0.6,
+ topP: 0.95,
+ topK: 20,
+ minP: 0.01,
+ repetitionPenalty: 1,
+ presencePenalty: 0,
+ systemPrompt: "INSTALLATION PROMPT",
+ systemVariables: "scope=installation",
+};
+
+/** The recommendation a Qwen load publishes. None of it may be pinned onto a chat. */
+export const MODEL_DEFAULTS = {
+ temperature: 0.31,
+ topP: 0.41,
+ topK: 33,
+ minP: 0.02,
+ repetitionPenalty: 1.05,
+ presencePenalty: 0.25,
+};
+
+/** Per-chat sentinels. A value tagged for one chat appearing anywhere else is the leak. */
+const EDITS: Record<string, { temperature: number; systemPrompt: string }> = {
+ A: { temperature: 1.37, systemPrompt: "CHAT A ONLY 5f3a" },
+ B: { temperature: 1.11, systemPrompt: "CHAT B ONLY 9c21" },
+ // With no chat open an edit is the installation's, and must reach the server.
+ "": { temperature: 0.83, systemPrompt: "NO CHAT OPEN 7e44" },
+};
+
+/** The Qwen3 recommended table, as qwen-params.ts applies it. */
+function qwenTable(thinkingOn: boolean, checkpoint: string) {
+ const base = thinkingOn
+ ? { temperature: 0.6, topP: 0.95, topK: 20, minP: 0 }
+ : { temperature: 0.7, topP: 0.8, topK: 20, minP: 0 };
+ const lower = checkpoint.toLowerCase();
+ return lower.includes("qwen3.5") || lower.includes("qwen3.6")
+ ? { ...base, presencePenalty: 1.5 }
+ : base;
+}
+
+export const OPS = [
+ "hydrate",
+ "openA",
+ "openB",
+ "reopenA",
+ "editTemp",
+ "editPrompt",
+ "loadQwen",
+ "qwenPostLoad",
+ "qwenToggleOn",
+ "qwenToggleOff",
+ "switchLlama",
+ "switchExternal",
+ "unload",
+] as const;
+
+export type Op = (typeof OPS)[number];
+
+export interface Violation {
+ invariant: string;
+ step: string;
+ detail: string;
+}
+
+let scenarioCounter = 0;
+
+export interface World {
+ run(ops: readonly Op[]): Promise<Violation[]>;
+}
+
+interface StoreModule {
+ useChatRuntimeStore: {
+ getState: () => Record<string, (...args: never[]) => unknown> & {
+ params: Record<string, unknown>;
+ paramsByModel: Record<string, Record<string, unknown>>;
+ activePresetSource: string;
+ settingsHydrated: boolean;
+ };
+ };
+ beginThreadScopedPairing: (threadId: string) => void;
+}
+
+/** Let the debounced writers and their promise chains finish. */
+async function drain(tick: (ms: number) => void): Promise<void> {
+ for (let round = 0; round < 3; round += 1) {
+ tick(1000);
+ for (let i = 0; i < 6; i += 1) {
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+ }
+}
+
+/**
+ * Run one ordering against a fresh store and return every invariant it broke.
+ *
+ * `tick` advances the mocked clock so the 400ms settings and snapshot debounces settle
+ * between ops instead of bleeding into the next scenario.
+ *
+ * `strict` turns on the shadow-model check (I1/I4/I6): every value a chat is owed is still
+ * what it shows. Orderings that hydrate in the middle run without it, because a chat opened
+ * before the server answered is following a cache, not a choice.
+ */
+export async function runScenario(
+ ops: readonly Op[],
+ tick: (ms: number) => void,
+ strict = true,
+): Promise<Violation[]> {
+ scenarioCounter += 1;
+ settingsHttp.settings = { inferenceParams: { ...INSTALLATION } };
+ settingsHttp.puts.length = 0;
+ settingsHttp.gate = null;
+ settingsHttp.release = null;
+ threadRows.reset();
+
+ const mod: StoreModule = await import(
+ `${STORE_URL}?scenario=${scenarioCounter}`
+ );
+ const qwen: { applyQwenThinkingParams: (on: boolean) => void } = await import(
+ `${QWEN_URL}?scenario=${scenarioCounter}`
+ );
+ const {
+ sanitizeThreadScopedSettings,
+ }: {
+ sanitizeThreadScopedSettings: (value: unknown) => Record<string, unknown>;
+ } = await import(SETTINGS_URL);
+
+ const violations: Violation[] = [];
+ /** What each chat is owed: every sampling key it has been given a value for. */
+ const owed = new Map<string, Record<string, unknown>>();
+ /** The chat whose snapshot the store is showing, or "" for none. */
+ let applied = "";
+ /** Edits made with no chat open: the installation owes each of these a write. */
+ const globalEdits: Record<string, unknown> = {};
+
+ const state = () => mod.useChatRuntimeStore.getState();
+
+ const record = (invariant: string, step: string, detail: string) => {
+ violations.push({ invariant, step, detail });
+ };
+
+ const sampling = (params: Record<string, unknown>) => {
+ const out: Record<string, unknown> = {};
+ for (const key of SAMPLING_KEYS) out[key] = params[key];
+ return out;
+ };
+
+ /** Does `blob` mention a value that belongs to `threadId` alone? */
+ const mentions = (blob: unknown, threadId: string): string | null => {
+ const text = JSON.stringify(blob ?? null);
+ const edit = EDITS[threadId];
+ if (text.includes(JSON.stringify(edit.systemPrompt))) {
+ return edit.systemPrompt;
+ }
+ // Numbers are matched structurally, not by substring: 1.37 inside 11.37 is not a hit.
+ const hit = (value: unknown): boolean => {
+ if (value === edit.temperature) return true;
+ if (Array.isArray(value)) return value.some(hit);
+ if (value !== null && typeof value === "object") {
+ return Object.values(value).some(hit);
+ }
+ return false;
+ };
+ return hit(blob) ? String(edit.temperature) : null;
+ };
+
+ const check = (step: string) => {
+ const live = state();
+ const params = live.params;
+
+ // I7 -- every sampling param the backend would be sent is a usable value.
+ for (const key of SAMPLING_KEYS) {
+ const value = params[key];
+ if (key === "systemPrompt" || key === "systemVariables") {
+ if (typeof value !== "string") {
+ record("I7", step, `${key} is ${JSON.stringify(value)}`);
+ }
+ continue;
+ }
+ if (typeof value !== "number" || !Number.isFinite(value)) {
+ record("I7", step, `${key} is ${JSON.stringify(value)}`);
+ continue;
+ }
+ const bound = BOUNDS[key];
+ if (value < bound.min || value > bound.max) {
+ // Out of the PATCH range: the sanitizer drops it, so the chat cannot store it.
+ record(
+ "I7-range",
+ step,
+ `${key}=${value} outside [${bound.min},${bound.max}]`,
+ );
+ }
+ }
+
+ // I2 -- a value one chat owns reaches neither the installation nor any other chat.
+ for (const threadId of ["A", "B"]) {
+ const leaked = mentions(settingsHttp.puts, threadId);
+ if (leaked !== null) {
+ record(
+ "I2-installation",
+ step,
+ `chat ${threadId}'s ${leaked} in a PUT`,
+ );
+ }
+ const other = threadId === "A" ? "B" : "A";
+ const inOther = mentions(threadRows.rows.get(other) ?? null, threadId);
+ if (inOther !== null) {
+ record(
+ "I2-other-chat",
+ step,
+ `chat ${threadId}'s ${inOther} in ${other}'s row`,
+ );
+ }
+ if (applied === other) {
+ const onScreen = mentions(sampling(params), threadId);
+ if (onScreen !== null) {
+ record(
+ "I2-on-screen",
+ step,
+ `chat ${threadId}'s ${onScreen} shown in ${other}`,
+ );
+ }
+ }
+ // I5 -- and never against a model, which every other chat replays from.
+ const inMemory = mentions(live.paramsByModel, threadId);
+ if (inMemory !== null) {
+ record("I5", step, `chat ${threadId}'s ${inMemory} in paramsByModel`);
+ }
+ }
+
+ // I3 -- an edit made with no chat open is the installation's, and has to reach it.
+ if (live.settingsHydrated) {
+ for (const [key, value] of Object.entries(globalEdits)) {
+ const sent = settingsHttp.puts.some((put) => {
+ const params = put.inferenceParams as
+ | Record<string, unknown>
+ | undefined;
+ return params !== undefined && Object.is(params[key], value);
+ });
+ if (!sent) {
+ record(
+ "I3",
+ step,
+ `${key}=${JSON.stringify(value)} set with no chat open never reached /api/chat/settings`,
+ );
+ }
+ }
+ }
+
+ // I1/I4/I6 -- every value the open chat is owed is still the value it shows.
+ if (strict && applied !== "" && owed.has(applied)) {
+ const want = owed.get(applied) as Record<string, unknown>;
+ for (const [key, value] of Object.entries(want)) {
+ if (!Object.is(params[key], value)) {
+ record(
+ "I1",
+ step,
+ `chat ${applied} ${key}: owed ${JSON.stringify(value)}, shows ${JSON.stringify(params[key])}`,
+ );
+ }
+ }
+ }
+ };
+
+ /** The chat the user is acting in, or "" when none is applied. */
+ const actor = () => applied;
+
+ const open = (threadId: string) => {
+ state().setActiveThreadId(threadId as never);
+ mod.beginThreadScopedPairing(threadId);
+ const row = threadRows.rows.get(threadId);
+ state().applyThreadScopedSettings(
+ threadId as never,
+ (row ? sanitizeThreadScopedSettings(row) : null) as never,
+ );
+ applied = threadId;
+ // A chat with no snapshot pins whatever it opened on, so from here that is what it
+ // is owed. A chat that has one keeps the model built up on its earlier visits.
+ if (!owed.has(threadId)) {
+ owed.set(threadId, sampling(state().params));
+ }
+ };
+
+ const editParam = (patch: Record<string, unknown>) => {
+ const live = state();
+ live.setParams({ ...live.params, ...patch } as never);
+ const who = actor();
+ if (who === "") {
+ // Only once hydration answered: setParams gates its HTTP write on settingsHydrated,
+ // so an earlier edit is fenced instead and reaches the server on the NEXT edit.
+ if (live.settingsHydrated) Object.assign(globalEdits, patch);
+ return;
+ }
+ Object.assign(owed.get(who) ?? {}, patch);
+ };
+
+ const perform = async (op: Op): Promise<void> => {
+ const live = state();
+ switch (op) {
+ case "hydrate":
+ await live.hydratePersistedSettings();
+ break;
+ case "openA":
+ case "reopenA":
+ open("A");
+ break;
+ case "openB":
+ open("B");
+ break;
+ case "editTemp":
+ editParam({ temperature: EDITS[actor()].temperature });
+ break;
+ case "editPrompt":
+ editParam({ systemPrompt: EDITS[actor()].systemPrompt });
+ break;
+ case "loadQwen":
+ // An interactive load: the destination checkpoint and its recommendation.
+ live.setParams(
+ { ...live.params, ...MODEL_DEFAULTS, checkpoint: QWEN } as never,
+ { fromModelDefaults: true } as never,
+ );
+ break;
+ case "qwenPostLoad":
+ // The toggle's table, but published by the load, so it is marked and never pinned.
+ live.setParams(
+ {
+ ...live.params,
+ ...qwenTable(true, String(live.params.checkpoint ?? "")),
+ } as never,
+ { fromModelDefaults: true } as never,
+ );
+ break;
+ case "qwenToggleOn":
+ case "qwenToggleOff": {
+ const on = op === "qwenToggleOn";
+ const checkpoint = String(live.params.checkpoint ?? "");
+ qwen.applyQwenThinkingParams(on);
+ // A user action, so a chat takes it -- but only where the toggle applies.
+ if (
+ checkpoint.toLowerCase().includes("qwen3") &&
+ live.activePresetSource === "builtin-default"
+ ) {
+ const who = actor();
+ if (who !== "") {
+ Object.assign(owed.get(who) ?? {}, qwenTable(on, checkpoint));
+ }
+ }
+ break;
+ }
+ case "switchLlama":
+ live.setCheckpoint(LLAMA as never, null as never);
+ break;
+ case "switchExternal":
+ live.setCheckpoint(EXTERNAL as never, null as never);
+ break;
+ case "unload":
+ live.clearCheckpoint();
+ break;
+ }
+ };
+
+ for (const op of ops) {
+ await perform(op);
+ await drain(tick);
+ check(op);
+ if (violations.length > 0) break;
+ }
+ return violations;
+}
diff --git a/studio/frontend/tests/thread-sampling-resolver.mjs b/studio/frontend/tests/thread-sampling-resolver.mjs
new file mode 100644
index 00000000000..bb7365fe5d4
--- /dev/null
+++ b/studio/frontend/tests/thread-sampling-resolver.mjs
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// store-settings-resolver, plus the two things a per-chat sampling simulation needs.
+//
+// 1. The thread row: the store reaches it through a dynamic relative import the "@/" stub
+// map does not cover, so it has to be intercepted here.
+// 2. Scenario scoping: the store keeps the whole feature in module state, so a simulation
+// running hundreds of orderings needs a fresh copy per ordering. A "?scenario=N" query
+// gives one, and the modules listed below are re-instantiated with it so they talk to
+// THAT copy. Everything else stays shared, which is what makes the stubs observable.
+import { existsSync } from "node:fs";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+import { resolve as resolveSettings } from "./store-settings-resolver.mjs";
+
+const ROW_STUB = new URL(
+ "./helpers/store-stubs/chat-history-storage.ts",
+ import.meta.url,
+).href;
+
+/** Modules that must follow the scenario's store instance, not the shared one. */
+const SCENARIO_SCOPED = new Set([
+ new URL("../src/features/chat/stores/chat-runtime-store.ts", import.meta.url)
+ .href,
+ new URL("../src/features/chat/utils/qwen-params.ts", import.meta.url).href,
+]);
+
+function firstExisting(base) {
+ for (const candidate of [`${base}.ts`, `${base}/index.ts`, base]) {
+ if (existsSync(candidate)) {
+ return pathToFileURL(candidate).href;
+ }
+ }
+ return null;
+}
+
+export function resolve(specifier, context, next) {
+ if (specifier.endsWith("utils/chat-history-storage")) {
+ return next(ROW_STUB, context);
+ }
+ const scenario = context.parentURL?.startsWith("file:")
+ ? new URL(context.parentURL).searchParams.get("scenario")
+ : null;
+ if (scenario !== null && specifier.startsWith(".")) {
+ // Relative resolution drops the parent's query, so this is the plain path.
+ const target = firstExisting(
+ fileURLToPath(new URL(specifier, context.parentURL)),
+ );
+ if (target !== null && SCENARIO_SCOPED.has(target)) {
+ return next(`${target}?scenario=${scenario}`, context);
+ }
+ }
+ return resolveSettings(specifier, context, next);
+}
diff --git a/studio/frontend/tests/thread-scoped-commit-restores-defaults.test.ts b/studio/frontend/tests/thread-scoped-commit-restores-defaults.test.ts
new file mode 100644
index 00000000000..6946a432b74
--- /dev/null
+++ b/studio/frontend/tests/thread-scoped-commit-restores-defaults.test.ts
@@ -0,0 +1,159 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Leaving a chat while its settings read is still out writes the edits made in it to that
+// chat's row. The store is still showing them, so unless the installation values go back
+// over them the next chat takes them: a chat with no snapshot captures the store as the
+// defaults and is pinned with another chat's temperature and system prompt.
+//
+// The same commit runs when a failed read is retried and when a chat is forked, both with
+// the chat still open, and there the edit must stay on screen. Drives both orders.
+
+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();
+// 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("./thread-sampling-resolver.mjs", import.meta.url);
+
+const { settingsHttp } = await import("./helpers/store-stubs/settings-http.ts");
+const { threadRows } = await import(
+ "./helpers/store-stubs/chat-history-storage.ts"
+);
+
+const STORE_URL = new URL(
+ "../src/features/chat/stores/chat-runtime-store.ts",
+ import.meta.url,
+).href;
+
+const MODEL_A = "unsloth/Model-A";
+const CHAT_A = "chat-whose-read-is-still-out";
+const CHAT_B = "chat-with-no-snapshot";
+
+const INSTALLATION_TEMPERATURE = 0.6;
+/** What the user drags the slider to while chat A's read is still out. */
+const EDITED_TEMPERATURE = 1.37;
+const EDITED_PROMPT = "answer only in haiku";
+
+/** The debounced settings write, plus the write chains it hangs off. */
+async function settle(): Promise<void> {
+ await new Promise((resolve) => setTimeout(resolve, 900));
+}
+
+interface StoreModule {
+ useChatRuntimeStore: {
+ getState: () => Record<string, (...args: never[]) => unknown> & {
+ params: Record<string, unknown>;
+ };
+ };
+ beginThreadScopedPairing: (threadId: string) => void;
+ commitHeldThreadScopedEditsToTheirThread: () => Promise<void>;
+}
+
+/** A fresh copy of the store, with the installation defaults hydrated and a model set. */
+async function bootStore(scenario: string): Promise<StoreModule> {
+ settingsHttp.settings = {
+ // Off, so nothing here is about a model's own remembered entry.
+ rememberParamsPerModel: false,
+ inferenceParams: { temperature: INSTALLATION_TEMPERATURE },
+ };
+ settingsHttp.puts.length = 0;
+ threadRows.reset();
+ const mod = (await import(
+ `${STORE_URL}?scenario=${scenario}`
+ )) as never as StoreModule;
+ await mod.useChatRuntimeStore.getState().hydratePersistedSettings();
+ mod.useChatRuntimeStore
+ .getState()
+ .setCheckpoint(MODEL_A as never, null as never);
+ return mod;
+}
+
+test("a chat left mid-read keeps its edits, and the next chat gets the defaults", async () => {
+ const {
+ useChatRuntimeStore,
+ beginThreadScopedPairing,
+ commitHeldThreadScopedEditsToTheirThread,
+ } = await bootStore("commit-restores-defaults");
+ const state = () => useChatRuntimeStore.getState();
+
+ // Chat A is on screen and its read has not answered yet.
+ state().setActiveThreadId(CHAT_A as never);
+ beginThreadScopedPairing(CHAT_A);
+
+ // The user drags temperature and writes a prompt: both are held for this chat.
+ state().setParams({
+ ...state().params,
+ temperature: EDITED_TEMPERATURE,
+ systemPrompt: EDITED_PROMPT,
+ } as never);
+
+ // They leave for chat B before the read lands, so A's pairing tears down.
+ state().setActiveThreadId(CHAT_B as never);
+ await commitHeldThreadScopedEditsToTheirThread();
+ await settle();
+
+ // The edits went to the chat they were made in.
+ assert.deepEqual(
+ threadRows.writesFor(CHAT_A).map((write) => write.settingsPatch),
+ [{ temperature: EDITED_TEMPERATURE, systemPrompt: EDITED_PROMPT }],
+ "the held edits did not reach the chat they were made in",
+ );
+
+ // Chat B turns out to own no snapshot, so it follows the installation defaults.
+ beginThreadScopedPairing(CHAT_B);
+ state().applyThreadScopedSettings(CHAT_B as never, null as never);
+ await settle();
+
+ assert.equal(
+ state().params.temperature,
+ INSTALLATION_TEMPERATURE,
+ "chat A's temperature followed the user into chat B",
+ );
+ assert.equal(
+ state().params.systemPrompt,
+ "",
+ "chat A's system prompt followed the user into chat B",
+ );
+ const pinned = threadRows.rows.get(CHAT_B) ?? {};
+ assert.equal(
+ pinned.temperature,
+ INSTALLATION_TEMPERATURE,
+ "chat B was pinned with chat A's temperature",
+ );
+ assert.equal(
+ pinned.systemPrompt,
+ "",
+ "chat B was pinned with chat A's system prompt",
+ );
+});
+
+test("a commit made with the chat still open leaves the edit on screen", async () => {
+ const {
+ useChatRuntimeStore,
+ beginThreadScopedPairing,
+ commitHeldThreadScopedEditsToTheirThread,
+ } = await bootStore("commit-keeps-open-chat");
+ const state = () => useChatRuntimeStore.getState();
+
+ state().setActiveThreadId(CHAT_A as never);
+ beginThreadScopedPairing(CHAT_A);
+ state().setParams({
+ ...state().params,
+ temperature: EDITED_TEMPERATURE,
+ } as never);
+
+ // The read failed and is about to be retried; the chat is still open.
+ await commitHeldThreadScopedEditsToTheirThread();
+ await settle();
+
+ assert.equal(
+ state().params.temperature,
+ EDITED_TEMPERATURE,
+ "the retry commit put the defaults back over an edit the user is looking at",
+ );
+});
diff --git a/studio/frontend/tests/thread-scoped-held-edit-model-memory.test.ts b/studio/frontend/tests/thread-scoped-held-edit-model-memory.test.ts
new file mode 100644
index 00000000000..14cd589960a
--- /dev/null
+++ b/studio/frontend/tests/thread-scoped-held-edit-model-memory.test.ts
@@ -0,0 +1,113 @@
+// 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 pairing window from the model side. An edit made while a saved chat's snapshot read
+// is still out lives in heldThreadScopedEdits, not in a snapshot, and
+// threadScopedSettingsThreadId is still null because nothing has been applied yet.
+//
+// Every outgoing-model snapshot runs through withoutActiveThreadParams, which used to
+// return early on that null id alone. A model switch inside the window therefore
+// snapshotted the chat's sampling and prompt into the OUTGOING model's memory, shared with
+// every other chat: the next chat opened on that model replays the first chat's prompt and
+// sliders. Drives the real store through that order.
+
+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();
+// 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("./thread-sampling-resolver.mjs", import.meta.url);
+
+const { settingsHttp } = await import("./helpers/store-stubs/settings-http.ts");
+
+const STORE_URL = new URL(
+ "../src/features/chat/stores/chat-runtime-store.ts",
+ import.meta.url,
+).href;
+
+const QWEN = "unsloth/Qwen3.5-9B-GGUF";
+const LLAMA = "unsloth/Llama-4-8B";
+const CHAT_A = "chat-a-read-still-out";
+
+/** What the installation is holding before anything happens. */
+const INSTALLATION_TEMPERATURE = 0.6;
+const INSTALLATION_PROMPT = "INSTALLATION PROMPT";
+/** Chat A's sentinels. Either one appearing anywhere shared is the leak. */
+const EDITED_TEMPERATURE = 1.37;
+const EDITED_PROMPT = "CHAT A ONLY 5f3a";
+
+interface Store {
+ useChatRuntimeStore: {
+ getState: () => Record<string, (...args: never[]) => unknown> & {
+ params: Record<string, unknown>;
+ paramsByModel: Record<string, Record<string, unknown>>;
+ };
+ };
+ beginThreadScopedPairing: (threadId: string) => void;
+}
+
+/** A scenario-scoped copy of the store: the whole feature lives in module state. */
+async function freshStore(scenario: string): Promise<Store> {
+ settingsHttp.settings = {
+ rememberParamsPerModel: true,
+ inferenceParams: {
+ temperature: INSTALLATION_TEMPERATURE,
+ systemPrompt: INSTALLATION_PROMPT,
+ },
+ };
+ settingsHttp.puts.length = 0;
+ const mod = (await import(`${STORE_URL}?scenario=${scenario}`)) as never;
+ return mod as Store;
+}
+
+test("an edit held for an unpaired chat stays out of the outgoing model's memory", async () => {
+ const { useChatRuntimeStore, beginThreadScopedPairing } =
+ await freshStore("held-edit-model-memory");
+ const state = () => useChatRuntimeStore.getState();
+ await state().hydratePersistedSettings();
+ state().setCheckpoint(QWEN as never, null as never);
+
+ // A saved chat is on screen, its read unanswered: the pairing window is open.
+ state().setActiveThreadId(CHAT_A as never);
+ beginThreadScopedPairing(CHAT_A);
+
+ // The user drags temperature and rewrites the prompt: both held for chat A.
+ state().setParams({
+ ...state().params,
+ temperature: EDITED_TEMPERATURE,
+ systemPrompt: EDITED_PROMPT,
+ } as never);
+ assert.equal(state().params.temperature, EDITED_TEMPERATURE);
+ assert.equal(state().params.systemPrompt, EDITED_PROMPT);
+
+ // Then the model is switched before the read lands, which snapshots the outgoing one.
+ state().setCheckpoint(LLAMA as never, null as never);
+
+ const remembered = state().paramsByModel[QWEN] ?? {};
+ assert.notEqual(
+ remembered.temperature,
+ EDITED_TEMPERATURE,
+ "chat A's temperature was remembered against the model it was switched off",
+ );
+ assert.notEqual(
+ remembered.systemPrompt,
+ EDITED_PROMPT,
+ "chat A's system prompt was remembered against the model it was switched off",
+ );
+ // What the model is owed is what the installation had, not nothing: a model that was
+ // never edited still keeps what it ran with, which is the point of the snapshot.
+ assert.equal(remembered.temperature, INSTALLATION_TEMPERATURE);
+ assert.equal(remembered.systemPrompt, INSTALLATION_PROMPT);
+
+ // Nor may it reach the installation, which every snapshot-less chat follows.
+ const puts = JSON.stringify(settingsHttp.puts);
+ assert.ok(!puts.includes(EDITED_PROMPT), "chat A's prompt reached a PUT");
+ assert.ok(
+ !puts.includes(String(EDITED_TEMPERATURE)),
+ "chat A's temperature reached a PUT",
+ );
+});
diff --git a/studio/frontend/tests/thread-scoped-pairing-default-refresh.test.ts b/studio/frontend/tests/thread-scoped-pairing-default-refresh.test.ts
new file mode 100644
index 00000000000..42c679e6d59
--- /dev/null
+++ b/studio/frontend/tests/thread-scoped-pairing-default-refresh.test.ts
@@ -0,0 +1,118 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Closing the pairing window restores the fields whose edits were held, because those
+// edits belong to the chat and must not become the installation default that every
+// snapshot-less chat follows. The value it restores is the sample taken when the window
+// opened.
+//
+// That sample goes stale if a model finishes loading inside the window: setParams
+// publishes the new model's recommendation, marked fromModelDefaults, so it is NOT
+// captured as a chat edit and IS written to /api/chat/settings. Restoring the pre-window
+// sample over it leaves this session's in-memory defaults behind the server's, pinning the
+// old value onto the next snapshot-less chat until reload. Drives that order.
+
+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();
+// 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("./thread-sampling-resolver.mjs", import.meta.url);
+
+const { settingsHttp } = await import("./helpers/store-stubs/settings-http.ts");
+
+const STORE_URL = new URL(
+ "../src/features/chat/stores/chat-runtime-store.ts",
+ import.meta.url,
+).href;
+
+const MODEL_A = "unsloth/Model-A";
+const MODEL_B = "unsloth/Model-B";
+const SAVED_CHAT = "chat-read-still-out";
+const SNAPSHOT_LESS_CHAT = "chat-with-no-snapshot";
+
+const INSTALLATION_TEMPERATURE = 0.6;
+/** What the user drags the slider to while the chat's read is still out. */
+const EDITED_TEMPERATURE = 1.37;
+/** What model B recommends when it finishes loading inside that window. */
+const B_DEFAULT_TEMPERATURE = 0.31;
+/** What the chat turns out to have had stored all along. */
+const STORED_TEMPERATURE = 0.9;
+
+/** The debounced settings PUT, plus the write chains it hangs off. */
+async function settle(): Promise<void> {
+ await new Promise((resolve) => setTimeout(resolve, 900));
+}
+
+test("a default published inside the pairing window survives the window closing", async () => {
+ settingsHttp.settings = {
+ // Off, so nothing here is about a model's own remembered entry.
+ rememberParamsPerModel: false,
+ inferenceParams: { temperature: INSTALLATION_TEMPERATURE },
+ };
+ settingsHttp.puts.length = 0;
+ const { useChatRuntimeStore, beginThreadScopedPairing } = (await import(
+ `${STORE_URL}?scenario=pairing-default-refresh`
+ )) as never as {
+ useChatRuntimeStore: {
+ getState: () => Record<string, (...args: never[]) => unknown> & {
+ params: Record<string, unknown>;
+ };
+ };
+ beginThreadScopedPairing: (threadId: string) => void;
+ };
+ const state = () => useChatRuntimeStore.getState();
+ await state().hydratePersistedSettings();
+ state().setCheckpoint(MODEL_A as never, null as never);
+
+ // A saved chat is on screen and its read has not answered yet.
+ state().setActiveThreadId(SAVED_CHAT as never);
+ beginThreadScopedPairing(SAVED_CHAT);
+
+ // The user drags temperature: the edit is held for this chat.
+ state().setParams({
+ ...state().params,
+ temperature: EDITED_TEMPERATURE,
+ } as never);
+
+ // Model B finishes loading in the same window and publishes its recommendation.
+ state().setParams(
+ {
+ ...state().params,
+ checkpoint: MODEL_B,
+ temperature: B_DEFAULT_TEMPERATURE,
+ } as never,
+ { fromModelDefaults: true } as never,
+ );
+ await settle();
+
+ // That value went to the installation, so it is what the defaults now are.
+ const sentTemperatures = settingsHttp.puts
+ .map((put) => (put.inferenceParams as Record<string, unknown>)?.temperature)
+ .filter((value) => value !== undefined);
+ assert.deepEqual(
+ sentTemperatures,
+ [B_DEFAULT_TEMPERATURE],
+ "the model default published inside the window never reached the installation",
+ );
+
+ // The read finally lands and the window closes.
+ state().applyThreadScopedSettings(SAVED_CHAT as never, {
+ temperature: STORED_TEMPERATURE,
+ } as never);
+
+ // A chat with no snapshot of its own follows the installation defaults, which the
+ // server holds as B's value. Reverting to the pre-window sample here is the bug.
+ state().setActiveThreadId(SNAPSHOT_LESS_CHAT as never);
+ beginThreadScopedPairing(SNAPSHOT_LESS_CHAT);
+ state().applyThreadScopedSettings(SNAPSHOT_LESS_CHAT as never, null as never);
+ assert.equal(
+ state().params.temperature,
+ B_DEFAULT_TEMPERATURE,
+ "a snapshot-less chat is pinned with the pre-window default the server no longer holds",
+ );
+});
diff --git a/studio/frontend/tests/thread-scoped-pairing-invariants.test.ts b/studio/frontend/tests/thread-scoped-pairing-invariants.test.ts
index 8947b330966..f0581284b38 100644
--- a/studio/frontend/tests/thread-scoped-pairing-invariants.test.ts
+++ b/studio/frontend/tests/thread-scoped-pairing-invariants.test.ts
@@ -543,3 +543,204 @@ test("a provider constraint does not rewrite what the chat stored", () => {
assert.match(capture, /constraintSuppressedThreadFields\.delete\(field\)/);
assert.match(store, /constraintSuppressedThreadFields\.clear\(\);/);
});
+
+// The sampling params live under `params`, so the generic key loops have to be told where
+// to look: reading the field directly gets undefined and stores nothing, which looks
+// exactly like the feature working until you reopen.
+test("the sampling params are read and applied through params", () => {
+ assert.match(
+ store,
+ /return isThreadScopedParamKey\(key\)\s*\?\s*state\.params\[key\]\s*:\s*\(state as Record<string, unknown>\)\[key\];/,
+ );
+ // Read through the same helper on both paths, including the held-edit branch.
+ assert.equal(
+ store.match(/readThreadScopedValue\(state, key\)/g)?.length,
+ 3,
+ "the snapshot, the held edit and the sameness check",
+ );
+ // One object, so they are gathered and set together rather than as fields.
+ assert.match(store, /paramsPatch\[key\] = value;/);
+ assert.match(
+ store,
+ /if \(hasKeys\(paramsPatch\)\) \{\s*nextState\.params = \{ \.\.\.state\.params, \.\.\.paramsPatch \};/,
+ );
+});
+
+// A model's own recommendation is not a choice the user made in this chat. Storing it
+// would pin every chat to whatever model happened to load while it was open.
+test("only a user edit to a sampling param lands on the chat", () => {
+ const drop = slice(store, "function withoutCapturedThreadEdits", "\n}");
+ assert.match(
+ drop,
+ // The capture may carry the edited value as a further argument; what this pins is
+ // that it happens for a sampling key, and only when the value is not the model's.
+ /isThreadScopedParamKey\(key\) &&\s*!fromModelDefaults &&[\s\S]{0,300}?captureThreadScopedEdit\(\s*key\b/,
+ );
+ // What the chat takes reaches neither the installation defaults nor this model's memory.
+ const setParams = slice(store, "setParams: (params, options)", "\n setCustomPresets:");
+ assert.match(setParams, /persistParamEdit\(\s*sharedParams,/);
+ assert.match(setParams, /getParamsByModelAfterEdit\([\s\S]{0,200}?sharedParams,/);
+ assert.doesNotMatch(
+ setParams,
+ /getParamsByModelAfterEdit\([\s\S]{0,200}?changedParams,/,
+ "the chat's edit is remembered against the model and leaks to new chats on it",
+ );
+
+ // Both paths that apply a model's own params say so.
+ const runtime = read("../src/features/chat/hooks/use-chat-model-runtime.ts");
+ const status = read("../src/features/chat/lib/apply-inference-status-to-store.ts");
+ for (const source of [runtime, status]) {
+ assert.match(
+ source,
+ /mergeBackendRecommendedInference\([\s\S]{0,700}?fromModelDefaults: true/,
+ );
+ }
+});
+
+// The store holds the edit under `params`, so the flush that runs when the user leaves
+// mid-read must look there: a direct field read is undefined, the sanitizer drops it, and
+// the edit the user watched happen is gone with no error.
+test("an edit held through the pairing window keeps its sampling value", () => {
+ const changes = slice(store, "function heldThreadScopedChanges", "\n}");
+ assert.match(changes, /readThreadScopedValue\(\s*live,\s*edit\.field as ThreadScopedSettingKey,\s*\)/);
+ assert.doesNotMatch(
+ changes,
+ /edited\[edit\.field\] = live\[edit\.field\]/,
+ "reads the field directly, which is undefined for every sampling key",
+ );
+});
+
+// fromModelDefaults only ever changed where the value was persisted; the recommendation
+// still landed in the live params, so the chat ran the model's sampling and the next
+// unrelated edit snapshotted that over what the chat had stored.
+test("a model's recommendation does not overwrite the chat's sampling", () => {
+ const setParams = slice(store, "setParams: (params, options)", "\n setCustomPresets:");
+ // Over the replay, not the raw params: a chat outranks the model's memory and defaults.
+ assert.match(
+ setParams,
+ /const effective = replayed\s*\?\s*restoreThreadScopedParams\(nextParams\)\s*:\s*nextParams;/,
+ );
+ assert.match(setParams, /const replayed = checkpointChanged \|\| fromModelDefaults;/);
+ // and the restored object is the one that reaches the store
+ assert.match(setParams, /params: effective,/);
+ assert.doesNotMatch(setParams, /params: nextParams,/);
+
+ const restore = slice(store, "function restoreThreadScopedParams", "\n}");
+ // An edit still waiting on the chat's read answers first, but the stored snapshot is
+ // what a paired chat restores from, so the override has to be consulted either way.
+ assert.match(restore, /const held = [\s\S]{0,120}?threadScopedOverride\(key\)/);
+ assert.match(restore, /if \(held === undefined/);
+ // ?? and never ||: 0, "" and -1 are values the user sets on purpose.
+ assert.doesNotMatch(restore, /\|\| threadScopedOverride\(key\)/);
+});
+
+// A pinned chat stores every sampling key, so restoring them all would mean the mode the
+// user just asked for arrives with the previous mode's temperature and top-p. The
+// load-time path applies the same table unasked, so it stays marked.
+test("toggling Think applies its params even in a chat that pins sampling", () => {
+ const qwen = read("../src/features/chat/utils/qwen-params.ts");
+ assert.match(qwen, /store\.setParams\(\{ \.\.\.store\.params, \.\.\.params \}\);/);
+ assert.doesNotMatch(
+ qwen,
+ /fromModelDefaults/,
+ "the toggle is treated as a model default, so a pinned chat never changes mode params",
+ );
+ // The post-load application of the same table stays marked.
+ const runtime = read("../src/features/chat/hooks/use-chat-model-runtime.ts");
+ const post = slice(runtime, "store.setParams({ ...store.params, ...p }", "\n }");
+ assert.match(post, /fromModelDefaults: true/);
+});
+
+// Restoring the chat's value makes it equal on both sides of the diff, so diffing the
+// restored object drops the key and the model's recommendation never reaches the
+// installation defaults, leaving every new chat on whatever model loaded before it.
+test("a chat pinning a param does not withhold the model's default from the rest", () => {
+ const setParams = slice(store, "setParams: (params, options)", "\n setCustomPresets:");
+ assert.match(
+ setParams,
+ /getChangedInferenceParams\(\s*nextParams,\s*state\.params,\s*!fromModelDefaults,\s*\)/,
+ );
+ assert.doesNotMatch(
+ setParams,
+ /getChangedInferenceParams\(\s*effective,/,
+ "the restored object decides what is persisted, so pinned keys are withheld",
+ );
+ // Called once: it bumps the mutation versions, so a second diff double-counts.
+ assert.equal(setParams.match(/getChangedInferenceParams\(/g)?.length, 1);
+ // The live store still gets the restored object; only persistence uses the model's.
+ assert.match(setParams, /params: effective,/);
+});
+
+// The write above changes the installation default, but applyThreadScopedSettings falls
+// back to an in-memory copy taken on the way into a chat. Left stale, a chat opened after
+// a model load runs the sampling of whichever model was loaded before it.
+test("the in-memory defaults follow the model defaults that were just written", () => {
+ const setParams = slice(store, "setParams: (params, options)", "\n setCustomPresets:");
+ assert.match(setParams, /noteThreadScopedDefaults\(sharedParams\);/);
+ const note = slice(store, "function noteThreadScopedDefaults", "\n}");
+ assert.match(note, /if \(!isThreadScopedParamKey\(key\)\) continue;/);
+ // Only ever updated, never created: with no chat open there is nothing to hold.
+ assert.match(note, /if \(globalThreadScopedDefaults === null\) continue;/);
+ // A held field is restored from the pre-window sample when the pairing closes, so a
+ // default published inside the window has to be recorded or this session stays behind.
+ assert.match(
+ note,
+ /if \(isHeldThreadScopedField\(key\)\) \{\s*hydratedDefaultsByHeldField\.set\(key, value\);/,
+ );
+ // and it is the fallback apply() actually reads
+ assert.match(store, /stored\?\.\[key\] \?\? globalThreadScopedDefaults\?\.\[key\]/);
+});
+
+// setCheckpoint replays the destination model's remembered params without going through
+// setParams. An external switch has no load after it to correct the result, so the chat
+// silently adopts that model's prompt and sampling and keeps them.
+test("switching model in a chat keeps the chat's sampling, not the model's", () => {
+ const set = slice(store, "setCheckpoint: (modelId, ggufVariant, options)", "\n setActiveThreadId:");
+ assert.match(
+ set,
+ /const restoredParams = checkpointChanged\s*\?\s*restoreThreadScopedParams\(nextParams\)\s*:\s*nextParams;/,
+ );
+ assert.match(set, /params: restoredParams,/);
+ // Persistence still reads the unrestored object, as in setParams: the model's own
+ // values reach the defaults even though the chat keeps running on its own.
+ assert.match(set, /getReplayStatePatch\(state, nextParams, outgoing, baseParams\)/);
+});
+
+// rememberOutgoingModel snapshots the live params, which inside a chat are that chat's.
+// Filtering the incoming edit cannot undo it: the outgoing snapshot is written first,
+// and on a model with no entry it is persisted whole.
+test("the model being left does not remember the open chat's values", () => {
+ const remember = slice(store, "function rememberOutgoingModel", "\n}");
+ assert.match(
+ remember,
+ /pickRememberedParams\(\s*withoutActiveThreadParams\(state, outgoing\),\s*\)/,
+ );
+ assert.doesNotMatch(
+ remember,
+ /pickRememberedParams\(outgoing\)/,
+ "the chat's sampling and prompt are stored as the model's own",
+ );
+ const strip = slice(store, "function withoutActiveThreadParams", "\n}");
+ // Only keys this chat owns, and what the model already knew beats the installation copy,
+ // so leaving a chat does not flatten a preference set outside one. A chat whose read is
+ // still out owns its keys too: the edit is in the held list rather than in a snapshot.
+ assert.match(
+ strip,
+ /if \(held === undefined && threadScopedOverride\(key\) === undefined\) continue;/,
+ );
+ assert.match(
+ strip,
+ /remembered\?\.\[key\] \?\?\s*globalThreadScopedDefaults\?\.\[key\]/,
+ );
+ // and for a held key neither of those may exist yet, so the sample taken when the
+ // window opened is the pre-edit value.
+ assert.match(
+ strip,
+ /held !== undefined \? pairingWindowDefaults\?\.\[key\] : undefined/,
+ );
+ // With no chat open and none awaiting its read there is nothing of a chat's here.
+ assert.match(
+ strip,
+ /if \(threadScopedSettingsThreadId === null && pendingPairingThreadId === null\)/,
+ );
+});
diff --git a/studio/frontend/tests/thread-scoped-params-pre-hydration.test.ts b/studio/frontend/tests/thread-scoped-params-pre-hydration.test.ts
new file mode 100644
index 00000000000..7b300d83938
--- /dev/null
+++ b/studio/frontend/tests/thread-scoped-params-pre-hydration.test.ts
@@ -0,0 +1,94 @@
+// 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 settings sheet is live while the initial /api/chat/settings request is still out:
+// its sliders and system prompt editor call setParams directly, with no hydration guard
+// (only the preset buttons have one). The pairing for the open chat has already begun,
+// which is what holds a pill toggled in that window for the chat.
+//
+// Sampling has to be held the same way. Gating the capture on settingsHydrated, as the
+// global HTTP write is, left the edit uncaptured: the chat's own snapshot then applied
+// over it, and the pairing capture read it off the store as an installation default, which
+// pins it onto the next snapshot-less chat. Drives the real store through that order.
+
+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();
+// 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, beginThreadScopedPairing } = await import(
+ "../src/features/chat/stores/chat-runtime-store.ts"
+);
+
+const SAVED_CHAT = "thread-with-a-snapshot";
+const OTHER_CHAT = "thread-with-no-snapshot";
+
+/** What the installation was set to before the user touched anything. */
+const INSTALLATION_TEMPERATURE = 0.7;
+/** What the user drags the slider to while the settings request is still out. */
+const EDITED_TEMPERATURE = 0.15;
+/** What this chat had stored from an earlier visit. */
+const STORED_TEMPERATURE = 1.3;
+
+test("a sampling edit made before hydration belongs to the open chat", async () => {
+ settingsHttp.settings = {
+ inferenceParams: { temperature: INSTALLATION_TEMPERATURE },
+ };
+ settingsHttp.hold();
+ const hydrating = useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ // The composer is up on a saved chat whose read has not gone out: pairing window open.
+ useChatRuntimeStore.getState().setActiveThreadId(SAVED_CHAT);
+ beginThreadScopedPairing(SAVED_CHAT);
+
+ // The user opens Advanced settings and drags Temperature; no hydration guard there.
+ const before = useChatRuntimeStore.getState().params;
+ useChatRuntimeStore
+ .getState()
+ .setParams({ ...before, temperature: EDITED_TEMPERATURE });
+ assert.equal(
+ useChatRuntimeStore.getState().params.temperature,
+ EDITED_TEMPERATURE,
+ );
+
+ settingsHttp.release?.();
+ await hydrating;
+
+ // The mutation-version fence already kept the response off the key the user moved.
+ assert.equal(
+ useChatRuntimeStore.getState().params.temperature,
+ EDITED_TEMPERATURE,
+ "hydration overwrote the edit",
+ );
+
+ // Hydration done, the chat's own read answers with what it had stored.
+ useChatRuntimeStore
+ .getState()
+ .applyThreadScopedSettings(SAVED_CHAT, { temperature: STORED_TEMPERATURE });
+ const inTheEditedChat = useChatRuntimeStore.getState().params.temperature;
+
+ // Leaving for a chat with no snapshot: it must run on the installation value, not on the
+ // previous chat's edit, and being pinned on open it keeps whatever it lands on for good.
+ useChatRuntimeStore.getState().applyThreadScopedSettings(null, null);
+ useChatRuntimeStore.getState().setActiveThreadId(OTHER_CHAT);
+ beginThreadScopedPairing(OTHER_CHAT);
+ useChatRuntimeStore.getState().applyThreadScopedSettings(OTHER_CHAT, null);
+ const inTheNextChat = useChatRuntimeStore.getState().params.temperature;
+
+ // Both together: an uncaptured edit loses the user's value in the chat they made
+ // it in AND stands in as the installation default for the next chat.
+ assert.deepEqual(
+ { inTheEditedChat, inTheNextChat },
+ {
+ inTheEditedChat: EDITED_TEMPERATURE,
+ inTheNextChat: INSTALLATION_TEMPERATURE,
+ },
+ );
+});
diff --git a/studio/frontend/tests/thread-scoped-sampling-compat.test.ts b/studio/frontend/tests/thread-scoped-sampling-compat.test.ts
new file mode 100644
index 00000000000..a5be712b237
--- /dev/null
+++ b/studio/frontend/tests/thread-scoped-sampling-compat.test.ts
@@ -0,0 +1,628 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Rows written by a Studio without per-chat sampling, rows written by one that has more of
+// it than this build, and the values at the edges of what the sanitizer accepts. Every chat
+// in an existing installation is the first case: the snapshot is re-read through
+// sanitizeThreadScopedSettings on every open, and anything it drops is a setting the user
+// watched themselves choose.
+//
+// The falsy set is the one to watch: temperature 0, minP 0, topP 0, topK -1 and an empty
+// prompt are deliberate choices and all falsy or negative, so a `||` where a `??` belongs,
+// or an `if (value)` guard, silently reverts them. ?? only defers for null and undefined,
+// which is why the store's fallbacks have to use it:
+// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing
+
+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("./thread-sampling-resolver.mjs", import.meta.url);
+
+const { settingsHttp } = await import("./helpers/store-stubs/settings-http.ts");
+const { threadRows } = await import(
+ "./helpers/store-stubs/chat-history-storage.ts"
+);
+const { SAMPLING_KEYS, hasThreadScopedSettings, sanitizeThreadScopedSettings } =
+ {
+ ...(await import("../src/features/chat/utils/thread-scoped-settings.ts")),
+ SAMPLING_KEYS: [
+ "temperature",
+ "topP",
+ "topK",
+ "minP",
+ "repetitionPenalty",
+ "presencePenalty",
+ "systemPrompt",
+ "systemVariables",
+ ] as const,
+ };
+
+const STORE_URL = new URL(
+ "../src/features/chat/stores/chat-runtime-store.ts",
+ import.meta.url,
+).href;
+
+const INSTALLATION = {
+ temperature: 0.6,
+ topP: 0.95,
+ topK: 20,
+ minP: 0.01,
+ repetitionPenalty: 1,
+ presencePenalty: 0,
+ systemPrompt: "INSTALLATION PROMPT",
+ systemVariables: "scope=installation",
+};
+
+/** A row exactly as a Studio from before per-chat sampling would have left it. */
+const LEGACY_ROW = {
+ reasoningEnabled: false,
+ reasoningEffort: "low",
+ toolsEnabled: true,
+ codeToolsEnabled: false,
+ imageToolsEnabled: false,
+ webFetchToolsEnabled: true,
+ deepResearchEnabled: false,
+ artifactsEnabled: true,
+ mcpEnabledForChat: false,
+ permissionMode: "off",
+ ragEnabled: true,
+ ragSource: { type: "kb", kbId: "notes" },
+ ragMode: "dense",
+ ragTopK: 7,
+ ragAutoInject: "on",
+ ragAutoInjectMinScore: 0.4,
+};
+
+let scenario = 0;
+
+/** A store, its two sinks, and the pairing sequence the provider drives. */
+async function world(rows: Record<string, Record<string, unknown>> = {}) {
+ scenario += 1;
+ settingsHttp.settings = { inferenceParams: { ...INSTALLATION } };
+ settingsHttp.puts.length = 0;
+ settingsHttp.gate = null;
+ settingsHttp.release = null;
+ threadRows.reset();
+ for (const [threadId, row] of Object.entries(rows)) {
+ threadRows.rows.set(threadId, row);
+ }
+ const mod = await import(`${STORE_URL}?scenario=compat${scenario}`);
+ const store = () => mod.useChatRuntimeStore.getState();
+ await store().hydratePersistedSettings();
+ return {
+ mod,
+ store,
+ open(threadId: string, override?: unknown) {
+ store().setActiveThreadId(threadId);
+ mod.beginThreadScopedPairing(threadId);
+ const raw =
+ override === undefined ? threadRows.rows.get(threadId) : override;
+ const settings =
+ raw === null || raw === undefined
+ ? null
+ : sanitizeThreadScopedSettings(raw);
+ store().applyThreadScopedSettings(
+ threadId,
+ settings !== null && hasThreadScopedSettings(settings)
+ ? settings
+ : null,
+ );
+ },
+ sampling() {
+ const out: Record<string, unknown> = {};
+ for (const key of SAMPLING_KEYS) out[key] = store().params[key];
+ return out;
+ },
+ };
+}
+
+async function settle(tick: (ms: number) => void): Promise<void> {
+ for (let round = 0; round < 3; round += 1) {
+ tick(1000);
+ for (let i = 0; i < 6; i += 1) {
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+ }
+}
+
+function assertUsable(sampling: Record<string, unknown>, where: string): void {
+ for (const key of SAMPLING_KEYS) {
+ const value = sampling[key];
+ if (key === "systemPrompt" || key === "systemVariables") {
+ assert.equal(typeof value, "string", `${where}: ${key} is not a string`);
+ continue;
+ }
+ assert.equal(typeof value, "number", `${where}: ${key} is not a number`);
+ assert.ok(
+ Number.isFinite(value as number),
+ `${where}: ${key} is ${String(value)}`,
+ );
+ }
+}
+
+// ---------------------------------------------------------------------------
+// C1 -- a row from before any of this existed
+// ---------------------------------------------------------------------------
+
+test("C1: a legacy row opens on the installation sampling, and nothing is zeroed", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const w = await world({ L: { ...LEGACY_ROW } });
+ await settle((ms) => t.mock.timers.tick(ms));
+
+ w.open("L");
+ await settle((ms) => t.mock.timers.tick(ms));
+
+ assertUsable(w.sampling(), "legacy open");
+ // the installation's values, since the row says nothing about sampling
+ assert.deepEqual(w.sampling(), INSTALLATION);
+ // and everything the row DID say is applied
+ assert.equal(w.store().ragTopK, 7);
+ assert.equal(w.store().permissionMode, "off");
+ assert.equal(w.store().reasoningEnabled, false);
+ assert.equal(w.store().toolsEnabled, true);
+ // the row is left as it was: a chat that already has a snapshot is not re-pinned,
+ // so an old Studio reading it back still finds only the keys it knows.
+ assert.deepEqual(threadRows.rows.get("L"), LEGACY_ROW);
+});
+
+// The behaviour a live review item asks about, reported as observed, not as desired: a
+// legacy chat stored no sampling, so it follows the installation defaults and a model load
+// moves those. Nothing chosen is lost, but the second visit shows different numbers.
+test("C1b: a legacy chat follows the installation defaults, which a model load moves", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const w = await world({ L: { ...LEGACY_ROW } });
+ await settle((ms) => t.mock.timers.tick(ms));
+ w.open("L");
+ await settle((ms) => t.mock.timers.tick(ms));
+ const onFirstVisit = w.sampling();
+ assert.equal(onFirstVisit.temperature, INSTALLATION.temperature);
+
+ // a different model loads, publishing its own recommendation
+ w.store().setParams(
+ {
+ ...w.store().params,
+ temperature: 0.31,
+ topP: 0.41,
+ checkpoint: "unsloth/Qwen3.5-9B-GGUF",
+ },
+ { fromModelDefaults: true },
+ );
+ await settle((ms) => t.mock.timers.tick(ms));
+ // the chat pinned nothing, so it takes the model's values, as it did before this
+ assert.equal(w.store().params.temperature, 0.31);
+
+ w.open("Z");
+ w.open("L");
+ await settle((ms) => t.mock.timers.tick(ms));
+ const onSecondVisit = w.sampling();
+ assertUsable(onSecondVisit, "legacy reopen");
+ // OBSERVED: the reopened legacy chat shows the model's sampling. It stored none, so the
+ // fallback is the installation default, and the load moved that.
+ assert.equal(onSecondVisit.temperature, 0.31);
+ assert.notEqual(onSecondVisit.temperature, onFirstVisit.temperature);
+ // and it is still not carrying any sampling of its own
+ assert.deepEqual(threadRows.rows.get("L"), LEGACY_ROW);
+});
+
+test("C1c: a legacy chat that the user then edits pins the WHOLE set, not just the edit", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const w = await world({ L: { ...LEGACY_ROW } });
+ await settle((ms) => t.mock.timers.tick(ms));
+ w.open("L");
+ w.store().setParams({ ...w.store().params, temperature: 1.37 });
+ await settle((ms) => t.mock.timers.tick(ms));
+
+ // The write for a chat that already had a snapshot is a full replacement built from the
+ // store, so all seven other keys are pinned too and the chat stops drifting.
+ const row = threadRows.rows.get("L") as Record<string, unknown>;
+ assert.equal(row.temperature, 1.37);
+ for (const key of SAMPLING_KEYS) {
+ assert.notEqual(row[key], undefined, `${key} was not pinned`);
+ }
+ // the legacy keys survive the replacement
+ assert.equal(row.ragTopK, 7);
+ assert.equal(row.permissionMode, "off");
+ assert.deepEqual(row.ragSource, { type: "kb", kbId: "notes" });
+
+ // and a model load no longer moves it
+ w.store().setParams(
+ {
+ ...w.store().params,
+ temperature: 0.31,
+ checkpoint: "unsloth/Qwen3.5-9B-GGUF",
+ },
+ { fromModelDefaults: true },
+ );
+ await settle((ms) => t.mock.timers.tick(ms));
+ assert.equal(w.store().params.temperature, 1.37);
+});
+
+// ---------------------------------------------------------------------------
+// C2 -- nothing at all
+// ---------------------------------------------------------------------------
+
+test("C2: an empty, null or absent snapshot opens on the installation settings", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ for (const snapshot of [null, {}, undefined]) {
+ const w = await world();
+ await settle((ms) => t.mock.timers.tick(ms));
+ w.open("E", snapshot === undefined ? null : snapshot);
+ await settle((ms) => t.mock.timers.tick(ms));
+ const where = `snapshot ${JSON.stringify(snapshot ?? null)}`;
+ assertUsable(w.sampling(), where);
+ assert.deepEqual(w.sampling(), INSTALLATION, where);
+ // a chat with nothing stored pins what it opened on, so later default changes
+ // cannot rewrite what it runs with
+ const row = threadRows.rows.get("E") as Record<string, unknown>;
+ for (const key of SAMPLING_KEYS) {
+ assert.equal(
+ row[key],
+ INSTALLATION[key as keyof typeof INSTALLATION],
+ where,
+ );
+ }
+ }
+});
+
+test("C2b: hasThreadScopedSettings tells an empty snapshot from a falsy one", () => {
+ assert.equal(hasThreadScopedSettings(null), false);
+ assert.equal(hasThreadScopedSettings(undefined), false);
+ assert.equal(hasThreadScopedSettings({}), false);
+ // every one of these IS a snapshot, however falsy the value
+ assert.equal(hasThreadScopedSettings({ temperature: 0 }), true);
+ assert.equal(hasThreadScopedSettings({ topP: 0 }), true);
+ assert.equal(hasThreadScopedSettings({ minP: 0 }), true);
+ assert.equal(hasThreadScopedSettings({ topK: -1 }), true);
+ assert.equal(hasThreadScopedSettings({ systemPrompt: "" }), true);
+ assert.equal(hasThreadScopedSettings({ systemVariables: "" }), true);
+});
+
+// ---------------------------------------------------------------------------
+// C3 -- a row from a Studio newer or stranger than this one
+// ---------------------------------------------------------------------------
+
+test("C3: unknown future keys are dropped, and the known ones still arrive", () => {
+ const settings = sanitizeThreadScopedSettings({
+ temperature: 0.42,
+ systemPrompt: "kept",
+ // whatever a later build decides to store per chat
+ samplerOrder: ["min_p", "temperature"],
+ dryMultiplier: 0.8,
+ xtcThreshold: 0.1,
+ speculativeDraft: { model: "unsloth/tiny", tokens: 4 },
+ reasoningBudget: 8192,
+ __proto__: { polluted: true },
+ });
+ assert.deepEqual(settings, { temperature: 0.42, systemPrompt: "kept" });
+ assert.equal(
+ (Object.prototype as unknown as Record<string, unknown>).polluted,
+ undefined,
+ "the sanitizer let a prototype through",
+ );
+});
+
+test("C3b: wrong-typed and out-of-range values are dropped, never coerced", () => {
+ const settings = sanitizeThreadScopedSettings({
+ temperature: "hot",
+ topK: 999,
+ topP: -5,
+ minP: null,
+ repetitionPenalty: 0.5,
+ presencePenalty: -2,
+ systemPrompt: 12345,
+ systemVariables: {},
+ });
+ assert.deepEqual(settings, {});
+});
+
+test("C3c: the sanitizer never throws, whatever it is handed", () => {
+ const hostile: unknown[] = [
+ null,
+ undefined,
+ 0,
+ "",
+ "temperature",
+ [1, 2, 3],
+ Number.NaN,
+ () => undefined,
+ new Date(),
+ Object.create(null),
+ { temperature: Number.NaN },
+ { temperature: Number.POSITIVE_INFINITY },
+ { temperature: Number.NEGATIVE_INFINITY },
+ { topK: 1.5 },
+ { topK: Number.MAX_SAFE_INTEGER },
+ { systemPrompt: Symbol("s") },
+ { systemPrompt: { toString: () => "not a string" } },
+ { ragSource: { type: "kb" } },
+ { ragSource: "kb" },
+ {
+ get temperature() {
+ throw new Error("should not be reached twice");
+ },
+ },
+ ];
+ for (const value of hostile) {
+ let settings: Record<string, unknown> = {};
+ try {
+ settings = sanitizeThreadScopedSettings(value) as Record<string, unknown>;
+ } catch (error) {
+ // A throwing getter is the only case allowed to propagate, and only because a
+ // row is JSON: it cannot carry one. Everything else must be handled.
+ assert.ok(
+ value !== null &&
+ typeof value === "object" &&
+ Object.getOwnPropertyDescriptor(value, "temperature")?.get !==
+ undefined,
+ `sanitizeThreadScopedSettings threw on ${String(value)}: ${String(error)}`,
+ );
+ continue;
+ }
+ for (const [key, sanitized] of Object.entries(settings)) {
+ assert.notEqual(sanitized, undefined, `${key} came through as undefined`);
+ assert.notEqual(sanitized, null, `${key} came through as null`);
+ if (typeof sanitized === "number") {
+ assert.ok(
+ Number.isFinite(sanitized),
+ `${key} came through as ${sanitized}`,
+ );
+ }
+ }
+ }
+});
+
+test("C3d: a NaN or Infinity in a row cannot reach the store", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const w = await world({
+ N: {
+ ...LEGACY_ROW,
+ temperature: Number.NaN,
+ topP: Number.POSITIVE_INFINITY,
+ minP: Number.NEGATIVE_INFINITY,
+ systemPrompt: null,
+ },
+ });
+ await settle((ms) => t.mock.timers.tick(ms));
+ w.open("N");
+ await settle((ms) => t.mock.timers.tick(ms));
+ assertUsable(w.sampling(), "NaN row");
+ assert.deepEqual(w.sampling(), INSTALLATION);
+});
+
+// A model recommendation the sanitizer refuses. Nothing ships one today (Llasa's top_p:
+// 1.2 was brought back to 1.0), but the load path applies a recommendation to the live
+// params unclamped, so a custom model_defaults yaml still reaches this.
+test("C3e: an out-of-range recommendation never reaches a chat that pinned that key", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const w = await world();
+ await settle((ms) => t.mock.timers.tick(ms));
+ w.open("A");
+ await settle((ms) => t.mock.timers.tick(ms));
+
+ w.store().setParams(
+ { ...w.store().params, topP: 1.2, checkpoint: "unsloth/Llasa-3B" },
+ { fromModelDefaults: true },
+ );
+ w.store().setParams({ ...w.store().params, temperature: 1.37 });
+ await settle((ms) => t.mock.timers.tick(ms));
+
+ // A pinned every key when it opened, so it keeps its own in-range value. Pinning on open
+ // is what makes this safe: an unpinned chat has nothing to put back.
+ assert.equal(w.store().params.topP, INSTALLATION.topP);
+ const row = threadRows.rows.get("A") as Record<string, unknown>;
+ assert.equal(row.topP, INSTALLATION.topP);
+ assert.equal(row.temperature, 1.37);
+
+ w.open("Z");
+ w.open("A");
+ await settle((ms) => t.mock.timers.tick(ms));
+ assertUsable(w.sampling(), "after an out-of-range recommendation");
+ assert.equal(w.store().params.temperature, 1.37);
+ assert.equal(w.store().params.topP, INSTALLATION.topP);
+});
+
+test("C3f: an out-of-range recommendation taken with no chat open cannot be pinned", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const w = await world();
+ await settle((ms) => t.mock.timers.tick(ms));
+
+ // no chat open, so nothing puts an in-range value back
+ w.store().setParams(
+ { ...w.store().params, topP: 1.2, checkpoint: "unsloth/Llasa-3B" },
+ { fromModelDefaults: true },
+ );
+ await settle((ms) => t.mock.timers.tick(ms));
+ // OBSERVED: the live params run it, and it reaches the installation settings, which
+ // have no such bound. Only the per-chat row does.
+ assert.equal(w.store().params.topP, 1.2);
+ assert.match(JSON.stringify(settingsHttp.puts), /"topP":1\.2/);
+
+ // a chat opened on it pins what it can, omitting topP rather than sending a body the
+ // PATCH would refuse whole, which would cost the chat all seven other keys
+ w.open("A");
+ await settle((ms) => t.mock.timers.tick(ms));
+ const row = threadRows.rows.get("A") as Record<string, unknown>;
+ assert.equal(row.topP, undefined);
+ assert.equal(row.temperature, INSTALLATION.temperature);
+ assert.equal(row.systemPrompt, INSTALLATION.systemPrompt);
+
+ // so the chat keeps running on 1.2, and on reopen has no stored value for it
+ assertUsable(w.sampling(), "out-of-range recommendation, no chat open");
+ assert.equal(w.store().params.topP, 1.2);
+});
+
+// ---------------------------------------------------------------------------
+// C4 -- the falsy and negative edges
+// ---------------------------------------------------------------------------
+
+const FALSY_EDGE = {
+ temperature: 0,
+ topP: 0,
+ topK: -1,
+ minP: 0,
+ repetitionPenalty: 1,
+ presencePenalty: 0,
+ systemPrompt: "",
+ systemVariables: "",
+};
+
+test("C4: the sanitizer keeps every falsy and negative value", () => {
+ assert.deepEqual(sanitizeThreadScopedSettings(FALSY_EDGE), FALSY_EDGE);
+ // topK 0 is inside the range too, and distinct from -1
+ assert.deepEqual(sanitizeThreadScopedSettings({ topK: 0 }), { topK: 0 });
+ assert.deepEqual(sanitizeThreadScopedSettings({ topK: -1 }), { topK: -1 });
+ // and each on its own, so a partial row cannot lose one
+ for (const [key, value] of Object.entries(FALSY_EDGE)) {
+ assert.deepEqual(
+ sanitizeThreadScopedSettings({ [key]: value }),
+ { [key]: value },
+ `${key}=${JSON.stringify(value)} was dropped`,
+ );
+ }
+});
+
+test("C4b: a falsy edit round-trips capture -> persist -> restore", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ for (const topK of [-1, 0]) {
+ const edge = { ...FALSY_EDGE, topK };
+ const w = await world();
+ await settle((ms) => t.mock.timers.tick(ms));
+ w.open("A");
+ w.store().setParams({ ...w.store().params, ...edge });
+ await settle((ms) => t.mock.timers.tick(ms));
+
+ // captured onto the chat, whole
+ const row = threadRows.rows.get("A") as Record<string, unknown>;
+ for (const [key, value] of Object.entries(edge)) {
+ assert.equal(row[key], value, `topK ${topK}: ${key} was not stored`);
+ }
+ // and not onto the installation
+ assert.deepEqual(settingsHttp.puts, [], `topK ${topK}: an edit leaked`);
+
+ // another chat opens on the installation values, untouched by any of it
+ w.open("B");
+ await settle((ms) => t.mock.timers.tick(ms));
+ assert.deepEqual(w.sampling(), INSTALLATION, `topK ${topK}: B inherited A`);
+
+ // and A gets all of it back
+ w.open("A");
+ await settle((ms) => t.mock.timers.tick(ms));
+ assert.deepEqual(
+ w.sampling(),
+ edge,
+ `topK ${topK}: A lost a value on reopen`,
+ );
+ }
+});
+
+test("C4c: a falsy pinned value survives a model load and a model switch", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const w = await world();
+ await settle((ms) => t.mock.timers.tick(ms));
+ w.open("A");
+ w.store().setParams({ ...w.store().params, ...FALSY_EDGE });
+ await settle((ms) => t.mock.timers.tick(ms));
+
+ // a load with a full, non-falsy recommendation
+ w.store().setParams(
+ {
+ ...w.store().params,
+ temperature: 0.31,
+ topP: 0.41,
+ topK: 33,
+ minP: 0.02,
+ presencePenalty: 0.25,
+ systemPrompt: "the model's",
+ checkpoint: "unsloth/Qwen3.5-9B-GGUF",
+ },
+ { fromModelDefaults: true },
+ );
+ await settle((ms) => t.mock.timers.tick(ms));
+ assert.deepEqual(w.sampling(), FALSY_EDGE, "the load overwrote a falsy pin");
+
+ // and an external switch, which has no load after it to put anything back
+ w.store().setCheckpoint("external::anthropic::claude-opus-5", null);
+ await settle((ms) => t.mock.timers.tick(ms));
+ assert.deepEqual(
+ w.sampling(),
+ FALSY_EDGE,
+ "the switch overwrote a falsy pin",
+ );
+
+ // none of it reached the model's memory either
+ const byModel = JSON.stringify(w.store().paramsByModel);
+ assert.doesNotMatch(byModel, /"topK":-1/);
+});
+
+test("C4d: an empty system prompt is a choice, not an absent one", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const w = await world();
+ await settle((ms) => t.mock.timers.tick(ms));
+ // A is given a prompt, B is deliberately cleared
+ w.open("A");
+ w.store().setParams({ ...w.store().params, systemPrompt: "A's prompt" });
+ await settle((ms) => t.mock.timers.tick(ms));
+ w.open("B");
+ w.store().setParams({ ...w.store().params, systemPrompt: "" });
+ await settle((ms) => t.mock.timers.tick(ms));
+
+ assert.equal(
+ (threadRows.rows.get("B") as Record<string, unknown>).systemPrompt,
+ "",
+ );
+ w.open("A");
+ await settle((ms) => t.mock.timers.tick(ms));
+ assert.equal(w.store().params.systemPrompt, "A's prompt");
+ w.open("B");
+ await settle((ms) => t.mock.timers.tick(ms));
+ assert.equal(
+ w.store().params.systemPrompt,
+ "",
+ "the cleared prompt came back as the installation's",
+ );
+});
+
+// ---------------------------------------------------------------------------
+// C5 -- a prompt far larger than anything a slider produces
+// ---------------------------------------------------------------------------
+
+test("C5: a one-megabyte system prompt is neither truncated nor fatal", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const huge = "x".repeat(1024 * 1024);
+ assert.equal(huge.length, 1_048_576);
+
+ // through the sanitizer untouched
+ assert.equal(
+ sanitizeThreadScopedSettings({ systemPrompt: huge }).systemPrompt,
+ huge,
+ );
+
+ const w = await world();
+ await settle((ms) => t.mock.timers.tick(ms));
+ w.open("A");
+ w.store().setParams({ ...w.store().params, systemPrompt: huge });
+ await settle((ms) => t.mock.timers.tick(ms));
+
+ const row = threadRows.rows.get("A") as Record<string, unknown>;
+ assert.equal((row.systemPrompt as string).length, huge.length);
+ assert.equal(row.systemPrompt, huge);
+
+ // and back again after a visit elsewhere
+ w.open("B");
+ await settle((ms) => t.mock.timers.tick(ms));
+ assert.equal(w.store().params.systemPrompt, INSTALLATION.systemPrompt);
+ w.open("A");
+ await settle((ms) => t.mock.timers.tick(ms));
+ assert.equal((w.store().params.systemPrompt as string).length, huge.length);
+ // and it stayed the chat's: a megabyte in the installation payload would be sent
+ // on every settings write for the rest of the session
+ assert.doesNotMatch(
+ JSON.stringify(settingsHttp.puts).slice(0, 200_000),
+ /xxxxxxxxxx/,
+ );
+});
diff --git a/studio/frontend/tests/thread-scoped-sampling-simulation.test.ts b/studio/frontend/tests/thread-scoped-sampling-simulation.test.ts
new file mode 100644
index 00000000000..01ec9ae7e25
--- /dev/null
+++ b/studio/frontend/tests/thread-scoped-sampling-simulation.test.ts
@@ -0,0 +1,650 @@
+// 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 eight sampling keys became per-chat, and unlike every other thread-scoped setting
+// they live under `params` rather than as store fields of their own. That difference is
+// enough to lose an edit or leak it, and neither shows until a chat is reopened, so this
+// drives the real store through every ordering of the ops that touch them, checking after
+// EVERY step that:
+//
+// I1 a value the user set in a chat is still what that chat shows when it is reopened
+// I2 it reaches neither another chat nor the installation-wide settings
+// I3 an edit made with NO chat open does reach the installation-wide settings
+// I4 a model's own recommendation reaches the installation and the model's memory,
+// and is never pinned onto the open chat
+// I5 a chat's pinned values never reach paramsByModel
+// I6 the Qwen Think toggle does land on a chat that pins sampling
+// I7 no operation leaves a sampling param unusable or outside the range the row stores
+//
+// The orderings are generated, not hand-written: the failures this is for are all
+// "these three things in the other order".
+
+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, fireWindowEvent } = 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("./thread-sampling-resolver.mjs", import.meta.url);
+
+const { settingsHttp } = await import("./helpers/store-stubs/settings-http.ts");
+const { threadRows } = await import(
+ "./helpers/store-stubs/chat-history-storage.ts"
+);
+const {
+ EXTERNAL,
+ INSTALLATION,
+ LLAMA,
+ MODEL_DEFAULTS,
+ QWEN,
+ SAMPLING_KEYS,
+ runScenario,
+} = await import("./helpers/thread-sampling-world.ts");
+type Op = Parameters<typeof runScenario>[0][number];
+
+const STORE_URL = new URL(
+ "../src/features/chat/stores/chat-runtime-store.ts",
+ import.meta.url,
+).href;
+
+/** Every ordering of `items`. */
+function permutations<T>(items: readonly T[]): T[][] {
+ if (items.length <= 1) return [[...items]];
+ const out: T[][] = [];
+ for (let i = 0; i < items.length; i += 1) {
+ const rest = [...items.slice(0, i), ...items.slice(i + 1)];
+ for (const tail of permutations(rest)) out.push([items[i], ...tail]);
+ }
+ return out;
+}
+
+/** Every ordered selection of `size` distinct items from `items`. */
+function arrangements<T>(items: readonly T[], size: number): T[][] {
+ if (size === 0) return [[]];
+ const out: T[][] = [];
+ for (let i = 0; i < items.length; i += 1) {
+ const rest = [...items.slice(0, i), ...items.slice(i + 1)];
+ for (const tail of arrangements(rest, size - 1))
+ out.push([items[i], ...tail]);
+ }
+ return out;
+}
+
+/** Run a batch of orderings and fail with the first broken invariant of each. */
+async function sweep(
+ label: string,
+ orderings: readonly Op[][],
+ tick: (ms: number) => void,
+ strict = true,
+): Promise<void> {
+ const failures: string[] = [];
+ for (const ops of orderings) {
+ const violations = await runScenario(ops, tick, strict);
+ for (const violation of violations) {
+ failures.push(
+ `[${violation.invariant}] after ${violation.step} in ${ops.join(" > ")}: ${violation.detail}`,
+ );
+ }
+ }
+ assert.deepEqual(
+ failures.slice(0, 12),
+ [],
+ `${label}: ${failures.length} violation(s) across ${orderings.length} orderings`,
+ );
+}
+
+// ---------------------------------------------------------------------------
+// A. the ordering matrix
+// ---------------------------------------------------------------------------
+
+test("A1: every ordering of edit / load / Think / model switch / reopen", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const orderings = permutations<Op>([
+ "editTemp",
+ "loadQwen",
+ "qwenToggleOn",
+ "switchLlama",
+ "reopenA",
+ ]).map((tail) => ["hydrate", "openA", ...tail] as Op[]);
+ assert.equal(orderings.length, 120);
+ await sweep("A1", orderings, (ms) => t.mock.timers.tick(ms));
+});
+
+test("A2: every ordering of prompt edit / post-load defaults / external / unload / second chat", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const orderings = permutations<Op>([
+ "editPrompt",
+ "qwenPostLoad",
+ "switchExternal",
+ "unload",
+ "openB",
+ ]).map(
+ (tail) => ["hydrate", "loadQwen", "openA", ...tail, "reopenA"] as Op[],
+ );
+ assert.equal(orderings.length, 120);
+ await sweep("A2", orderings, (ms) => t.mock.timers.tick(ms));
+});
+
+test("A3: both chats, both edits, both Think positions, in every order", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const orderings = permutations<Op>([
+ "editTemp",
+ "editPrompt",
+ "openB",
+ "qwenToggleOff",
+ "switchLlama",
+ ]).map(
+ (tail) =>
+ ["hydrate", "loadQwen", "openA", ...tail, "reopenA", "openB"] as Op[],
+ );
+ assert.equal(orderings.length, 120);
+ await sweep("A3", orderings, (ms) => t.mock.timers.tick(ms));
+});
+
+test("A4: every four-step interleaving over the wider alphabet", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const alphabet: Op[] = [
+ "editTemp",
+ "editPrompt",
+ "loadQwen",
+ "qwenPostLoad",
+ "openB",
+ "switchExternal",
+ "unload",
+ ];
+ const orderings = arrangements(alphabet, 4).map(
+ (middle) => ["hydrate", "openA", ...middle, "reopenA"] as Op[],
+ );
+ assert.equal(orderings.length, 840);
+ await sweep("A4", orderings, (ms) => t.mock.timers.tick(ms));
+});
+
+test("A5: hydration interleaved -- nothing leaks, whatever the order", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ // Without the shadow model: a chat opened before the server answered follows this
+ // browser's cache, so what it is "owed" is not yet decided. The leak and usability
+ // invariants still hold, and they are the ones that matter here.
+ const orderings = permutations<Op>([
+ "hydrate",
+ "openA",
+ "editTemp",
+ "loadQwen",
+ "openB",
+ ]).map((ops) => [...ops, "reopenA"] as Op[]);
+ assert.equal(orderings.length, 120);
+ await sweep("A5", orderings, (ms) => t.mock.timers.tick(ms), false);
+});
+
+test("A6: hand-picked long sequences", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const long: Op[][] = [
+ // the reported gap: two chats, a model in between, back to the first
+ [
+ "hydrate",
+ "openA",
+ "editTemp",
+ "editPrompt",
+ "loadQwen",
+ "openB",
+ "editTemp",
+ "switchLlama",
+ "reopenA",
+ "openB",
+ "reopenA",
+ ],
+ // a mode toggled either side of a model switch
+ [
+ "hydrate",
+ "loadQwen",
+ "openA",
+ "qwenToggleOn",
+ "switchLlama",
+ "qwenToggleOff",
+ "reopenA",
+ "switchExternal",
+ "reopenA",
+ ],
+ // an unload in the middle of a pinned chat
+ [
+ "hydrate",
+ "loadQwen",
+ "openA",
+ "editTemp",
+ "unload",
+ "reopenA",
+ "loadQwen",
+ "reopenA",
+ ],
+ // every model transition there is, with a pinned chat open throughout
+ [
+ "hydrate",
+ "openA",
+ "editTemp",
+ "editPrompt",
+ "loadQwen",
+ "switchLlama",
+ "switchExternal",
+ "unload",
+ "loadQwen",
+ "reopenA",
+ ],
+ // the installation edited first, then a chat that must not inherit the next one
+ [
+ "hydrate",
+ "editTemp",
+ "editPrompt",
+ "openA",
+ "editTemp",
+ "openB",
+ "reopenA",
+ "openB",
+ ],
+ // post-load defaults arriving repeatedly, as a status poll does
+ [
+ "hydrate",
+ "loadQwen",
+ "openA",
+ "editTemp",
+ "qwenPostLoad",
+ "qwenPostLoad",
+ "qwenPostLoad",
+ "reopenA",
+ ],
+ // a chat opened, left, and returned to twice over
+ [
+ "hydrate",
+ "openA",
+ "editPrompt",
+ "openB",
+ "reopenA",
+ "openB",
+ "reopenA",
+ "openB",
+ "reopenA",
+ ],
+ // Think toggled in one chat must not follow the user into the other
+ [
+ "hydrate",
+ "loadQwen",
+ "openA",
+ "qwenToggleOn",
+ "openB",
+ "qwenToggleOff",
+ "reopenA",
+ "openB",
+ ],
+ ];
+ await sweep("A6", long, (ms) => t.mock.timers.tick(ms));
+});
+
+// ---------------------------------------------------------------------------
+// The three facts the matrix asserts negatively, asserted positively once each.
+// A sweep that leaks nothing because nothing is ever stored would pass otherwise.
+// ---------------------------------------------------------------------------
+
+test("the pinned values really are stored on the chat's own row", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ await runScenario(
+ ["hydrate", "openA", "editTemp", "editPrompt", "openB", "reopenA"],
+ (ms) => t.mock.timers.tick(ms),
+ );
+ const row = threadRows.rows.get("A") as Record<string, unknown>;
+ assert.equal(row.temperature, 1.37);
+ assert.equal(row.systemPrompt, "CHAT A ONLY 5f3a");
+ // and the whole set, so a later default change cannot rewrite what it runs with
+ for (const key of SAMPLING_KEYS) {
+ assert.notEqual(row[key], undefined, `${key} is not on the row`);
+ }
+});
+
+test("I3: an edit with no chat open reaches the installation-wide settings", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ await runScenario(["hydrate", "editTemp", "editPrompt"], (ms) =>
+ t.mock.timers.tick(ms),
+ );
+ const sent = JSON.stringify(settingsHttp.puts);
+ assert.match(sent, /0\.83/);
+ assert.match(sent, /NO CHAT OPEN 7e44/);
+});
+
+test("I4: a model's recommendation reaches the installation and the model's memory", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ await runScenario(
+ ["hydrate", "openA", "editTemp", "editPrompt", "loadQwen", "switchLlama"],
+ (ms) => t.mock.timers.tick(ms),
+ );
+ const sent = JSON.stringify(settingsHttp.puts);
+ // the installation copy, even though the chat that was open kept its own values
+ assert.match(sent, /"temperature":0\.31/);
+ assert.match(sent, /"topP":0\.41/);
+ // and the model's own memory, taken when the model was left
+ const remembered = JSON.parse(
+ JSON.stringify(
+ (settingsHttp.puts.find((put) => "inferenceParamsByModel" in put)
+ ?.inferenceParamsByModel as Record<string, unknown>) ?? {},
+ ),
+ ) as Record<string, Record<string, unknown>>;
+ assert.equal(remembered[QWEN]?.temperature, MODEL_DEFAULTS.temperature);
+ // ...carrying the installation's prompt, never the open chat's
+ assert.equal(remembered[QWEN]?.systemPrompt, INSTALLATION.systemPrompt);
+});
+
+// ---------------------------------------------------------------------------
+// B. races
+// ---------------------------------------------------------------------------
+
+let raceScenario = 0;
+
+/** A store, a Qwen module bound to it, and the two sinks, all freshly wired. */
+async function raceWorld() {
+ raceScenario += 1;
+ settingsHttp.settings = { inferenceParams: { ...INSTALLATION } };
+ settingsHttp.puts.length = 0;
+ settingsHttp.gate = null;
+ settingsHttp.release = null;
+ threadRows.reset();
+ const mod = await import(`${STORE_URL}?scenario=race${raceScenario}`);
+ const { sanitizeThreadScopedSettings } = await import(
+ "../src/features/chat/utils/thread-scoped-settings.ts"
+ );
+ const store = () => mod.useChatRuntimeStore.getState();
+ return {
+ mod,
+ store,
+ /** setActiveThreadId, open the pairing window, but do NOT answer the read yet. */
+ beginOpen(threadId: string) {
+ store().setActiveThreadId(threadId);
+ mod.beginThreadScopedPairing(threadId);
+ },
+ /** The chat's read comes back. */
+ finishOpen(threadId: string, settings?: Record<string, unknown> | null) {
+ const row =
+ settings === undefined ? threadRows.rows.get(threadId) : settings;
+ store().applyThreadScopedSettings(
+ threadId,
+ row ? sanitizeThreadScopedSettings(row) : null,
+ );
+ },
+ open(threadId: string) {
+ this.beginOpen(threadId);
+ this.finishOpen(threadId);
+ },
+ };
+}
+
+async function settle(tick: (ms: number) => void): Promise<void> {
+ for (let round = 0; round < 3; round += 1) {
+ tick(1000);
+ for (let i = 0; i < 6; i += 1) {
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+ }
+}
+
+test("B1: a slider moved while /api/chat/settings is still in flight survives it", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const w = await raceWorld();
+ settingsHttp.hold();
+ const hydrating = w.store().hydratePersistedSettings();
+ w.store().setParams({ ...w.store().params, temperature: 1.42 });
+ settingsHttp.release?.();
+ await hydrating;
+ await settle((ms) => t.mock.timers.tick(ms));
+ assert.equal(
+ w.store().params.temperature,
+ 1.42,
+ "the edit was hydrated over",
+ );
+ // and a key the user did not touch still takes the server's value
+ assert.equal(w.store().params.systemPrompt, INSTALLATION.systemPrompt);
+});
+
+test("B2: an edit made while the chat's own read is out is stored on that chat", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const w = await raceWorld();
+ await w.store().hydratePersistedSettings();
+ await settle((ms) => t.mock.timers.tick(ms));
+ settingsHttp.puts.length = 0;
+
+ w.beginOpen("A");
+ // the user moves a slider and types a prompt before A's snapshot lands
+ w.store().setParams({
+ ...w.store().params,
+ temperature: 1.37,
+ systemPrompt: "HELD EDIT 5f3a",
+ });
+ w.finishOpen("A", { temperature: 0.22, topP: 0.33, systemPrompt: "STORED" });
+ await settle((ms) => t.mock.timers.tick(ms));
+
+ // the held edit wins over what the read brought back
+ assert.equal(w.store().params.temperature, 1.37);
+ assert.equal(w.store().params.systemPrompt, "HELD EDIT 5f3a");
+ // a key the user did not touch takes the stored value
+ assert.equal(w.store().params.topP, 0.33);
+ // and it reached A's row, not the installation
+ const row = threadRows.rows.get("A") as Record<string, unknown>;
+ assert.equal(row.temperature, 1.37);
+ assert.equal(row.systemPrompt, "HELD EDIT 5f3a");
+ assert.doesNotMatch(JSON.stringify(settingsHttp.puts), /HELD EDIT 5f3a/);
+ assert.doesNotMatch(JSON.stringify(settingsHttp.puts), /1\.37/);
+});
+
+test("B3: leaving mid-read sends the held edit to its own chat, not the next one", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const w = await raceWorld();
+ await w.store().hydratePersistedSettings();
+ await settle((ms) => t.mock.timers.tick(ms));
+ settingsHttp.puts.length = 0;
+
+ w.beginOpen("A");
+ w.store().setParams({
+ ...w.store().params,
+ temperature: 1.37,
+ systemPrompt: "HELD EDIT 5f3a",
+ });
+ // the user gives up on A and opens B before A's read lands
+ await w.mod.commitHeldThreadScopedEditsToTheirThread();
+ w.open("B");
+ await settle((ms) => t.mock.timers.tick(ms));
+
+ // A's row carries the edit as a merge, leaving the rest of its snapshot alone
+ const merged = threadRows
+ .writesFor("A")
+ .filter((write) => write.settingsPatch !== undefined);
+ assert.equal(merged.length, 1);
+ assert.deepEqual(merged[0].settingsPatch, {
+ temperature: 1.37,
+ systemPrompt: "HELD EDIT 5f3a",
+ });
+ // and it is A's alone as far as the installation is concerned
+ assert.doesNotMatch(JSON.stringify(settingsHttp.puts), /HELD EDIT/);
+ assert.doesNotMatch(JSON.stringify(settingsHttp.puts), /1\.37/);
+
+ // What B shows is NOT asserted here. Leaving a chat mid-read leaves the store holding its
+ // edits, and B's applyThreadScopedSettings captures the store as the in-memory defaults,
+ // so B opens on A's values and pins them. Long-standing behaviour of the held-edit path,
+ // not new: `ragTopK` leaks through the same line. Asserting it would freeze it in place.
+});
+
+test("B4: a model load landing during the pairing window does not take the chat's edit", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const w = await raceWorld();
+ await w.store().hydratePersistedSettings();
+ await settle((ms) => t.mock.timers.tick(ms));
+ settingsHttp.puts.length = 0;
+
+ w.beginOpen("A");
+ w.store().setParams({ ...w.store().params, temperature: 1.37 });
+ // the load finishes while A's read is still out
+ w.store().setParams(
+ { ...w.store().params, ...MODEL_DEFAULTS, checkpoint: QWEN },
+ { fromModelDefaults: true },
+ );
+ w.finishOpen("A", null);
+ await settle((ms) => t.mock.timers.tick(ms));
+
+ assert.equal(w.store().params.temperature, 1.37, "the load took the edit");
+ // and the chat was pinned with the user's value, not the one the load published
+ const row = threadRows.rows.get("A") as Record<string, unknown>;
+ assert.equal(
+ row.temperature,
+ 1.37,
+ "the model's value was pinned onto the chat",
+ );
+ // a key the user did not touch still follows the model
+ assert.equal(w.store().params.topP, MODEL_DEFAULTS.topP);
+ // the model's own recommendation still reached the installation
+ assert.match(JSON.stringify(settingsHttp.puts), /"topP":0\.41/);
+ // but the chat's temperature did not
+ assert.doesNotMatch(JSON.stringify(settingsHttp.puts), /1\.37/);
+});
+
+test("B4b: the held sampling edit that survives a load is the LAST one made", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const w = await raceWorld();
+ await w.store().hydratePersistedSettings();
+ await settle((ms) => t.mock.timers.tick(ms));
+
+ w.beginOpen("A");
+ // a slider dragged twice, then the load, then the read
+ w.store().setParams({ ...w.store().params, temperature: 1.2 });
+ w.store().setParams({ ...w.store().params, temperature: 1.37 });
+ w.store().setParams(
+ { ...w.store().params, ...MODEL_DEFAULTS, checkpoint: QWEN },
+ { fromModelDefaults: true },
+ );
+ w.finishOpen("A", null);
+ await settle((ms) => t.mock.timers.tick(ms));
+ assert.equal(w.store().params.temperature, 1.37);
+});
+
+test("B4c: a falsy held edit is not treated as no edit at all", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const w = await raceWorld();
+ await w.store().hydratePersistedSettings();
+ await settle((ms) => t.mock.timers.tick(ms));
+
+ w.beginOpen("A");
+ // 0, "" and -1 are all deliberate choices, and all falsy or negative
+ w.store().setParams({
+ ...w.store().params,
+ temperature: 0,
+ minP: 0,
+ topK: -1,
+ systemPrompt: "",
+ });
+ w.store().setParams(
+ { ...w.store().params, ...MODEL_DEFAULTS, checkpoint: QWEN },
+ { fromModelDefaults: true },
+ );
+ w.finishOpen("A", null);
+ await settle((ms) => t.mock.timers.tick(ms));
+
+ const params = w.store().params;
+ assert.equal(params.temperature, 0);
+ assert.equal(params.minP, 0);
+ assert.equal(params.topK, -1);
+ assert.equal(params.systemPrompt, "");
+ const row = threadRows.rows.get("A") as Record<string, unknown>;
+ assert.equal(row.temperature, 0);
+ assert.equal(row.minP, 0);
+ assert.equal(row.topK, -1);
+ assert.equal(row.systemPrompt, "");
+});
+
+test("B5: two rapid model switches with a pinned chat open", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const w = await raceWorld();
+ await w.store().hydratePersistedSettings();
+ await settle((ms) => t.mock.timers.tick(ms));
+ w.open("A");
+ w.store().setParams({
+ ...w.store().params,
+ temperature: 1.37,
+ systemPrompt: "CHAT A ONLY 5f3a",
+ });
+ await settle((ms) => t.mock.timers.tick(ms));
+ settingsHttp.puts.length = 0;
+
+ // no settle between them: the second switch lands while the first is still writing
+ w.store().setCheckpoint(LLAMA, null);
+ w.store().setCheckpoint(EXTERNAL, null);
+ await settle((ms) => t.mock.timers.tick(ms));
+
+ assert.equal(w.store().params.temperature, 1.37);
+ assert.equal(w.store().params.systemPrompt, "CHAT A ONLY 5f3a");
+ const byModel = JSON.stringify(w.store().paramsByModel);
+ assert.doesNotMatch(
+ byModel,
+ /CHAT A ONLY/,
+ "the chat's prompt became a model's",
+ );
+ assert.doesNotMatch(
+ byModel,
+ /1\.37/,
+ "the chat's temperature became a model's",
+ );
+ assert.doesNotMatch(JSON.stringify(settingsHttp.puts), /CHAT A ONLY/);
+});
+
+test("B6: a thread switch while a load is in flight keeps each chat's own values", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const w = await raceWorld();
+ await w.store().hydratePersistedSettings();
+ await settle((ms) => t.mock.timers.tick(ms));
+ w.open("A");
+ w.store().setParams({ ...w.store().params, temperature: 1.37 });
+ await settle((ms) => t.mock.timers.tick(ms));
+
+ // the user opens B, and the load that was started in A finishes into B
+ w.beginOpen("B");
+ w.store().setParams(
+ { ...w.store().params, ...MODEL_DEFAULTS, checkpoint: QWEN },
+ { fromModelDefaults: true },
+ );
+ w.finishOpen("B", null);
+ await settle((ms) => t.mock.timers.tick(ms));
+ assert.notEqual(
+ w.store().params.temperature,
+ 1.37,
+ "A's temperature followed into B",
+ );
+
+ w.open("A");
+ await settle((ms) => t.mock.timers.tick(ms));
+ assert.equal(w.store().params.temperature, 1.37, "A lost its temperature");
+});
+
+test("B7: a tab closing with a held edit beacons it to the chat it was made in", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const w = await raceWorld();
+ await w.store().hydratePersistedSettings();
+ await settle((ms) => t.mock.timers.tick(ms));
+ settingsHttp.puts.length = 0;
+
+ w.beginOpen("A");
+ w.store().setParams({
+ ...w.store().params,
+ temperature: 1.37,
+ systemPrompt: "HELD EDIT 5f3a",
+ });
+ // pagehide, which is what the store listens on; the read never landed
+ const delivered = fireWindowEvent("pagehide", {});
+ assert.ok(delivered > 0, "the store is not listening for the terminal event");
+ await settle((ms) => t.mock.timers.tick(ms));
+
+ // The beacon is a PATCH, so it is not in `puts`; what it queued for replay is the
+ // durable record of what the closing tab tried to save, and for which chat.
+ const beaconed = JSON.parse(
+ localStorageFake.get("unsloth_chat_thread_settings_replay") ?? "{}",
+ ) as Record<string, { settingsPatch?: Record<string, unknown> }>;
+ assert.deepEqual(beaconed.A?.settingsPatch, {
+ temperature: 1.37,
+ systemPrompt: "HELD EDIT 5f3a",
+ });
+ // the tab-close flush of the installation settings must not carry it
+ assert.doesNotMatch(JSON.stringify(settingsHttp.puts), /HELD EDIT 5f3a/);
+});
diff --git a/studio/frontend/tests/thread-scoped-settings.test.ts b/studio/frontend/tests/thread-scoped-settings.test.ts
index 3425177f6b1..3d4e0a67616 100644
--- a/studio/frontend/tests/thread-scoped-settings.test.ts
+++ b/studio/frontend/tests/thread-scoped-settings.test.ts
@@ -136,3 +136,83 @@ test("an empty snapshot reads as no snapshot", () => {
assert.equal(hasThreadScopedSettings({}), false);
assert.equal(hasThreadScopedSettings({ toolsEnabled: false }), true);
});
+
+// The reported gap: returning to a chat started under one system prompt showed whichever
+// prompt the last chat had. These live under `params`, which is all that makes them special.
+test("the sampling params and the system prompt travel with the chat", () => {
+ const settings = sanitizeThreadScopedSettings({
+ temperature: 0.2,
+ topP: 0.85,
+ topK: 40,
+ minP: 0.02,
+ repetitionPenalty: 1.1,
+ presencePenalty: 0.5,
+ systemPrompt: "You are a terse reviewer.",
+ systemVariables: "name=Ada",
+ });
+ assert.deepEqual(settings, {
+ temperature: 0.2,
+ topP: 0.85,
+ topK: 40,
+ minP: 0.02,
+ repetitionPenalty: 1.1,
+ presencePenalty: 0.5,
+ systemPrompt: "You are a terse reviewer.",
+ systemVariables: "name=Ada",
+ });
+ for (const key of Object.keys(settings)) {
+ assert.ok(isThreadScopedSettingKey(key), key);
+ assert.ok(isThreadOwnedSettingKey(key), key);
+ }
+});
+
+// The bounds are the PATCH model's, so a value the server would refuse must not
+// be sent: extra="forbid" refuses the whole body on one bad field.
+test("a sampling value outside the slider range is dropped", () => {
+ assert.deepEqual(
+ sanitizeThreadScopedSettings({
+ temperature: 2.5,
+ topP: -0.1,
+ topK: 101,
+ minP: 2,
+ repetitionPenalty: 0.5,
+ presencePenalty: 3,
+ }),
+ {},
+ );
+ // The edges themselves are inside.
+ assert.deepEqual(
+ sanitizeThreadScopedSettings({ temperature: 2, topP: 0, topK: 100 }),
+ { temperature: 2, topP: 0, topK: 100 },
+ );
+});
+
+// -1 disables top-k, and default.yaml and whole model families resolve to it, so dropping
+// it means reopening such a chat silently takes whatever top-k the installation last saw.
+test("the disabled top-k value is kept, and it is the floor", () => {
+ assert.deepEqual(sanitizeThreadScopedSettings({ topK: -1 }), { topK: -1 });
+ assert.deepEqual(sanitizeThreadScopedSettings({ topK: -2 }), {});
+});
+
+test("a non-string prompt is dropped rather than coerced", () => {
+ assert.deepEqual(
+ sanitizeThreadScopedSettings({ systemPrompt: 12, systemVariables: null }),
+ {},
+ );
+ // An empty prompt is a real choice, not a missing one.
+ assert.deepEqual(sanitizeThreadScopedSettings({ systemPrompt: "" }), {
+ systemPrompt: "",
+ });
+});
+
+// Context belongs to the model that loaded, not to the conversation, so a chat
+// restoring a budget the current model cannot hold is not a thing that happens.
+test("the context and the model are not per-chat", () => {
+ for (const key of ["maxSeqLength", "maxTokens", "checkpoint"]) {
+ assert.equal(isThreadScopedSettingKey(key), false, key);
+ }
+ assert.deepEqual(
+ sanitizeThreadScopedSettings({ maxTokens: 4096, checkpoint: "some/model" }),
+ {},
+ );
+});
diff --git a/tests/studio/test_new_chat_context_recount.py b/tests/studio/test_new_chat_context_recount.py
index db79d4eb556..c1fb8aea839 100644
--- a/tests/studio/test_new_chat_context_recount.py
+++ b/tests/studio/test_new_chat_context_recount.py
@@ -204,6 +204,14 @@ function getReplayedParams(
function getReplayStatePatch(): any {
return {};
}
+// The open chat's own sampling, laid back over the replay by the sliced
+// setCheckpoint. No thread-scoped snapshot is ever seeded here -- this file is
+// about the context window, not about which chat pinned a temperature -- so
+// nothing is held and the replay passes through untouched. The real restore is
+// covered by studio/frontend/tests/thread-scoped-pairing-invariants.test.ts.
+function restoreThreadScopedParams(params: any): any {
+ return params;
+}
function saveLastExternalCheckpoint(_id: string | null): void {}
function saveBool(_key: string, _value: boolean): void {}
function parseExternalModelId(id: string): any {