Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
// 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 { loadedPlacementFrom } from "./partial-offload";
// eslint-disable-next-line no-restricted-imports -- The model-picker index would put the pickers in the startup bundle.
import {
adoptCachedRepoConfig,
loadedContextFields,
normalizeMlxKvQuant,
resolveResidentInitialConfig,
savedContextPin,
} from "@/features/model-picker/model-config/per-model-config";
// eslint-disable-next-line no-restricted-imports -- Leaf module; the model-picker index pulls in chat.
import { pinnedReasoningEnabled } from "@/features/model-picker/components/model-selector/reasoning-enabled-pin";
import { modelDisplayName } from "@/features/hub/lib/model-identity";
import { getInferenceStatus } from "../api/chat-api";
import { isSpeechOnlyStatus } from "./speech-only-status";
import {
mergeBackendRecommendedInference,
replayMaxTokensCap,
} from "../presets/preset-policy";
import { clampReasoningEffortToLevels } from "../provider-capabilities";
import {
CHAT_REASONING_ENABLED_KEY,
type ReasoningEffort,
type ReasoningStyle,
loadOptionalBool,
loadedGpuMemoryFields,
normalizeSpeculativeType,
noteLoadedModelReasoningMode,
pinHoldsLiveEffort,
resolvePreserveThinkingOnLoad,
resolveToolsEnabledOnLoad,
takeEffortDisplacedByPin,
useChatRuntimeStore,
} from "../stores/chat-runtime-store";
import {
type InferenceStatusResponse,
isMultimodalResponse,
} from "../types/api";
import type { ChatModelRow } from "../types/runtime";
import { showLoadWarning } from "../utils/load-warning-toast";
import { resolveQwenThinkingParams } from "../utils/qwen-sampling-table";
import { sameGpuSelection } from "@/hooks/gpu-selection";
import { resolveBatchSizeSeed } from "./resolve-batch-size-seed";
import { resolveChatTemplateSeed } from "./resolve-chat-template-seed";
import { resolveCtxPinSeed } from "./resolve-ctx-pin-seed";
import { engineLaunchFieldsFrom } from "./engine-launch-fields";
import { mlxOffloadStateFrom } from "./mlx-runtime-state";
import { resolveLlamaExtraArgsSeed } from "./resolve-llama-extra-args-seed";
import { shouldSeedVisionSwitch } from "./resolve-vision-switch-seed";
type LocalReasoningEffort = Extract<ReasoningEffort, "low" | "medium" | "high">;
function sameArray<T>(a: T[] | null, b: T[] | null): boolean {
return JSON.stringify(a) === JSON.stringify(b);
}
// Re-exported from the store, which owns the vocabulary.
export { normalizeSpeculativeType } from "../stores/chat-runtime-store";
export function clampLocalReasoningEffort(
value: ReasoningEffort,
): LocalReasoningEffort {
if (value === "low" || value === "medium" || value === "high") {
return value;
}
return "low";
}
/** Shared so every load path keeps hybrid high|max|Off effort controls. */
export function reasoningCapsFromLoad(resp: {
reasoning_style?: ReasoningStyle | null;
reasoning_effort_levels?: string[] | null;
}): {
reasoningStyle: ReasoningStyle;
reasoningEffortLevels: readonly ReasoningEffort[];
supportsReasoningOff: boolean;
} {
const reasoningStyle: ReasoningStyle =
resp.reasoning_style ?? "enable_thinking";
const reasoningEffortLevels: readonly ReasoningEffort[] =
resp.reasoning_effort_levels && resp.reasoning_effort_levels.length > 0
? (resp.reasoning_effort_levels as ReasoningEffort[])
: (["low", "medium", "high"] as const);
// Only pure gpt-oss-style reasoning_effort is always-on.
return {
reasoningStyle,
reasoningEffortLevels,
supportsReasoningOff: reasoningStyle !== "reasoning_effort",
};
}
export function resolveInferenceCheckpointId(
status: InferenceStatusResponse,
): string | null {
if (!status.active_model) return null;
return status.model_identifier ?? status.active_model;
}
function ensureActiveModelInStoreList(
status: InferenceStatusResponse,
checkpointId: string,
): void {
const store = useChatRuntimeStore.getState();
const caps = {
isMlx: status.is_mlx ?? false,
isAudio: status.is_audio ?? false,
audioType: status.audio_type ?? null,
hasAudioInput: status.has_audio_input ?? false,
hasVideoInput: status.has_video_input ?? false,
speaks: status.speaks ?? false,
};
const existing = store.models.find((model) => model.id === checkpointId);
if (existing) {
// Backend capability outranks catalog; adoption has no later sync call.
if (Object.entries(caps).some(([k, v]) => existing[k as keyof typeof caps] !== v)) {
store.setModels(
store.models.map((m) => (m.id === checkpointId ? { ...m, ...caps } : m)),
);
}
return;
}
const summary: ChatModelRow = {
id: checkpointId,
name: modelDisplayName(status.active_model ?? checkpointId),
isVision: status.is_vision ?? false,
isLora: false,
isGguf: status.is_gguf ?? false,
...caps,
};
store.setModels([...store.models, summary]);
}
export type ApplyInferenceStatusOptions = {
previousCheckpoint?: string;
/** Variant before setCheckpoint synced it, so a variant-only switch reseeds. */
previousGgufVariant?: string | null;
seedLoadParams?: boolean;
adoptingExistingServerModel?: boolean;
};
/** The resident engine launch settings, in the store's params shape. */
function residentEngineParams(status: InferenceStatusResponse) {
return {
engine: status.engine ?? "auto",
enginePrecision: status.engine_precision ?? "auto",
engineParallelism: status.engine_parallelism ?? "tensor",
engineKvCacheDtype: status.engine_kv_cache_dtype ?? "auto",
engineSeed: status.engine_seed ?? null,
engineGpuMemoryUtilization: status.engine_gpu_memory_utilization ?? null,
// As requested, so a model started with --no-load-in-4bit reloads in 16-bit too. vLLM / SGLang
// record false because they take engine_precision instead, so they leave the choice alone.
...((status.engine ?? "auto") === "auto"
? { loadIn4bit: status.load_in_4bit !== false }
: {}),
};
}
/** Mirror refresh() hydration so adopted CLI models get reasoning/tools flags. */
export function applyActiveModelStatusToStore(
status: InferenceStatusResponse,
options: ApplyInferenceStatusOptions = {},
): void {
const checkpointId = resolveInferenceCheckpointId(status);
if (!checkpointId) return;
// Publish residency here, or a load looks unloaded for up to 10s.
useChatRuntimeStore.setState({
residentCheckpoint: checkpointId,
loadedEngine: status.engine ?? "auto",
loadedEnginePrecision: status.engine_precision ?? "auto",
loadedEngineParallelism: status.engine_parallelism ?? "tensor",
loadedEngineLaunch: engineLaunchFieldsFrom(status),
});
adoptCachedRepoConfig(checkpointId, status.gguf_variant ?? null);
const store = useChatRuntimeStore.getState();
const residentEngine = residentEngineParams(status);
if (
(Object.keys(residentEngine) as (keyof typeof residentEngine)[]).some(
(key) => (store.params[key] ?? null) !== residentEngine[key],
)
) {
store.setParams({ ...store.params, ...residentEngine });
}
const previousCheckpoint =
options.previousCheckpoint ?? store.params.checkpoint;
if (status.inference) {
store.setParams(
mergeBackendRecommendedInference({
current: { ...store.params, ...residentEngine },
response: status,
modelId: checkpointId,
presetSource: store.activePresetSource,
loadedContextLength: loadedContextFields(status).loadedContextLength,
}),
// Remembered settings outrank the recommendation, capped at the loaded context.
{
fromModelDefaults: true,
maxTokensCap: replayMaxTokensCap(status.context_length),
migrateOwnedGlobalQwenDefaults:
options.adoptingExistingServerModel === true,
},
);
}
const previousGgufVariant =
options.previousGgufVariant !== undefined
? options.previousGgufVariant
: store.activeGgufVariant;
const hydratingExistingModel =
previousCheckpoint !== checkpointId ||
previousGgufVariant !== (status.gguf_variant ?? null);
if (hydratingExistingModel) {
showLoadWarning(status.memory_warning);
}
const supportsReasoning = status.supports_reasoning ?? false;
const reasoningAlwaysOn = status.reasoning_always_on ?? false;
const reasoningStyle = status.reasoning_style ?? "enable_thinking";
const reasoningEffortLevels =
status.reasoning_effort_levels && status.reasoning_effort_levels.length > 0
? (status.reasoning_effort_levels as ReasoningEffort[])
: (["low", "medium", "high"] as const);
const supportsPreserveThinking = status.supports_preserve_thinking ?? false;
const preserveThinkingOnLoad = resolvePreserveThinkingOnLoad(status);
const supportsTools = status.supports_tools ?? false;
const storedReasoningEnabled = loadOptionalBool(CHAT_REASONING_ENABLED_KEY);
// Page-start adoption keeps the restored chat / installation value; the pin seeds loads only.
const pinnedThinking = options.adoptingExistingServerModel
? null
: pinnedReasoningEnabled(checkpointId);
const currentSpecType = normalizeSpeculativeType(status.speculative_type);
const incomingMlxKvQuant = normalizeMlxKvQuant(status.mlx_kv_quant_requested);
const incomingMlxInt8Prefill = status.mlx_int8_prefill_requested === true;
const incomingMlxAnePrefill = status.mlx_ane_prefill_requested === true;
const incomingMlxFastVerify = status.mlx_fast_verify_requested === true;
const incomingMlxOffload = mlxOffloadStateFrom(status);
const prevState = useChatRuntimeStore.getState();
// A pin is one model's; clamp the chat's own level once the model is actually resident.
const effortToClamp =
(pinHoldsLiveEffort() ? takeEffortDisplacedByPin() : null) ??
prevState.reasoningEffort;
const clampedReasoningEffort =
reasoningStyle === "enable_thinking_effort" ||
reasoningStyle === "reasoning_effort"
? clampReasoningEffortToLevels(effortToClamp, reasoningEffortLevels)
: clampLocalReasoningEffort(effortToClamp);
const nextDefaultChatTemplate =
status.chat_template === undefined
? prevState.defaultChatTemplate
: status.chat_template;
// During a load performLoad owns the params; a stale poll must not clobber them.
const seedLoadParams = options.seedLoadParams ?? !prevState.modelLoading;
const slotsModelChanged = hydratingExistingModel;
// Read the override only on a fresh store or model change, via the resident resolver.
const slotsUnseeded =
prevState.loadedNParallel === null && prevState.nParallel === null;
const batchesUnseeded =
prevState.loadedNBatch === null &&
prevState.nBatch === null &&
prevState.loadedNUbatch === null &&
prevState.nUbatch === null;
const remembered =
(status.is_gguf
? slotsUnseeded || batchesUnseeded || slotsModelChanged
: hydratingExistingModel)
? resolveResidentInitialConfig(checkpointId, status.gguf_variant ?? null)
: null;
const rememberedNParallel = remembered?.remembered
? (remembered.config.nParallel ?? null)
: null;
const rememberedNBatch =
status.is_gguf && remembered?.remembered
? (remembered.config.nBatch ?? null)
: null;
const rememberedNUbatch =
status.is_gguf && remembered?.remembered
? (remembered.config.nUbatch ?? null)
: null;
const nBatchSeed = resolveBatchSizeSeed({
incoming: status.requested_n_batch,
isGguf: status.is_gguf ?? true,
previous: { value: prevState.nBatch, loaded: prevState.loadedNBatch },
seedLoadParams,
modelChanged: slotsModelChanged,
});
const nUbatchSeed = resolveBatchSizeSeed({
incoming: status.requested_n_ubatch,
isGguf: status.is_gguf ?? true,
previous: { value: prevState.nUbatch, loaded: prevState.loadedNUbatch },
seedLoadParams,
modelChanged: slotsModelChanged,
});
const loadModeSeed = resolveBatchSizeSeed<string>({
incoming: status.requested_load_mode,
isGguf: status.is_gguf ?? true,
previous: { value: prevState.loadMode, loaded: prevState.loadedLoadMode },
seedLoadParams,
modelChanged: slotsModelChanged,
});
const specDraftCacheSeed = resolveBatchSizeSeed<string>({
incoming: status.requested_spec_draft_cache_type,
isGguf: status.is_gguf ?? true,
previous: {
value: prevState.specDraftCacheDtype,
loaded: prevState.loadedSpecDraftCacheDtype,
},
seedLoadParams,
modelChanged: slotsModelChanged,
});
const ctxCheckpointsSeed = resolveBatchSizeSeed({
incoming: status.requested_ctx_checkpoints,
isGguf: status.is_gguf ?? true,
previous: {
value: prevState.ctxCheckpoints,
loaded: prevState.loadedCtxCheckpoints,
},
seedLoadParams,
modelChanged: slotsModelChanged,
});
const cacheRamSeed = resolveBatchSizeSeed({
incoming: status.requested_cache_ram,
isGguf: status.is_gguf ?? true,
previous: { value: prevState.cacheRam, loaded: prevState.loadedCacheRam },
seedLoadParams,
modelChanged: slotsModelChanged,
});
// A positive requested n_ctx does not mean a user pin; see resolveCtxPinSeed.
const ctxPinFields = resolveCtxPinSeed({
incoming: status.requested_context_length,
isGguf:
(status.is_gguf ?? true) ||
(status.is_mlx ?? false) ||
(status.is_npu ?? false),
isMlx: (status.is_mlx ?? false) || (status.is_npu ?? false),
seedLoadParams,
modelChanged: slotsModelChanged,
// Both fields: older records still carry the MLX pin in maxSeqLength.
remembered: remembered?.remembered ? savedContextPin(remembered.config) : null,
// Raw values: normalisation would turn Manual with AUTO layers into null.
gpuMemoryMode: status.gpu_memory_mode ?? null,
gpuLayers: status.gpu_layers ?? null,
loadedPin: prevState.loadedCustomContextLength ?? null,
});
const reasoningBudgetApplicable =
status.is_gguf === true && status.is_diffusion !== true;
const incomingReasoningBudget = reasoningBudgetApplicable
? (status.reasoning_budget ?? -1)
: -1;
const incomingReasoningBudgetMessage = reasoningBudgetApplicable
? (status.reasoning_budget_message ?? "")
: "";
const reasoningBudgetStatusChanged =
prevState.loadedReasoningBudget !== incomingReasoningBudget ||
prevState.loadedReasoningBudgetMessage !== incomingReasoningBudgetMessage;
const reasoningBudgetEditPending =
prevState.loadedReasoningBudget !== null &&
prevState.reasoningBudget !== prevState.loadedReasoningBudget;
const reasoningBudgetMessageEditPending =
prevState.loadedReasoningBudgetMessage !== null &&
prevState.reasoningBudgetMessage !==
prevState.loadedReasoningBudgetMessage;
const reasoningBudgetStatusFields = {
loadedReasoningBudget: incomingReasoningBudget,
loadedReasoningBudgetMessage: incomingReasoningBudgetMessage,
...(!reasoningBudgetEditPending || hydratingExistingModel
? { reasoningBudget: incomingReasoningBudget }
: {}),
...(!reasoningBudgetMessageEditPending || hydratingExistingModel
? { reasoningBudgetMessage: incomingReasoningBudgetMessage }
: {}),
};
const incomingGpuMode = status.is_gguf
? (status.gpu_memory_mode ?? "auto")
: null;
const incomingGpuLayers =
incomingGpuMode === "manual" ? (status.gpu_layers ?? null) : null;
const incomingNCpuMoe =
incomingGpuMode === "manual" ? (status.n_cpu_moe ?? null) : null;
const incomingSplit =
incomingGpuMode === "manual" ? (status.tensor_split ?? null) : null;
const incomingGpuFields = loadedGpuMemoryFields(status);
const incomingGpuIds = incomingGpuFields.loadedGpuIds;
const incomingGpuIndexKind = incomingGpuFields.loadedGpuIndexKind;
const placementOrContextChanged =
prevState.loadedGpuMemoryMode !== incomingGpuMode ||
prevState.loadedGpuLayers !== incomingGpuLayers ||
prevState.loadedNCpuMoe !== incomingNCpuMoe ||
!sameArray(prevState.loadedSplitRatio, incomingSplit) ||
!sameGpuSelection(
{
ids: prevState.loadedGpuIds,
indexKind: prevState.loadedGpuIndexKind,
},
{ ids: incomingGpuIds, indexKind: incomingGpuIndexKind },
) ||
(ctxPinFields.loadedCustomContextLength !== undefined &&
prevState.loadedCustomContextLength !==
ctxPinFields.loadedCustomContextLength);
const gpuMemoryEditsPending =
(prevState.loadedGpuMemoryMode !== null &&
prevState.gpuMemoryMode !== prevState.loadedGpuMemoryMode) ||
(prevState.loadedGpuMemoryMode === "manual" &&
(prevState.gpuLayers !== prevState.loadedGpuLayers ||
prevState.nCpuMoe !== prevState.loadedNCpuMoe ||
!sameArray(prevState.splitRatio, prevState.loadedSplitRatio))) ||
prevState.customContextLength !== prevState.loadedCustomContextLength;
const gpuIdsEditPending = !sameGpuSelection(
{
ids: prevState.selectedGpuIds,
indexKind: prevState.selectedGpuIndexKind,
},
{
ids: prevState.loadedGpuIds,
indexKind: prevState.loadedGpuIndexKind,
},
);
// Preserve editable groups only when this tab has an unapplied change.
const preserveSameModelEdits = placementOrContextChanged && !hydratingExistingModel;
const placementAndContextFields = {
...incomingGpuFields,
...ctxPinFields,
...(preserveSameModelEdits &&
gpuMemoryEditsPending && {
gpuMemoryMode: prevState.gpuMemoryMode,
gpuLayers: prevState.gpuLayers,
nCpuMoe: prevState.nCpuMoe,
splitRatio: prevState.splitRatio,
customContextLength: prevState.customContextLength,
}),
...(preserveSameModelEdits &&
gpuIdsEditPending && {
selectedGpuIds: prevState.selectedGpuIds,
selectedGpuIndexKind: prevState.selectedGpuIndexKind,
}),
};
useChatRuntimeStore.setState({
supportsReasoning,
reasoningAlwaysOn,
reasoningStyle,
supportsReasoningOff: reasoningStyle !== "reasoning_effort",
reasoningEffortLevels,
reasoningEffort: clampedReasoningEffort,
supportsPreserveThinking,
...(hydratingExistingModel && {
preserveThinking: preserveThinkingOnLoad,
}),
supportsTools,
...resolveToolsEnabledOnLoad(supportsTools),
reasoningEnabled: supportsReasoning
? reasoningStyle === "reasoning_effort"
? true
: hydratingExistingModel && pinnedThinking !== null
? pinnedThinking
: useChatRuntimeStore.getState().reasoningEnabled
: true,
...loadedContextFields(status),
...(status.is_gguf
? {}
: { activeNativePathToken: null, activeNativePathExpiresAtMs: null }),
modelRequiresTrustRemoteCode: status.requires_trust_remote_code ?? false,
defaultChatTemplate: nextDefaultChatTemplate,
loadedIsMultimodal: isMultimodalResponse(status),
loadedIsDiffusion: status.is_diffusion ?? false,
activeModelIsLocal: status.is_local_model ?? false,
specFallbackReason: status.spec_fallback_reason ?? null,
mmprojFallbackReason: status.mmproj_fallback_reason ?? null,
loadedPlacement: loadedPlacementFrom(status),
specDrafterKind: status.spec_drafter_kind ?? null,
// Controls follow the server while clean; loaded baselines always describe
// the settled resident, including same-model reloads from another client.
...(seedLoadParams &&
(status.speculative_type !== undefined ||
prevState.loadedSpeculativeType === null ||
hydratingExistingModel) && {
loadedSpeculativeType: currentSpecType,
...((prevState.loadedSpeculativeType === null ||
hydratingExistingModel ||
prevState.speculativeType === prevState.loadedSpeculativeType) && {
speculativeType: currentSpecType,
}),
}),
...(seedLoadParams &&
status.spec_draft_n_max !== undefined && {
loadedSpecDraftNMax: status.spec_draft_n_max ?? null,
...((hydratingExistingModel ||
prevState.specDraftNMax === prevState.loadedSpecDraftNMax) && {
specDraftNMax: status.spec_draft_n_max ?? null,
}),
}),
...(seedLoadParams &&
status.spec_draft_model !== undefined && {
loadedSpecDraftModel: status.spec_draft_model ?? null,
...((hydratingExistingModel ||
prevState.specDraftModel === prevState.loadedSpecDraftModel) && {
specDraftModel: status.spec_draft_model ?? null,
}),
}),
...(seedLoadParams &&
status.cache_type_kv !== undefined && {
loadedKvCacheDtype: status.cache_type_kv,
...((prevState.loadedKvCacheDtype === null ||
hydratingExistingModel ||
prevState.kvCacheDtype === prevState.loadedKvCacheDtype) && {
kvCacheDtype: status.cache_type_kv,
}),
}),
...(seedLoadParams &&
status.tensor_parallel !== undefined && {
loadedTensorParallel: status.tensor_parallel,
...((prevState.loadedTensorParallel === null ||
hydratingExistingModel ||
prevState.tensorParallel === prevState.loadedTensorParallel) && {
tensorParallel: status.tensor_parallel,
}),
}),
// A load knob like tensorParallel above. Without a reseed a tab that never performed the
// load shows Vision ON over a projector-off server and the next Reload puts it back.
// Seeded from disable_vision, the request the load ran with, not vision_disabled_by_user,
// which cannot round-trip a text-only GGUF. See shouldSeedVisionSwitch.
...(seedLoadParams &&
status.disable_vision !== undefined &&
shouldSeedVisionSwitch({
incoming: status.disable_vision,
previous: prevState,
hydratingExistingModel,
}) && {
disableVision: status.disable_vision,
}),
// Unguarded: the rollback baseline must track the running server.
...(seedLoadParams &&
status.disable_vision !== undefined && {
loadedDisableVision: status.disable_vision,
}),
...(seedLoadParams &&
status.vision_disabled_by_user !== undefined && {
loadedVisionDisabledByUser: status.vision_disabled_by_user,
}),
// Like kvCacheDtype: baselines and verdict follow a same-model reload, each control only while clean.
...(seedLoadParams &&
status.mlx_kv_quant_requested !== undefined &&
(status.is_mlx === true
? {
loadedMlxKvQuantRequested: incomingMlxKvQuant,
mlxKvQuantReason: status.mlx_kv_quant_reason ?? null,
chatTemplateOverrideReason:
status.chat_template_override_reason ?? null,
mlxKvQuantNote: status.mlx_kv_quant_note ?? null,
loadedMlxInt8PrefillRequested: incomingMlxInt8Prefill,
loadedMlxAnePrefillRequested: incomingMlxAnePrefill,
loadedMlxFastVerifyRequested: incomingMlxFastVerify,
...incomingMlxOffload,
...((hydratingExistingModel ||
(prevState.mlxPleOffload ?? null) ===
(prevState.loadedMlxPleOffloadRequested ?? null)) && {
mlxPleOffload: incomingMlxOffload.loadedMlxPleOffloadRequested,
}),
...((hydratingExistingModel ||
(prevState.mlxExpertOffload ?? null) ===
(prevState.loadedMlxExpertOffloadRequested ?? null)) && {
mlxExpertOffload: incomingMlxOffload.loadedMlxExpertOffloadRequested,
}),
...((hydratingExistingModel ||
(prevState.mlxKvQuant ?? null) ===
(prevState.loadedMlxKvQuantRequested ?? null)) && {
mlxKvQuant: incomingMlxKvQuant,
}),
...((hydratingExistingModel ||
prevState.mlxInt8Prefill ===
prevState.loadedMlxInt8PrefillRequested) && {
mlxInt8Prefill: incomingMlxInt8Prefill,
}),
...((hydratingExistingModel ||
prevState.mlxAnePrefill ===
prevState.loadedMlxAnePrefillRequested) && {
mlxAnePrefill: incomingMlxAnePrefill,
}),
...((hydratingExistingModel ||
prevState.mlxFastVerify ===
prevState.loadedMlxFastVerifyRequested) && {
mlxFastVerify: incomingMlxFastVerify,
}),
}
: {
loadedMlxKvQuantRequested: null,
mlxKvQuantReason: null,
chatTemplateOverrideReason: null,
mlxKvQuantNote: null,
loadedMlxInt8PrefillRequested: false,
loadedMlxAnePrefillRequested: false,
loadedMlxFastVerifyRequested: false,
...incomingMlxOffload,
})),
// Baseline only, never the control: the echo is the RESOLVED count and would pin a blank
...(seedLoadParams &&
status.requested_parallel_slots != null && {
loadedNParallel: status.requested_parallel_slots,
}),
// A slotless load must not keep the previous baseline, since rollback re-sends it.
...(seedLoadParams &&
status.requested_parallel_slots === null && {
loadedNParallel: null,
}),
// Per-model: a change underneath this tab blanks the control like performLoad's cross-model
// reset, or the old count follows onto the new model. The baseline still has the rollback.
...(seedLoadParams && slotsModelChanged && { nParallel: null }),
...(seedLoadParams &&
(prevState.loadedReasoningBudget === null ||
hydratingExistingModel ||
reasoningBudgetStatusChanged) &&
reasoningBudgetStatusFields),
// Rollback needs the request, not the effective environment-resolved value.
// Refresh on every settled echo: a same-model reload can change only the request.
...(seedLoadParams && {
...(!reasoningBudgetApplicable ||
status.requested_reasoning_budget !== undefined
? {
loadedReasoningBudgetRequested: reasoningBudgetApplicable
? (status.requested_reasoning_budget ?? -1)
: -1,
}
: {}),
...(!reasoningBudgetApplicable ||
status.requested_reasoning_budget_message !== undefined
? {
loadedReasoningBudgetMessageRequested: reasoningBudgetApplicable
? (status.requested_reasoning_budget_message ?? "")
: "",
}
: {}),
}),
// AFTER that clear, or the next Apply would save a blank over a remembered override.
...(seedLoadParams &&
(slotsUnseeded || slotsModelChanged) &&
rememberedNParallel != null &&
rememberedNParallel === status.requested_parallel_slots && {
nParallel: rememberedNParallel,
}),
// Adopt the running server's extra args every settle, so rollbacks restore what ran.
...resolveLlamaExtraArgsSeed({
incoming: status.requested_llama_extra_args,
isGguf: status.is_gguf ?? true,
hydratingExistingModel,
seedLoadParams,
}),
...("loaded" in nBatchSeed && { loadedNBatch: nBatchSeed.loaded ?? null }),
...("value" in nBatchSeed && { nBatch: nBatchSeed.value ?? null }),
...("loaded" in nUbatchSeed && {
loadedNUbatch: nUbatchSeed.loaded ?? null,
}),
...("value" in nUbatchSeed && { nUbatch: nUbatchSeed.value ?? null }),
...("loaded" in loadModeSeed && {
loadedLoadMode: loadModeSeed.loaded ?? null,
}),
...("value" in loadModeSeed && { loadMode: loadModeSeed.value ?? null }),
...("loaded" in specDraftCacheSeed && {
loadedSpecDraftCacheDtype: specDraftCacheSeed.loaded ?? null,
}),
...("value" in specDraftCacheSeed && {
specDraftCacheDtype: specDraftCacheSeed.value ?? null,
}),
...("loaded" in ctxCheckpointsSeed && {
loadedCtxCheckpoints: ctxCheckpointsSeed.loaded ?? null,
}),
...("value" in ctxCheckpointsSeed && {
ctxCheckpoints: ctxCheckpointsSeed.value ?? null,
}),
...("loaded" in cacheRamSeed && {
loadedCacheRam: cacheRamSeed.loaded ?? null,
}),
...("value" in cacheRamSeed && { cacheRam: cacheRamSeed.value ?? null }),
// The model-change clear lives inside resolveBatchSizeSeed; nulling here drops adopted sizes.
...(seedLoadParams &&
(batchesUnseeded || slotsModelChanged) &&
rememberedNBatch != null &&
rememberedNBatch === status.requested_n_batch && {
nBatch: rememberedNBatch,
}),
...(seedLoadParams &&
(batchesUnseeded || slotsModelChanged) &&
rememberedNUbatch != null &&
rememberedNUbatch === status.requested_n_ubatch && {
nUbatch: rememberedNUbatch,
}),
...(seedLoadParams &&
(prevState.loadedGpuMemoryMode === null ||
hydratingExistingModel ||
placementOrContextChanged) &&
placementAndContextFields),
// Follow status like the GPU group, or Apply saves model A's template under B.
...resolveChatTemplateSeed({
incoming: status.chat_template_override,
previous: {
chatTemplateOverride: prevState.chatTemplateOverride,
loadedChatTemplateOverride: prevState.loadedChatTemplateOverride,
},
hydratingExistingModel,
seedLoadParams,
}),
});
ensureActiveModelInStoreList(status, checkpointId);
if (
supportsReasoning &&
hydratingExistingModel &&
storedReasoningEnabled === null &&
pinnedThinking === null
) {
// Anchored size regex; mirrors use-chat-model-runtime.ts and the inline regex in llama_cpp.py.
let reasoningDefault = true;
const mid = checkpointId.toLowerCase();
if (mid.includes("qwen3.5") || mid.includes("qwen3.6")) {
// Scan segments right to left; the trailing boundary prevents matching "8bit".
const sizeRe = /(?:^|[-_.])(\d+\.?\d*)\s*([bm])(?:$|[-_.])/;
const sizeMatch = mid
.replace(/\\/g, "/")
.split("/")
.reduceRight<RegExpMatchArray | null>(
(found, seg) => found ?? seg.match(sizeRe),
null,
);
if (sizeMatch) {
const size = Number.parseFloat(sizeMatch[1]);
const sizeB = sizeMatch[2] === "m" ? size / 1000 : size;
if (sizeB <= 9) reasoningDefault = false;
}
}
useChatRuntimeStore.setState({ reasoningEnabled: reasoningDefault });
}
noteLoadedModelReasoningMode(
checkpointId,
reasoningAlwaysOn || useChatRuntimeStore.getState().reasoningEnabled,
);
// Layer the active Qwen mode over the family defaults so a refresh cannot undo performLoad.
if (status.inference && supportsReasoning) {
const current = useChatRuntimeStore.getState();
const qwenParams = resolveQwenThinkingParams(
checkpointId,
reasoningAlwaysOn || current.reasoningEnabled,
);
if (qwenParams !== null && current.activePresetSource === "builtin-default") {
current.setParams(
{ ...current.params, ...qwenParams },
{
fromModelDefaults: true,
maxTokensCap: replayMaxTokensCap(status.context_length),
migrateOwnedGlobalQwenDefaults:
options.adoptingExistingServerModel === true,
},
);
}
}
}
export async function tryAdoptServerActiveModel(options?: {
allowWhileModelLoading?: boolean;
status?: InferenceStatusResponse;
}): Promise<boolean> {
const store = useChatRuntimeStore.getState();
if (store.params.checkpoint) {
return true;
}
if (store.modelLoading && !options?.allowWhileModelLoading) {
return false;
}
let status: InferenceStatusResponse;
if (options?.status) {
status = options.status;
} else {
try {
status = await getInferenceStatus();
} catch {
return false;
}
}
// Not chat-adoptable; the sweep picks a real chat model, which evicts it.
if (
!status.active_model ||
(status.loading?.length ?? 0) > 0 ||
isSpeechOnlyStatus(status)
) {
return false;
}
const checkpointId = resolveInferenceCheckpointId(status);
if (!checkpointId) {
return false;
}
const latest = useChatRuntimeStore.getState();
const previousCheckpoint = latest.params.checkpoint;
if (
previousCheckpoint ||
(latest.modelLoading && !options?.allowWhileModelLoading)
) {
return !!previousCheckpoint;
}
const previousGgufVariant = latest.activeGgufVariant;
store.setCheckpoint(checkpointId, status.gguf_variant);
applyActiveModelStatusToStore(status, {
previousCheckpoint,
previousGgufVariant,
seedLoadParams: options?.allowWhileModelLoading,
adoptingExistingServerModel: true,
});
return true;
}