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.

Keep the context length a load was given instead of resetting it to Auto (#9841)

Daniel Han870224748272
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index dd6d6281605..bd60ee74603 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -154,7 +154,7 @@ import {
} from "../stores/chat-runtime-store";
import {
resolveFitMaxSeqLength,
- resolveManualAutoCtxPin,
+ resolveExplicitCtxPin,
} from "../presets/preset-policy";
import { ensureGpuDeviceCache } from "@/hooks/use-gpu-info";
import { useExternalProvidersStore } from "../stores/external-providers-store";
@@ -3365,15 +3365,10 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
is_gguf: loadResp.is_gguf ?? candidate.kind === "gguf",
});
if (candidate.kind === "gguf") {
- // Keep an explicit Manual+Auto context pin the load just applied (so a
- // later Apply doesn't silently revert it to auto-fit sizing), mirroring
- // the interactive path's keepCustomCtx; other cases baseline on
- // ggufContextLength.
- const keepCustomCtx = resolveManualAutoCtxPin(
- effectiveGpuMemoryMode,
- effectiveGpuLayers,
- config.customContextLength ?? null,
- );
+ // The Context Length saved for this model, not fitMaxSeqLength: the wire
+ // value is Auto-resolved for a same-model reload, so pinning it would
+ // convert Auto into a number the user never set (see resolveExplicitCtxPin).
+ const keepCustomCtx = resolveExplicitCtxPin(config.customContextLength);
// Slots this auto-load committed. Diffusion ignores --parallel, so a count
// there would mint a phantom override a saved preset carries onto a GGUF.
const committedSlots =
@@ -3430,9 +3425,8 @@ async function autoLoadSmallestModel(options?: AutoLoadOptions): Promise<{
defaultChatTemplate: loadResp.chat_template ?? null,
chatTemplateOverride: effectiveChatTemplateOverride,
loadedChatTemplateOverride: effectiveChatTemplateOverride,
- // Retain the saved requested context so re-saving the config keeps the
- // override; null stays null (auto/VRAM-fit).
- customContextLength: config.customContextLength,
+ // Same value as the baseline above, so the control opens undirtied.
+ customContextLength: keepCustomCtx,
loadedIsMultimodal: isMultimodalResponse(loadResp),
mmprojFallbackReason: loadResp.mmproj_fallback_reason ?? null,
loadedIsDiffusion: loadResp.is_diffusion ?? false,
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 14bebf3e55a..d88da4bf7bb 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
@@ -89,7 +89,7 @@ import {
mergeBackendRecommendedInference,
resolveFitMaxSeqLength,
resolveLoadMaxSeqLength,
- resolveManualAutoCtxPin,
+ resolveExplicitCtxPin,
} from "../presets/preset-policy";
import { recordLastLocalModelLoad } from "../utils/last-local-model-load";
import { loadFallbackNotice } from "../utils/mmproj-fallback";
@@ -1574,6 +1574,12 @@ export function useChatModelRuntime() {
loadSplitRatio = null;
}
+ // 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, and a pin read
+ // back out of one of those is a number the user never chose.
+ const explicitCtxPin = loadCustomContextLength;
// 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 --
@@ -1764,14 +1770,10 @@ export function useChatModelRuntime() {
const reportedNativeCtx = loadResponse.is_gguf
? (loadResponse.native_context_length ?? null)
: null;
- // Keep an explicit Manual+Auto context pin (so a later Apply doesn't
- // revert it to Auto) and retain the user's requested context so
- // re-open/re-save keeps the intended override, not the backend's
- // auto-fit context; null stays null.
- const keepCustomCtx = resolveManualAutoCtxPin(
- loadGpuMemoryMode,
- loadGpuLayers,
- loadCustomContextLength,
+ // The user's own Context Length (see explicitCtxPin), so an Auto load
+ // stays Auto whatever n_ctx the send rules resolved for it.
+ const keepCustomCtx = resolveExplicitCtxPin(
+ loadResponse.is_gguf ? explicitCtxPin : null,
);
const reasoningAlwaysOn = loadResponse.reasoning_always_on ?? false;
const reasoningStyle = loadResponse.reasoning_style ?? "enable_thinking";
diff --git a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
index ce976a1a294..ae72899501b 100644
--- a/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
+++ b/studio/frontend/src/features/chat/lib/apply-inference-status-to-store.ts
@@ -8,10 +8,7 @@ import { resolveResidentInitialConfig } from "@/features/model-picker";
import { modelDisplayName } from "@/features/hub/lib/model-identity";
import { getInferenceStatus } from "../api/chat-api";
import { isSpeechOnlyStatus } from "./speech-only-status";
-import {
- mergeBackendRecommendedInference,
- resolveManualAutoCtxPin,
-} from "../presets/preset-policy";
+import { mergeBackendRecommendedInference } from "../presets/preset-policy";
import { clampReasoningEffortToLevels } from "../provider-capabilities";
import {
CHAT_REASONING_ENABLED_KEY,
@@ -33,6 +30,7 @@ import { resolveQwenThinkingParams } from "../utils/qwen-params";
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 { shouldSeedVisionSwitch } from "./resolve-vision-switch-seed";
type LocalReasoningEffort = Extract<ReasoningEffort, "low" | "medium" | "high">;
@@ -304,18 +302,29 @@ export function applyActiveModelStatusToStore(
seedLoadParams,
modelChanged: slotsModelChanged,
});
- // A Manual + Auto-layers load sent its positive context pin as max_seq_length,
- // and status only exposes the RESOLVED context; re-seed the pin from the
- // requested value (parity with the load paths' keepCustomCtx). Baselines
- // unconditionally: anything but an applicable pin is null, so a previous
- // model's pin can't survive a model change underneath and reload at the old length.
- const gpuPin = status.is_gguf
- ? resolveManualAutoCtxPin(
- status.gpu_memory_mode ?? "auto",
- status.gpu_layers ?? -1,
- status.requested_context_length ?? null,
- )
- : null;
+ // A load sends its context pin as max_seq_length and status only exposes the
+ // resolved context plus the requested n_ctx, and a positive requested n_ctx
+ // does NOT mean a human asked for it: an Auto same-model reload under a custom
+ // preset reports one too. So the pin is re-seeded here from what this tab (or
+ // the model's saved config) actually recorded, never inferred from the echo
+ // alone, and the echo is trusted only where it is unambiguous. See
+ // resolveCtxPinSeed for the full rule, including the mid-load window where
+ // status still answers for the OUTGOING model.
+ const ctxPinFields = resolveCtxPinSeed({
+ incoming: status.requested_context_length,
+ isGguf: status.is_gguf ?? true,
+ seedLoadParams,
+ modelChanged: slotsModelChanged,
+ remembered: remembered?.remembered
+ ? (remembered.config.customContextLength ?? null)
+ : null,
+ // Raw, not the normalised incomingGpuMode/incomingGpuLayers below: the rule
+ // needs "Manual with AUTO layers", and those normalise layers to null off
+ // manual, which would read as "no layers reported" rather than as Auto.
+ gpuMemoryMode: status.gpu_memory_mode ?? null,
+ gpuLayers: status.gpu_layers ?? null,
+ loadedPin: prevState.loadedCustomContextLength ?? null,
+ });
const incomingGpuMode = status.is_gguf
? (status.gpu_memory_mode ?? "auto")
: null;
@@ -340,7 +349,11 @@ export function applyActiveModelStatusToStore(
},
{ ids: incomingGpuIds, indexKind: incomingGpuIndexKind },
) ||
- prevState.loadedCustomContextLength !== gpuPin;
+ // Only a pin this status will actually move counts: a difference it declines
+ // to apply (mid-load, or an echo it cannot read intent out of) is not one.
+ (ctxPinFields.loadedCustomContextLength !== undefined &&
+ prevState.loadedCustomContextLength !==
+ ctxPinFields.loadedCustomContextLength);
const gpuMemoryEditsPending =
(prevState.loadedGpuMemoryMode !== null &&
prevState.gpuMemoryMode !== prevState.loadedGpuMemoryMode) ||
@@ -364,8 +377,7 @@ export function applyActiveModelStatusToStore(
const preserveSameModelEdits = gpuStatusChanged && !hydratingExistingModel;
const gpuStatusFields = {
...incomingGpuFields,
- customContextLength: gpuPin,
- loadedCustomContextLength: gpuPin,
+ ...ctxPinFields,
...(preserveSameModelEdits &&
gpuMemoryEditsPending && {
gpuMemoryMode: prevState.gpuMemoryMode,
diff --git a/studio/frontend/src/features/chat/lib/resolve-ctx-pin-seed.ts b/studio/frontend/src/features/chat/lib/resolve-ctx-pin-seed.ts
new file mode 100644
index 00000000000..58c9b8f18ad
--- /dev/null
+++ b/studio/frontend/src/features/chat/lib/resolve-ctx-pin-seed.ts
@@ -0,0 +1,127 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// what a fresh /api/inference/status does to the Context Length control and its baseline
+
+/**
+ * The subset of the pair this rule owns -- the editable Context Length (null =
+ * Auto) and the value the resident server was invoked with, as this tab last saw
+ * it -- to write back. Empty means leave the store alone.
+ */
+export interface CtxPinSeed {
+ customContextLength?: number | null;
+ loadedCustomContextLength?: number | null;
+}
+
+const CLEAR: CtxPinSeed = {
+ customContextLength: null,
+ loadedCustomContextLength: null,
+};
+
+/**
+ * Status reports `requested_n_ctx` (the n_ctx the running server was launched
+ * with) and nothing about whether a human chose it, and the two are not the same
+ * question: `resolveLoadMaxSeqLength` sends the resolved context on a same-model
+ * reload so the reload does not resize, so an Auto reload under a custom or
+ * modified preset reports a positive `requested_n_ctx` exactly like an explicit
+ * pin does. A positive value is therefore evidence of nothing on its own, and no
+ * backend field could fix that: the frontend sends the same number in both
+ * cases, so the backend has no more information than this does.
+ *
+ * Two exceptions, both where the echo says more than "positive". Under Manual
+ * memory with Auto layers the load sends its pin through
+ * `resolveFitMaxSeqLength`, which puts 0 on the wire for Auto without exception,
+ * so a positive echo there IS an explicit pin and is adopted. And an echo that
+ * contradicts the pin this tab recorded means another client reloaded the same
+ * model at a different context, so the baseline is dropped rather than resent.
+ *
+ * Otherwise this never invents a pin out of a positive echo. It clears one only on the
+ * unambiguous signal (0, the wire value for Auto, which only an Auto load
+ * sends), it leaves the control alone entirely while the model has not changed
+ * -- whatever this tab's own load recorded there is better evidence than the
+ * echo -- and on a model change, where nothing in the store belongs to the model
+ * that arrived, it adopts that model's SAVED Context Length only when the
+ * running server corroborates it by matching. That last step is the rule the
+ * batch sizes next door already use for their own remembered values.
+ */
+export function resolveCtxPinSeed(options: {
+ /** ``status.requested_context_length``; undefined on a backend that omits the field. */
+ incoming: number | null | undefined;
+ /** ``status.is_gguf``: only a GGUF load carries an n_ctx. */
+ isGguf: boolean;
+ /** No load of this tab's own is in flight (``!modelLoading``). */
+ seedLoadParams: boolean;
+ /** The model/variant changed underneath this tab, so nothing recorded here survives it. */
+ modelChanged: boolean;
+ /** This model's SAVED Context Length, or null when it saved none / has no record. */
+ remembered: number | null;
+ /** ``status.gpu_memory_mode`` for the resident server. */
+ gpuMemoryMode?: "auto" | "manual" | null;
+ /** ``status.gpu_layers`` as reported, NOT normalised: negative means Auto layers. */
+ gpuLayers?: number | null;
+ /** ``loadedCustomContextLength``: the n_ctx this tab last recorded for this server. */
+ loadedPin?: number | null;
+}): CtxPinSeed {
+ const {
+ incoming,
+ isGguf,
+ seedLoadParams,
+ modelChanged,
+ remembered,
+ gpuMemoryMode,
+ gpuLayers,
+ loadedPin,
+ } = options;
+ // while a load is in flight performLoad owns the load params. This is also the
+ // mid-load window where status still answers for the OUTGOING model (refreshes
+ // do run with modelLoading true), so nothing here can plant a stale pin.
+ if (!seedLoadParams) return {};
+ // a non-GGUF has no n_ctx: its max_seq_length must not be left standing as one
+ if (!isGguf) return CLEAR;
+ if (incoming === undefined) {
+ // An older backend saying nothing. Nothing recorded against the model that
+ // just left may survive it, but a steady poll must not touch the control.
+ return modelChanged ? CLEAR : {};
+ }
+ // 0 is the wire value for Auto and only an Auto load sends it, so this is the
+ // one echo that proves its own meaning.
+ if (incoming === null || !(incoming > 0)) return CLEAR;
+ // One placement mode has no ambiguity to reason around: under Manual memory
+ // with Auto layers the load sends its pin as max_seq_length through
+ // resolveFitMaxSeqLength, which answers `customContextLength > 0 ? it : 0`.
+ // Auto there is 0 on the wire, always, so a POSITIVE echo in this mode is
+ // proof of an explicit pin rather than evidence of nothing. Read before the
+ // branches below because it outranks both of them: it is better evidence than
+ // a saved config, and on a model change it describes the model that arrived.
+ if (gpuMemoryMode === "manual" && gpuLayers != null && gpuLayers < 0) {
+ return { customContextLength: incoming, loadedCustomContextLength: incoming };
+ }
+ if (!modelChanged) {
+ // Same model, ambiguous echo. What is in the store came from watching this
+ // tab's own load, which knew what the user actually asked for; an echo that
+ // an Auto reload produces just as readily is not grounds to overwrite it,
+ // in either direction.
+ //
+ // Unless it CONTRADICTS the record. Another tab or an API client can reload
+ // the same model at a different context, and then the pin here describes an
+ // invocation that is no longer running: keeping it means the next unrelated
+ // Apply resends it and silently takes back the other client's choice. The
+ // echo still cannot say whether a human chose the new value, so it is not
+ // adopted; the stale baseline is dropped instead, which leaves the control
+ // on Auto and the next Apply agreeing with the server rather than fighting
+ // it. Clearing is safe against an Auto reload of our own pinned model too:
+ // that reports the resolved context, which IS the pin, so it matches here
+ // and nothing moves.
+ return loadedPin != null && loadedPin !== incoming ? CLEAR : {};
+ }
+ // A model changed underneath this tab, so nothing in the store belongs to the
+ // one that arrived. Its saved config is the only record of intent left;
+ // require the running server to match it, or a stale pin would be re-pinned
+ // onto a server that is not running it.
+ return remembered != null && remembered > 0 && remembered === incoming
+ ? {
+ customContextLength: remembered,
+ loadedCustomContextLength: remembered,
+ }
+ : CLEAR;
+}
diff --git a/studio/frontend/src/features/chat/presets/preset-policy.ts b/studio/frontend/src/features/chat/presets/preset-policy.ts
index c94369a7727..b27591f33e2 100644
--- a/studio/frontend/src/features/chat/presets/preset-policy.ts
+++ b/studio/frontend/src/features/chat/presets/preset-policy.ts
@@ -365,16 +365,30 @@ export function resolveFitMaxSeqLength(
return customContextLength && customContextLength > 0 ? customContextLength : 0;
}
-// A Manual + Auto-layers load sends its positive context pin as max_seq_length;
-// keep it across a status reseed/Apply so the model isn't reverted to auto-fit
-// sizing. Anything else (Auto mode, pinned layers, no pin) baselines to null.
-// The caller keeps its own isGguf/targetIsGguf guard inline.
-export function resolveManualAutoCtxPin(
- gpuMemoryMode: "auto" | "manual",
- gpuLayers: number,
- customContextLength: number | null,
+/**
+ * The context pin a completed load leaves behind: the Context Length the user
+ * EXPLICITLY set for it, or null for Auto.
+ *
+ * Takes the user's setting, never the n_ctx that went on the wire. The wire
+ * value cannot answer this: `resolveLoadMaxSeqLength`'s isReloadingCurrentGguf
+ * branch sends the resolved context on a same-model reload so the reload does
+ * not resize, so under a custom or modified preset an Auto load puts a positive
+ * n_ctx on the wire too. Reading a pin back out of that turned Auto into a
+ * numeric pin at the current context on any same-model reload, after which a GPU
+ * memory change could no longer auto-resize.
+ *
+ * Takes no GPU Memory mode, deliberately. `resolveLoadMaxSeqLength` honors a pin
+ * in every mode, but the predicate this replaces kept one only under Manual +
+ * Auto layers: a survival rule narrower than the send rule, so a load on Default
+ * sent the user's pin and then dropped it on completion. That was the bug.
+ *
+ * Callers keep their own isGguf/targetIsGguf guard inline: a non-GGUF load has
+ * no n_ctx, and its max_seq_length must not be pinned as one.
+ */
+export function resolveExplicitCtxPin(
+ customContextLength: number | null | undefined,
): number | null {
- return gpuMemoryMode === "manual" && gpuLayers < 0 && (customContextLength ?? 0) > 0
+ return customContextLength && customContextLength > 0
? customContextLength
: null;
}
diff --git a/studio/frontend/src/features/chat/shared-composer.tsx b/studio/frontend/src/features/chat/shared-composer.tsx
index f8c78e8034e..6cf37b2c0b5 100644
--- a/studio/frontend/src/features/chat/shared-composer.tsx
+++ b/studio/frontend/src/features/chat/shared-composer.tsx
@@ -122,7 +122,7 @@ import {
loadModel,
validateModel,
} from "./api/chat-api";
-import { resolveFitMaxSeqLength, resolveManualAutoCtxPin } from "./presets/preset-policy";
+import { resolveFitMaxSeqLength, resolveExplicitCtxPin } from "./presets/preset-policy";
import { ensureGpuDeviceCache } from "@/hooks/use-gpu-info";
import {
parseExternalModelId,
@@ -1618,16 +1618,13 @@ export function SharedComposer({
store.setModelRequiresTrustRemoteCode(
resp.requires_trust_remote_code ?? false,
);
- // Keep an explicit Manual+Auto context pin the load just applied (so a
- // later Apply/Reset doesn't silently revert the model to auto-fit
- // sizing), mirroring the interactive path's keepCustomCtx. Non-GGUF
- // compare loads don't send the pin, so their baseline clears.
+ // This pane's own saved Context Length, not compareMaxSeqLength: the wire
+ // value is Auto-resolved for a same-model reload, so pinning it would
+ // convert Auto into a number the user never set (see resolveExplicitCtxPin).
+ // Non-GGUF compare loads send a sequence length rather than an n_ctx, so
+ // their baseline clears.
const keepCustomCtx = targetIsGguf
- ? resolveManualAutoCtxPin(
- effectiveGpuMemoryMode,
- effectiveGpuLayers,
- effectiveCustomContextLength,
- )
+ ? resolveExplicitCtxPin(effectiveCustomContextLength)
: null;
// Slots this compare load committed. Diffusion ignores --parallel, so a
// count there would mint a phantom override a preset carries onto a GGUF.
@@ -1697,12 +1694,10 @@ export function SharedComposer({
loadedVisionDisabledByUser: resp.vision_disabled_by_user ?? false,
mmprojFallbackReason: resp.mmproj_fallback_reason ?? null,
activeModelIsLocal: resp.is_local_model ?? false,
- // Record the context this pane loaded with (like the single-model path)
- // so when it becomes the active model, the UI and later reload/save use
- // its context, not the previous/default one.
- customContextLength: targetIsGguf
- ? (ownConfig.customContextLength ?? keepCustomCtx)
- : null,
+ // Same value as the baseline above, so that when this pane becomes the
+ // active model the UI and later reload/save use the context it actually
+ // loaded with, not the previous/default one.
+ customContextLength: keepCustomCtx,
ggufContextLength: resp.is_gguf ? (resp.context_length ?? null) : null,
ggufNativeContextLength: resp.is_gguf
? (resp.native_context_length ?? null)
diff --git a/studio/frontend/tests/context-pin-survives-load.test.ts b/studio/frontend/tests/context-pin-survives-load.test.ts
new file mode 100644
index 00000000000..e923d377989
--- /dev/null
+++ b/studio/frontend/tests/context-pin-survives-load.test.ts
@@ -0,0 +1,489 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// What happens to an explicit Context Length once the load that used it finishes.
+//
+// The send rule honors a pin in every GPU Memory mode, but the survival rule used to be
+// narrower: only a Manual + Auto-layers load kept its pin, so a load on Default sent the
+// user's 262,144 and then dropped it. The panel re-seeded to Auto and the next load sent
+// 0, which the backend resolves to its host-offload fallback of 8,192 (_AUTO_OFFLOAD_CTX)
+// for a model that fits no GPU subset: "it's ignoring my Context Length and always stop
+// at Auto (8,192)".
+//
+// The rule is now "the pin is the Context Length the user EXPLICITLY set, Auto pins
+// nothing". Not "the n_ctx the load was invoked with": those are different questions.
+// resolveLoadMaxSeqLength sends the resolved context on a same-model reload so the reload
+// does not resize, so with the control on Auto a custom or modified preset puts a positive
+// n_ctx on the wire, and reading a pin back out of it converted Auto into a numeric pin at
+// the current context -- after which a GPU memory change can no longer auto-resize.
+//
+// So both of these have to hold at once, and they pull against each other:
+// 1. an explicitly set context survives a completed load, in EVERY GPU Memory mode;
+// 2. Auto stays Auto across a same-model reload, under EVERY preset source.
+// The three in-app writers are checked at the source, like the llama-extra-args status test
+// next door: each sits inside one large object literal with no seam to call. The status
+// path has a seam (resolveCtxPinSeed) and is checked through it.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import path from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+
+import { registerBundlerResolver } from "./helpers/kit.ts";
+
+registerBundlerResolver();
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const read = (relative: string) =>
+ readFileSync(path.join(HERE, "..", relative), "utf8");
+
+const APPLIER = read(
+ "src/features/chat/lib/apply-inference-status-to-store.ts",
+);
+const RUNTIME = read("src/features/chat/hooks/use-chat-model-runtime.ts");
+const ADAPTER = read("src/features/chat/api/chat-adapter.ts");
+const COMPOSER = read("src/features/chat/shared-composer.tsx");
+const CONFIG_PAGE = read(
+ "src/features/model-picker/components/model-config-page.tsx",
+);
+
+const policy = await import("../src/features/chat/presets/preset-policy.ts");
+const { resolveCtxPinSeed } = await import(
+ "../src/features/chat/lib/resolve-ctx-pin-seed.ts"
+);
+const { loadedConfigSignature } = await import(
+ "../src/features/model-picker/model-config/config-signature.ts"
+);
+
+const RETIRED_PREDICATE = /resolveManualAutoCtxPin/;
+/** A writer feeding a WIRE value back in as the pin: the regression this guards. */
+const WIRE_AS_PIN =
+ /resolveExplicitCtxPin\([^)]*\b(?:loadMaxSeqLength|fitMaxSeqLength|compareMaxSeqLength|effectiveMaxSeqLength|requested_context_length)\b/;
+
+/** An empty Context Length pair: the control on Auto with a matching baseline. */
+const CLEARED = { customContextLength: null, loadedCustomContextLength: null };
+
+const MODEL = "unsloth/Some-Huge-MoE-GGUF";
+const OTHER_MODEL = "unsloth/Something-Else-GGUF";
+const VARIANT = "UD-Q4_K_XL";
+const REQUESTED = 262144;
+const PRESET_SOURCES = ["builtin-default", "custom", "modified"] as const;
+
+/** The sources every writer-level assertion runs over. */
+const WRITERS = [
+ ["applier", APPLIER],
+ ["runtime", RUNTIME],
+ ["adapter", ADAPTER],
+ ["composer", COMPOSER],
+] as const;
+
+type Mode = "auto" | "manual";
+
+/**
+ * What a completed load leaves in customContextLength, given the Context Length
+ * the user had set for it. The three in-app writers all reduce to this.
+ */
+const pinAfterLoad = (customContextLength: number | null) =>
+ policy.resolveExplicitCtxPin(customContextLength);
+
+/** The n_ctx a load would put on the wire as max_seq_length. */
+function sentNCtx(
+ customContextLength: number | null,
+ {
+ mode = "auto",
+ gpuLayers = -1,
+ residentCtx = 0,
+ modelId = MODEL,
+ currentCheckpoint = MODEL,
+ // The configuration the bug was reported in.
+ presetSource = "builtin-default",
+ }: {
+ mode?: Mode;
+ gpuLayers?: number;
+ residentCtx?: number;
+ modelId?: string;
+ currentCheckpoint?: string;
+ presetSource?: (typeof PRESET_SOURCES)[number];
+ } = {},
+): number {
+ return policy.resolveFitMaxSeqLength(
+ true,
+ mode,
+ gpuLayers,
+ customContextLength,
+ policy.resolveLoadMaxSeqLength({
+ modelId,
+ ggufVariant: VARIANT,
+ isGguf: true,
+ customContextLength,
+ ggufContextLength: residentCtx,
+ currentCheckpoint,
+ activeGgufVariant: VARIANT,
+ maxSeqLength: 4096,
+ presetSource,
+ }),
+ );
+}
+
+/** A per-model config as ModelConfigPage seeds it from the live store. */
+function configWithPin(pin: number | null) {
+ return {
+ customContextLength: pin,
+ gpuMemoryMode: "auto",
+ gpuLayers: -1,
+ nCpuMoe: 0,
+ } as never;
+}
+
+test("a completed load keeps the context it was invoked with, in every mode", () => {
+ // No GPU Memory mode in the signature at all: that is the fix.
+ for (const [mode, gpuLayers] of [
+ ["auto", -1],
+ ["auto", 20],
+ ["manual", -1],
+ ["manual", 20],
+ ] as const) {
+ const sent = sentNCtx(REQUESTED, { mode, gpuLayers });
+ assert.equal(sent, REQUESTED, `${mode}/${gpuLayers} sent the wrong n_ctx`);
+ assert.equal(
+ pinAfterLoad(REQUESTED),
+ REQUESTED,
+ `${mode}/${gpuLayers} dropped the pin`,
+ );
+ }
+});
+
+test("the next load still sends the user's number", () => {
+ // The reported failure: the SECOND load came back at 8,192, because the pin
+ // was gone by then and 0 went out instead.
+ const pin = pinAfterLoad(REQUESTED);
+ assert.equal(
+ sentNCtx(pin, { residentCtx: REQUESTED }),
+ REQUESTED,
+ "the reload reverted to Auto",
+ );
+ // And it stays put over any number of reloads.
+ assert.equal(pinAfterLoad(pin), REQUESTED);
+});
+
+test("the settings panel does not remount back to Auto", () => {
+ // customContextLength is the first field of modelConfigInstanceKey, so a pin
+ // that vanishes on completion re-keys the editor and snaps it back to Auto.
+ const pin = pinAfterLoad(REQUESTED);
+ assert.equal(
+ loadedConfigSignature(configWithPin(pin)),
+ loadedConfigSignature(configWithPin(REQUESTED)),
+ "the editor would remount and lose the pin",
+ );
+ // ...and the panel would have read the cleared config as Auto.
+ assert.notEqual(
+ loadedConfigSignature(configWithPin(null)),
+ loadedConfigSignature(configWithPin(REQUESTED)),
+ );
+ assert.notEqual(pin, null);
+ // The link this rests on: null is what the panel calls Auto.
+ assert.match(
+ CONFIG_PAGE,
+ /const contextIsAuto = config\.customContextLength == null;/,
+ );
+});
+
+test("an Auto load still clears the pin and stays Auto", () => {
+ // 0 is the wire value for Auto: the backend sizes the context itself, so there
+ // is nothing to pin and the control must keep reading Auto.
+ const sentAuto = sentNCtx(null);
+ assert.equal(sentAuto, 0);
+ const pinAfterAutoLoad = pinAfterLoad(null);
+ assert.equal(pinAfterAutoLoad, null);
+ assert.equal(sentNCtx(pinAfterAutoLoad, { residentCtx: 8192 }), 0);
+ // A pin cleared by hand (the user dragging back to Auto) reads the same way.
+ assert.equal(policy.resolveExplicitCtxPin(0), null);
+ assert.equal(policy.resolveExplicitCtxPin(null), null);
+ assert.equal(policy.resolveExplicitCtxPin(undefined), null);
+});
+
+test("a model change does not carry the old pin across", () => {
+ // Nothing the outgoing model left in the store may reach the incoming one, and
+ // the status echo cannot stand in for it: a length that happens to match the
+ // old pin is exactly what an Auto load on the new model reports too.
+ const seed = (over: Partial<Parameters<typeof resolveCtxPinSeed>[0]> = {}) =>
+ resolveCtxPinSeed({
+ incoming: REQUESTED,
+ isGguf: true,
+ seedLoadParams: true,
+ modelChanged: true,
+ remembered: null,
+ ...over,
+ });
+ // The new model came up on Auto. 0 proves its own meaning, so the pin clears.
+ assert.deepEqual(seed({ incoming: 0 }), CLEARED);
+ // The new model came up at the outgoing pin's length with nothing saved for it:
+ // still cleared, because nothing recorded that a human asked for it.
+ assert.deepEqual(seed(), CLEARED);
+ // The new model's OWN saved Context Length, corroborated by the server running
+ // it, is the only thing that can seed a pin here.
+ assert.deepEqual(seed({ remembered: REQUESTED }), {
+ customContextLength: REQUESTED,
+ loadedCustomContextLength: REQUESTED,
+ });
+ // A saved pin the running server is NOT honouring seeds nothing.
+ assert.deepEqual(seed({ remembered: 8192 }), CLEARED);
+ // A non-GGUF has no n_ctx, so a GGUF pin cannot be left standing over it.
+ assert.deepEqual(seed({ isGguf: false }), CLEARED);
+ // The next load for the new model is Auto, not the old model's length.
+ assert.equal(
+ sentNCtx(null, { modelId: OTHER_MODEL, currentCheckpoint: MODEL }),
+ 0,
+ );
+ // performLoad clears it outright on a cross-model switch, before the load.
+ assert.match(RUNTIME, /customContextLength: null,\s*\n\s*\}\);/);
+ // The applier reads the saved value through the same resolver the batch sizes
+ // use, so "remembered" is this model's record and not the store's leftovers.
+ assert.match(
+ APPLIER,
+ /remembered: remembered\?\.remembered\s*\n\s*\? \(remembered\.config\.customContextLength \?\? null\)\s*\n\s*: null,/,
+ );
+});
+
+test("a poll landing mid-load cannot plant the outgoing model's context", () => {
+ // The one window where status still answers for the model on its way out.
+ // Harmless while the pin was almost always null; now it is a real number.
+ assert.deepEqual(
+ resolveCtxPinSeed({
+ incoming: REQUESTED,
+ isGguf: true,
+ seedLoadParams: false,
+ modelChanged: true,
+ remembered: REQUESTED,
+ }),
+ {},
+ "a mid-load poll planted a pin",
+ );
+ // And it cannot clear one either: performLoad owns the pair for the whole load.
+ assert.deepEqual(
+ resolveCtxPinSeed({
+ incoming: 0,
+ isGguf: true,
+ seedLoadParams: false,
+ modelChanged: false,
+ remembered: null,
+ }),
+ {},
+ "a mid-load poll cleared the pin",
+ );
+ // An empty seed writes no keys at all, so the store keeps what it had.
+ assert.match(APPLIER, /const ctxPinFields = resolveCtxPinSeed\(\{/);
+ assert.match(APPLIER, /\.\.\.ctxPinFields,/);
+ // A baseline this status will not apply is not a change worth preserving edits over.
+ assert.match(
+ APPLIER,
+ /\(ctxPinFields\.loadedCustomContextLength !== undefined &&\s*\n\s*prevState\.loadedCustomContextLength !==\s*\n?\s*ctxPinFields\.loadedCustomContextLength\);/,
+ );
+});
+
+test("Auto stays Auto across a same-model reload, under every preset source", () => {
+ // resolveLoadMaxSeqLength's isReloadingCurrentGguf branch: outside
+ // builtin-default, a same-model reload on Auto puts the RESOLVED context on the
+ // wire so the reload does not resize. Reading a pin back out of that turned
+ // Auto into a numeric pin at the current context on any same-model reload --
+ // applying an unrelated model setting was enough -- after which a GPU memory
+ // change could no longer auto-resize the context.
+ assert.equal(policy.getPresetSource("Default"), "builtin-default");
+ assert.equal(policy.getPresetSource("My Preset"), "custom");
+ const onTheWire = Object.fromEntries(
+ PRESET_SOURCES.map((presetSource) => [
+ presetSource,
+ sentNCtx(null, { presetSource, residentCtx: REQUESTED }),
+ ]),
+ );
+ // Not hypothetical: two of the three really do send a number for Auto.
+ assert.deepEqual(onTheWire, {
+ "builtin-default": 0,
+ custom: REQUESTED,
+ modified: REQUESTED,
+ });
+ for (const presetSource of PRESET_SOURCES) {
+ // The control was on Auto, so the load leaves it on Auto whatever it sent...
+ const pin = pinAfterLoad(null);
+ assert.equal(pin, null, `${presetSource} turned Auto into a pin`);
+ // ...and the reload after it is still Auto, so the context can still resize.
+ assert.equal(
+ sentNCtx(pin, { presetSource, residentCtx: REQUESTED }),
+ onTheWire[presetSource],
+ );
+ }
+ // The status echo of those reloads says REQUESTED, and is refused as evidence.
+ assert.deepEqual(
+ resolveCtxPinSeed({
+ incoming: REQUESTED,
+ isGguf: true,
+ seedLoadParams: true,
+ modelChanged: false,
+ remembered: REQUESTED,
+ }),
+ {},
+ "the status path re-pinned an Auto reload",
+ );
+ // No writer may go back to feeding a wire value in as the pin.
+ for (const [label, source] of WRITERS) {
+ assert.doesNotMatch(source, WIRE_AS_PIN, `${label} pins a wire value`);
+ }
+});
+
+test("the clamp that stops a manual reload resizing is not a user pin", () => {
+ // performLoad substitutes the resolved context for Auto when layers are pinned
+ // on the same model, or the reload would send 0 and llama.cpp's --fit-off
+ // branch would take that as the NATIVE context. That is the app protecting the
+ // load, not the user choosing a length, so the pin is captured BEFORE it.
+ const capture = RUNTIME.indexOf("const explicitCtxPin = loadCustomContextLength;");
+ const clamp = RUNTIME.indexOf("loadCustomContextLength = loadGgufContextLength;");
+ assert.notEqual(capture, -1, "the load no longer captures the user's setting");
+ assert.notEqual(clamp, -1);
+ assert.ok(
+ capture < clamp,
+ "the clamp now runs before the pin is captured, so the app's substituted length " +
+ "would be recorded as the user's choice",
+ );
+});
+
+test("the three in-app writers pin what the user asked for, not what they sent", () => {
+ // The regression: all three took the resolved n_ctx, which is the user's number
+ // only when there is one, and the current context otherwise.
+ assert.match(
+ RUNTIME,
+ /const keepCustomCtx = resolveExplicitCtxPin\(\s*\n\s*loadResponse\.is_gguf \? explicitCtxPin : null,\s*\n\s*\);/,
+ );
+ assert.match(
+ RUNTIME,
+ /customContextLength: keepCustomCtx,\s*\n\s*loadedCustomContextLength: keepCustomCtx,/,
+ );
+ assert.match(
+ ADAPTER,
+ /const keepCustomCtx = resolveExplicitCtxPin\(config\.customContextLength\);/,
+ );
+ assert.match(ADAPTER, /customContextLength: keepCustomCtx,/);
+ assert.match(ADAPTER, /loadedCustomContextLength: keepCustomCtx,/);
+ assert.match(
+ COMPOSER,
+ /const keepCustomCtx = targetIsGguf\s*\n\s*\? resolveExplicitCtxPin\(effectiveCustomContextLength\)\s*\n\s*: null;/,
+ );
+ assert.match(COMPOSER, /customContextLength: keepCustomCtx,/);
+ assert.match(COMPOSER, /loadedCustomContextLength: keepCustomCtx,/);
+ // Each argument is that path's own per-model setting, which is also what fed
+ // its send rule, so a pinned load's -c and its pin cannot disagree.
+ assert.match(COMPOSER, /const effectiveCustomContextLength = ownConfig\.customContextLength;/);
+ assert.match(
+ ADAPTER,
+ /customContextLength: config\.customContextLength,\s*\n\s*ggufContextLength: null,/,
+ );
+});
+
+test("the Manual-only predicate is retired, not left to be picked up again", () => {
+ // It answered a different question and had no caller left once the four
+ // writers moved off it.
+ assert.equal(
+ (policy as Record<string, unknown>).resolveManualAutoCtxPin,
+ undefined,
+ );
+ // Neither is the wire-valued predicate that replaced it and read Auto as a pin.
+ assert.equal(
+ (policy as Record<string, unknown>).resolveLoadedCtxPin,
+ undefined,
+ );
+ for (const [label, source] of WRITERS) {
+ assert.doesNotMatch(
+ source,
+ RETIRED_PREDICATE,
+ `${label} still calls the retired predicate`,
+ );
+ }
+ // The SEND rule it was named after stays: Manual + Auto layers still sends 0
+ // when there is no pin, because llama.cpp's --fit owns the sizing there.
+ assert.equal(sentNCtx(null, { mode: "manual", gpuLayers: -1 }), 0);
+ assert.equal(
+ sentNCtx(REQUESTED, { mode: "manual", gpuLayers: -1 }),
+ REQUESTED,
+ );
+});
+
+test("another client reloading the same model at a new context invalidates the baseline", () => {
+ // The pin here describes an invocation that is no longer running. Keeping it
+ // means the next unrelated Apply resends it and silently takes back the other
+ // client's context, so a contradicted baseline is dropped. The echo still
+ // cannot say whether a human chose the new value, so it is not adopted either.
+ const seed = (over: Partial<Parameters<typeof resolveCtxPinSeed>[0]> = {}) =>
+ resolveCtxPinSeed({
+ incoming: REQUESTED,
+ isGguf: true,
+ seedLoadParams: true,
+ modelChanged: false,
+ remembered: null,
+ ...over,
+ });
+
+ // Contradicted: we recorded 8192, the server reports it is running 262144.
+ assert.deepEqual(seed({ loadedPin: 8192 }), CLEARED);
+ // Agreeing echoes leave the control alone, which is what keeps an explicit pin
+ // alive across every ordinary poll.
+ assert.deepEqual(seed({ loadedPin: REQUESTED }), {});
+ // Auto here holds: with no pin recorded there is no baseline to contradict, and
+ // an Auto reload under a custom preset reports a positive n_ctx exactly like
+ // this. Adopting it would be the bug this file exists to prevent.
+ assert.deepEqual(seed({ loadedPin: null }), {});
+ // Our own pinned model reloaded on Auto reports the resolved context, which IS
+ // the pin, so it matches and nothing moves.
+ assert.deepEqual(seed({ loadedPin: REQUESTED, incoming: REQUESTED }), {});
+ // Still nothing mid-load: performLoad owns the pair there.
+ assert.deepEqual(seed({ loadedPin: 8192, seedLoadParams: false }), {});
+});
+
+test("a positive echo under manual memory with auto layers is an explicit pin", () => {
+ // resolveFitMaxSeqLength is what that placement sends, and it answers
+ // `customContextLength > 0 ? it : 0`, so Auto is 0 on the wire without
+ // exception and a positive echo cannot have come from Auto.
+ assert.equal(policy.resolveFitMaxSeqLength(true, "manual", -1, null, 4096), 0);
+ assert.equal(
+ policy.resolveFitMaxSeqLength(true, "manual", -1, REQUESTED, 4096),
+ REQUESTED,
+ );
+
+ const seed = (over: Partial<Parameters<typeof resolveCtxPinSeed>[0]> = {}) =>
+ resolveCtxPinSeed({
+ incoming: REQUESTED,
+ isGguf: true,
+ seedLoadParams: true,
+ modelChanged: false,
+ remembered: null,
+ gpuMemoryMode: "manual",
+ gpuLayers: -1,
+ ...over,
+ });
+ const PINNED = {
+ customContextLength: REQUESTED,
+ loadedCustomContextLength: REQUESTED,
+ };
+
+ // A fresh tab hydrating a resident pinned server, with nothing saved for it.
+ assert.deepEqual(seed(), PINNED);
+ // Same on a model change: the echo describes the model that ARRIVED, so it
+ // beats both the store's leftovers and a saved config.
+ assert.deepEqual(seed({ modelChanged: true }), PINNED);
+ // Auto in this mode still reports 0, and 0 still clears.
+ assert.deepEqual(seed({ incoming: 0 }), CLEARED);
+ // Pinned layers is a different placement: it does not send through
+ // resolveFitMaxSeqLength, so the echo is ambiguous again and is not adopted.
+ assert.deepEqual(seed({ gpuLayers: 20 }), {});
+ // Neither is Default memory, which is where the original bug lived.
+ assert.deepEqual(seed({ gpuMemoryMode: "auto", gpuLayers: -1 }), {});
+ // The mid-load window outranks it, as it does everything else here.
+ assert.deepEqual(seed({ seedLoadParams: false }), {});
+ // The applier passes the RAW status fields: the normalised ones null out
+ // layers off manual, which would read as "not reported" rather than as Auto.
+ assert.match(APPLIER, /gpuMemoryMode: status\.gpu_memory_mode \?\? null,/);
+ assert.match(APPLIER, /gpuLayers: status\.gpu_layers \?\? null,/);
+ assert.match(
+ APPLIER,
+ /loadedPin: prevState\.loadedCustomContextLength \?\? null,/,
+ );
+});
diff --git a/tests/studio/test_chat_autoload_failure_gate.py b/tests/studio/test_chat_autoload_failure_gate.py
index 26b05c181a9..cc4244044b7 100644
--- a/tests/studio/test_chat_autoload_failure_gate.py
+++ b/tests/studio/test_chat_autoload_failure_gate.py
@@ -351,7 +351,12 @@ function resolveInitialConfig(_id: string, _variant: any) {
}
function resolveLoadMaxSeqLength(args: any) { return args.maxSeqLength ?? 0; }
function resolveFitMaxSeqLength(..._a: any[]) { return 0; }
-function resolveManualAutoCtxPin(..._a: any[]) { return null; }
+// Mirrors the real predicate rather than returning a constant: the sliced region
+// stores its result as the load's context pin, so a stub that always answered null
+// would make every autoload scenario here agree with a bug in it. It takes the
+// user's own Context Length (config.customContextLength above), never the n_ctx
+// that went on the wire, which is Auto-resolved on a same-model reload.
+function resolveExplicitCtxPin(n: any) { return n && n > 0 ? n : null; }
async function ensureGpuDeviceCache() {}
function reconcilePersistedGpuIds(ids: any) { return ids; }
function saveSpeculativeType(_x: any) {}