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: one request per chat model load, sent to both /validate and /load (#15139)

oobabooga3df124b46f5b
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 6f47d8f422f..872ccaf0e3d 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -16,10 +16,10 @@ import {
modelVisibleMessage,
toolOnlyImages,
} from "./mcp-image";
+import { llamaServerLoadFields } from "../lib/load-request";
import {
clearedServerTuningState,
committedServerTuningState,
- serverTuningLoadPayload,
} from "../lib/server-tuning-fields";
import { authFetch, getAuthToken } from "@/features/auth";
import { withSandboxAttachmentPaths } from "../sandbox-attachments";
@@ -320,6 +320,7 @@ import type {
MmprojFallbackReason,
GgufVariantDetail,
InferenceStatusResponse,
+ LoadModelRequest,
OpenAIChatChunk,
OpenAIChatCompletionsRequest,
OpenAIChatMessage,
@@ -3469,34 +3470,10 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
};
}
- async function canAutoLoad(payload: {
- model_path: string;
- max_seq_length: number;
- is_lora: boolean;
- gguf_variant?: string | null;
- // GGUF-only: the guard needs /load's placement policy. Layer/MoE/split are not sent.
- gpu_ids?: number[];
- gpu_memory_mode?: "auto" | "manual";
- cache_type_kv?: string | null;
- tensor_parallel?: boolean | null;
- reasoning_budget?: number;
- reasoning_budget_message?: string;
- // The projector is part of what the guard sizes: a skipped one needs ~1 GB less.
- disable_vision?: boolean | null;
- // The drafter's estimated size differs by mode (a DSpark sidecar is ~11 GB).
- speculative_type?: string | null;
- spec_draft_n_max?: number | null;
- n_parallel?: number | null;
- load_in_4bit?: boolean;
- }): Promise<boolean> {
+ async function canAutoLoad(request: LoadModelRequest): Promise<boolean> {
// Before the POST, so an abort costs nothing: no request was sent.
options?.abortSignal?.throwIfAborted();
- const validation = await validateModel({
- ...payload,
- hf_token: hfToken,
- load_in_4bit: payload.load_in_4bit ?? true,
- trust_remote_code: trustRemoteCode,
- }).catch((error: unknown) => {
+ const validation = await validateModel(request).catch((error: unknown) => {
// A rejected /validate never reaches loadAttempts, so count it here or a dead backend POSTs
// once per cached repo.
validateFailures += 1;
@@ -3539,10 +3516,10 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
async function canAutoLoadRecordingFailures(
label: string,
- payload: Parameters<typeof canAutoLoad>[0],
+ request: LoadModelRequest,
): Promise<boolean> {
try {
- return await canAutoLoad(payload);
+ return await canAutoLoad(request);
} catch (error) {
recordCandidateFailure(label, error);
throw error;
@@ -3707,67 +3684,8 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
const effectiveChatTemplateOverride = config.chatTemplateOverride?.trim()
? config.chatTemplateOverride
: null;
- if (
- !(await canAutoLoadRecordingFailures(failureLabel, {
- model_path: modelPath,
- max_seq_length: fitMaxSeqLength,
- is_lora: false,
- gguf_variant: candidate.ggufVariant,
- load_in_4bit: config.loadIn4bit !== false,
- cache_type_kv: config.kvCacheDtype,
- tensor_parallel: effectiveTensorParallel,
- disable_vision: effectiveDisableVision,
- n_parallel: config.nParallel ?? null,
- speculative_type: effectiveSpeculativeType,
- spec_draft_n_max: effectiveSpecDraftNMax,
- ...(candidate.kind === "gguf"
- ? {
- gpu_ids: effectiveGpuIds ?? undefined,
- gpu_memory_mode: effectiveGpuMemoryMode,
- // A remembered manual DiffusionGemma split (0 especially) must not be refused as a full-GGUF occupant.
- gpu_layers: effectiveGpuLayers,
- reasoning_budget: isDiffusion ? -1 : config.reasoningBudget,
- reasoning_budget_message: isDiffusion
- ? ""
- : config.reasoningBudgetMessage,
- // omitted when blank: a null counts as set and strips inherited -b / -ub
- ...(config.nBatch != null ? { n_batch: config.nBatch } : {}),
- ...(config.nUbatch != null ? { n_ubatch: config.nUbatch } : {}),
- // Draft cache dtype changes the estimate, so preflight must match the launch.
- ...serverTuningLoadPayload(config),
- // Checked with the same arguments the load sends, or a list the backend refuses would pass this gate.
- ...(resolvedExtraArgs !== undefined
- ? { llama_extra_args: resolvedExtraArgs ?? [] }
- : {}),
- }
- : {}),
- }))
- ) {
- skippedAutoLoadCandidates.add(
- autoLoadCandidateKey(
- candidate.kind,
- // A cached repo and a local row can alias the same files, so blocking one must block the other.
- candidate.loadId ?? candidate.id,
- candidate.ggufVariant,
- ),
- );
- return false;
- }
- const autoLoadPin = retainedContextPin({
- isMlx: isServedByMlx(
- candidate.kind === "gguf",
- platform.deviceType,
- platform.chatOnlyReason,
- ),
- // What the load asked for, so a pin carried in either field is kept.
- requestedContextLength: fitMaxSeqLength,
- });
- loadAttempts += 1;
- options?.abortSignal?.throwIfAborted();
- const loadResp = await loadModel({
+ const request: LoadModelRequest = {
model_path: modelPath,
- // Keep a speech model loaded for read aloud when Keep multiple models loaded allows it.
- alongside: true,
hf_token: hfToken,
max_seq_length: fitMaxSeqLength,
load_in_4bit: config.loadIn4bit !== false,
@@ -3783,15 +3701,16 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
speculative_type: effectiveSpeculativeType,
spec_draft_n_max: effectiveSpecDraftNMax,
...mlxDrafter,
- reasoning_budget:
- candidate.kind === "gguf" && !isDiffusion ? config.reasoningBudget : -1,
- reasoning_budget_message:
- candidate.kind === "gguf" && !isDiffusion
- ? config.reasoningBudgetMessage
- : "",
tensor_parallel: effectiveTensorParallel,
disable_vision: effectiveDisableVision,
n_parallel: config.nParallel ?? null,
+ // Remembered pass-through args: nothing is resident at startup to inherit them from.
+ ...llamaServerLoadFields(
+ { ...config, llamaExtraArgs: resolvedExtraArgs },
+ { isGguf: candidate.kind === "gguf", isDiffusion },
+ ),
+ // GGUF-only. A remembered manual DiffusionGemma split (0 especially) must not be refused as a
+ // full-GGUF occupant.
...(candidate.kind === "gguf"
? {
gpu_memory_mode: effectiveGpuMemoryMode,
@@ -3799,17 +3718,33 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
n_cpu_moe: effectiveNCpuMoe,
tensor_split: effectiveTensorSplit ?? undefined,
gpu_ids: effectiveGpuIds ?? undefined,
- ...(config.nBatch != null ? { n_batch: config.nBatch } : {}),
- ...(config.nUbatch != null ? { n_ubatch: config.nUbatch } : {}),
- // Remembered like the rest of this block, or the auto-load reverts the override.
- ...serverTuningLoadPayload(config),
- // Undefined predates the field; an empty list is an explicit none.
- ...(resolvedExtraArgs !== undefined
- ? { llama_extra_args: resolvedExtraArgs ?? [] }
- : {}),
}
: {}),
- }).catch((error: unknown) => {
+ };
+ if (!(await canAutoLoadRecordingFailures(failureLabel, request))) {
+ skippedAutoLoadCandidates.add(
+ autoLoadCandidateKey(
+ candidate.kind,
+ // A cached repo and a local row can alias the same files, so blocking one must block the other.
+ candidate.loadId ?? candidate.id,
+ candidate.ggufVariant,
+ ),
+ );
+ return false;
+ }
+ const autoLoadPin = retainedContextPin({
+ isMlx: isServedByMlx(
+ candidate.kind === "gguf",
+ platform.deviceType,
+ platform.chatOnlyReason,
+ ),
+ // What the load asked for, so a pin carried in either field is kept.
+ requestedContextLength: fitMaxSeqLength,
+ });
+ loadAttempts += 1;
+ options?.abortSignal?.throwIfAborted();
+ // Keep a speech model loaded for read aloud when Keep multiple models loaded allows it.
+ const loadResp = await loadModel({ ...request, alongside: true }).catch((error: unknown) => {
// The sweep's parameterless catches discard this error, so record it before rethrowing.
noteLoadFailure(failureLabel, error);
throw error;
@@ -4172,20 +4107,29 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
rt.selectedGpuIds,
rt.selectedGpuIndexKind,
);
- // Preflight before downloading gigabytes; the load reuses this snapshot.
- if (
- !(await canAutoLoad({
- model_path: DEFAULT_CHAT_MODEL_REPO,
- max_seq_length: 0,
- is_lora: false,
- gguf_variant: DEFAULT_CHAT_MODEL_VARIANT,
- // The same live-store GPU pick the load below sends.
- gpu_ids: defaultGpuIds ?? undefined,
- gpu_memory_mode: rt.gpuMemoryMode,
- speculative_type: specSettings.speculativeType,
- spec_draft_n_max: specSettings.specDraftNMax,
- }))
- ) {
+ const request: LoadModelRequest = {
+ model_path: DEFAULT_CHAT_MODEL_REPO,
+ hf_token: hfToken,
+ // Model default under both modes: Auto layers + no pin means resolveFitMaxSeqLength returns 0.
+ max_seq_length: 0,
+ load_in_4bit: true,
+ is_lora: false,
+ gguf_variant: DEFAULT_CHAT_MODEL_VARIANT,
+ trust_remote_code: trustRemoteCode,
+ speculative_type: specSettings.speculativeType,
+ spec_draft_n_max: specSettings.specDraftNMax,
+ reasoning_budget: -1,
+ reasoning_budget_message: "",
+ // GPU Memory mode is a standing preference and the GPU pick is the on-screen one; the
+ // per-model layer/MoE/split knobs and context pin stay at their defaults.
+ gpu_memory_mode: rt.gpuMemoryMode,
+ gpu_layers: GPU_LAYERS_AUTO,
+ n_cpu_moe: 0,
+ gpu_ids: defaultGpuIds ?? undefined,
+ };
+ // Preflight BEFORE the transfer: training or the placement guard can refuse this model, and
+ // learning that after gigabytes costs a long wait. The load sends this same request.
+ if (!(await canAutoLoad(request))) {
toast.dismiss(toastId);
return { loaded: false, blockedByTrustRemoteCode };
}
@@ -4217,27 +4161,7 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
);
loadAttempts += 1;
options?.abortSignal?.throwIfAborted();
- const loadResp = await loadModel({
- model_path: DEFAULT_CHAT_MODEL_REPO,
- alongside: true,
- hf_token: hfToken,
- // Model default under both modes: Auto layers + no pin means resolveFitMaxSeqLength returns 0.
- max_seq_length: 0,
- load_in_4bit: true,
- is_lora: false,
- gguf_variant: DEFAULT_CHAT_MODEL_VARIANT,
- trust_remote_code: trustRemoteCode,
- speculative_type: specSettings.speculativeType,
- spec_draft_n_max: specSettings.specDraftNMax,
- reasoning_budget: -1,
- reasoning_budget_message: "",
- // GPU Memory mode is a standing preference; per-model knobs stay default and the GPU pick is
- // the on-screen one the preflight used.
- gpu_memory_mode: rt.gpuMemoryMode,
- gpu_layers: GPU_LAYERS_AUTO,
- n_cpu_moe: 0,
- gpu_ids: defaultGpuIds ?? undefined,
- });
+ const loadResp = await loadModel({ ...request, alongside: true });
reportEvicted(loadResp);
options?.abortSignal?.throwIfAborted();
applyAutoLoadRuntimeState(options, () => {
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 88d854bf9d9..d70d52f6b32 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -32,6 +32,7 @@ import {
} from "@/lib/model-lifecycle-events";
import type { AgentsMdRecord } from "../utils/agents-md";
import { showLoadWarning } from "../utils/load-warning-toast";
+import { validateRequestBody, wireLoadRequest } from "../lib/load-request";
import type {
MessageRecord,
ModelType,
@@ -415,12 +416,7 @@ export async function loadModel(
const response = await authFetch("/api/inference/load", {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- ...payload,
- hf_token: preparedToken.token,
- native_path_lease: payload.nativePathLease ?? null,
- nativePathLease: undefined,
- }),
+ body: JSON.stringify(wireLoadRequest(payload, preparedToken.token)),
signal: options?.signal,
});
const loaded = await parseJsonOrThrow<LoadModelResponse>(response, "Model load");
@@ -474,47 +470,7 @@ export async function validateModel(
method: "POST",
headers: { "Content-Type": "application/json" },
signal: options?.signal,
- body: JSON.stringify({
- model_path: payload.model_path,
- native_path_lease: payload.nativePathLease ?? null,
- hf_token: preparedToken.token,
- gguf_variant: payload.gguf_variant ?? null,
- engine: payload.engine ?? "auto",
- engine_precision: payload.engine_precision ?? "auto",
- engine_parallelism: payload.engine_parallelism ?? "tensor",
- engine_kv_cache_dtype: payload.engine_kv_cache_dtype ?? "auto",
- engine_seed: payload.engine_seed ?? null,
- engine_gpu_memory_utilization:
- payload.engine_gpu_memory_utilization ?? null,
- // Intended load settings so validate's preflight matches the follow-up /load.
- max_seq_length: payload.max_seq_length,
- load_in_4bit: payload.load_in_4bit,
- cache_type_kv: payload.cache_type_kv ?? null,
- tensor_parallel: payload.tensor_parallel ?? false,
- disable_vision: payload.disable_vision ?? false,
- gpu_ids: payload.gpu_ids,
- // Takes no VRAM, so validate must not preflight it and refuse what /load takes.
- audio_device: payload.audio_device ?? null,
- // Tell validate the placement mode so it applies the same fit policy as /load.
- gpu_memory_mode: payload.gpu_memory_mode,
- // Only 0 changes the verdict: a zero-layer DiffusionGemma split places no layers.
- gpu_layers: payload.gpu_layers,
- // Slots scale the KV estimate; keep validate sized like the load.
- n_parallel: payload.n_parallel,
- reasoning_budget: payload.reasoning_budget ?? -1,
- reasoning_budget_message: payload.reasoning_budget_message ?? "",
- // Extra args can change ctx-size or cache, so preflight must price the same command.
- ...(payload.llama_extra_args !== undefined
- ? // biome-ignore lint/style/useNamingConvention: API schema
- { llama_extra_args: payload.llama_extra_args }
- : {}),
- // batch sizes scale the same estimate; omitted when blank so they never read as set
- ...(payload.n_batch != null ? { n_batch: payload.n_batch } : {}),
- ...(payload.n_ubatch != null ? { n_ubatch: payload.n_ubatch } : {}),
- // Drafter size differs by kind (DSpark ~11 GB), so preflight needs the mode to match /load.
- speculative_type: payload.speculative_type ?? null,
- spec_draft_n_max: payload.spec_draft_n_max ?? null,
- }),
+ body: JSON.stringify(validateRequestBody(payload, preparedToken.token)),
});
return parseJsonOrThrow<ValidateModelResponse>(response);
}
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 30ded6c6d1e..48fd257f8e7 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
@@ -8,6 +8,7 @@ import {
} from "../lib/cache-miss-download";
import { mlxRuntimeStateFrom } from "../lib/mlx-runtime-state";
import { shouldRestorePreviousModel } from "../lib/restore-previous-model";
+import { llamaServerLoadFields } from "../lib/load-request";
import {
type ServerTuningValues,
clearedServerTuningState,
@@ -172,6 +173,7 @@ import {
type CpuFallbackReason,
type MmprojFallbackReason,
type InferenceStatusResponse,
+ type LoadModelRequest,
isMultimodalResponse,
} from "../types/api";
import { isExternalModelId } from "../external-providers";
@@ -2199,133 +2201,170 @@ export function useChatModelRuntime() {
const validateNativePathLease = nativePathToken
? (await consumeNativePathToken(nativePathToken, "validate-model")).nativePathLease
: undefined;
- // Validate with the same effective context /load uses.
const switchingModelOrVariant =
currentCheckpoint !== modelId ||
(loadActiveGgufVariant ?? null) !== (ggufVariant ?? null);
const resetsPerModelSettings = Boolean(
currentCheckpoint && switchingModelOrVariant && !keepSpeculative,
);
+ // Size staged settings before validation; reset the store only after unloading.
+ const persistedSpeculativeType = resetsPerModelSettings
+ ? readPersistedSpeculativeType()
+ : null;
+ if (resetsPerModelSettings) {
+ loadSpeculativeType =
+ pendingLoadConfig?.speculativeType != null
+ ? normalizeSpeculativeType(pendingLoadConfig.speculativeType)
+ : persistedSpeculativeType;
+ loadSpecDraftNMax = pendingLoadConfig?.specDraftNMax ?? null;
+ loadNParallel = pendingLoadConfig?.nParallel ?? null;
+ loadReasoningBudget = pendingLoadConfig?.reasoningBudget ?? -1;
+ loadReasoningBudgetMessage =
+ pendingLoadConfig?.reasoningBudgetMessage ?? "";
+ loadNBatch = pendingLoadConfig?.nBatch ?? null;
+ loadNUbatch = pendingLoadConfig?.nUbatch ?? null;
+ loadServerTuning = {
+ loadMode: pendingLoadConfig?.loadMode ?? null,
+ specDraftCacheDtype:
+ pendingLoadConfig?.specDraftCacheDtype ?? null,
+ ctxCheckpoints: pendingLoadConfig?.ctxCheckpoints ?? null,
+ cacheRam: pendingLoadConfig?.cacheRam ?? null,
+ };
+ loadMlxKvQuant = pendingLoadConfig?.mlxKvQuant ?? null;
+ loadMlxInt8Prefill = pendingLoadConfig?.mlxInt8Prefill ?? false;
+ loadMlxPleOffload = pendingLoadConfig?.mlxPleOffload ?? null;
+ loadMlxExpertOffload = pendingLoadConfig?.mlxExpertOffload ?? null;
+ loadChatTemplateOverride =
+ pendingLoadConfig?.chatTemplateOverride?.trim()
+ ? pendingLoadConfig.chatTemplateOverride
+ : null;
+ loadCustomContextLength =
+ pendingLoadConfig?.customContextLength ?? null;
+ loadSelectedGpuIds = stagedGpuIds;
+ loadGpuLayers = pendingLoadConfig?.gpuLayers ?? GPU_LAYERS_AUTO;
+ loadNCpuMoe = pendingLoadConfig?.nCpuMoe ?? 0;
+ loadSplitRatio = reconcileTensorSplit(
+ pendingLoadConfig?.tensorSplit,
+ pendingLoadConfig?.selectedGpuIds,
+ stagedGpuIds,
+ );
+ }
+
+ // The Context Length the USER set for this load, captured before the clamp below can stand in for
+ // it. This, not the n_ctx that goes on the wire, is what the completed load pins: several send
+ // rules put a positive n_ctx on the wire with the control on Auto.
+ const targetIsMlx = isServedByMlx(
+ isGguf,
+ platform.deviceType,
+ platform.chatOnlyReason,
+ );
+ // Only a same-model reload without a staged config reuses the resident's settings; otherwise the
+ // drafter is this model's own and a standing mode goes through the resolver.
+ if (targetIsMlx && (pendingLoadConfig != null || switchingModelOrVariant)) {
+ loadSpecDraftModel = pendingLoadConfig?.specDraftModel ?? null;
+ if (loadSpeculativeType && pendingLoadConfig?.speculativeType == null) {
+ loadSpeculativeType = resolveSpeculativeType(null, loadSpeculativeType, true);
+ }
+ }
+ const explicitCtxPin = loadRequestContextPin(
+ loadCustomContextLength,
+ targetIsMlx,
+ pinnedMaxSeqLength,
+ );
// Pinning layers on the SAME model keeps the currently resolved context: with no explicit pin, a
// manual+pinned reload would send 0, which the backend's --fit off branch treats as the NATIVE
// context, far larger than the sheet shows when the load was fit-sized, a likely OOM.
// loadedContextLength is that resolved value; a model already at native reloads unchanged.
- // Validation takes it too, so /validate and /load size the same context.
- const fixedLayerContext = (
- customContextLength: number | null,
- gpuLayers: number,
- ): number | null =>
+ if (
isGguf &&
!switchingModelOrVariant &&
loadGpuMemoryMode === "manual" &&
- gpuLayers >= 0 &&
- customContextLength == null &&
+ loadGpuLayers >= 0 &&
+ loadCustomContextLength == null &&
(loadContextLength ?? 0) > 0
- ? loadContextLength
- : customContextLength;
- const validateCustomContextLength = resetsPerModelSettings
- ? null
- : fixedLayerContext(loadCustomContextLength, loadGpuLayers);
- const validateGpuIds = resetsPerModelSettings
- ? stagedGpuIds
- : loadSelectedGpuIds;
- // The reset below re-baselines gpuLayers to Auto; mirror it here.
- const validateGpuLayers = resetsPerModelSettings
- ? GPU_LAYERS_AUTO
- : loadGpuLayers;
- const validateNParallel = resetsPerModelSettings
- ? (pendingLoadConfig?.nParallel ?? null)
- : loadNParallel;
- const validateReasoningBudget = resetsPerModelSettings
- ? (pendingLoadConfig?.reasoningBudget ?? -1)
- : loadReasoningBudget;
- const validateReasoningBudgetMessage = resetsPerModelSettings
- ? (pendingLoadConfig?.reasoningBudgetMessage ?? "")
- : loadReasoningBudgetMessage;
- const validateNBatch = resetsPerModelSettings
- ? (pendingLoadConfig?.nBatch ?? null)
- : loadNBatch;
- const validateNUbatch = resetsPerModelSettings
- ? (pendingLoadConfig?.nUbatch ?? null)
- : loadNUbatch;
- const validateServerTuning: ServerTuningValues =
- resetsPerModelSettings
- ? {
- loadMode: pendingLoadConfig?.loadMode ?? null,
- specDraftCacheDtype:
- pendingLoadConfig?.specDraftCacheDtype ?? null,
- ctxCheckpoints: pendingLoadConfig?.ctxCheckpoints ?? null,
- cacheRam: pendingLoadConfig?.cacheRam ?? null,
- }
- : loadServerTuning;
- const validateMaxSeqLength = resolveFitMaxSeqLength(
+ ) {
+ loadCustomContextLength = loadContextLength;
+ }
+ // A GGUF native context can exceed maxSeqLength, so sizing on raw maxSeqLength could pass
+ // /validate, unload, then have /load refuse it.
+ const effectiveMaxSeqLength = resolveLoadMaxSeqLength({
+ modelId,
+ ggufVariant,
+ isGguf,
+ customContextLength: loadCustomContextLength,
+ loadedContextLength: loadContextLength,
+ currentCheckpoint,
+ activeGgufVariant: loadActiveGgufVariant,
+ isMlx: targetIsMlx,
+ pinnedMaxSeqLength,
+ defaultMaxSeqLength: unpinnedDefaultRequest(
+ previousIsMlx,
+ stateBeforeUnload.params.maxSeqLength,
+ DEFAULT_MAX_SEQ_LENGTH,
+ ),
+ presetSource: loadActivePresetSource,
+ loadedContextPin: stateBeforeUnload.loadedCustomContextLength,
+ });
+ const loadMaxSeqLength = resolveFitMaxSeqLength(
isGguf,
loadGpuMemoryMode,
- validateGpuLayers,
- validateCustomContextLength,
- resolveLoadMaxSeqLength({
- modelId,
- ggufVariant,
- isGguf,
- customContextLength: validateCustomContextLength,
- loadedContextLength: loadContextLength,
- currentCheckpoint,
- activeGgufVariant: loadActiveGgufVariant,
- isMlx: isServedByMlx(isGguf, platform.deviceType, platform.chatOnlyReason),
- pinnedMaxSeqLength,
- defaultMaxSeqLength: unpinnedDefaultRequest(
- previousIsMlx,
- stateBeforeUnload.params.maxSeqLength,
- DEFAULT_MAX_SEQ_LENGTH,
- ),
- presetSource: loadActivePresetSource,
- loadedContextPin: stateBeforeUnload.loadedCustomContextLength,
- }),
+ loadGpuLayers,
+ loadCustomContextLength,
+ effectiveMaxSeqLength,
);
- const validation = await validateModel({
+ const effectiveChatTemplateOverride =
+ loadChatTemplateOverride?.trim() ? loadChatTemplateOverride : null;
+ // Build lazily: validation, the engine offer and consent update these values.
+ const loadRequest = (): LoadModelRequest => ({
model_path: loadPath,
- engine_precision: stateBeforeUnload.params.enginePrecision ?? "auto",
- engine_parallelism: stateBeforeUnload.params.engineParallelism ?? "tensor",
- ...engineLaunchFieldsFromParams(stateBeforeUnload.params),
- engine: isGguf ? "auto" : (stateBeforeUnload.params.engine ?? "auto"),
- nativePathLease: validateNativePathLease,
+ ...loadEngineFields,
+ engine: isGguf ? "auto" : loadEngineFields.engine,
hf_token: hfToken,
- max_seq_length: validateMaxSeqLength,
- load_in_4bit:
- (stateBeforeUnload.params.engine ?? "auto") === "auto" &&
- stateBeforeUnload.params.loadIn4bit !== false,
+ max_seq_length: loadMaxSeqLength,
+ max_seq_length_auto_derived: isReplayedLoadContext(
+ isGguf,
+ loadCustomContextLength,
+ loadMaxSeqLength,
+ ),
+ load_in_4bit: loadEngineFields.engine === "auto" && loadIn4bitChoice,
is_lora: isLora,
gguf_variant: ggufVariant ?? null,
+ trust_remote_code: trustRemoteCode,
+ approved_remote_code_fingerprint: approvedRemoteCodeFingerprint,
+ chat_template_override: effectiveChatTemplateOverride,
cache_type_kv: loadKvCacheDtype,
+ mlx_kv_quant: loadMlxKvQuant ?? null,
+ mlx_int8_prefill: loadMlxInt8Prefill,
+ mlx_ple_offload: loadMlxPleOffload,
+ mlx_expert_offload: loadMlxExpertOffload,
+ speculative_type: loadSpeculativeType,
+ spec_draft_n_max: loadSpecDraftNMax,
+ ...(targetIsMlx ? { spec_draft_model: loadSpecDraftModel } : {}),
+ n_parallel: loadNParallel,
+ ...llamaServerLoadFields(
+ {
+ reasoningBudget: loadReasoningBudget,
+ reasoningBudgetMessage: loadReasoningBudgetMessage,
+ nBatch: loadNBatch,
+ nUbatch: loadNUbatch,
+ llamaExtraArgs: loadLlamaExtraArgs,
+ ...loadServerTuning,
+ },
+ { isGguf, isDiffusion: targetIsDiffusion },
+ ),
tensor_parallel: loadTensorParallel,
disable_vision: loadDisableVision,
- gpu_ids: validateGpuIds ?? undefined,
- ...(isGguf
- ? {
- gpu_memory_mode: loadGpuMemoryMode,
- // Sized like the follow-up /load, else a manual DiffusionGemma split 409s when it fits.
- gpu_layers: validateGpuLayers,
- n_parallel: validateNParallel,
- reasoning_budget: targetIsDiffusion
- ? -1
- : validateReasoningBudget,
- reasoning_budget_message: targetIsDiffusion
- ? ""
- : validateReasoningBudgetMessage,
- ...(validateNBatch != null
- ? { n_batch: validateNBatch }
- : {}),
- ...(validateNUbatch != null
- ? { n_ubatch: validateNUbatch }
- : {}),
- // Same values as /load: the preflight must approve the command /load sends.
- ...serverTuningLoadPayload(validateServerTuning),
- // Same extra args as /load: --ctx-size or cache overrides change the memory estimate.
- ...(!targetIsDiffusion && loadLlamaExtraArgs !== undefined
- ? { llama_extra_args: loadLlamaExtraArgs ?? [] }
- : {}),
- }
- : {}),
+ // A manual DiffusionGemma split keeps its layer count, or a training guard judges it a
+ // full-GGUF occupant.
+ gpu_memory_mode: loadGpuMemoryMode,
+ gpu_layers: loadGpuLayers,
+ n_cpu_moe: loadNCpuMoe,
+ tensor_split: loadSplitRatio ?? undefined,
+ gpu_ids: loadSelectedGpuIds ?? undefined,
+ });
+ const validation = await validateModel({
+ ...loadRequest(),
+ nativePathLease: validateNativePathLease,
});
isLora = validation.is_lora ?? isLora;
// validateModel cannot be aborted, so stop here if a replacement superseded this load.
@@ -2403,22 +2442,7 @@ export function useChatModelRuntime() {
if (!nativePathToken) {
Object.assign(
validation,
- await validateModel(
- {
- model_path: loadPath,
- ...loadEngineFields,
- hf_token: hfToken,
- max_seq_length: validateMaxSeqLength,
- load_in_4bit: false,
- is_lora: isLora,
- gguf_variant: ggufVariant ?? null,
- cache_type_kv: loadKvCacheDtype,
- tensor_parallel: loadTensorParallel,
- disable_vision: loadDisableVision,
- gpu_ids: validateGpuIds ?? undefined,
- },
- { signal: abortCtrl.signal },
- ),
+ await validateModel(loadRequest(), { signal: abortCtrl.signal }),
);
if (abortCtrl.signal.aborted) throw new Error("Cancelled");
}
@@ -2513,7 +2537,6 @@ export function useChatModelRuntime() {
// On a switch, fall back to the standing spec preference so forced MTP does not follow.
if (resetsPerModelSettings) {
- const persistedSpeculativeType = readPersistedSpeculativeType();
useChatRuntimeStore.setState({
speculativeType: persistedSpeculativeType,
loadedSpeculativeType: persistedSpeculativeType,
@@ -2543,95 +2566,8 @@ export function useChatModelRuntime() {
splitRatio: null,
customContextLength: null,
});
- loadSpeculativeType =
- pendingLoadConfig?.speculativeType != null
- ? normalizeSpeculativeType(pendingLoadConfig.speculativeType)
- : persistedSpeculativeType;
- loadSpecDraftNMax = pendingLoadConfig?.specDraftNMax ?? null;
- loadNParallel = pendingLoadConfig?.nParallel ?? null;
- loadReasoningBudget = pendingLoadConfig?.reasoningBudget ?? -1;
- loadReasoningBudgetMessage =
- pendingLoadConfig?.reasoningBudgetMessage ?? "";
- loadNBatch = pendingLoadConfig?.nBatch ?? null;
- loadNUbatch = pendingLoadConfig?.nUbatch ?? null;
- loadServerTuning = {
- loadMode: pendingLoadConfig?.loadMode ?? null,
- specDraftCacheDtype:
- pendingLoadConfig?.specDraftCacheDtype ?? null,
- ctxCheckpoints: pendingLoadConfig?.ctxCheckpoints ?? null,
- cacheRam: pendingLoadConfig?.cacheRam ?? null,
- };
- loadMlxKvQuant = pendingLoadConfig?.mlxKvQuant ?? null;
- loadMlxInt8Prefill = pendingLoadConfig?.mlxInt8Prefill ?? false;
- loadMlxPleOffload = pendingLoadConfig?.mlxPleOffload ?? null;
- loadMlxExpertOffload = pendingLoadConfig?.mlxExpertOffload ?? null;
- loadChatTemplateOverride =
- pendingLoadConfig?.chatTemplateOverride?.trim()
- ? pendingLoadConfig.chatTemplateOverride
- : null;
- // Keep the click-time snapshot in lock-step with the store reset.
- loadCustomContextLength =
- pendingLoadConfig?.customContextLength ?? null;
- loadSelectedGpuIds = stagedGpuIds;
- loadGpuLayers = pendingLoadConfig?.gpuLayers ?? GPU_LAYERS_AUTO;
- loadNCpuMoe = pendingLoadConfig?.nCpuMoe ?? 0;
- loadSplitRatio = reconcileTensorSplit(
- pendingLoadConfig?.tensorSplit,
- pendingLoadConfig?.selectedGpuIds,
- stagedGpuIds,
- );
- }
-
- // The user's Context Length, captured before the clamp: this is what the load pins.
- const targetIsMlx = isServedByMlx(
- isGguf,
- platform.deviceType,
- platform.chatOnlyReason,
- );
- // Only a same-model reload without a staged config reuses the resident's settings; otherwise the
- // drafter is this model's own and a standing mode goes through the resolver.
- if (targetIsMlx && (pendingLoadConfig != null || switchingModelOrVariant)) {
- loadSpecDraftModel = pendingLoadConfig?.specDraftModel ?? null;
- if (loadSpeculativeType && pendingLoadConfig?.speculativeType == null) {
- loadSpeculativeType = resolveSpeculativeType(null, loadSpeculativeType, true);
- }
}
- const explicitCtxPin = loadRequestContextPin(
- loadCustomContextLength,
- targetIsMlx,
- pinnedMaxSeqLength,
- );
- loadCustomContextLength = fixedLayerContext(
- loadCustomContextLength,
- loadGpuLayers,
- );
- const effectiveMaxSeqLength = resolveLoadMaxSeqLength({
- modelId,
- ggufVariant,
- isGguf,
- customContextLength: loadCustomContextLength,
- loadedContextLength: loadContextLength,
- currentCheckpoint,
- activeGgufVariant: loadActiveGgufVariant,
- isMlx: targetIsMlx,
- pinnedMaxSeqLength,
- defaultMaxSeqLength: unpinnedDefaultRequest(
- previousIsMlx,
- stateBeforeUnload.params.maxSeqLength,
- DEFAULT_MAX_SEQ_LENGTH,
- ),
- presetSource: loadActivePresetSource,
- loadedContextPin: stateBeforeUnload.loadedCustomContextLength,
- });
- const loadMaxSeqLength = resolveFitMaxSeqLength(
- isGguf,
- loadGpuMemoryMode,
- loadGpuLayers,
- loadCustomContextLength,
- effectiveMaxSeqLength,
- );
- const effectiveChatTemplateOverride =
- loadChatTemplateOverride?.trim() ? loadChatTemplateOverride : null;
+ // Invalidate factories started before the final loading boundary.
if (!keepsOthers && !touchesOnlySelected) {
requestLocalPromptQueueStop();
}
@@ -2642,59 +2578,10 @@ export function useChatModelRuntime() {
loadRun.loadAttemptPath = loadPath;
const loadResponse = await loadModel({
- model_path: loadPath,
- ...loadEngineFields,
- engine: isGguf ? "auto" : loadEngineFields.engine,
+ ...loadRequest(),
load_request_id: loadRun.requestId,
nativePathLease: loadNativePathLease,
- hf_token: hfToken,
- max_seq_length: loadMaxSeqLength,
- max_seq_length_auto_derived: isReplayedLoadContext(
- isGguf,
- loadCustomContextLength,
- loadMaxSeqLength,
- ),
- load_in_4bit:
- loadEngineFields.engine === "auto" && loadIn4bitChoice,
- is_lora: isLora,
- gguf_variant: ggufVariant ?? null,
- trust_remote_code: trustRemoteCode,
- approved_remote_code_fingerprint: approvedRemoteCodeFingerprint,
- chat_template_override: effectiveChatTemplateOverride,
- cache_type_kv: loadKvCacheDtype,
- mlx_kv_quant: loadMlxKvQuant ?? null,
- mlx_int8_prefill: loadMlxInt8Prefill,
- mlx_ple_offload: loadMlxPleOffload,
- mlx_expert_offload: loadMlxExpertOffload,
- speculative_type: loadSpeculativeType,
- spec_draft_n_max: loadSpecDraftNMax,
- ...(targetIsMlx ? { spec_draft_model: loadSpecDraftModel } : {}),
- n_parallel: loadNParallel,
- reasoning_budget:
- isGguf && !targetIsDiffusion ? loadReasoningBudget : -1,
- reasoning_budget_message:
- isGguf && !targetIsDiffusion ? loadReasoningBudgetMessage : "",
- // [] means launch with none; llama-server flags only, never transformers or diffusion.
- ...(isGguf && !targetIsDiffusion && loadLlamaExtraArgs !== undefined
- ? { llama_extra_args: loadLlamaExtraArgs ?? [] }
- : {}),
- // omitted when blank: a null counts as set and strips inherited -b / -ub
- ...(isGguf && loadNBatch != null ? { n_batch: loadNBatch } : {}),
- ...(isGguf && loadNUbatch != null
- ? { n_ubatch: loadNUbatch }
- : {}),
- ...(isGguf && !targetIsDiffusion
- ? serverTuningLoadPayload(loadServerTuning)
- : {}),
- tensor_parallel: loadTensorParallel,
- disable_vision: loadDisableVision,
- gpu_memory_mode: loadGpuMemoryMode,
- gpu_layers: loadGpuLayers,
- n_cpu_moe: loadNCpuMoe,
- tensor_split: loadSplitRatio ?? undefined,
- gpu_ids: loadSelectedGpuIds ?? undefined,
force_cancel_active: forceCancelActive,
-
force_reload: forceReload,
alongside: keepModelsLoaded || touchesOnlySelected,
});
diff --git a/studio/frontend/src/features/chat/lib/load-request.ts b/studio/frontend/src/features/chat/lib/load-request.ts
new file mode 100644
index 00000000000..8cf298d583b
--- /dev/null
+++ b/studio/frontend/src/features/chat/lib/load-request.ts
@@ -0,0 +1,72 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import type { LoadModelRequest } from "../types/api";
+import {
+ type ServerTuningValues,
+ serverTuningLoadPayload,
+} from "./server-tuning-fields";
+
+export interface LlamaServerLoadSettings extends ServerTuningValues {
+ reasoningBudget?: number | null;
+ reasoningBudgetMessage?: string | null;
+ nBatch?: number | null;
+ nUbatch?: number | null;
+ /** undefined: this config never read them, so the route keeps the stored list. */
+ llamaExtraArgs?: string[] | null;
+}
+
+// Omit blank knobs: a sent null strips inherited flags via model_fields_set.
+export function llamaServerLoadFields(
+ settings: LlamaServerLoadSettings,
+ target: { isGguf: boolean; isDiffusion: boolean },
+): Partial<LoadModelRequest> {
+ const llamaServer = target.isGguf && !target.isDiffusion;
+ return {
+ reasoning_budget: llamaServer ? (settings.reasoningBudget ?? -1) : -1,
+ reasoning_budget_message: llamaServer
+ ? (settings.reasoningBudgetMessage ?? "")
+ : "",
+ ...(target.isGguf && settings.nBatch != null
+ ? { n_batch: settings.nBatch }
+ : {}),
+ ...(target.isGguf && settings.nUbatch != null
+ ? { n_ubatch: settings.nUbatch }
+ : {}),
+ ...(llamaServer ? serverTuningLoadPayload(settings) : {}),
+ ...(llamaServer && settings.llamaExtraArgs !== undefined
+ ? // biome-ignore lint/style/useNamingConvention: API schema
+ { llama_extra_args: settings.llamaExtraArgs ?? [] }
+ : {}),
+ };
+}
+
+export function wireLoadRequest(
+ payload: LoadModelRequest,
+ hfToken: string | null,
+) {
+ return {
+ ...payload,
+ hf_token: hfToken,
+ native_path_lease: payload.nativePathLease ?? null,
+ nativePathLease: undefined,
+ };
+}
+
+// Forward every load field; an allow-list previously dropped settings that affect validation.
+export function validateRequestBody(
+ payload: LoadModelRequest,
+ hfToken: string | null,
+) {
+ return {
+ ...wireLoadRequest(payload, hfToken),
+ engine: payload.engine ?? "auto",
+ engine_precision: payload.engine_precision ?? "auto",
+ engine_parallelism: payload.engine_parallelism ?? "tensor",
+ engine_kv_cache_dtype: payload.engine_kv_cache_dtype ?? "auto",
+ tensor_parallel: payload.tensor_parallel ?? false,
+ disable_vision: payload.disable_vision ?? false,
+ reasoning_budget: payload.reasoning_budget ?? -1,
+ reasoning_budget_message: payload.reasoning_budget_message ?? "",
+ };
+}
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index eef8b12f16f..6765b1e81bd 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -10,10 +10,10 @@ import {
import { useChatArtifactsStore } from "./artifacts/store";
import { mlxRuntimeStateFrom } from "./lib/mlx-runtime-state";
import { offloadCountsFrom, offloadWarning } from "./lib/partial-offload";
+import { llamaServerLoadFields } from "./lib/load-request";
import {
clearedServerTuningState,
committedServerTuningState,
- serverTuningLoadPayload,
} from "./lib/server-tuning-fields";
import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button";
import { useTextareaSkillMentions } from "@/components/assistant-ui/skill-mentions";
@@ -81,7 +81,7 @@ import { isTauri } from "@/lib/api-base";
import { classifiedAttachmentFiles, isVideoFile } from "@/lib/video-utils";
import { newAttachmentId } from "./audio-attachment-adapter";
import { isDownloadCancelled } from "@/lib/native-files";
-import { isMultimodalResponse } from "./types/api";
+import { isMultimodalResponse, type LoadModelRequest } from "./types/api";
import { getImageInputUnavailableReason } from "./utils/image-input-support";
import {
CHAT_IMAGE_ACCEPT,
@@ -1786,8 +1786,8 @@ export function SharedComposer({
effectiveCustomContextLength,
effectiveMaxSeqLength,
);
- // Re-run as the engine the offer dialog picks, so its settings are checked before /load.
- const panePayload = () => ({
+ // Build lazily: the engine offer can replace paneEngineFields before revalidation.
+ const panePayload = (): LoadModelRequest => ({
model_path: sel.id,
hf_token: currentStore.hfToken || null,
max_seq_length: compareMaxSeqLength,
@@ -1797,34 +1797,29 @@ export function SharedComposer({
trust_remote_code: loadTrustRemoteCode,
chat_template_override: effectiveChatTemplateOverride,
cache_type_kv: ownConfig.kvCacheDtype ?? null,
+ mlx_kv_quant: ownConfig.mlxKvQuant ?? null,
+ mlx_int8_prefill: ownConfig.mlxInt8Prefill ?? false,
+ mlx_ple_offload: ownConfig.mlxPleOffload ?? null,
+ mlx_expert_offload: ownConfig.mlxExpertOffload ?? null,
+ speculative_type: effectiveSpeculativeType,
+ spec_draft_n_max: effectiveSpecDraftNMax,
+ ...(targetIsMlx ? { spec_draft_model: ownConfig.specDraftModel ?? null } : {}),
tensor_parallel: effectiveTensorParallel,
disable_vision: effectiveDisableVision,
- // GGUF-only, like the load: a non-GGUF target must not inherit a hidden GPU pick.
+ n_parallel: ownConfig.nParallel ?? null,
+ ...llamaServerLoadFields(ownConfig, {
+ isGguf: targetIsGguf,
+ isDiffusion: resolvedIsDiffusion === true,
+ }),
+ // GGUF-only: a non-GGUF target must not inherit a hidden GGUF GPU pick. A manual DiffusionGemma
+ // split keeps its layer count, or it is judged a full-GGUF occupant.
...(targetIsGguf
? {
- gpu_ids: effectiveSelectedGpuIds ?? undefined,
gpu_memory_mode: effectiveGpuMemoryMode,
gpu_layers: effectiveGpuLayers,
- n_parallel: ownConfig.nParallel ?? null,
- reasoning_budget: resolvedIsDiffusion
- ? -1
- : ownConfig.reasoningBudget,
- reasoning_budget_message: resolvedIsDiffusion
- ? ""
- : ownConfig.reasoningBudgetMessage,
- // Omitted when unread so the load inherits it, which keeps CLI-set flags working.
- ...(ownConfig.llamaExtraArgs !== undefined
- ? // biome-ignore lint/style/useNamingConvention: API schema
- { llama_extra_args: ownConfig.llamaExtraArgs ?? [] }
- : {}),
- // Omitted when blank: a null counts as set and strips inherited -b / -ub.
- ...(ownConfig.nBatch != null
- ? { n_batch: ownConfig.nBatch }
- : {}),
- ...(ownConfig.nUbatch != null
- ? { n_ubatch: ownConfig.nUbatch }
- : {}),
- ...serverTuningLoadPayload(ownConfig),
+ n_cpu_moe: effectiveNCpuMoe,
+ tensor_split: compareLoadKnobs.splitRatio ?? undefined,
+ gpu_ids: effectiveSelectedGpuIds ?? undefined,
}
: {}),
});
@@ -1917,58 +1912,13 @@ export function SharedComposer({
applyCompareStopDecision();
const loadRequestId = crypto.randomUUID();
const resp = await loadModel({
- model_path: sel.id,
+ ...panePayload(),
+ hf_token: useChatRuntimeStore.getState().hfToken || null,
alongside: useChatRuntimeStore.getState().keepModelsLoaded,
load_request_id: loadRequestId,
- hf_token: useChatRuntimeStore.getState().hfToken || null,
- max_seq_length: compareMaxSeqLength,
- ...paneEngineFields,
- is_lora: sel.isLora,
- gguf_variant: sel.ggufVariant ?? null,
- trust_remote_code: loadTrustRemoteCode,
approved_remote_code_fingerprint: approvedRemoteCodeFingerprint,
- chat_template_override: effectiveChatTemplateOverride,
- cache_type_kv: ownConfig.kvCacheDtype ?? null,
- mlx_kv_quant: ownConfig.mlxKvQuant ?? null,
- mlx_int8_prefill: ownConfig.mlxInt8Prefill ?? false,
- mlx_ple_offload: ownConfig.mlxPleOffload ?? null,
- mlx_expert_offload: ownConfig.mlxExpertOffload ?? null,
- speculative_type: effectiveSpeculativeType,
- spec_draft_n_max: effectiveSpecDraftNMax,
- ...(targetIsMlx ? { spec_draft_model: ownConfig.specDraftModel ?? null } : {}),
- reasoning_budget:
- targetIsGguf && !resolvedIsDiffusion
- ? ownConfig.reasoningBudget
- : -1,
- reasoning_budget_message:
- targetIsGguf && !resolvedIsDiffusion
- ? ownConfig.reasoningBudgetMessage
- : "",
- tensor_parallel: effectiveTensorParallel,
- disable_vision: effectiveDisableVision,
- n_parallel: ownConfig.nParallel ?? null,
force_cancel_active:
compareStopDecision?.forceCancelActive ?? false,
- ...(targetIsGguf
- ? {
- gpu_memory_mode: effectiveGpuMemoryMode,
- gpu_layers: effectiveGpuLayers,
- n_cpu_moe: effectiveNCpuMoe,
- tensor_split: compareLoadKnobs.splitRatio ?? undefined,
- gpu_ids: effectiveSelectedGpuIds ?? undefined,
- ...(ownConfig.llamaExtraArgs !== undefined
- ? // biome-ignore lint/style/useNamingConvention: API schema
- { llama_extra_args: ownConfig.llamaExtraArgs ?? [] }
- : {}),
- ...(ownConfig.nBatch != null
- ? { n_batch: ownConfig.nBatch }
- : {}),
- ...(ownConfig.nUbatch != null
- ? { n_ubatch: ownConfig.nUbatch }
- : {}),
- ...serverTuningLoadPayload(ownConfig),
- }
- : {}),
}, {
signal: compareSignal,
onRequestStart: () => {
diff --git a/studio/frontend/tests/chat-load-request-one-builder.test.ts b/studio/frontend/tests/chat-load-request-one-builder.test.ts
new file mode 100644
index 00000000000..3b834359e45
--- /dev/null
+++ b/studio/frontend/tests/chat-load-request-one-builder.test.ts
@@ -0,0 +1,219 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import { readSrc, readText, registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const { llamaServerLoadFields, validateRequestBody } = await import(
+ "../src/features/chat/lib/load-request.ts"
+);
+
+function validateModelRequestFields(): string[] {
+ const source = readText("../../backend/models/inference.py");
+ const start = source.indexOf("class ValidateModelRequest(BaseModel):");
+ assert.ok(start >= 0, "ValidateModelRequest moved");
+ const body = source.slice(start, source.indexOf("\nclass ", start + 1));
+ return [...body.matchAll(/^ {4}(\w+):/gm)].map((match) => match[1]);
+}
+
+function loadModelRequestFields(): Set<string> {
+ const source = readSrc("features/chat/types/api.ts");
+ const start = source.indexOf("export interface LoadModelRequest {");
+ const body = source.slice(start, source.indexOf("\n}\n", start));
+ return new Set(
+ [...body.matchAll(/^ {2}(\w+)\??:/gm)].map((match) => match[1]),
+ );
+}
+
+const VALIDATE_ONLY = new Set([
+ "include_context_length",
+ "include_chat_template",
+]);
+const RENAMED = new Map([["native_path_lease", "nativePathLease"]]);
+
+test("every field /validate prices can ride the load request", () => {
+ const loadFields = loadModelRequestFields();
+ const missing = validateModelRequestFields().filter(
+ (field) =>
+ !VALIDATE_ONLY.has(field) && !loadFields.has(RENAMED.get(field) ?? field),
+ );
+ assert.deepEqual(missing, []);
+});
+
+test("/validate receives every load setting it prices, not a hand-kept subset", () => {
+ const fields = validateModelRequestFields().filter(
+ (field) =>
+ !VALIDATE_ONLY.has(field) && !RENAMED.has(field) && field !== "hf_token",
+ );
+ const request = Object.fromEntries(
+ fields.map((field) => [field, `set:${field}`]),
+ );
+ const body = validateRequestBody(
+ { ...request, nativePathLease: "lease" } as never,
+ "token",
+ ) as Record<string, unknown>;
+ for (const field of fields) assert.equal(body[field], `set:${field}`, field);
+ for (const field of [
+ "ctx_checkpoints",
+ "spec_draft_cache_type",
+ "tensor_split",
+ ]) {
+ assert.ok(fields.includes(field), field);
+ }
+ assert.equal(body.native_path_lease, "lease");
+ assert.equal(body.hf_token, "token");
+ assert.equal("nativePathLease" in JSON.parse(JSON.stringify(body)), false);
+});
+
+test("an unset non-nullable /validate field gets its default, not a null the route refuses", () => {
+ const body = validateRequestBody(
+ {
+ model_path: "org/m",
+ hf_token: null,
+ max_seq_length: 0,
+ load_in_4bit: true,
+ is_lora: false,
+ tensor_parallel: null,
+ disable_vision: null,
+ },
+ null,
+ ) as Record<string, unknown>;
+ assert.deepEqual(
+ {
+ engine: body.engine,
+ engine_precision: body.engine_precision,
+ engine_parallelism: body.engine_parallelism,
+ engine_kv_cache_dtype: body.engine_kv_cache_dtype,
+ tensor_parallel: body.tensor_parallel,
+ disable_vision: body.disable_vision,
+ reasoning_budget: body.reasoning_budget,
+ reasoning_budget_message: body.reasoning_budget_message,
+ },
+ {
+ engine: "auto",
+ engine_precision: "auto",
+ engine_parallelism: "tensor",
+ engine_kv_cache_dtype: "auto",
+ tensor_parallel: false,
+ disable_vision: false,
+ reasoning_budget: -1,
+ reasoning_budget_message: "",
+ },
+ );
+});
+
+const TUNED = {
+ reasoningBudget: 512,
+ reasoningBudgetMessage: "stop",
+ nBatch: 1024,
+ nUbatch: 256,
+ ctxCheckpoints: 0,
+ specDraftCacheDtype: "q8_0",
+ loadMode: "mmap",
+ cacheRam: 4096,
+ llamaExtraArgs: ["--ctx-size", "8192"],
+};
+
+test("llama-server's knobs reach a GGUF llama-server and nothing else", () => {
+ assert.deepEqual(
+ llamaServerLoadFields(TUNED, { isGguf: true, isDiffusion: false }),
+ {
+ reasoning_budget: 512,
+ reasoning_budget_message: "stop",
+ n_batch: 1024,
+ n_ubatch: 256,
+ load_mode: "mmap",
+ spec_draft_cache_type: "q8_0",
+ ctx_checkpoints: 0,
+ cache_ram: 4096,
+ llama_extra_args: ["--ctx-size", "8192"],
+ },
+ );
+ assert.deepEqual(
+ llamaServerLoadFields(TUNED, { isGguf: true, isDiffusion: true }),
+ {
+ reasoning_budget: -1,
+ reasoning_budget_message: "",
+ n_batch: 1024,
+ n_ubatch: 256,
+ },
+ );
+ assert.deepEqual(
+ llamaServerLoadFields(TUNED, { isGguf: false, isDiffusion: false }),
+ {
+ reasoning_budget: -1,
+ reasoning_budget_message: "",
+ },
+ );
+});
+
+test("blank knobs are omitted, and pass-through args only once the config has read them", () => {
+ const llama = { isGguf: true, isDiffusion: false };
+ assert.deepEqual(
+ llamaServerLoadFields({ nBatch: null, ctxCheckpoints: null }, llama),
+ {
+ reasoning_budget: -1,
+ reasoning_budget_message: "",
+ },
+ );
+ assert.equal("llama_extra_args" in llamaServerLoadFields({}, llama), false);
+ assert.deepEqual(
+ llamaServerLoadFields({ llamaExtraArgs: null }, llama).llama_extra_args,
+ [],
+ );
+});
+
+test("every chat load path sends one request to /validate and /load", () => {
+ const runtime = readSrc("features/chat/hooks/use-chat-model-runtime.ts");
+ assert.match(runtime, /await validateModel\(\{\s*\.\.\.loadRequest\(\),/);
+ assert.match(
+ runtime,
+ /await validateModel\(loadRequest\(\), \{ signal: abortCtrl\.signal \}\)/,
+ );
+ assert.match(runtime, /await loadModel\(\{\s*\.\.\.loadRequest\(\),/);
+
+ const composer = readSrc("features/chat/shared-composer.tsx");
+ assert.equal(
+ composer.match(/await validateModel\(panePayload\(\),/g)?.length,
+ 2,
+ );
+ assert.match(composer, /await loadModel\(\{\s*\.\.\.panePayload\(\),/);
+
+ const adapter = readSrc("features/chat/api/chat-adapter.ts");
+ assert.match(adapter, /validateModel\(request\)/);
+ assert.match(
+ adapter,
+ /canAutoLoadRecordingFailures\(failureLabel, request\)/,
+ );
+ assert.match(adapter, /canAutoLoad\(request\)/);
+ assert.equal(
+ adapter.match(/await loadModel\(\{ \.\.\.request, alongside: true \}\)/g)
+ ?.length,
+ 2,
+ );
+});
+
+test("the llama-server knobs are spelled in one place", () => {
+ for (const file of [
+ "features/chat/shared-composer.tsx",
+ "features/chat/api/chat-adapter.ts",
+ "features/chat/api/chat-api.ts",
+ ]) {
+ const source = readSrc(file);
+ assert.doesNotMatch(
+ source,
+ /llama_extra_args:|serverTuningLoadPayload\(|n_batch:/,
+ file,
+ );
+ }
+ // The runtime's one remaining spelling replays the previous server's own echo on a rollback.
+ const runtime = readSrc("features/chat/hooks/use-chat-model-runtime.ts");
+ assert.equal(runtime.match(/serverTuningLoadPayload\(/g)?.length, 1);
+ assert.match(
+ runtime,
+ /\.\.\.serverTuningLoadPayload\(\{\s*loadMode: rollbackState\.loadedLoadMode,/,
+ );
+});
diff --git a/studio/frontend/tests/chat-save-conflict-detail.test.ts b/studio/frontend/tests/chat-save-conflict-detail.test.ts
index e4d1c1c96a4..a4914f8d228 100644
--- a/studio/frontend/tests/chat-save-conflict-detail.test.ts
+++ b/studio/frontend/tests/chat-save-conflict-detail.test.ts
@@ -66,6 +66,7 @@ function harness(response: ReturnType<typeof jsonResponse>) {
isCoalescedHistoryEvent: () => false,
},
"../utils/load-warning-toast": { showLoadWarning: () => {} },
+ "../lib/load-request": {},
"./generation-length.ts": {},
"./gguf-variants-request": {},
"./padded-response": { assertCompletedPaddedBody: () => {} },
diff --git a/studio/frontend/tests/compare-pane-managed-engine.test.ts b/studio/frontend/tests/compare-pane-managed-engine.test.ts
index a8b6165e183..b32f1281d57 100644
--- a/studio/frontend/tests/compare-pane-managed-engine.test.ts
+++ b/studio/frontend/tests/compare-pane-managed-engine.test.ts
@@ -65,7 +65,8 @@ test("a compare pane loads its remembered vLLM or SGLang settings", () => {
assert.equal(tuned.engine_kv_cache_dtype, "fp8");
assert.equal(tuned.engine_seed, 0);
assert.equal(tuned.engine_gpu_memory_utilization, 0.5);
- assert.equal(composer.match(/\.\.\.paneEngineFields,/g)?.length, 2);
+ assert.equal(composer.match(/\.\.\.paneEngineFields,/g)?.length, 1);
+ assert.match(composer, /loadModel\(\{\s*\.\.\.panePayload\(\),/);
});
test("a default or GGUF compare pane keeps the default backend and no GPU pick", () => {
diff --git a/studio/frontend/tests/context-pin-survives-load.test.ts b/studio/frontend/tests/context-pin-survives-load.test.ts
index bc771d05dd9..3d51756de0d 100644
--- a/studio/frontend/tests/context-pin-survives-load.test.ts
+++ b/studio/frontend/tests/context-pin-survives-load.test.ts
@@ -235,7 +235,8 @@ test("choosing Auto after a pinned load asks the server to size itself again", (
});
test("each same-model resolver call hands over the resident pin", () => {
- assert.equal(RUNTIME.match(/loadedContextPin: (?:live|stateBeforeUnload)\.loadedCustomContextLength,/g)?.length, 3);
+ // One call sizes both /validate and /load; the other decides whether the resident already matches.
+ assert.equal(RUNTIME.match(/loadedContextPin: (?:live|stateBeforeUnload)\.loadedCustomContextLength,/g)?.length, 2);
});
test("Auto stays Auto across a same-model reload, under every preset source", () => {
@@ -280,7 +281,7 @@ test("Auto stays Auto across a same-model reload, under every preset source", ()
test("the clamp that stops a manual reload resizing is not a user pin", () => {
// The pin is captured before performLoad substitutes the resolved context for Auto.
const capture = RUNTIME.indexOf("const explicitCtxPin = loadRequestContextPin(");
- const clamp = RUNTIME.indexOf("loadCustomContextLength = fixedLayerContext(");
+ const clamp = RUNTIME.indexOf("loadCustomContextLength = loadContextLength;");
assert.notEqual(capture, -1, "the load no longer captures the user's setting");
assert.notEqual(clamp, -1);
assert.ok(
@@ -288,11 +289,10 @@ test("the clamp that stops a manual reload resizing is not a user pin", () => {
"the clamp now runs before the pin is captured, so the app's substituted length " +
"would be recorded as the user's choice",
);
- // /validate sizes the context the load will send, clamp included.
- assert.match(
- RUNTIME,
- /const validateCustomContextLength = resetsPerModelSettings\s*\?\s*null\s*:\s*fixedLayerContext\(loadCustomContextLength, loadGpuLayers\);/,
- );
+ // /validate sizes the context the load will send, clamp included: it sends the same request.
+ const request = RUNTIME.indexOf("const loadRequest = (): LoadModelRequest =>");
+ assert.ok(clamp < request);
+ assert.match(RUNTIME, /await validateModel\(\{\s*\.\.\.loadRequest\(\),/);
});
test("the three in-app writers pin what the user asked for, not what they sent", () => {
diff --git a/studio/frontend/tests/llama-extra-args-diagnostics.test.ts b/studio/frontend/tests/llama-extra-args-diagnostics.test.ts
index 7aa8476d5d3..d7bd9db560e 100644
--- a/studio/frontend/tests/llama-extra-args-diagnostics.test.ts
+++ b/studio/frontend/tests/llama-extra-args-diagnostics.test.ts
@@ -582,10 +582,7 @@ test("a config that never read the stored value is not sent as a clear", () => {
test("the load sends the flags only once they are known", () => {
const composer = readSrc("features/chat/shared-composer.tsx").replace(/\s+/g, " ");
- assert.match(
- composer,
- /ownConfig\.llamaExtraArgs !== undefined \? .* \{ llama_extra_args: ownConfig\.llamaExtraArgs \?\? \[\] \} : \{\}/,
- );
+ assert.match(composer, /\.\.\.llamaServerLoadFields\(ownConfig, \{/);
});
test("the panel's own Load goes through the runtime, which sends them too", () => {
@@ -594,10 +591,7 @@ test("the panel's own Load goes through the runtime, which sends them too", () =
runtime,
/let loadLlamaExtraArgs = pendingLoadConfig\?\.llamaExtraArgs/,
);
- assert.match(
- runtime,
- /isGguf && !targetIsDiffusion && loadLlamaExtraArgs !== undefined \? \{ llama_extra_args: loadLlamaExtraArgs \?\? \[\] \} : \{\}/,
- );
+ assert.match(runtime, /llamaExtraArgs: loadLlamaExtraArgs,/);
});
test("the box follows a config change it did not make", () => {
@@ -705,15 +699,8 @@ test("a hydrated list is judged even when the row cannot be", () => {
test("the runtime preflight is sized with the arguments the load sends", () => {
const runtime = readSrc("features/chat/hooks/use-chat-model-runtime.ts").replace(/\s+/g, " ");
- // A --ctx-size or cache override changes the memory /validate estimates.
- const validateCall = runtime.slice(
- runtime.indexOf("await validateModel({"),
- runtime.indexOf("// Upgrade consent runs before"),
- );
- assert.match(
- validateCall,
- /loadLlamaExtraArgs !== undefined \? \{ llama_extra_args: loadLlamaExtraArgs \?\? \[\] \}/,
- );
+ // A --ctx-size or cache override changes the memory /validate estimates, so it sends the load's own request.
+ assert.match(runtime, /await validateModel\(\{ \.\.\.loadRequest\(\),/);
});
test("a catalogue read from the previous binary is discarded", () => {
diff --git a/studio/frontend/tests/llama-extra-args-panel-hydration.test.ts b/studio/frontend/tests/llama-extra-args-panel-hydration.test.ts
index 7f5504f231d..e455e4444f6 100644
--- a/studio/frontend/tests/llama-extra-args-panel-hydration.test.ts
+++ b/studio/frontend/tests/llama-extra-args-panel-hydration.test.ts
@@ -69,9 +69,9 @@ test("a background auto-load hydrates a server-only override", () => {
assert.match(ADAPTER, /const cleaned = clean\(resolvedExtraArgs\);/);
// Cached inventory can return a different loadId than the one the row was written under.
assert.match(ADAPTER, /candidate\.id,\n\s*candidate\.ggufVariant \?\? null,/);
- assert.equal(
- ADAPTER.match(/llama_extra_args: resolvedExtraArgs \?\? \[\]/g)?.length,
- 2,
+ assert.match(
+ ADAPTER,
+ /llamaServerLoadFields\(\s*\{ \.\.\.config, llamaExtraArgs: resolvedExtraArgs \}/,
);
assert.match(ADAPTER, /candidate\.kind === "gguf" &&\s*\n?\s*!isDiffusion/);
});
diff --git a/studio/frontend/tests/load-in-4bit-setting.test.ts b/studio/frontend/tests/load-in-4bit-setting.test.ts
index 1197b730e99..6702eb5ab3d 100644
--- a/studio/frontend/tests/load-in-4bit-setting.test.ts
+++ b/studio/frontend/tests/load-in-4bit-setting.test.ts
@@ -95,10 +95,7 @@ test("every default-engine load path sends the choice, vLLM and SGLang never 4-b
runtime,
/load_in_4bit:\s*loadEngineFields\.engine === "auto" && loadIn4bitChoice,/,
);
- assert.match(
- runtime,
- /load_in_4bit:\s*\(stateBeforeUnload\.params\.engine \?\? "auto"\) === "auto" &&\s*stateBeforeUnload\.params\.loadIn4bit !== false,/,
- );
+ assert.match(runtime, /await validateModel\(\{\s*\.\.\.loadRequest\(\),/);
const composer = readSrc("features/chat/shared-composer.tsx");
assert.match(
composer,
@@ -108,7 +105,7 @@ test("every default-engine load path sends the choice, vLLM and SGLang never 4-b
assert.equal(
(adapter.match(/load_in_4bit: config\.loadIn4bit !== false,/g) ?? [])
.length,
- 2,
+ 1,
);
});
diff --git a/studio/frontend/tests/load-rollback-after-lost-reply.test.ts b/studio/frontend/tests/load-rollback-after-lost-reply.test.ts
index bede2a625a5..45632bdf223 100644
--- a/studio/frontend/tests/load-rollback-after-lost-reply.test.ts
+++ b/studio/frontend/tests/load-rollback-after-lost-reply.test.ts
@@ -113,6 +113,10 @@ function realLoadModel(auth: AuthApi): ChatApi {
isCoalescedHistoryEvent: () => false,
},
"../utils/load-warning-toast": { showLoadWarning: () => {} },
+ "../lib/load-request": loadWithStubs(
+ new URL("../src/features/chat/lib/load-request.ts", import.meta.url),
+ { "./server-tuning-fields": {} },
+ ),
"./generation-length.ts": {},
"./gguf-variants-request": {},
"@/features/hf-auth": { prepareHfTokenForUse: async () => ({ proceed: true }) },
diff --git a/studio/frontend/tests/load-warning-toast.test.ts b/studio/frontend/tests/load-warning-toast.test.ts
index 9b3c155829e..0bc02016486 100644
--- a/studio/frontend/tests/load-warning-toast.test.ts
+++ b/studio/frontend/tests/load-warning-toast.test.ts
@@ -53,6 +53,10 @@ function chatApi(body: Record<string, unknown>) {
"../utils/load-warning-toast": {
showLoadWarning: (warning: string | null | undefined) => shown.push(warning),
},
+ "../lib/load-request": loadWithStubs(
+ new URL("../src/features/chat/lib/load-request.ts", import.meta.url),
+ { "./server-tuning-fields": {} },
+ ),
"./generation-length.ts": {},
"./gguf-variants-request": {},
"./padded-response": { assertCompletedPaddedBody: () => {} },
diff --git a/studio/frontend/tests/managed-engine-offer.test.ts b/studio/frontend/tests/managed-engine-offer.test.ts
index 96dfc80a41a..0c617ae4f4a 100644
--- a/studio/frontend/tests/managed-engine-offer.test.ts
+++ b/studio/frontend/tests/managed-engine-offer.test.ts
@@ -67,8 +67,10 @@ test("the chat load asks before unloading anything and loads with the chosen eng
const offerAt = source.indexOf("confirmManagedEngineIfNeeded(");
const unloadAt = source.indexOf("await unloadModel({ model_path: currentCheckpoint })");
assert.ok(offerAt > 0 && unloadAt > offerAt, "the offer must come before the preliminary unload");
- assert.match(source, /loadModel\(\{\s*model_path: loadPath,\s*\.\.\.loadEngineFields,/);
- const revalidateAt = source.indexOf("...loadEngineFields,", offerAt);
+ // The request reads loadEngineFields when built, so both the re-validate and the load see the pick.
+ assert.match(source, /loadRequest = \(\): LoadModelRequest => \(\{\s*model_path: loadPath,\s*\.\.\.loadEngineFields,/);
+ assert.match(source, /loadModel\(\{\s*\.\.\.loadRequest\(\),/);
+ const revalidateAt = source.indexOf("validateModel(loadRequest(), { signal: abortCtrl.signal })", offerAt);
assert.ok(revalidateAt > offerAt && revalidateAt < unloadAt, "the chosen engine must be validated before the unload");
// Keep loaded models: the switch re-asks about running chats and then replaces, like any managed load.
const branch = source.slice(offerAt, unloadAt);
@@ -77,7 +79,7 @@ test("the chat load asks before unloading anything and loads with the chosen eng
// Declining the replacement prompt this engine needs is a cancellation, and the toast stops promising kept models.
const offerBranch = source.slice(offerAt, unloadAt);
assert.match(offerBranch, /abortCtrl\.abort\(\);\s*throw new Error\("Cancelled"\);/);
- assert.match(offerBranch, /\},\s*\{ signal: abortCtrl\.signal \},\s*\),/);
+ assert.match(offerBranch, /validateModel\(loadRequest\(\), \{ signal: abortCtrl\.signal \}\)/);
assert.match(offerBranch, /loadingDescription = loadingDescription\.replace\(switchingNote, "Switching models\."\);/);
});
diff --git a/studio/frontend/tests/read-aloud-beside-chat.test.ts b/studio/frontend/tests/read-aloud-beside-chat.test.ts
index cbb375638a0..5dbf9503245 100644
--- a/studio/frontend/tests/read-aloud-beside-chat.test.ts
+++ b/studio/frontend/tests/read-aloud-beside-chat.test.ts
@@ -86,10 +86,10 @@ test("under Off, the speech load says it unloads the chat model and offers to ke
test("the chat model's automatic loads keep the speech model loaded", () => {
const loads =
chatAdapter.match(
- /const loadResp = await loadModel\(\{[\s\S]*?\n\s*\}\)/g,
+ /const loadResp = await loadModel\(\{[\s\S]*?\}\)/g,
) ?? [];
assert.equal(loads.length, 2);
- for (const load of loads) assert.match(load, /alongside: true,/);
+ for (const load of loads) assert.match(load, /alongside: true\b/);
// Silent before: say what they unloaded to make room.
assert.equal(chatAdapter.match(/reportEvicted\(loadResp\);/g)?.length, 2);
assert.match(
diff --git a/studio/frontend/tests/switch-validate-gpu-ids.test.ts b/studio/frontend/tests/switch-validate-gpu-ids.test.ts
index b944b0d75da..3d689f51e83 100644
--- a/studio/frontend/tests/switch-validate-gpu-ids.test.ts
+++ b/studio/frontend/tests/switch-validate-gpu-ids.test.ts
@@ -6,46 +6,19 @@ import test from "node:test";
import { readSrc } from "./helpers/kit.ts";
const runtime = readSrc("features/chat/hooks/use-chat-model-runtime.ts");
-const slice = (from: string, to: string) => {
- const start = runtime.indexOf(from);
- const end = runtime.indexOf(to, start);
- assert.ok(start >= 0 && end > start, from);
- return runtime.slice(start, end);
-};
-const pick = new Function(
- "pendingLoadConfig",
- "stateBeforeUnload",
- "targetIsDiffusion",
- "reconcilePersistedGpuIds",
- "resetsPerModelSettings",
- "reconcileTensorSplit",
- `let loadSplitRatio = null;
- ${slice("const stagedGpuIds =", "let loadSpeculativeType")}
- ${slice("const validateGpuIds =", "// The reset below")}
- if (resetsPerModelSettings) {
- ${slice("loadSelectedGpuIds = stagedGpuIds;", "loadGpuLayers =")}
- }
- return { validateGpuIds, loadSelectedGpuIds };`,
-) as (...args: unknown[]) => { validateGpuIds: unknown; loadSelectedGpuIds: unknown };
-const reconcile = (ids: number[] | null) => ids;
test("a switch validates the GPUs the load will use", () => {
- const cases: [unknown, boolean][] = [
- [{ selectedGpuIds: [1] }, true],
- [{ selectedGpuIds: null }, true],
- [undefined, true],
- [{ selectedGpuIds: [1] }, false],
- [undefined, false],
- ];
- for (const [pending, resets] of cases) {
- const { validateGpuIds, loadSelectedGpuIds } = pick(
- pending,
- { selectedGpuIds: [3], selectedGpuIndexKind: null },
- false,
- reconcile,
- resets,
- () => null,
- );
- assert.deepEqual(validateGpuIds, loadSelectedGpuIds, JSON.stringify([pending, resets]));
- }
+ assert.doesNotMatch(runtime, /validateGpuIds/);
+ const reset = runtime.indexOf("loadSelectedGpuIds = stagedGpuIds;");
+ const request = runtime.indexOf(
+ "const loadRequest = (): LoadModelRequest =>",
+ );
+ const validate = runtime.indexOf("await validateModel({");
+ assert.ok(reset > 0 && reset < request && request < validate);
+ assert.match(
+ runtime.slice(request, validate),
+ /gpu_ids: loadSelectedGpuIds \?\? undefined,/,
+ );
+ assert.match(runtime, /await validateModel\(\{\s*\.\.\.loadRequest\(\),/);
+ assert.match(runtime, /await loadModel\(\{\s*\.\.\.loadRequest\(\),/);
});
diff --git a/studio/frontend/tests/thread-read-sharing.test.ts b/studio/frontend/tests/thread-read-sharing.test.ts
index ceb0a1842aa..feef8435e38 100644
--- a/studio/frontend/tests/thread-read-sharing.test.ts
+++ b/studio/frontend/tests/thread-read-sharing.test.ts
@@ -66,6 +66,7 @@ function harness() {
CHAT_HISTORY_REVISION_KEY: "unsloth_chat_history_revision",
},
"../utils/load-warning-toast": { showLoadWarning: () => {} },
+ "../lib/load-request": {},
"./generation-length.ts": {},
"./gguf-variants-request": {},
"./padded-response": { assertCompletedPaddedBody: () => {} },
diff --git a/studio/frontend/tests/tool-approval-gone.test.ts b/studio/frontend/tests/tool-approval-gone.test.ts
index f0e57237a64..f72c5001d72 100644
--- a/studio/frontend/tests/tool-approval-gone.test.ts
+++ b/studio/frontend/tests/tool-approval-gone.test.ts
@@ -56,6 +56,7 @@ function harness(response: ReturnType<typeof jsonResponse>) {
isCoalescedHistoryEvent: () => false,
},
"../utils/load-warning-toast": { showLoadWarning: () => {} },
+ "../lib/load-request": {},
"./generation-length.ts": {},
"./gguf-variants-request": {},
"./padded-response": { assertCompletedPaddedBody: () => {} },
diff --git a/tests/studio/test_chat_autoload_failure_gate.py b/tests/studio/test_chat_autoload_failure_gate.py
index b719f0c905a..b7469c7dd1f 100644
--- a/tests/studio/test_chat_autoload_failure_gate.py
+++ b/tests/studio/test_chat_autoload_failure_gate.py
@@ -48,6 +48,23 @@ def _wait_gate_source() -> str:
return gate
+# Inlined, not copied: it builds the llama-server half of the /load payload these scenarios assert on.
+LOAD_REQUEST = _source_path("studio/frontend/src/features/chat/lib/load-request.ts")
+
+
+def _load_request_source() -> str:
+ """The load-request module with its imports dropped; PREAMBLE supplies serverTuningLoadPayload."""
+ source = "\n".join(
+ line
+ for line in LOAD_REQUEST.read_text(encoding = "utf-8").splitlines()
+ if not line.startswith(
+ ("import ", " type ServerTuningValues,", " serverTuningLoadPayload,", "} from ")
+ )
+ )
+ assert "export function llamaServerLoadFields(" in source
+ return source
+
+
# Short so no scenario waits out the real 30s cap; the shipped value is asserted in
# tests/studio/test_chat_mount_cli_load_adoption.py.
PONYFILLS = """
@@ -878,7 +895,7 @@ def _build_harness(run_dir: Path):
# Any mention, not just a call; comments are stripped first.
code = re.sub(r"/\*.*?\*/", "", body, flags = re.S)
code = re.sub(r"//[^\n]*", "", code)
- preamble = PREAMBLE + PONYFILLS + _wait_gate_source()
+ preamble = PREAMBLE + PONYFILLS + _wait_gate_source() + _load_request_source()
missing = sorted(
name
for name in imported
diff --git a/tests/studio/test_model_picker_contracts.py b/tests/studio/test_model_picker_contracts.py
index 529a135ccdc..ed22bc71890 100644
--- a/tests/studio/test_model_picker_contracts.py
+++ b/tests/studio/test_model_picker_contracts.py
@@ -552,7 +552,7 @@ def test_diffusion_load_paths_disable_tensor_parallel():
compare = _read("features/chat/shared-composer.tsx")
compact_compare = " ".join(compare.split())
assert "const effectiveTensorParallel = resolvedIsDiffusion ? false :" in compact_compare
- assert compare.count("tensor_parallel: effectiveTensorParallel") == 2
+ assert compare.count("tensor_parallel: effectiveTensorParallel") == 1
runtime = " ".join(_read("features/chat/hooks/use-chat-model-runtime.ts").split())
assert "const loadTensorParallel = targetIsDiffusion ? false :" in runtime
@@ -566,7 +566,7 @@ def test_diffusion_load_paths_disable_tensor_parallel():
compact_autoload = " ".join(autoload.split())
assert "config.selectedGpuIds != null || config.tensorParallel === true" in compact_autoload
assert "const effectiveTensorParallel = isDiffusion ? false :" in compact_autoload
- assert autoload.count("tensor_parallel: effectiveTensorParallel") == 2
+ assert autoload.count("tensor_parallel: effectiveTensorParallel") == 1
def test_diffusion_load_keeps_the_standing_gpu_memory_mode():
@@ -710,8 +710,10 @@ def test_a_pinned_cached_row_loads_from_the_id_the_backend_pinned():
assert (
'(typeof selection === "string" ? null : selection.loadId) || modelId' in runtime
), "loadPath must fall back to the id, so an unpinned pick is unchanged"
- # Staged metadata, validate, the engine-switch revalidate and load all read the copy that loads.
- assert runtime.count("model_path: loadPath,") == 4
+ # Staged metadata, and the one request validate, the engine-switch revalidate and load all send,
+ # read the copy that loads.
+ assert runtime.count("model_path: loadPath,") == 2
+ assert "...loadRequest()," in runtime
assert "model_path: modelId," not in runtime
# A rollback reads the approval under the snapshot path, so store it under both keys.
assert "rememberApprovedRemoteCode(loadPath, approvedRemoteCodeFingerprint);" in runtime
@@ -2118,15 +2120,17 @@ def test_parallel_slots_setting_wired_end_to_end():
assert "pendingLoadConfig?.nParallel" in runtime
# Both backends take a width: llama-server slots, or the MLX batch width.
assert "n_parallel: loadNParallel," in runtime
- assert "n_parallel: validateNParallel," in runtime
+ # /validate is sent the load's own request, so the preflight sizes the same slots.
+ assert "...loadRequest()," in runtime
assert "loadNParallel = pendingLoadConfig?.nParallel ?? null;" in runtime
assert "n_parallel: rollbackState.loadedNParallel," in runtime
chat_api = _read("features/chat/api/chat-api.ts")
- assert "n_parallel: payload.n_parallel," in chat_api
+ assert "validateRequestBody(payload, preparedToken.token)" in chat_api
+ assert "...wireLoadRequest(payload, hfToken)," in _read("features/chat/lib/load-request.ts")
composer = _read("features/chat/shared-composer.tsx")
- assert composer.count("n_parallel: ownConfig.nParallel ?? null,") == 2
+ assert composer.count("n_parallel: ownConfig.nParallel ?? null,") == 1
adapter = _read("features/chat/api/chat-adapter.ts")
- assert adapter.count("n_parallel: config.nParallel ?? null,") == 2
+ assert adapter.count("n_parallel: config.nParallel ?? null,") == 1
assert "loadedNParallel: committedSlots," in adapter
status = _read("features/chat/lib/apply-inference-status-to-store.ts")
# Hydration seeds only the rollback baseline; adopting the echo would pin a blank default.
@@ -2361,13 +2365,20 @@ def test_batch_sizes_setting_wired_end_to_end():
api_types = _read("features/chat/types/api.ts")
assert "n_batch?: number | null;" in api_types
assert "n_ubatch?: number | null;" in api_types
+ # One rule for every load path: omitted when blank, since an explicit null reads as set and
+ # strips inherited -b / -ub.
+ load_request = " ".join(_read("features/chat/lib/load-request.ts").split())
+ assert (
+ "...(target.isGguf && settings.nBatch != null ? { n_batch: settings.nBatch } : {}),"
+ in load_request
+ )
+ assert (
+ "...(target.isGguf && settings.nUbatch != null ? { n_ubatch: settings.nUbatch } : {}),"
+ in load_request
+ )
runtime = " ".join(_read("features/chat/hooks/use-chat-model-runtime.ts").split())
assert "pendingLoadConfig?.nBatch" in runtime
- # omitted when blank: an explicit null reads as set and strips inherited -b / -ub
- assert "...(isGguf && loadNBatch != null ? { n_batch: loadNBatch } : {})," in runtime
- assert "...(isGguf && loadNUbatch != null ? { n_ubatch: loadNUbatch } : {})," in runtime
- assert "...(validateNBatch != null ? { n_batch: validateNBatch } : {})," in runtime
- assert "...(validateNUbatch != null ? { n_ubatch: validateNUbatch } : {})," in runtime
+ assert "nBatch: loadNBatch, nUbatch: loadNUbatch," in runtime
assert "n_batch: isGguf ? loadNBatch : null," not in runtime
runtime = _read("features/chat/hooks/use-chat-model-runtime.ts")
assert "loadNBatch = pendingLoadConfig?.nBatch ?? null;" in runtime
@@ -2376,19 +2387,14 @@ def test_batch_sizes_setting_wired_end_to_end():
assert "{ n_ubatch: rollbackState.loadedNUbatch }" in runtime
assert "n_batch: rollbackState.loadedNBatch," not in runtime
chat_api = " ".join(_read("features/chat/api/chat-api.ts").split())
- assert "...(payload.n_batch != null ? { n_batch: payload.n_batch } : {})," in chat_api
- assert "...(payload.n_ubatch != null ? { n_ubatch: payload.n_ubatch } : {})," in chat_api
+ assert "validateRequestBody(payload, preparedToken.token)" in chat_api
composer = " ".join(_read("features/chat/shared-composer.tsx").split())
+ assert composer.count("...llamaServerLoadFields(ownConfig, {") == 1
+ adapter = " ".join(_read("features/chat/api/chat-adapter.ts").split())
assert (
- composer.count("...(ownConfig.nBatch != null ? { n_batch: ownConfig.nBatch } : {}),") == 2
- )
- assert (
- composer.count("...(ownConfig.nUbatch != null ? { n_ubatch: ownConfig.nUbatch } : {}),")
- == 2
+ adapter.count("...llamaServerLoadFields( { ...config, llamaExtraArgs: resolvedExtraArgs },")
+ == 1
)
- adapter = " ".join(_read("features/chat/api/chat-adapter.ts").split())
- assert adapter.count("...(config.nBatch != null ? { n_batch: config.nBatch } : {}),") == 2
- assert adapter.count("...(config.nUbatch != null ? { n_ubatch: config.nUbatch } : {}),") == 2
assert "loadedNBatch: committedNBatch," in adapter
assert "loadedNUbatch: committedNUbatch," in adapter
status = " ".join(_read("features/chat/lib/apply-inference-status-to-store.ts").split())
@@ -2520,7 +2526,7 @@ def test_chat_autoload_records_every_validation_failure():
assert "throw error;" in wrapper
autoload = adapter.split("async function loadAutoLoadCandidate", 1)[1]
autoload = autoload.split("async function autoLoadSmallestModel", 1)[0]
- assert "canAutoLoadRecordingFailures(failureLabel, {" in autoload
+ assert "canAutoLoadRecordingFailures(failureLabel, request)" in autoload
assert "recordCandidateFailure(failureLabel, error)" in autoload
# The preflight cancellation must also go through the helper, or it records without halting.
assert "recordCandidateFailure(failureLabel, cancelled)" in autoload
@@ -2691,22 +2697,20 @@ def test_a_recipe_compares_the_requested_reasoning_budget():
def test_validate_sends_reasoning_controls_before_the_runtime_unloads():
- api = _read("features/chat/api/chat-api.ts")
- validate_body = api.split("export async function validateModel", 1)[1].split(
- "export async function", 1
- )[0]
+ body = _read("features/chat/lib/load-request.ts")
+ validate_body = body.split("export function validateRequestBody", 1)[1]
assert "reasoning_budget: payload.reasoning_budget ?? -1" in validate_body
assert 'reasoning_budget_message: payload.reasoning_budget_message ?? ""' in validate_body
+ # The preflight is sent the load's own request, reasoning budget included, before any unload.
runtime = _read("features/chat/hooks/use-chat-model-runtime.ts")
- validation = runtime.index("const validation = await validateModel({")
+ request = runtime.index("const loadRequest = (): LoadModelRequest =>")
+ validation = runtime.index("const validation = await validateModel({", request)
unload = runtime.index("await unloadModel(", validation)
- assert validation < unload
- validate_payload = runtime[validation:unload]
- assert "reasoning_budget:" in validate_payload
- assert "validateReasoningBudget" in validate_payload
- assert "reasoning_budget_message:" in validate_payload
- assert "validateReasoningBudgetMessage" in validate_payload
+ assert request < validation < unload
+ assert "reasoningBudget: loadReasoningBudget," in runtime[request:validation]
+ assert "reasoningBudgetMessage: loadReasoningBudgetMessage," in runtime[request:validation]
+ assert "...loadRequest()," in runtime[validation:unload]
def test_backfill_compares_server_keys_by_normalized_identity():
@@ -3573,10 +3577,11 @@ def test_the_default_is_preflighted_before_the_managed_download():
src = _read("features/chat/api/chat-adapter.ts")
fallback = src.split(" return { loaded: false, blockedByTrustRemoteCode: false };", 1)[1]
fallback = fallback.split("export function createOpenAIStreamAdapter", 1)[0]
- assert fallback.index("canAutoLoad({") < fallback.index("ensureDefaultModelDownloaded(")
+ assert fallback.index("canAutoLoad(request)") < fallback.index("ensureDefaultModelDownloaded(")
assert fallback.index("const rt = useChatRuntimeStore.getState();") < fallback.index(
- "canAutoLoad({"
+ "canAutoLoad(request)"
)
+ assert "await loadModel({ ...request, alongside: true })" in fallback
def test_cached_non_gguf_rows_get_the_chat_only_platform_gate():