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: add a sampling seed to the chat run settings (#9144)

Maheswar Kumarca62b6b94420
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.py
index e79c3a8fbd3..5b2597495e5 100644
--- a/studio/backend/routes/chat_history.py
+++ b/studio/backend/routes/chat_history.py
@@ -13,7 +13,15 @@ import sqlite3
from typing import Annotated, Any, Literal, Optional, Union
from fastapi import APIRouter, Depends, HTTPException, Query, Request
-from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
+from pydantic import (
+ BaseModel,
+ BeforeValidator,
+ ConfigDict,
+ Field,
+ ValidationError,
+ field_serializer,
+ field_validator,
+)
from auth.authentication import get_current_subject
from core.inference.llama_server_args import BATCH_MAX, BATCH_MIN, PARALLEL_MAX, PARALLEL_MIN
@@ -68,6 +76,22 @@ router = APIRouter()
logger = get_logger(__name__)
+def _reject_boolean(value: Any) -> Any:
+ """bool subclasses int, so lax mode would take `true` for a number the user never set."""
+ if isinstance(value, bool):
+ raise ValueError("Expected a number, got a boolean.")
+ return value
+
+
+NotABoolean = Annotated[Optional[int], BeforeValidator(_reject_boolean)]
+
+# llama.cpp spends 0xFFFFFFFF on its "draw one" sentinel, so a pin stops one below it.
+MAX_SAMPLING_SEED = 2**32 - 2
+SamplingSeed = Optional[
+ Annotated[int, Field(ge = 0, le = MAX_SAMPLING_SEED), BeforeValidator(_reject_boolean)]
+]
+
+
class ChatRagThreadSource(BaseModel):
model_config = ConfigDict(extra = "forbid")
@@ -121,6 +145,7 @@ class ChatThreadSettings(BaseModel):
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)
+ seed: SamplingSeed = None
# Not length-capped, like the installation-wide copy: truncating here would
# silently change what the chat runs with.
systemPrompt: Optional[str] = None
@@ -144,6 +169,21 @@ class ChatThread(BaseModel):
forkedFromMessageId: Optional[str] = None
settings: Optional[ChatThreadSettings] = None
+ @field_serializer("settings")
+ def _only_the_keys_the_snapshot_stored(
+ self, settings: Optional[ChatThreadSettings]
+ ) -> Optional[dict]:
+ """Report a key the snapshot never held as absent rather than as null.
+
+ `seed` is the one setting whose null is a value: it means this chat draws its own
+ rather than taking the pinned one. Spelling every unset field as null, which is
+ what the default dump does, would make a snapshot written before the field existed
+ read as a chat that had cleared it.
+ """
+ if settings is None:
+ return None
+ return settings.model_dump(exclude_unset = True)
+
def thread_from_row(row: dict) -> ChatThread:
"""Build a ChatThread from a DATABASE row, tolerating a snapshot it cannot read.
@@ -364,6 +404,7 @@ class ChatInferenceSettings(BaseModel):
systemVariables: Optional[str] = None
trustRemoteCode: Optional[bool] = None
fastMode: Optional[bool] = None
+ seed: SamplingSeed = None
class ChatPresetLoadConfig(BaseModel):
@@ -379,22 +420,13 @@ class ChatPresetLoadConfig(BaseModel):
# The normalizer emits both keys on every preset (null included) and this model is
# extra="forbid", so without them PUT /api/chat/settings 400s the whole save for any
# preset carrying a loadConfig, including one that only pinned nParallel.
- nBatch: Optional[int] = Field(default = None, ge = BATCH_MIN, le = BATCH_MAX)
- nUbatch: Optional[int] = Field(default = None, ge = BATCH_MIN, le = BATCH_MAX)
+ nBatch: NotABoolean = Field(default = None, ge = BATCH_MIN, le = BATCH_MAX)
+ nUbatch: NotABoolean = Field(default = None, ge = BATCH_MIN, le = BATCH_MAX)
tensorParallel: Optional[bool] = None
gpuMemoryMode: Optional[Literal["manual"]] = None
gpuLayers: Optional[int] = None
nCpuMoe: Optional[int] = Field(default = None, ge = 0)
- @field_validator("nBatch", "nUbatch", mode = "before")
- @classmethod
- def _no_booleans(cls, value: Any) -> Any:
- # Same contract as LoadRequest: bool subclasses int, so lax mode would store
- # `true` as 1 here while /load 422s it.
- if isinstance(value, bool):
- raise ValueError("Expected a number, got a boolean.")
- return value
-
class ChatPreset(BaseModel):
model_config = ConfigDict(extra = "forbid")
diff --git a/studio/backend/tests/test_chat_settings_payload.py b/studio/backend/tests/test_chat_settings_payload.py
index 226e4e13c64..5c3a60d4a92 100644
--- a/studio/backend/tests/test_chat_settings_payload.py
+++ b/studio/backend/tests/test_chat_settings_payload.py
@@ -206,3 +206,42 @@ def test_the_rejection_detail_can_be_rendered_as_json():
put_settings({"ragAutoInjectMinScore": float("nan")}, current_subject = "t")
assert excinfo.value.status_code == 400
json.dumps(excinfo.value.detail, allow_nan = False)
+
+
+def test_a_sampling_seed_survives_the_payload():
+ payload = ChatSettingsPayload.model_validate({"inferenceParams": {"seed": 3407}})
+ assert payload.model_dump(exclude_unset = True) == {"inferenceParams": {"seed": 3407}}
+
+
+def test_clearing_the_seed_reaches_the_merge_as_null():
+ """A cleared seed is an explicit null, not an omission: the merge overwrites per
+ key and never removes one, so an omitted seed would leave the old pin in place."""
+ payload = ChatSettingsPayload.model_validate({"inferenceParams": {"seed": None}})
+ updates = payload.model_dump(exclude_unset = True)
+ assert updates == {"inferenceParams": {"seed": None}}
+
+ merged = _deep_merge_settings({"inferenceParams": {"seed": 3407, "topP": 0.9}}, updates)
+ assert merged["inferenceParams"] == {"seed": None, "topP": 0.9}
+
+
+ "seed",
+ [
+ # bool subclasses int, so lax mode would store either as a pin the user never set.
+ True,
+ False,
+ -1,
+ 2**32 - 1, # llama.cpp's "draw one" sentinel, not a value a pin can name.
+ 2**32,
+ 1e40,
+ ],
+)
+def test_out_of_range_seeds_are_refused(seed):
+ with pytest.raises(ValidationError):
+ ChatSettingsPayload.model_validate({"inferenceParams": {"seed": seed}})
+
+
[email protected]("seed", [0, 3407, 2**32 - 2])
+def test_the_whole_uint32_pin_range_is_accepted(seed):
+ payload = ChatSettingsPayload.model_validate({"inferenceParams": {"seed": seed}})
+ assert payload.model_dump(exclude_unset = True) == {"inferenceParams": {"seed": seed}}
diff --git a/studio/backend/tests/test_chat_thread_settings.py b/studio/backend/tests/test_chat_thread_settings.py
index 5465e35431b..e544469d96d 100644
--- a/studio/backend/tests/test_chat_thread_settings.py
+++ b/studio/backend/tests/test_chat_thread_settings.py
@@ -13,6 +13,8 @@ import sys
from pathlib import Path
import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
from pydantic import ValidationError
_BACKEND = Path(__file__).resolve().parents[1]
@@ -24,6 +26,7 @@ from routes.chat_history import ( # noqa: E402
ChatThreadPatch,
ChatThreadSettings,
_settings_write_from_patch,
+ readable_thread_settings,
thread_from_row,
)
from storage import studio_db # noqa: E402
@@ -668,3 +671,63 @@ def test_an_older_build_drops_only_the_sampling_it_cannot_read():
{"toolsEnabled": True, "temperature": 0.3, "somethingNewer": "?"}
)
assert kept == {"toolsEnabled": True, "temperature": 0.3}
+
+
+def test_a_chat_carries_its_own_sampling_seed():
+ """The seed sits with the sliders the snapshot already carries, so without it a pin
+ taken in one chat fixes the draw for every other chat on the same model."""
+ assert ChatThreadSettings.model_validate({"seed": 3407}).seed == 3407
+ assert ChatThreadSettings.model_validate({"seed": 0}).seed == 0
+ assert ChatThreadSettings.model_validate({"seed": 2**32 - 2}).seed == 2**32 - 2
+
+
+ "seed",
+ [
+ # bool subclasses int, so lax mode would store either as a pin the user never set.
+ True,
+ False,
+ -1,
+ 2**32 - 1, # llama.cpp's "draw one" sentinel, not a value a pin can name.
+ 2**32,
+ 1.5,
+ ],
+)
+def test_a_thread_seed_takes_the_same_range_as_the_installation_copy(seed):
+ with pytest.raises(ValidationError):
+ ChatThreadSettings.model_validate({"seed": seed})
+
+
+def test_a_cleared_seed_stays_in_the_stored_snapshot():
+ """null is the clear, not an absence: dropping the key would let the installation pin
+ come back for the one chat the user deliberately unpinned."""
+ assert readable_thread_settings({"seed": None}) == {"seed": None}
+ assert ChatThreadSettings.model_validate({"seed": None}).seed is None
+
+
+def _thread_row(settings):
+ row = {"id": "thread-1", "modelType": "base", "createdAt": 0}
+ return row if settings is None else {**row, "settings": settings}
+
+
+ "stored, expected",
+ [
+ # Written before the seed existed. Absent, so the chat takes the pin it inherits.
+ ({"temperature": 0.3}, {"temperature": 0.3}),
+ # Written by a build that has it, with the pin cleared. null is the chat's choice.
+ ({"temperature": 0.3, "seed": None}, {"temperature": 0.3, "seed": None}),
+ ({"temperature": 0.3, "seed": 3407}, {"temperature": 0.3, "seed": 3407}),
+ ],
+)
+def test_the_response_says_absent_for_a_key_the_snapshot_never_held(stored, expected):
+ """The default dump spells every unset field as null, and the client drops those, so
+ a pre-seed snapshot would read as a chat that had cleared the pin."""
+ app = FastAPI()
+
+ @app.get("/thread", response_model = ChatThread)
+ def _read():
+ return thread_from_row(_thread_row(stored))
+
+ with TestClient(app) as client:
+ assert client.get("/thread").json()["settings"] == expected
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 7b149e26216..10fb4f6d0b6 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -171,7 +171,7 @@ import type {
OpenAIMessageContent,
OpenAIReasoningContentPart,
} from "../types/api";
-import type { ChatModelSummary } from "../types/runtime";
+import { modelReadsSamplingSeed, type ChatModelRow } from "../types/runtime";
import { loadFallbackNotice } from "../utils/mmproj-fallback";
import {
getStoredChatThread,
@@ -2318,6 +2318,9 @@ function queuedResolvedModelFromStore(
? {
isVision: activeModel.isVision,
isGguf: activeModel.isGguf,
+ // The queued run mints its own summary for a model with no catalog row, and
+ // the sampling seed is gated on this.
+ isMlx: activeModel.isMlx,
isAudio: activeModel.isAudio,
audioType: activeModel.audioType,
hasAudioInput: activeModel.hasAudioInput,
@@ -3680,12 +3683,15 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
maxTokensCap: loadResp.context_length ?? undefined,
},
);
- const defaultModel: ChatModelSummary = {
+ const defaultModel: ChatModelRow = {
id: DEFAULT_CHAT_MODEL_REPO,
name: loadResp.display_name ?? DEFAULT_CHAT_MODEL_LABEL,
isVision: loadResp.is_vision ?? false,
isLora: false,
isGguf: true,
+ isMlx: false,
+ isAudio: false,
+ hasAudioInput: false,
};
if (!store.models.some((m) => m.id === DEFAULT_CHAT_MODEL_REPO)) {
store.setModels([...store.models, defaultModel]);
@@ -3814,6 +3820,7 @@ async function resolveQueuedEmptyLocalModel(
modelCapabilities: {
isVision: status.is_vision ?? false,
isGguf: status.is_gguf ?? false,
+ isMlx: status.is_mlx ?? false,
isAudio: status.is_audio ?? false,
audioType: status.audio_type ?? null,
hasAudioInput: status.has_audio_input ?? false,
@@ -5786,6 +5793,12 @@ export function createOpenAIStreamAdapter(
min_p: params.minP,
repetition_penalty: params.repetitionPenalty,
presence_penalty: params.presencePenalty,
+ // Omitted when unset so the server keeps drawing a fresh seed, and when the
+ // backend does not read one, so a pin left over from a GGUF is not sent
+ // invisibly after a switch to transformers.
+ ...(params.seed == null || !modelReadsSamplingSeed(activeModel)
+ ? {}
+ : { seed: params.seed }),
image_base64: imageBase64,
audio_base64: audioBase64,
video_base64: videoBase64,
diff --git a/studio/frontend/src/features/chat/chat-settings-sheet.tsx b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
index 54176d1ecfb..8ed9842587e 100644
--- a/studio/frontend/src/features/chat/chat-settings-sheet.tsx
+++ b/studio/frontend/src/features/chat/chat-settings-sheet.tsx
@@ -105,7 +105,11 @@ import {
isLocalModelPath,
useChatRuntimeStore,
} from "./stores/chat-runtime-store";
-import type { InferenceParams } from "./types/runtime";
+import {
+ MAX_SAMPLING_SEED,
+ modelReadsSamplingSeed,
+ type InferenceParams,
+} from "./types/runtime";
export { defaultInferenceParams, type Preset } from "./presets/preset-policy";
export type { InferenceParams } from "./types/runtime";
@@ -515,6 +519,13 @@ export function ChatSettingsPanel({
isLoadedGguf ||
ggufContextLength != null ||
(currentCheckpoint?.toLowerCase().endsWith(".gguf") ?? false);
+ const activeModel = useChatRuntimeStore(
+ (s) => s.models.find((m) => m.id === currentCheckpoint) ?? null,
+ );
+ // Same call the request body makes, on the same summary, so the panel cannot offer a
+ // seed the body drops. An external selection carries an `external::` id that no local
+ // entry matches, so the summary answers that case without a separate guard.
+ const showSeed = modelReadsSamplingSeed(activeModel);
const platformDeviceType = usePlatformStore((s) => s.deviceType);
// Unified memory, not just Darwin: an Intel Mac spills to system RAM like a PC.
const isUnifiedMemory = usePlatformStore((s) => s.appleSilicon);
@@ -618,6 +629,36 @@ export function ChatSettingsPanel({
const [systemPromptDraft, setSystemPromptDraft] = useState("");
const [systemVariablesDraft, setSystemVariablesDraft] = useState("");
const [systemVariablesOpen, setSystemVariablesOpen] = useState(false);
+ // Raw keystrokes while the Seed box is being typed into, null once committed.
+ // Clamping straight into params would rewrite the box mid-entry, so the commit
+ // waits for blur the way NumericValueInput's does.
+ const [seedDraft, setSeedDraft] = useState<string | null>(null);
+ // What blur would commit, available before it runs. Clicking Save blurs the box during
+ // mousedown, but React has not re-rendered by the time that button's onClick fires, so
+ // a handler reading `params` there still sees the seed from before the entry.
+ // NumericValueInput bridges the same gap with its imperative commit().
+ const committedSeed = useMemo<number | null>(() => {
+ if (seedDraft === null) return params.seed ?? null;
+ // Measured after the padding: a zero-padded seed is short enough to keep, and
+ // truncating instead of clamping would rewrite it.
+ const digits = seedDraft.replace(/^0+(?=\d)/, "");
+ if (digits === "") return null;
+ return digits.length > 10
+ ? MAX_SAMPLING_SEED
+ : Math.min(Number(digits), MAX_SAMPLING_SEED);
+ }, [params.seed, seedDraft]);
+ const paramsWithCommittedSeed = useMemo(
+ () =>
+ committedSeed === (params.seed ?? null)
+ ? params
+ : { ...params, seed: committedSeed },
+ [committedSeed, params],
+ );
+ // Removing a focused element fires no blur, so a draft the user walked away from
+ // would keep reporting through committedSeed with the field gone.
+ useEffect(() => {
+ setSeedDraft(null);
+ }, [currentCheckpoint, showSeed]);
// When the prompt overflows the inline box, clicking opens the popup editor.
const systemPromptBoxRef = useRef<HTMLTextAreaElement>(null);
const [systemPromptOverflows, setSystemPromptOverflows] = useState(false);
@@ -661,8 +702,12 @@ export function ChatSettingsPanel({
}
const samplingChanged =
activePresetDefinition.name === "Default"
- ? activePresetSource === "modified"
- : !isSamePresetConfig(activePresetDefinition.params, params);
+ ? activePresetSource === "modified" ||
+ committedSeed !== (params.seed ?? null)
+ : !isSamePresetConfig(
+ activePresetDefinition.params,
+ paramsWithCommittedSeed,
+ );
const currentLoadConfig = capturePresetLoadConfig();
const loadChanged = !isSamePresetLoadConfig(
activePresetDefinition.loadConfig,
@@ -673,6 +718,8 @@ export function ChatSettingsPanel({
activePresetDefinition,
activePresetSource,
params,
+ committedSeed,
+ paramsWithCommittedSeed,
customContextLength,
ggufContextLength,
kvCacheDtype,
@@ -781,6 +828,8 @@ export function ChatSettingsPanel({
};
}
+ const setSeed = set("seed");
+
// Lower a live Max Tokens that no longer fits the connection's cap.
// `resolveExternalMaxTokensClamp` documents why an unresolved provider must not be
// read as the 32,768 fallback.
@@ -866,7 +915,7 @@ export function ChatSettingsPanel({
...next,
{
name: saveName,
- params: toPresetParams(params),
+ params: toPresetParams(paramsWithCommittedSeed),
...(loadConfig ? { loadConfig } : {}),
},
];
@@ -1491,6 +1540,54 @@ export function ChatSettingsPanel({
}
info="Maximum number of tokens to generate per response. Generation stops at this limit or when the model emits an end-of-sequence token."
/>
+ {showSeed ? (
+ <div className="flex items-center justify-between gap-3">
+ <div className="flex min-w-0 items-center gap-1.5">
+ <span className="min-w-0 text-ui-13 font-medium leading-[1.25] tracking-nav text-nav-fg">
+ Seed
+ </span>
+ <InfoHint>
+ Pins the sampling draw so the same prompt and settings can
+ reproduce the same reply. Leave blank to draw a fresh seed
+ each request. It only fixes the draw, so the other sampling
+ settings have to stay put as well; at Temperature 0 decoding
+ is already greedy and a seed changes nothing. Matching a
+ reply also needs the model loaded with Parallel Slots at 1
+ and Speculative Decoding off, since both change how tokens
+ are batched and that moves the result.
+ </InfoHint>
+ </div>
+ <InputGroup className="panel-input-group w-[8.5rem] shrink-0">
+ <InputGroupInput
+ id="inference-seed"
+ // A TEXT input: type="number" reports an unreadable entry as "", clearing the pin.
+ type="text"
+ inputMode="numeric"
+ autoComplete="off"
+ spellCheck={false}
+ value={
+ seedDraft ??
+ (params.seed == null ? "" : String(params.seed))
+ }
+ onChange={(e) =>
+ setSeedDraft(e.target.value.replace(/\D/g, ""))
+ }
+ onBlur={() => {
+ if (seedDraft === null) return;
+ setSeedDraft(null);
+ setSeed(committedSeed);
+ }}
+ onKeyDown={(e) => {
+ // Blur is the only commit, so Enter has to reach it.
+ if (e.key === "Enter") e.currentTarget.blur();
+ }}
+ placeholder="Random"
+ aria-label="Seed"
+ className="!h-9 min-h-0 min-w-0 self-stretch !px-3 py-0 text-ui-13 font-medium leading-9 text-nav-fg md:text-ui-13"
+ />
+ </InputGroup>
+ </div>
+ ) : null}
</div>
</CollapsibleSection>
diff --git a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
index 75dcda4d0e2..ea40aee1d47 100644
--- a/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
+++ b/studio/frontend/src/features/chat/hooks/use-chat-model-runtime.ts
@@ -109,7 +109,7 @@ import {
} from "@/features/model-picker/api/llama-flags";
import type {
ChatLoraSummary,
- ChatModelSummary,
+ ChatModelRow,
} from "../types/runtime";
export type SelectedModelInput = {
@@ -249,7 +249,7 @@ function describeModel(model: {
return tags.join(" · ");
}
-function toChatModelSummary(model: {
+function toChatModelRow(model: {
id: string;
name?: string | null;
is_lora?: boolean;
@@ -260,7 +260,7 @@ function toChatModelSummary(model: {
audio_type?: string | null;
has_audio_input?: boolean;
has_video_input?: boolean;
-}): ChatModelSummary {
+}): ChatModelRow {
return {
id: model.id,
name: model.name || model.id,
@@ -288,6 +288,7 @@ export function syncModelCapabilities(
is_vision?: boolean;
is_lora?: boolean;
is_gguf?: boolean;
+ is_mlx?: boolean;
is_audio?: boolean;
audio_type?: string | null;
has_audio_input?: boolean;
@@ -299,6 +300,9 @@ export function syncModelCapabilities(
const synced = {
isVision: Boolean(resp.is_vision),
isGguf: Boolean(resp.is_gguf),
+ // A locally scanned model is in no /api/models/list row, so this is the only place
+ // its summary learns it is served by MLX, and the seed gate reads that.
+ isMlx: Boolean(resp.is_mlx),
isAudio: Boolean(resp.is_audio),
audioType: resp.audio_type ?? null,
hasAudioInput: Boolean(resp.has_audio_input),
@@ -398,7 +402,7 @@ async function syncInferenceStatusToStore(options?: {
// describes a moment that has passed.
if (signal?.aborted || superseded()) return;
- setModels(listRes.models.map(toChatModelSummary));
+ setModels(listRes.models.map(toChatModelRow));
if (lorasRes) {
setLoras(lorasRes.loras.map(toLoraSummary));
}
diff --git a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
index eb20aa0b1bb..530eb06c729 100644
--- a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
+++ b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
@@ -27,7 +27,7 @@ import {
type InferenceStatusResponse,
isMultimodalResponse,
} from "../types/api";
-import type { ChatModelSummary } from "../types/runtime";
+import type { ChatModelRow } from "../types/runtime";
import { resolveQwenThinkingParams } from "../utils/qwen-params";
import { sameGpuSelection } from "@/hooks/gpu-selection";
import { resolveBatchSizeSeed } from "./resolve-batch-size-seed";
@@ -99,6 +99,8 @@ function ensureActiveModelInStoreList(
): void {
const store = useChatRuntimeStore.getState();
const caps = {
+ // Adopting a model the backend already had mints a row with no catalog entry behind it.
+ isMlx: status.is_mlx ?? false,
isAudio: status.is_audio ?? false,
audioType: status.audio_type ?? null,
hasAudioInput: status.has_audio_input ?? false,
@@ -115,7 +117,7 @@ function ensureActiveModelInStoreList(
}
return;
}
- const summary: ChatModelSummary = {
+ const summary: ChatModelRow = {
id: checkpointId,
// active_model is already the clean public id; its leaf matches the catalog rows,
// and the fallback keeps a snapshot path out of the trigger.
diff --git a/studio/frontend/src/features/chat/lib/per-model-params.ts b/studio/frontend/src/features/chat/lib/per-model-params.ts
index 990c87639b6..46fa1497dff 100644
--- a/studio/frontend/src/features/chat/lib/per-model-params.ts
+++ b/studio/frontend/src/features/chat/lib/per-model-params.ts
@@ -26,6 +26,7 @@ export const PERSISTED_INFERENCE_PARAM_KEYS = [
"systemVariables",
"trustRemoteCode",
"fastMode",
+ "seed",
] as const satisfies readonly PersistedInferenceParamKey[];
/** What the memory records. `maxSeqLength` is left out: the context belongs to
diff --git a/studio/frontend/src/features/chat/presets/preset-policy.ts b/studio/frontend/src/features/chat/presets/preset-policy.ts
index 61c94707b43..c94369a7727 100644
--- a/studio/frontend/src/features/chat/presets/preset-policy.ts
+++ b/studio/frontend/src/features/chat/presets/preset-policy.ts
@@ -27,6 +27,7 @@ export type PresetOwnedParams = Pick<
| "maxTokens"
| "systemPrompt"
| "systemVariables"
+ | "seed"
>;
export const BUILTIN_PRESETS: Preset[] = [
@@ -111,6 +112,8 @@ export function getPresetOwnedParams(
maxTokens: params.maxTokens,
systemPrompt: params.systemPrompt ?? "",
systemVariables: params.systemVariables ?? "",
+ // Normalised, so a preset saved before the field existed never reads as modified.
+ seed: params.seed ?? null,
};
}
@@ -129,7 +132,8 @@ export function isSamePresetConfig(
left.presencePenalty === right.presencePenalty &&
left.maxTokens === right.maxTokens &&
left.systemPrompt === right.systemPrompt &&
- left.systemVariables === right.systemVariables
+ left.systemVariables === right.systemVariables &&
+ left.seed === right.seed
);
}
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index bd47afc76f3..f8c78e8034e 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -1733,6 +1733,7 @@ export function SharedComposer({
const synced = {
isVision: Boolean(resp.is_vision),
isGguf: Boolean(resp.is_gguf),
+ isMlx: Boolean(resp.is_mlx),
isAudio: Boolean(resp.is_audio),
audioType: resp.audio_type ?? null,
hasAudioInput: Boolean(resp.has_audio_input),
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 9973ef6f770..471ab9054ab 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -47,7 +47,7 @@ import {
} from "../lib/per-model-params";
import {
type ChatLoraSummary,
- type ChatModelSummary,
+ type ChatModelRow,
DEFAULT_INFERENCE_PARAMS,
type InferenceParams,
} from "../types/runtime";
@@ -958,6 +958,14 @@ function heldThreadScopedParamValue(key: string): unknown {
return undefined;
}
+/**
+ * The first value that is actually set. `??` cannot do this any more: `seed` is null when
+ * the pin is cleared, and null there is the chat's own choice rather than a missing key.
+ */
+function firstSetThreadScopedValue(...values: unknown[]): unknown {
+ return values.find((value) => value !== 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
@@ -966,8 +974,12 @@ function heldThreadScopedParamValue(key: string): unknown {
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);
+ // Not ||, and not ?? either: 0, "", -1 and a cleared seed's null are all values a
+ // user sets on purpose here.
+ const held = firstSetThreadScopedValue(
+ heldThreadScopedParamValue(key),
+ threadScopedOverride(key),
+ );
if (held === undefined || isSameThreadScopedValue(held, params[key])) {
continue;
}
@@ -1005,10 +1017,11 @@ function withoutActiveThreadParams(
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);
+ const own = firstSetThreadScopedValue(
+ remembered?.[key],
+ globalThreadScopedDefaults?.[key],
+ held !== undefined ? pairingWindowDefaults?.[key] : undefined,
+ );
if (own === undefined || isSameThreadScopedValue(own, params[key])) {
continue;
}
@@ -2415,7 +2428,7 @@ type ChatRuntimeStore = {
customPresets: Preset[];
activePreset: string;
activePresetSource: ChatPresetSource;
- models: ChatModelSummary[];
+ models: ChatModelRow[];
loras: ChatLoraSummary[];
runningByThreadId: Record<string, boolean>;
/**
@@ -2791,7 +2804,7 @@ type ChatRuntimeStore = {
setCustomPresets: (presets: Preset[]) => void;
setActivePreset: (name: string) => void;
setActivePresetSource: (source: ChatPresetSource) => void;
- setModels: (models: ChatModelSummary[]) => void;
+ setModels: (models: ChatModelRow[]) => void;
setLoras: (loras: ChatLoraSummary[]) => void;
/**
* `local` defaults to true, so an unqualified caller still counts for the model-swap gate.
@@ -4404,7 +4417,10 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
continue;
}
// a key the snapshot omits falls back to the defaults, not to the outgoing chat's value.
- const value = stored?.[key] ?? globalThreadScopedDefaults?.[key];
+ const value = firstSetThreadScopedValue(
+ stored?.[key],
+ globalThreadScopedDefaults?.[key],
+ );
if (value === undefined) continue;
applied[key] = value;
if (isSameThreadScopedValue(value, readThreadScopedValue(state, key))) {
diff --git a/studio/frontend/src/features/chat/types/api.ts b/studio/frontend/src/features/chat/types/api.ts
index e552141b40f..ea967159075 100644
--- a/studio/frontend/src/features/chat/types/api.ts
+++ b/studio/frontend/src/features/chat/types/api.ts
@@ -608,6 +608,8 @@ export interface OpenAIChatCompletionsRequest {
min_p?: number;
repetition_penalty?: number;
presence_penalty?: number;
+ /** Omitted when unset, which leaves the server to draw its own seed. */
+ seed?: number;
image_base64?: string;
audio_base64?: string;
video_base64?: string;
diff --git a/studio/frontend/src/features/chat/types/runtime.ts b/studio/frontend/src/features/chat/types/runtime.ts
index be1c0d3e048..79651f07e13 100644
--- a/studio/frontend/src/features/chat/types/runtime.ts
+++ b/studio/frontend/src/features/chat/types/runtime.ts
@@ -21,6 +21,38 @@ export interface InferenceParams {
* https://platform.claude.com/docs/en/build-with-claude/fast-mode
*/
fastMode?: boolean;
+ /**
+ * Sampling seed forwarded to the backends that read one so a generation can be
+ * reproduced. `null` is unset, which leaves the backend to draw its own per request.
+ */
+ seed?: number | null;
+}
+
+/** llama.cpp reads the seed as a uint32 and spends 0xFFFFFFFF on LLAMA_DEFAULT_SEED,
+ * its "draw one" sentinel, so a pin can name every value below that and no other. */
+export const MAX_SAMPLING_SEED = 4_294_967_294;
+
+/** An absent flag reads as false, so a row that omits one makes the gate answer wrong. */
+export type SeedGateFlags = Required<
+ Pick<ChatModelSummary, "isGguf" | "isMlx" | "isAudio" | "hasAudioInput">
+>;
+
+/** What the store holds, so every place that mints a row has to state those flags. */
+export type ChatModelRow = ChatModelSummary & SeedGateFlags;
+
+/** Whether the loaded model's backend reads a sampling seed. Shared so the panel cannot
+ * offer the field where the request would drop it, and takes the same `models[]` summary
+ * the request body already reads `isGguf` from, so the two cannot answer differently. */
+export function modelReadsSamplingSeed(
+ activeModel: SeedGateFlags | null | undefined,
+): boolean {
+ // An audio-output model answers through generateAudio, whose request carries no seed.
+ if (activeModel?.isAudio && !activeModel.hasAudioInput) {
+ return false;
+ }
+ // llama-server takes a seed, and so does MLX. The transformers backend declares no
+ // `seed` kwarg, so worker.py's `_backend_declares` gate drops it before generation.
+ return activeModel?.isGguf === true || activeModel?.isMlx === true;
}
/** The params that survive a reload. `checkpoint` names the model rather than
@@ -43,6 +75,7 @@ export const DEFAULT_INFERENCE_PARAMS: InferenceParams = {
checkpoint: "",
trustRemoteCode: false,
fastMode: false,
+ seed: null,
};
export interface ChatModelSummary {
diff --git a/studio/frontend/src/features/chat/utils/chat-settings-storage.ts b/studio/frontend/src/features/chat/utils/chat-settings-storage.ts
index 09c43beb035..21326b2c2e5 100644
--- a/studio/frontend/src/features/chat/utils/chat-settings-storage.ts
+++ b/studio/frontend/src/features/chat/utils/chat-settings-storage.ts
@@ -19,6 +19,7 @@ import {
type Preset,
} from "../presets/preset-policy";
import type { ReasoningEffort } from "../stores/chat-runtime-store";
+import { MAX_SAMPLING_SEED } from "../types/runtime";
import {
assignSanitizedMirroredSettings,
hasNoMirroredSettings,
@@ -153,6 +154,18 @@ function sanitizeInferenceParams(
if (typeof value.fastMode === "boolean") {
params.fastMode = value.fastMode;
}
+ // Bounded here as well as in the panel: this gates the hydration read and the outgoing PUT alike.
+ if (value.seed === null) {
+ // Kept, not dropped: the server merge overwrites the keys it receives and removes none.
+ params.seed = null;
+ } else if (
+ typeof value.seed === "number" &&
+ Number.isInteger(value.seed) &&
+ value.seed >= 0 &&
+ value.seed <= MAX_SAMPLING_SEED
+ ) {
+ params.seed = value.seed;
+ }
return hasKeys(params) ? params : undefined;
}
diff --git a/studio/frontend/src/features/chat/utils/queued-model-capabilities.ts b/studio/frontend/src/features/chat/utils/queued-model-capabilities.ts
index 032fbdd724d..fa5e17fe042 100644
--- a/studio/frontend/src/features/chat/utils/queued-model-capabilities.ts
+++ b/studio/frontend/src/features/chat/utils/queued-model-capabilities.ts
@@ -1,9 +1,10 @@
-import type { ChatModelSummary } from "../types/runtime";
+import type { ChatModelRow } from "../types/runtime";
export type QueuedModelCapabilities = Pick<
- ChatModelSummary,
+ ChatModelRow,
| "isVision"
| "isGguf"
+ | "isMlx"
| "isAudio"
| "audioType"
| "hasAudioInput"
@@ -16,10 +17,10 @@ export type QueuedModelCapabilities = Pick<
* catalog values, and a model loaded outside Unsloth gets a minimal entry.
*/
export function mergeQueuedModelCapabilities(
- models: ChatModelSummary[],
+ models: ChatModelRow[],
checkpoint: string,
capabilities: QueuedModelCapabilities | null,
-): ChatModelSummary[] {
+): ChatModelRow[] {
if (!capabilities) {
return models;
}
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 79943442deb..3d378c2c376 100644
--- a/studio/frontend/src/features/chat/utils/thread-scoped-settings.ts
+++ b/studio/frontend/src/features/chat/utils/thread-scoped-settings.ts
@@ -12,6 +12,7 @@ import type {
RagSource,
ReasoningEffort,
} from "../stores/chat-runtime-store";
+import { MAX_SAMPLING_SEED } from "../types/runtime.ts";
import {
isRecord,
sanitizeBoundedNumber,
@@ -44,6 +45,8 @@ export interface ThreadScopedSettings {
minP?: number;
repetitionPenalty?: number;
presencePenalty?: number;
+ /** null is the cleared pin, and is the only thread-scoped value that is not undefined. */
+ seed?: number | null;
systemPrompt?: string;
systemVariables?: string;
}
@@ -56,6 +59,7 @@ export const THREAD_SCOPED_PARAM_KEYS = [
"minP",
"repetitionPenalty",
"presencePenalty",
+ "seed",
"systemPrompt",
"systemVariables",
] as const satisfies readonly (keyof ThreadScopedSettings)[];
@@ -105,6 +109,7 @@ const THREAD_SCOPED_NUMBER_BOUNDS = {
minP: { min: 0, max: 1, integer: false },
repetitionPenalty: { min: 1, max: 2, integer: false },
presencePenalty: { min: 0, max: 2, integer: false },
+ seed: { min: 0, max: MAX_SAMPLING_SEED, integer: true },
} as const satisfies Partial<
Record<
keyof ThreadScopedSettings,
@@ -183,6 +188,8 @@ export function sanitizeThreadScopedSettings(
for (const key of THREAD_SCOPED_STRING_KEYS) {
if (typeof value[key] === "string") target[key] = value[key];
}
+ // null is a value here, not an absence, and sanitizeBoundedNumber reads it as one.
+ if (value.seed === null) settings.seed = null;
const ragSource = sanitizeRagSource(value.ragSource);
if (ragSource) settings.ragSource = ragSource;
return settings;
diff --git a/studio/frontend/tests/chat-sampling-seed.test.ts b/studio/frontend/tests/chat-sampling-seed.test.ts
new file mode 100644
index 00000000000..bf39ceece68
--- /dev/null
+++ b/studio/frontend/tests/chat-sampling-seed.test.ts
@@ -0,0 +1,372 @@
+// 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 sampling seed is the one inference param whose unset state is a value, not an
+// absence: null means "let the server draw one". Every layer it crosses tests presence
+// with `!== undefined`, so these pin the places a truthiness check or an omission would
+// quietly drop a seed of 0 or a deliberate clear.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+import {
+ PERSISTED_INFERENCE_PARAM_KEYS,
+ REMEMBERED_INFERENCE_PARAM_KEYS,
+ getReplayedParams,
+ pickRememberedParams,
+} from "../src/features/chat/lib/per-model-params.ts";
+import {
+ type ChatModelRow,
+ DEFAULT_INFERENCE_PARAMS,
+ type InferenceParams,
+ MAX_SAMPLING_SEED,
+ modelReadsSamplingSeed,
+} from "../src/features/chat/types/runtime.ts";
+import {
+ THREAD_SCOPED_PARAM_KEYS,
+ isThreadScopedSettingKey,
+ sanitizeThreadScopedSettings,
+} from "../src/features/chat/utils/thread-scoped-settings.ts";
+
+// Dynamic, unlike the two above: preset-policy value-imports ../types/runtime without an
+// extension, and a static import resolves before registerBundlerResolver's hook is live.
+const { applyPresetParams, getPresetOwnedParams, isSamePresetConfig } =
+ await import("../src/features/chat/presets/preset-policy.ts");
+
+const GGUF = "unsloth/Qwen3.5-9B-GGUF";
+
+function params(overrides: Partial<InferenceParams> = {}): InferenceParams {
+ return { ...DEFAULT_INFERENCE_PARAMS, checkpoint: GGUF, ...overrides };
+}
+
+function read(path: string): string {
+ return readFileSync(new URL(path, import.meta.url), "utf8");
+}
+
+function slice(source: string, from: string, to: string): string {
+ const start = source.indexOf(from);
+ const end = source.indexOf(to, start + from.length);
+ assert.ok(start !== -1, `not found: ${from}`);
+ assert.ok(end !== -1, `not found: ${to}`);
+ return source.slice(start, end);
+}
+
+test("an untouched install sends no seed", () => {
+ // Blank is the shipped state, so nothing changes for a user who never opens the field.
+ assert.equal(DEFAULT_INFERENCE_PARAMS.seed, null);
+});
+
+test("the seed persists and is remembered per model", () => {
+ assert.ok(PERSISTED_INFERENCE_PARAM_KEYS.includes("seed"));
+ // Derived from the persisted list by dropping maxSeqLength; a seed belongs to the
+ // sampling config, not the load, so it must survive that filter.
+ assert.ok(REMEMBERED_INFERENCE_PARAM_KEYS.includes("seed"));
+});
+
+test("a seed of 0 is remembered rather than read as unset", () => {
+ const picked = pickRememberedParams(params({ seed: 0 }));
+ assert.equal(picked.seed, 0);
+});
+
+test("a cleared seed is remembered as the clear", () => {
+ const picked = pickRememberedParams(params({ seed: null }));
+ assert.ok("seed" in picked);
+ assert.equal(picked.seed, null);
+});
+
+test("switching models replays each model's own seed", () => {
+ const replayed = getReplayedParams(
+ true,
+ { [GGUF]: { seed: 3407 } },
+ params({ seed: 11 }),
+ GGUF,
+ true,
+ );
+ assert.equal(replayed.seed, 3407);
+});
+
+test("a model whose row cleared the seed replays the clear", () => {
+ // An explicit null, so the switch does not inherit whichever seed was last on screen.
+ const replayed = getReplayedParams(
+ true,
+ { [GGUF]: { seed: null } },
+ params({ seed: 3407 }),
+ GGUF,
+ true,
+ );
+ assert.equal(replayed.seed, null);
+});
+
+test("a row written before the seed existed keeps what is on screen", () => {
+ // A gap is not a clear: the memory stores rows as written and invents nothing, so a
+ // pre-feature row leaves the seed alone rather than replaying a value it never held.
+ const replayed = getReplayedParams(
+ true,
+ { [GGUF]: { temperature: 0.7 } },
+ params({ seed: 3407 }),
+ GGUF,
+ true,
+ );
+ assert.equal(replayed.seed, 3407);
+});
+
+// The storage module, the adapter and the panel all pull a .tsx barrel into their
+// graph, so pin their source the way the sibling settings tests do.
+
+test("the settings sanitizer lets a cleared seed through", () => {
+ const storage = read("../src/features/chat/utils/chat-settings-storage.ts");
+ const body = slice(
+ storage,
+ "function sanitizeInferenceParams(",
+ "\nfunction sanitizeInferenceParamsByModel(",
+ );
+ // It gates both the read and the outgoing PUT, so a branch that only accepts numbers
+ // would drop the clear and leave the server's old pin in place.
+ assert.match(body, /value\.seed === null/);
+ assert.match(body, /Number\.isInteger\(value\.seed\)/);
+});
+
+test("the request omits the seed when it is unset", () => {
+ const adapter = read("../src/features/chat/api/chat-adapter.ts");
+ assert.match(adapter, /params\.seed == null \|\|/);
+ assert.match(adapter, /\{ seed: params\.seed \}/);
+});
+
+test("the pin covers llama.cpp's whole uint32 range bar the sentinel", () => {
+ // 0xFFFFFFFF is LLAMA_DEFAULT_SEED, llama.cpp's "draw one" value, so it is the one
+ // number a pin cannot name. llama-server parses the field as a uint32, so stopping at
+ // int32 max instead would refuse half the seeds it accepts for no reason.
+ assert.equal(MAX_SAMPLING_SEED, 0xffffffff - 1);
+});
+
+function row(
+ overrides: Partial<Parameters<typeof modelReadsSamplingSeed>[0] & object>,
+) {
+ return {
+ isGguf: false,
+ isMlx: false,
+ isAudio: false,
+ hasAudioInput: false,
+ ...overrides,
+ };
+}
+
+test("a seed reaches only the backends that read one", () => {
+ // llama-server reads the seed, and so does MLX: generate_chat_response takes it and
+ // builds _make_seeded_mlx_sampler, and worker.py's _backend_declares lets it through.
+ assert.ok(modelReadsSamplingSeed(row({ isGguf: true })));
+ assert.ok(modelReadsSamplingSeed(row({ isMlx: true })));
+ // The transformers backend declares no seed kwarg, so the same gate drops it there.
+ assert.ok(!modelReadsSamplingSeed(row({})));
+ // No summary at all is a model the panel knows nothing about, so it is offered nothing.
+ assert.ok(!modelReadsSamplingSeed(null));
+ assert.ok(!modelReadsSamplingSeed(undefined));
+ // An audio-output model answers through generateAudio, whose request carries no seed, so
+ // the control would promise a reproducibility it cannot deliver on that path.
+ assert.ok(
+ !modelReadsSamplingSeed(
+ row({ isGguf: true, isAudio: true, hasAudioInput: false }),
+ ),
+ );
+ // A model that takes audio IN still decodes through llama-server, so it keeps the field.
+ assert.ok(
+ modelReadsSamplingSeed(
+ row({ isGguf: true, isAudio: true, hasAudioInput: true }),
+ ),
+ );
+});
+
+test("the panel offers the seed only where the backend reads it", () => {
+ const sheet = read("../src/features/chat/chat-settings-sheet.tsx");
+ assert.match(sheet, /const showSeed = modelReadsSamplingSeed\(/);
+ // type="number" reports an entry the engine cannot parse as "", which would clear
+ // the pin with no error. chat-providers-dialog documents the same trap.
+ const field = slice(sheet, "{showSeed ? (", 'aria-label="Seed"');
+ const props = field
+ .split("\n")
+ .map((line) => line.trim())
+ .filter((line) => !line.startsWith("//"));
+ assert.ok(props.includes('type="text"'));
+ assert.ok(!props.includes('type="number"'));
+ // isGguf is deliberately not this helper: it also caps Max Tokens, and the two
+ // questions must stay separable even though both read the same summary today.
+ assert.doesNotMatch(sheet, /const isGguf = modelReadsSamplingSeed\(/);
+});
+
+test("the panel and the request body gate on the same argument", () => {
+ // A regex on the call name alone cannot see a call site passing an extra argument,
+ // which is how the panel and the body drifted apart the first time. Compare the
+ // argument text so an added or dropped signal at one site fails here.
+ const gateArguments = (source: string): string[] =>
+ [...source.matchAll(/modelReadsSamplingSeed\(([^)]*)\)/g)].map((match) =>
+ match[1].replace(/\s+/g, " ").trim(),
+ );
+ assert.deepEqual(
+ gateArguments(read("../src/features/chat/chat-settings-sheet.tsx")),
+ ["activeModel"],
+ );
+ assert.deepEqual(
+ gateArguments(read("../src/features/chat/api/chat-adapter.ts")),
+ ["activeModel"],
+ );
+});
+
+test("an over-long entry clamps rather than becoming another number", () => {
+ const sheet = read("../src/features/chat/chat-settings-sheet.tsx");
+ // The clamp lives in committedSeed now, so a click on Save reads the same value blur
+ // would have written rather than the one from before the entry.
+ const handler = slice(sheet, "const committedSeed = useMemo", "const paramsWithCommittedSeed");
+ // Truncating to 10 digits before clamping turned 12345678901234 into 1234567890.
+ assert.doesNotMatch(handler, /\.slice\(0, ?10\)/);
+ assert.match(handler, /digits\.length > 10\s*\?\s*MAX_SAMPLING_SEED/);
+ // And the length is measured after the padding, so a pasted 0000000003407 stays 3407
+ // instead of reading as 13 digits and clamping to the maximum.
+ assert.match(handler, /\^0\+\(\?=\\d\)/);
+});
+
+test("typing is not rewritten before the entry is finished", () => {
+ const sheet = read("../src/features/chat/chat-settings-sheet.tsx");
+ const field = slice(sheet, "{showSeed ? (", "placeholder=\"Random\"");
+ // The box shows the raw draft while it is being typed into, so a clamp cannot
+ // rewrite it mid-entry. NumericValueInput keeps a draft for the same reason.
+ assert.match(field, /value=\{\s*seedDraft \?\?/);
+ assert.match(field, /onChange=\{\(e\) =>\s*setSeedDraft\(/);
+ // Blur is the only commit, so it must not fire for a field nobody typed into,
+ // and Enter has to reach it.
+ assert.match(field, /if \(seedDraft === null\) return;/);
+ assert.match(field, /if \(e\.key === "Enter"\) e\.currentTarget\.blur\(\);/);
+});
+
+test("an abandoned entry does not outlive the box it was typed into", () => {
+ // Blur is the only commit and removing a focused element fires none, so both keys
+ // matter: a model switch and the field going away each strand a draft in committedSeed.
+ // Shape only: there is no DOM here, so the no-blur premise was measured in a browser.
+ const sheet = read("../src/features/chat/chat-settings-sheet.tsx");
+ const reset = slice(sheet, "useEffect(() => {\n setSeedDraft(null);", ");");
+ assert.match(reset, /\[currentCheckpoint, showSeed\]/);
+});
+
+test("a preset carries the seed it was saved with", () => {
+ // The field sits with Temperature through Max Tokens, all preset-owned, so saving a
+ // preset while a seed is pinned has to capture it rather than quietly drop it.
+ const saved = getPresetOwnedParams(params({ seed: 3407 }));
+ assert.equal(saved.seed, 3407);
+ const applied = applyPresetParams(
+ params({ seed: 11 }),
+ params({ seed: 3407 }),
+ );
+ assert.equal(applied.seed, 3407);
+ // And a preset saved with no pin clears one left on screen, so "Default" means default.
+ assert.equal(
+ applyPresetParams(params({ seed: 3407 }), params({ seed: null })).seed,
+ null,
+ );
+});
+
+test("moving the seed marks the preset modified", () => {
+ // Without this the panel would show a saved preset while sampling no longer matches it.
+ assert.ok(!isSamePresetConfig(params({ seed: 3407 }), params({ seed: 11 })));
+ assert.ok(isSamePresetConfig(params({ seed: 3407 }), params({ seed: 3407 })));
+});
+
+test("the stored seed is range-checked, not just the keystroke", () => {
+ const storage = read("../src/features/chat/utils/chat-settings-storage.ts");
+ const body = slice(
+ storage,
+ "function sanitizeInferenceParams(",
+ "\nfunction sanitizeInferenceParamsByModel(",
+ );
+ // The panel clamps what the user types; a row from another client or a hand-edited
+ // studio.db meets only this, and it feeds the request body straight through.
+ assert.match(body, /value\.seed >= 0/);
+ assert.match(body, /value\.seed <= MAX_SAMPLING_SEED/);
+});
+
+test("the request drops a seed the loaded model cannot use", () => {
+ const adapter = read("../src/features/chat/api/chat-adapter.ts");
+ // A pin set on a GGUF outlives a switch to transformers, where the panel hides the
+ // field: without this the user would keep sending a seed they can no longer see.
+ assert.match(adapter, /!modelReadsSamplingSeed\(/);
+ // The same summary the body already reads isGguf from for context_overflow, so
+ // "is this a GGUF" cannot be answered two ways inside one request.
+ assert.match(adapter, /activeModel\?\.isGguf === true/);
+});
+
+test("the seed belongs to the chat, not the installation", () => {
+ // Every other per-turn sampling control travels with the conversation. Left out, a pin
+ // taken in one chat would fix the draw for every other chat opened on the same model,
+ // and reopening the first could not bring its own value back.
+ assert.ok(THREAD_SCOPED_PARAM_KEYS.includes("seed"));
+ assert.equal(isThreadScopedSettingKey("seed"), true);
+});
+
+test("a chat stores a cleared seed rather than dropping the key", () => {
+ assert.deepEqual(sanitizeThreadScopedSettings({ seed: null }), { seed: null });
+ // The other half of that: a snapshot written before the field existed carries no seed,
+ // and the thread response now says so rather than spelling it null, so the chat falls
+ // through to the pin it inherits instead of reading as one that cleared it.
+ assert.deepEqual(sanitizeThreadScopedSettings({ topK: 40 }), { topK: 40 });
+ assert.deepEqual(sanitizeThreadScopedSettings({ seed: 3407 }), { seed: 3407 });
+ // The bound the panel and the installation copy already share, applied to the snapshot
+ // a chat writes: a row from another client meets only this.
+ for (const bad of [-1, 1.5, MAX_SAMPLING_SEED + 1, true, "3407"]) {
+ assert.deepEqual(sanitizeThreadScopedSettings({ seed: bad }), {}, String(bad));
+ }
+});
+
+test("a cleared seed is not read as a missing key", () => {
+ const store = read("../src/features/chat/stores/chat-runtime-store.ts");
+ const helper = slice(store, "function firstSetThreadScopedValue", "\n}");
+ // `??` would fall through a cleared seed's null to the installation default, putting
+ // the pin back on the one chat that dropped it. Only undefined means "not set".
+ assert.match(helper, /values\.find\(\(value\) => value !== undefined\)/);
+});
+
+// A model outside /api/models/list gets its models[] summary minted from a load or
+// status response, and the seed gate reads isMlx off that summary. Four separate places
+// mint or refresh one, and three of them were each missing the flag, so this is a rule
+// over the capability cluster rather than a spot check per place.
+// Compile-time, not runtime: a row omitting one of the four fails to build at the site
+// that mints it, including sites no test knows about. ChatModelSummary keeps them optional.
+type RequiredKeys<T> = {
+ [K in keyof T]-?: object extends Pick<T, K> ? never : K;
+}[keyof T];
+type Assert<T extends true> = T;
+type _EveryFlagTheSeedGateReadsIsRequired = Assert<
+ "isGguf" | "isMlx" | "isAudio" | "hasAudioInput" extends
+ RequiredKeys<ChatModelRow>
+ ? true
+ : false
+>;
+
+test("a models[] row states every flag the seed gate reads", () => {
+ const row: ChatModelRow = {
+ id: "m",
+ name: "m",
+ isVision: false,
+ isLora: false,
+ isGguf: true,
+ isMlx: false,
+ isAudio: false,
+ hasAudioInput: false,
+ };
+ assert.ok(modelReadsSamplingSeed(row));
+});
+
+test("saving a preset takes the seed being typed, not the one before it", () => {
+ const panel = read("../src/features/chat/chat-settings-sheet.tsx");
+ // Clicking Save blurs the box during mousedown, but React has not re-rendered by the
+ // time onClick runs, so a save reading `params` writes the pre-entry seed and, over an
+ // otherwise-unmodified preset, the button is still disabled and the click does nothing.
+ assert.match(panel, /params: toPresetParams\(paramsWithCommittedSeed\)/);
+ const unsaved = slice(panel, "const hasUnsavedPresetChanges", "const presetSaveState");
+ assert.match(unsaved, /isSamePresetConfig\(\s*activePresetDefinition\.params,\s*paramsWithCommittedSeed,/);
+ assert.match(unsaved, /committedSeed !== \(params\.seed \?\? null\)/);
+ // and blur commits the same value, so the two cannot answer differently
+ assert.match(panel, /setSeedDraft\(null\);\s*setSeed\(committedSeed\);/);
+});
diff --git a/studio/frontend/tests/queued-model-capabilities.test.ts b/studio/frontend/tests/queued-model-capabilities.test.ts
index 7132bbfeeb3..75d2eb1f614 100644
--- a/studio/frontend/tests/queued-model-capabilities.test.ts
+++ b/studio/frontend/tests/queued-model-capabilities.test.ts
@@ -22,6 +22,7 @@ test("status capabilities synthesize an audio model missing from the catalog", (
mergeQueuedModelCapabilities([], "local/audio-model", {
isVision: false,
isGguf: false,
+ isMlx: false,
isAudio: true,
audioType: "tts",
hasAudioInput: false,
@@ -33,6 +34,7 @@ test("status capabilities synthesize an audio model missing from the catalog", (
isLora: false,
isVision: false,
isGguf: false,
+ isMlx: false,
isAudio: true,
audioType: "tts",
hasAudioInput: false,
@@ -51,6 +53,7 @@ test("status capabilities override stale catalog flags", () => {
isVision: true,
isLora: true,
isGguf: true,
+ isMlx: false,
isAudio: false,
audioType: null,
hasAudioInput: true,
@@ -60,6 +63,7 @@ test("status capabilities override stale catalog flags", () => {
{
isVision: false,
isGguf: false,
+ isMlx: false,
isAudio: true,
audioType: "tts",
hasAudioInput: false,
@@ -72,6 +76,7 @@ test("status capabilities override stale catalog flags", () => {
isVision: false,
isLora: true,
isGguf: false,
+ isMlx: false,
isAudio: true,
audioType: "tts",
hasAudioInput: false,
@@ -84,6 +89,7 @@ test("audio-input capability keeps the synthesized model off the output-only pat
const [model] = mergeQueuedModelCapabilities([], "local/audio-vlm", {
isVision: false,
isGguf: false,
+ isMlx: false,
isAudio: true,
audioType: "audio_vlm",
hasAudioInput: true,
@@ -96,6 +102,7 @@ test("synthesized audio-only capability reaches image validation", () => {
const [model] = mergeQueuedModelCapabilities([], "local/audio-model", {
isVision: false,
isGguf: false,
+ isMlx: false,
isAudio: true,
audioType: "tts",
hasAudioInput: false,
diff --git a/studio/frontend/tests/thread-scoped-pairing-invariants.test.ts b/studio/frontend/tests/thread-scoped-pairing-invariants.test.ts
index 671a33572fa..bb6d6b9de5b 100644
--- a/studio/frontend/tests/thread-scoped-pairing-invariants.test.ts
+++ b/studio/frontend/tests/thread-scoped-pairing-invariants.test.ts
@@ -748,8 +748,12 @@ test("the in-memory defaults follow the model defaults that were just written",
note,
/if \(isHeldThreadScopedField\(key\)\) \{\s*hydratedDefaultsByHeldField\.set\(key, value\);/,
);
- // and it is the fallback apply() actually reads
- assert.match(store, /stored\?\.\[key\] \?\? globalThreadScopedDefaults\?\.\[key\]/);
+ // and it is the fallback apply() actually reads. Not ??: a cleared seed is stored as
+ // null, and ?? would read that as a missing key and hand back the installation pin.
+ assert.match(
+ store,
+ /firstSetThreadScopedValue\(\s*stored\?\.\[key\],\s*globalThreadScopedDefaults\?\.\[key\],/,
+ );
});
// setCheckpoint replays the destination model's remembered params without going through
@@ -791,7 +795,7 @@ test("the model being left does not remember the open chat's values", () => {
);
assert.match(
strip,
- /remembered\?\.\[key\] \?\?\s*globalThreadScopedDefaults\?\.\[key\]/,
+ /firstSetThreadScopedValue\(\s*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.