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.

Fix stale Qwen sampling defaults after Studio upgrades (#9643)

Lee Jackson96886fab96e9
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.py
index cb0fe5a9061..e71373ad33e 100644
--- a/studio/backend/routes/chat_history.py
+++ b/studio/backend/routes/chat_history.py
@@ -74,6 +74,7 @@ from storage.studio_db import (
upsert_chat_legacy_imports,
upsert_chat_message,
upsert_chat_settings_merge,
+ upsert_chat_settings_merge_if_current,
write_chat_thread_settings,
upsert_chat_thread,
)
@@ -558,6 +559,38 @@ class ChatSettingsResponse(BaseModel):
settings: dict[str, Any]
+class ConditionalChatSettingsPayload(BaseModel):
+ model_config = ConfigDict(extra = "forbid")
+
+ expected: ChatSettingsPayload
+ expectedAbsent: list[str] = Field(default_factory = list)
+ expectedAbsentPaths: list[list[str]] = Field(default_factory = list)
+ patch: ChatSettingsPayload
+
+ @field_validator("expectedAbsent")
+ @classmethod
+ def _known_absent_fields(cls, value: list[str]) -> list[str]:
+ unknown = set(value) - set(ChatSettingsPayload.model_fields)
+ if unknown:
+ unknown_names = ", ".join(sorted(unknown))
+ raise ValueError(f"Unknown chat settings field(s): {unknown_names}")
+ return value
+
+ @field_validator("expectedAbsentPaths")
+ @classmethod
+ def _known_absent_paths(cls, value: list[list[str]]) -> list[list[str]]:
+ for path in value:
+ if len(path) < 2 or any(not segment for segment in path):
+ raise ValueError("Expected-absent paths require at least two non-empty segments")
+ if path[0] not in ChatSettingsPayload.model_fields:
+ raise ValueError(f"Unknown chat settings field: {path[0]}")
+ return value
+
+
+class ConditionalChatSettingsResponse(ChatSettingsResponse):
+ applied: bool
+
+
class ChatMessagesBatchRequest(BaseModel):
threadIds: list[str]
@@ -1574,6 +1607,35 @@ def get_settings(current_subject: str = Depends(get_current_subject)):
return ChatSettingsResponse(settings = list_chat_settings())
[email protected]("/settings/compare-and-set", response_model = ConditionalChatSettingsResponse)
+def compare_and_set_settings(
+ payload: dict[str, Any], current_subject: str = Depends(get_current_subject)
+):
+ # A raw dict, as put_settings takes: automatic validation of a typed body
+ # renders the offending input back, and Starlette dumps with allow_nan =
+ # False, so a rejected NaN would 500 a request the validator refused.
+ try:
+ parsed = ConditionalChatSettingsPayload.model_validate(payload)
+ except ValidationError as exc:
+ raise HTTPException(status_code = 400, detail = safe_validation_errors(exc.errors())) from exc
+ try:
+ settings, applied = upsert_chat_settings_merge_if_current(
+ parsed.expected.model_dump(exclude_unset = True),
+ parsed.patch.model_dump(exclude_unset = True),
+ parsed.expectedAbsent,
+ parsed.expectedAbsentPaths,
+ )
+ return ConditionalChatSettingsResponse(settings = settings, applied = applied)
+ except CorruptSettingsError as exc:
+ raise log_and_http_error(
+ exc,
+ 409,
+ safe_curated_detail(exc),
+ event = "chat_history.compare_and_set_settings_conflict",
+ log = logger,
+ ) from exc
+
+
@router.put("/settings", response_model = ChatSettingsResponse)
def put_settings(payload: dict[str, Any], current_subject: str = Depends(get_current_subject)):
try:
diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.py
index 057f4de9f66..4e4a27308b3 100644
--- a/studio/backend/storage/studio_db.py
+++ b/studio/backend/storage/studio_db.py
@@ -4697,6 +4697,96 @@ def upsert_chat_settings_merge(updates: dict[str, Any]) -> dict[str, Any]:
conn.close()
+def _chat_settings_match_expected(current: Any, expected: Any) -> bool:
+ """Whether every expected leaf still has the value the caller read."""
+ if isinstance(expected, dict):
+ if not isinstance(current, dict):
+ return False
+ return all(
+ key in current and _chat_settings_match_expected(current[key], value)
+ for key, value in expected.items()
+ )
+ return current == expected
+
+
+def _chat_settings_path_exists(current: Any, path: Iterable[str]) -> bool:
+ """Whether every segment exists, without assigning meaning to its value."""
+ node = current
+ for segment in path:
+ if not isinstance(node, dict) or segment not in node:
+ return False
+ node = node[segment]
+ return True
+
+
+def upsert_chat_settings_merge_if_current(
+ expected: dict[str, Any],
+ updates: dict[str, Any],
+ expected_absent: Iterable[str] = (),
+ expected_absent_paths: Iterable[Iterable[str]] = (),
+) -> tuple[dict[str, Any], bool]:
+ """Atomically merge ``updates`` only if ``expected`` still matches.
+
+ Expected is a recursive subset so legacy keys omitted by the current client
+ do not prevent a guarded migration. Any field the client did read is fenced
+ against a newer tab write in the same BEGIN IMMEDIATE transaction.
+ """
+ # Contended timeout, not the default: this fires during hydration alongside
+ # the ordinary settings writer, and takes a write lock before knowing if it
+ # will write. Where WAL declined both share one writer, and the 5s default
+ # surfaces as a bare "database is locked" the route cannot map.
+ conn = get_connection(_CONTENDED_BUSY_TIMEOUT_SECONDS)
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ current, corrupt = _load_chat_settings_for_merge(conn)
+ matches_expected = _chat_settings_match_expected(current, expected)
+ has_new_expected_field = any(key in current for key in expected_absent)
+ has_new_expected_path = any(
+ _chat_settings_path_exists(current, path) for path in expected_absent_paths
+ )
+ if has_new_expected_field or has_new_expected_path or not matches_expected:
+ conn.commit()
+ return current, False
+ unsafe_partial_keys = [
+ key
+ for key, value in updates.items()
+ if key in corrupt and isinstance(value, dict) and key not in _ATOMIC_SETTING_KEYS
+ ]
+ if unsafe_partial_keys:
+ conn.commit()
+ keys = ", ".join(sorted(unsafe_partial_keys))
+ raise CorruptSettingsError(
+ f"Cannot apply partial settings patch to corrupt key(s): {keys}"
+ )
+ if not updates:
+ # Same short-circuit as the unconditional merge: without it an empty
+ # patch rewrites updated_at on every key, which anything watching
+ # those timestamps reads as a settings change.
+ conn.commit()
+ return current, True
+ merged = _deep_merge_settings(current, updates)
+ now = datetime.now(timezone.utc).isoformat()
+ conn.executemany(
+ """
+ INSERT INTO chat_settings (key, value_json, updated_at)
+ VALUES (?, ?, ?)
+ ON CONFLICT(key) DO UPDATE SET
+ value_json = excluded.value_json,
+ updated_at = excluded.updated_at
+ """,
+ [(key, json.dumps(value), now) for key, value in merged.items()],
+ )
+ conn.commit()
+ return merged, True
+ except CorruptSettingsError:
+ raise
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ conn.close()
+
+
# --- Legacy Dexie import ledger (recovery rationale in _ensure_schema's schema comment) ---
diff --git a/studio/backend/tests/test_chat_history_routes.py b/studio/backend/tests/test_chat_history_routes.py
index 9a2dbf479a1..af8fdb74e25 100644
--- a/studio/backend/tests/test_chat_history_routes.py
+++ b/studio/backend/tests/test_chat_history_routes.py
@@ -408,6 +408,40 @@ def test_chat_settings_payload_rejects_junk_per_model_params():
)
+def test_conditional_chat_settings_payload_validates_both_sides():
+ payload = chat_history.ConditionalChatSettingsPayload.model_validate(
+ {
+ "expected": {"inferenceParams": {"presencePenalty": 0.0}},
+ "expectedAbsent": ["reasoningEnabled"],
+ "expectedAbsentPaths": [["inferenceParams", "topK"]],
+ "patch": {"inferenceParams": {"presencePenalty": 1.5}},
+ }
+ )
+
+ assert payload.expected.inferenceParams.presencePenalty == 0.0
+ assert payload.expectedAbsent == ["reasoningEnabled"]
+ assert payload.expectedAbsentPaths == [["inferenceParams", "topK"]]
+ assert payload.patch.inferenceParams.presencePenalty == 1.5
+
+ with pytest.raises(ValidationError):
+ chat_history.ConditionalChatSettingsPayload.model_validate(
+ {
+ "expected": {},
+ "expectedAbsent": ["unknownSetting"],
+ "patch": {},
+ }
+ )
+
+ with pytest.raises(ValidationError):
+ chat_history.ConditionalChatSettingsPayload.model_validate(
+ {
+ "expected": {},
+ "expectedAbsentPaths": [["unknownSetting", "topK"]],
+ "patch": {},
+ }
+ )
+
+
def test_chat_settings_payload_accepts_preset_load_config():
payload = chat_history.ChatSettingsPayload.model_validate(
{
@@ -1341,3 +1375,25 @@ def test_the_two_conflicts_are_distinguishable_on_the_wire(monkeypatch, error, k
assert exc_info.value.status_code == 409
assert _conflict_kind(exc_info) == kind
+
+
+def test_compare_and_set_rejects_a_non_finite_number_renderably(monkeypatch):
+ # json.loads accepts a bare NaN, so it reaches validation; echoing it back
+ # would then hit Starlette's allow_nan = False and turn a refused request
+ # into a 500 during rendering.
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ app = FastAPI()
+ app.include_router(chat_history.router, prefix = "/api/chat")
+ app.dependency_overrides[chat_history.get_current_subject] = lambda: "admin"
+ client = TestClient(app)
+
+ response = client.post(
+ "/api/chat/settings/compare-and-set",
+ content = '{"expected": {"inferenceParams": {"temperature": NaN}}, "patch": {}}',
+ headers = {"Content-Type": "application/json"},
+ )
+
+ assert response.status_code == 400
+ assert "NaN" not in response.text
diff --git a/studio/backend/tests/test_chat_history_storage.py b/studio/backend/tests/test_chat_history_storage.py
index 0f7f5bdc7e7..bbf919af0e2 100644
--- a/studio/backend/tests/test_chat_history_storage.py
+++ b/studio/backend/tests/test_chat_history_storage.py
@@ -488,6 +488,120 @@ def test_settings_merge_preserves_nested_keys(tmp_path, monkeypatch):
assert params == {"temperature": 0.9, "topP": 0.8}
+def test_settings_compare_and_set_rejects_a_newer_nested_edit(tmp_path, monkeypatch):
+ _reset_studio_db(tmp_path, monkeypatch)
+ original = {"inferenceParams": {"temperature": 0.6, "presencePenalty": 0.0}}
+ studio_db.upsert_chat_settings_merge(original)
+ studio_db.upsert_chat_settings_merge({"inferenceParams": {"presencePenalty": 0.4}})
+
+ settings, applied = studio_db.upsert_chat_settings_merge_if_current(
+ original,
+ {"inferenceParams": {"presencePenalty": 1.5}},
+ )
+
+ assert applied is False
+ assert settings["inferenceParams"]["presencePenalty"] == 0.4
+ assert studio_db.list_chat_settings() == settings
+
+
+def test_settings_compare_and_set_atomically_applies_a_matching_patch(tmp_path, monkeypatch):
+ _reset_studio_db(tmp_path, monkeypatch)
+ original = {"inferenceParams": {"temperature": 0.6, "presencePenalty": 0.0}}
+ studio_db.upsert_chat_settings_merge(original)
+
+ settings, applied = studio_db.upsert_chat_settings_merge_if_current(
+ original,
+ {"inferenceParams": {"presencePenalty": 1.5}},
+ )
+
+ assert applied is True
+ assert settings["inferenceParams"] == {"temperature": 0.6, "presencePenalty": 1.5}
+
+
+def test_settings_compare_and_set_fences_an_expected_absent_field(tmp_path, monkeypatch):
+ _reset_studio_db(tmp_path, monkeypatch)
+ original = {"inferenceParams": {"presencePenalty": 0.0}}
+ studio_db.upsert_chat_settings_merge(original)
+ studio_db.upsert_chat_settings_merge({"reasoningEnabled": False})
+
+ settings, applied = studio_db.upsert_chat_settings_merge_if_current(
+ original,
+ {"inferenceParams": {"presencePenalty": 1.5}},
+ ["reasoningEnabled"],
+ )
+
+ assert applied is False
+ assert settings["reasoningEnabled"] is False
+ assert settings["inferenceParams"]["presencePenalty"] == 0.0
+
+
+def test_settings_compare_and_set_fences_an_expected_absent_nested_path(tmp_path, monkeypatch):
+ _reset_studio_db(tmp_path, monkeypatch)
+ original = {"inferenceParams": {"presencePenalty": 0.0}}
+ studio_db.upsert_chat_settings_merge(original)
+ studio_db.upsert_chat_settings_merge({"inferenceParams": {"topK": 40}})
+
+ settings, applied = studio_db.upsert_chat_settings_merge_if_current(
+ original,
+ {"inferenceParams": {"presencePenalty": 1.5}},
+ expected_absent_paths = [["inferenceParams", "topK"]],
+ )
+
+ assert applied is False
+ assert settings["inferenceParams"]["topK"] == 40
+ assert settings["inferenceParams"]["presencePenalty"] == 0.0
+
+
+def test_settings_compare_and_set_leaves_timestamps_alone_for_an_empty_patch(tmp_path, monkeypatch):
+ """An empty patch is not a settings change. Without the same short-circuit the
+ unconditional merge has, it would rewrite updated_at on every key, which reads
+ as a fresh edit to anything watching those timestamps."""
+ _reset_studio_db(tmp_path, monkeypatch)
+ studio_db.upsert_chat_settings_merge(
+ {"inferenceParams": {"temperature": 0.6}, "autoTitle": True}
+ )
+ conn = studio_db.get_connection()
+ before = {
+ row["key"]: row["updated_at"]
+ for row in conn.execute("SELECT key, updated_at FROM chat_settings")
+ }
+ conn.close()
+
+ settings, applied = studio_db.upsert_chat_settings_merge_if_current({}, {})
+
+ conn = studio_db.get_connection()
+ after = {
+ row["key"]: row["updated_at"]
+ for row in conn.execute("SELECT key, updated_at FROM chat_settings")
+ }
+ conn.close()
+ assert applied is True
+ assert after == before
+ assert settings["inferenceParams"] == {"temperature": 0.6}
+
+
+def test_settings_compare_and_set_fences_a_model_row_added_after_the_read(tmp_path, monkeypatch):
+ """Normalizing a differently cased model key writes a whole new exact-key row.
+ The subset compare only checks the spelling that was read, so the exact key
+ needs its own absence fence or a newer tab's row is overwritten wholesale."""
+ _reset_studio_db(tmp_path, monkeypatch)
+ lower = "unsloth/qwen3.8-27b-gguf"
+ exact = "unsloth/Qwen3.8-27B-GGUF"
+ legacy = {"temperature": 0.6, "minP": 0.01, "presencePenalty": 0.0}
+ studio_db.upsert_chat_settings_merge({"inferenceParamsByModel": {lower: legacy}})
+ newer = {"temperature": 0.31, "presencePenalty": 0.4}
+ studio_db.upsert_chat_settings_merge({"inferenceParamsByModel": {exact: newer}})
+
+ settings, applied = studio_db.upsert_chat_settings_merge_if_current(
+ {"inferenceParamsByModel": {lower: legacy}},
+ {"inferenceParamsByModel": {exact: {**legacy, "minP": 0.0, "presencePenalty": 1.5}}},
+ expected_absent_paths = [["inferenceParamsByModel", exact]],
+ )
+
+ assert applied is False
+ assert settings["inferenceParamsByModel"][exact] == newer
+
+
def test_settings_merge_keeps_each_model_s_remembered_params(tmp_path, monkeypatch):
"""Per-model memory patches one model at a time, so the merge has to keep the
others. Without this, tuning a second model would wipe the first one's settings
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index 42613a66b60..f7263ac6a23 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -161,6 +161,7 @@ import {
resolveToolsEnabledOnLoad,
saveSpeculativeType,
awaitThreadScopedPairing,
+ awaitPendingQwenDefaultsMigration,
flushPendingChatSettings,
useChatRuntimeStore,
} from "../stores/chat-runtime-store";
@@ -4073,6 +4074,10 @@ export function createOpenAIStreamAdapter(
// the first message after a startup edit. No wait at all unless something
// is actually queued or in flight.
await flushPendingChatSettings();
+ // And the migration a model pick may have just scheduled: an external
+ // selection gets no load or status callback, so this is the only join
+ // between it and the run that would otherwise send the replayed row.
+ await awaitPendingQwenDefaultsMigration();
// Every run reaches here: the composer, Reload, Continue, and send from the edit
// composer. Waiting for the open chat's own settings in this one place is what
// keeps the message-level controls from starting a run on the installation
diff --git a/studio/frontend/src/features/chat/api/chat-settings-api.ts b/studio/frontend/src/features/chat/api/chat-settings-api.ts
index dfad30e4d07..72cf8eb8842 100644
--- a/studio/frontend/src/features/chat/api/chat-settings-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-settings-api.ts
@@ -83,6 +83,12 @@ interface ChatSettingsResponse {
settings: PersistedChatSettings;
}
+interface ConditionalChatSettingsResponse extends ChatSettingsResponse {
+ applied: boolean;
+}
+
+export type ChatSettingsPath = [keyof PersistedChatSettings, ...string[]];
+
function parseErrorText(status: number, body: unknown): string {
if (
body &&
@@ -155,3 +161,29 @@ export async function saveChatSettingsPatch(
const data = await parseJsonOrThrow<ChatSettingsResponse>(response);
return data.settings;
}
+
+export async function saveChatSettingsPatchIfCurrent(
+ expected: PersistedChatSettings,
+ patch: PersistedChatSettings,
+ expectedAbsent: Array<keyof PersistedChatSettings> = [],
+ expectedAbsentPaths: ChatSettingsPath[] = [],
+): Promise<{ settings: PersistedChatSettings; applied: boolean }> {
+ const response = await authFetch("/api/chat/settings/compare-and-set", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ expected,
+ expectedAbsent,
+ expectedAbsentPaths,
+ patch,
+ }),
+ });
+ // A backend without this route answers 404 (--api-only) or 405 (the browser
+ // build's GET-only SPA catch-all). The desktop app adopts any backend above a
+ // version floor, so that pairing is supported, not a bug. Report "not
+ // applied" so the caller leaves the server alone.
+ if (response.status === 404 || response.status === 405) {
+ return { settings: expected, applied: false };
+ }
+ return parseJsonOrThrow<ConditionalChatSettingsResponse>(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 a7895f8b999..850ce3923cc 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
@@ -60,6 +60,7 @@ import {
GPU_LAYERS_AUTO,
isLocalModelPath,
loadedGpuMemoryFields,
+ noteLoadedModelReasoningMode,
persistGpuMemoryModeOnLoad,
readPersistedGpuMemoryMode,
readPersistedSpeculativeType,
@@ -100,7 +101,7 @@ import {
} from "../presets/preset-policy";
import { recordLastLocalModelLoad } from "../utils/last-local-model-load";
import { loadFallbackNotice } from "../utils/mmproj-fallback";
-import { resolveQwenThinkingParams } from "../utils/qwen-params";
+import { resolveQwenThinkingParams } from "../utils/qwen-sampling-table";
import { refreshContextUsage } from "../utils/refresh-context-usage";
import { ensureGpuDeviceCache } from "@/hooks/use-gpu-info";
import {
@@ -486,6 +487,10 @@ async function syncInferenceStatusToStore(options?: {
applyActiveModelStatusToStore(statusRes, {
previousCheckpoint: selectedCheckpoint,
previousGgufVariant,
+ // With no prior selection this is Studio discovering the server's
+ // resident model, so its global-only snapshot belongs to this
+ // checkpoint and is safe to migrate.
+ adoptingExistingServerModel: selectedCheckpoint === "",
});
// setModels(listRes...) above used catalog data, which omits audio
// capability. Re-apply live status so attach gates survive a refresh.
@@ -1996,6 +2001,9 @@ export function useChatModelRuntime() {
? nativePathExpiresAtMs
: null,
});
+ // fromLoad: this browser performed the load, so the mode it chose
+ // outranks a persisted toggle describing the previous model.
+ noteLoadedModelReasoningMode(modelId, nextReasoningEnabled, true);
// Unlock attach menus for capabilities the catalog entry lacked.
syncModelCapabilities(modelId, loadResponse);
// Qwen3-family: apply thinking-mode-specific params after load.
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 27f324cfad4..a167e7ad3eb 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
@@ -24,6 +24,7 @@ import {
loadOptionalBool,
loadedGpuMemoryFields,
normalizeSpeculativeType,
+ noteLoadedModelReasoningMode,
resolvePreserveThinkingOnLoad,
resolveToolsEnabledOnLoad,
useChatRuntimeStore,
@@ -33,7 +34,7 @@ import {
isMultimodalResponse,
} from "../types/api";
import type { ChatModelRow } from "../types/runtime";
-import { resolveQwenThinkingParams } from "../utils/qwen-params";
+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";
@@ -142,6 +143,9 @@ export type ApplyInferenceStatusOptions = {
* status -- without it a variant-only switch underneath the tab reads as
* steady state and the hydration reseed keeps the old quant's baselines. */
previousGgufVariant?: string | null;
+ /** This status belongs to the model already resident when Studio started,
+ * so the persisted global sampling snapshot belongs to this checkpoint. */
+ adoptingExistingServerModel?: boolean;
};
/** Mirror refresh() hydration so adopted CLI models get reasoning/tools flags. */
@@ -177,6 +181,8 @@ export function applyActiveModelStatusToStore(
{
fromModelDefaults: true,
maxTokensCap: replayMaxTokensCap(status.context_length),
+ migrateOwnedGlobalQwenDefaults:
+ options.adoptingExistingServerModel === true,
},
);
}
@@ -684,6 +690,11 @@ export function applyActiveModelStatusToStore(
useChatRuntimeStore.setState({ reasoningEnabled: reasoningDefault });
}
+ noteLoadedModelReasoningMode(
+ checkpointId,
+ reasoningAlwaysOn || useChatRuntimeStore.getState().reasoningEnabled,
+ );
+
// Every status merge carries the base family recommendation, including the
// refresh immediately after performLoad. Layer the active Qwen mode over it
// so that refresh cannot undo performLoad's thinking table. This also covers
@@ -701,6 +712,8 @@ export function applyActiveModelStatusToStore(
{
fromModelDefaults: true,
maxTokensCap: replayMaxTokensCap(status.context_length),
+ migrateOwnedGlobalQwenDefaults:
+ options.adoptingExistingServerModel === true,
},
);
}
@@ -746,6 +759,7 @@ export async function tryAdoptServerActiveModel(): Promise<boolean> {
applyActiveModelStatusToStore(status, {
previousCheckpoint,
previousGgufVariant,
+ adoptingExistingServerModel: true,
});
return true;
}
diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
index f838f4a4d7c..aab7e2375a4 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -16,6 +16,7 @@ import {
import { toast } from "@/lib/toast";
import { DRAFT_N_MAX_SPEC_TYPES } from "@/lib/speculative-modes";
import { create } from "zustand";
+import { getChatSettings } from "../api/chat-settings-api";
import {
GPU_LAYERS_AUTO,
recoverDroppedDiffusionSplit,
@@ -26,11 +27,13 @@ import {
isExternalModelId,
parseExternalModelId,
} from "../external-providers";
+import { isOllamaManifestRef } from "../utils/qwen-sampling-table";
import {
type ChatPresetSource,
type Preset,
getPresetSource,
} from "../presets/preset-policy";
+import { normalizeModelIdentity } from "../../hub/lib/model-identity";
import { normalizePresetLoadConfig } from "../presets/preset-load-config";
import {
CHAT_PROJECT_ATTACHMENT_TARGET_KEY,
@@ -57,7 +60,9 @@ import {
} from "../types/runtime";
import {
loadChatSettingsWithLegacyImport,
+ sanitizeChatSettings,
savePersistedChatSettingsPatch,
+ savePersistedChatSettingsPatchIfCurrent,
} from "../utils/chat-settings-storage";
import {
loadShadowOwnsMirroredSetting,
@@ -67,6 +72,11 @@ import {
normalizeStoredRagAutoInject,
} from "../utils/mirrored-chat-settings";
import { retryablePatchAfterFailure } from "../utils/settings-retry";
+import {
+ isPresenceBumpQwen,
+ migrateLegacyQwenDefaults,
+ type QwenDefaultsMigration,
+} from "../utils/qwen-defaults-migration";
import {
DEFAULT_AUTO_COMPACT_ENABLED,
DEFAULT_COMPACTION_HEADROOM_RATIO,
@@ -334,6 +344,38 @@ function loadLastExternalCheckpoint(): string | null {
}
}
+/**
+ * Two checkpoints naming the same model.
+ *
+ * normalizeModelIdentity, not toLowerCase: it folds case for repository ids and
+ * the case-insensitive path forms while preserving it for POSIX paths, where
+ * /home/u/Models/qwen3.8 and /home/u/models/qwen3.8 are two different files.
+ */
+function isOpaqueModelRef(modelId: string): boolean {
+ return isExternalModelId(modelId) || isOllamaManifestRef(modelId);
+}
+
+function sameCheckpointIdentity(
+ left: string | null | undefined,
+ right: string | null | undefined,
+): boolean {
+ if (!(left && right)) {
+ return false;
+ }
+ // Opaque ids compare exactly: a provider qualifies one and an encoded POSIX
+ // path sits inside the other, and normalizeModelIdentity would fold both.
+ if (isOpaqueModelRef(left) || isOpaqueModelRef(right)) {
+ return left === right;
+ }
+ return normalizeModelIdentity(left) === normalizeModelIdentity(right);
+}
+
+// A checkpoint that arrived without any adoption signal: restored from
+// localStorage at startup, or picked by the user while the settings GET was
+// still in flight. Chat settings are installation-wide, so neither may claim a
+// global snapshot another browser wrote for a different model.
+let unownedCheckpointBeforeHydration: string | null = null;
+
function saveLastExternalCheckpoint(value: string | null): void {
if (typeof window === "undefined") return;
try {
@@ -484,6 +526,14 @@ async function flushSettingsPatch(keepalive = false): Promise<void> {
// settings write still outstanding" on their own.
let unsettledFlushes = 0;
+function settingsWritesAreDrained(): boolean {
+ return (
+ pendingTimer === null &&
+ Object.keys(pendingPatch).length === 0 &&
+ unsettledFlushes === 0
+ );
+}
+
function enqueueSettingsFlush(): Promise<void> {
unsettledFlushes += 1;
inflightFlush = inflightFlush
@@ -578,9 +628,15 @@ function flushSettingsOnPageHidden(terminal: boolean): void {
// tab is going away, so send it rather than let the next session hydrate over it.
drainPreHydrationPatch();
if (Object.keys(pendingPatch).length === 0) return;
+ // Counted like any other flush: a keepalive PUT still on the wire would land
+ // after the compare-and-set and restore the legacy row.
+ unsettledFlushes += 1;
inflightFlush = inflightFlush
.catch(() => undefined)
- .then(() => flushSettingsPatch(true));
+ .then(() => flushSettingsPatch(true))
+ .finally(() => {
+ unsettledFlushes -= 1;
+ });
}
if (typeof window !== "undefined") {
@@ -2833,6 +2889,9 @@ type ChatRuntimeStore = {
fromModelDefaults?: boolean;
/** The context the model just loaded with. */
maxTokensCap?: number;
+ /** Defaults came from the server-resident model at startup, so a legacy
+ * global snapshot can be attributed to it. */
+ migrateOwnedGlobalQwenDefaults?: boolean;
},
) => void;
setCustomPresets: (presets: Preset[]) => void;
@@ -3121,6 +3180,52 @@ const scalarSettingMutationVersions = Object.fromEntries(
SCALAR_SETTING_KEYS.map((key) => [key, 0]),
) as Record<ScalarSettingKey, number>;
+let loadedModelReasoningMode: {
+ checkpoint: string;
+ enabled: boolean;
+ reasoningMutationVersion: number;
+ fromLoad: boolean;
+} | null = null;
+
+/**
+ * Record the mode a load/status response put the active model in. Persisted
+ * settings can describe the previous model, so they cannot pick the migration
+ * table after a family default changed on load.
+ *
+ * `fromLoad` marks a model this browser actually loaded. A status refresh only
+ * echoes the reasoningEnabled already in the store, which before hydration is
+ * this browser's local default, so it must not outrank the persisted toggle.
+ */
+export function noteLoadedModelReasoningMode(
+ checkpoint: string,
+ enabled: boolean,
+ fromLoad = false,
+): void {
+ const state = useChatRuntimeStore.getState();
+ const previous = loadedModelReasoningMode;
+ loadedModelReasoningMode = {
+ checkpoint,
+ // A thread pin is not a shared model default. When one is active, retain
+ // the installation value captured before that thread was applied.
+ enabled:
+ threadScopedOverride("reasoningEnabled") !== undefined
+ ? installationReasoningEnabled(state)
+ : enabled,
+ reasoningMutationVersion:
+ scalarSettingMutationVersions.reasoningEnabled,
+ // Sticky per checkpoint: performLoad marks the load, then awaits refresh(),
+ // whose status merge calls this again with the default false. Downgrading
+ // there would drop the load's claim before hydration could read it.
+ fromLoad:
+ fromLoad ||
+ (previous !== null &&
+ sameCheckpointIdentity(previous.checkpoint, checkpoint) &&
+ previous.reasoningMutationVersion ===
+ scalarSettingMutationVersions.reasoningEnabled &&
+ previous.fromLoad),
+ };
+}
+
function hasKeys(value: object): boolean {
return Object.keys(value).length > 0;
}
@@ -3422,9 +3527,21 @@ function loadedContextFor(checkpoint: string): number | null {
return loadedContext?.checkpoint === checkpoint ? loadedContext.cap : null;
}
-/** A model that took over from another while the request was in flight. Its
- * defaults lose to its own entry but outrank the global set, which belongs to
- * whichever model was used last. Not narrowed to the keys that moved. */
+function capParamsToLoadedContext(
+ state: ChatRuntimeStore,
+ params: InferenceParams,
+): InferenceParams {
+ const residentContextCap = isExternalModelId(params.checkpoint)
+ ? null
+ : state.loadedContextLength;
+ const cap = loadedContextFor(params.checkpoint) ?? residentContextCap;
+ return cap !== null && params.maxTokens > cap
+ ? { ...params, maxTokens: cap }
+ : params;
+}
+
+/** A model selected while the request was in flight. Its defaults lose to its
+ * own entry but outrank the global set, which belongs to the last model used. */
let modelLoadedBeforeHydration: string | null = null;
/** A model stepped off before hydration. Nothing can be filed for it yet, but the
@@ -3434,17 +3551,25 @@ let modelLeftBeforeHydration: string | null = null;
function noteModelDefaultsBeforeHydration(
checkpoint: string,
- replacedAnotherModel: boolean,
+ ownsPersistedGlobal: boolean,
): void {
- if (replacedAnotherModel) {
+ // A model the user selected while settings were in flight does not own the
+ // previous session's global snapshot, even as this tab's first checkpoint.
+ // Server-resident startup adoption is the one exception.
+ if (!ownsPersistedGlobal) {
modelLoadedBeforeHydration = checkpoint;
return;
}
// The model already resident at startup is the one the saved global set
// describes, so its defaults must not stand in front of it.
- if (modelLoadedBeforeHydration !== checkpoint) {
+ if (!sameCheckpointIdentity(modelLoadedBeforeHydration, checkpoint)) {
modelLoadedBeforeHydration = null;
}
+ // setCheckpoint marks any pre-hydration switch as an interactive pick, and
+ // this is the adoption signal that says otherwise.
+ if (sameCheckpointIdentity(unownedCheckpointBeforeHydration, checkpoint)) {
+ unownedCheckpointBeforeHydration = null;
+ }
}
/**
@@ -3487,7 +3612,10 @@ function getHydratedSettingsState(
): Partial<ChatRuntimeStore> {
const nextState: Partial<ChatRuntimeStore> = {};
const checkpoint = state.params.checkpoint;
- const loadedBeforeHydration = modelLoadedBeforeHydration === checkpoint;
+ const loadedBeforeHydration = sameCheckpointIdentity(
+ modelLoadedBeforeHydration,
+ checkpoint,
+ );
modelLoadedBeforeHydration = null;
// The toggle as it will read once this response lands, under the same fence
// the scalar loop below applies.
@@ -3571,7 +3699,12 @@ function getHydratedSettingsState(
const left = modelLeftBeforeHydration;
modelLeftBeforeHydration = null;
const byModel = nextState.paramsByModel ?? state.paramsByModel;
- if (remembersPerModel && left && left !== checkpoint && !byModel[left]) {
+ if (
+ remembersPerModel &&
+ left &&
+ !sameCheckpointIdentity(left, checkpoint) &&
+ !byModel[left]
+ ) {
const inherited: PersistedInferenceParams = {};
for (const key of REMEMBERED_INFERENCE_PARAM_KEYS) {
const value = settings.inferenceParams?.[key];
@@ -3622,6 +3755,17 @@ function getHydratedSettingsState(
) {
continue;
}
+ // Same reason, the other direction: a load that landed while this response
+ // was in flight already chose the mode for the running model and advances
+ // no mutation version, so the stored toggle describes the previous one. Let
+ // the load win, as its sampling table does. Only an actual load, though: a
+ // status refresh echoes local state and must not outrank the installation.
+ if (
+ key === "reasoningEnabled" &&
+ loadEstablishedReasoningMode(state, true)
+ ) {
+ continue;
+ }
// Only a local model or an openai_codex provider can run deep research, so a
// stored true must not arm the pill for any other external checkpoint.
if (
@@ -3711,6 +3855,522 @@ function setScalarSettingVersion<K extends ScalarSettingKey>(
writeGlobal();
}
+function localQwenMigrationSettings(
+ state: ChatRuntimeStore,
+): PersistedChatSettings {
+ return {
+ activePreset: state.activePreset,
+ activePresetSource: state.activePresetSource,
+ reasoningEnabled: installationReasoningEnabled(state),
+ inferenceParams: pickRememberedParams(
+ withoutActiveThreadParams(state, state.params),
+ ),
+ ...(Object.keys(state.paramsByModel).length > 0
+ ? { inferenceParamsByModel: state.paramsByModel }
+ : {}),
+ };
+}
+
+function installationReasoningEnabled(state: ChatRuntimeStore): boolean {
+ return threadScopedOverride("reasoningEnabled") !== undefined
+ ? (globalThreadScopedDefaults?.reasoningEnabled ?? state.reasoningEnabled)
+ : state.reasoningEnabled;
+}
+
+/**
+ * Whether a load or status response established the reasoning mode for the
+ * active model, with no user toggle since.
+ *
+ * A load writes reasoningEnabled without advancing its mutation version, so
+ * hydration would otherwise replay a toggle describing the previous model. The
+ * migration table and the hydrated pill both read this, so they cannot disagree
+ * and show a thinking pill above non-thinking sampling.
+ */
+function loadEstablishedReasoningMode(
+ state: ChatRuntimeStore,
+ requireLoad = false,
+): { enabled: boolean } | null {
+ const loaded = loadedModelReasoningMode;
+ if (
+ loaded !== null &&
+ sameCheckpointIdentity(loaded.checkpoint, state.params.checkpoint) &&
+ loaded.reasoningMutationVersion ===
+ scalarSettingMutationVersions.reasoningEnabled &&
+ (!requireLoad || loaded.fromLoad)
+ ) {
+ return { enabled: loaded.enabled };
+ }
+ return null;
+}
+
+function qwenMigrationThinkingOn(
+ settings: PersistedChatSettings,
+ state: ChatRuntimeStore,
+ reasoningMutationVersion = scalarSettingMutationVersions.reasoningEnabled,
+): boolean {
+ if (state.reasoningAlwaysOn) {
+ return true;
+ }
+ // Ahead of the established mode: a model that cannot reason never had the
+ // thinking table applied at load, so its recorded mode is just this browser's
+ // toggle. Only once status reported this checkpoint, though, since
+ // supportsReasoning starts false and "not asked yet" is not "cannot".
+ const statusSeen = sameCheckpointIdentity(
+ loadedModelReasoningMode?.checkpoint,
+ state.params.checkpoint,
+ );
+ if (statusSeen && !state.supportsReasoning) {
+ return false;
+ }
+ // requireLoad, as the hydrated pill uses: a status refresh echoes the toggle
+ // already in the store, which before hydration is this browser's own default.
+ const established = loadEstablishedReasoningMode(state, true);
+ if (established) {
+ return established.enabled;
+ }
+ return settings.reasoningEnabled !== undefined &&
+ scalarSettingMutationVersions.reasoningEnabled === reasoningMutationVersion
+ ? settings.reasoningEnabled
+ : installationReasoningEnabled(state);
+}
+
+function qwenMigrationRemembersPerModel(
+ settings: PersistedChatSettings,
+ state: ChatRuntimeStore,
+ rememberParamsPerModelMutationVersion =
+ scalarSettingMutationVersions.rememberParamsPerModel,
+): boolean {
+ return settings.rememberParamsPerModel !== undefined &&
+ scalarSettingMutationVersions.rememberParamsPerModel ===
+ rememberParamsPerModelMutationVersion
+ ? settings.rememberParamsPerModel
+ : state.rememberParamsPerModel;
+}
+
+const QWEN_MIGRATION_DECISION_FIELDS = [
+ "activePreset",
+ "activePresetSource",
+ "reasoningEnabled",
+ "rememberParamsPerModel",
+ "inferenceParamsByModel",
+] as const satisfies ReadonlyArray<keyof PersistedChatSettings>;
+
+// Raw, not sanitized: the server tests `key in current` against what is stored,
+// so asserting absence from the sanitized copy would fence a key the row has.
+/**
+ * True when a decision field is stored but sanitizes away, such as an explicit
+ * null or an empty inferenceParamsByModel map: the compare-and-set can assert a
+ * value or an absence and neither fits, and `expected` matches by recursive
+ * subset, so an empty map matches a populated one. Decline rather than migrate
+ * unfenced. An absent key is different, and stays fenced by expectedAbsent.
+ */
+function qwenMigrationHasUnfenceableField(
+ rawSettings: unknown,
+ sanitized: PersistedChatSettings,
+): boolean {
+ const raw =
+ typeof rawSettings === "object" && rawSettings !== null
+ ? (rawSettings as Record<string, unknown>)
+ : {};
+ return QWEN_MIGRATION_DECISION_FIELDS.some(
+ (field) => Object.hasOwn(raw, field) && sanitized[field] === undefined,
+ );
+}
+
+function qwenMigrationExpectedAbsent(
+ rawSettings: unknown,
+): Array<keyof PersistedChatSettings> {
+ const raw =
+ typeof rawSettings === "object" && rawSettings !== null
+ ? (rawSettings as Record<string, unknown>)
+ : {};
+ return QWEN_MIGRATION_DECISION_FIELDS.filter(
+ (field) => !Object.hasOwn(raw, field),
+ );
+}
+
+function qwenMigrationExpectedAbsentPaths(
+ rawSettings: unknown,
+ patch: PersistedChatSettings,
+): Array<[keyof PersistedChatSettings, string]> {
+ // Raw for the same reason as qwenMigrationExpectedAbsent: the server tests the
+ // stored row, so a key sanitizing away must not be fenced as absent.
+ const nested = (field: keyof PersistedChatSettings): Record<string, unknown> =>
+ typeof rawSettings === "object" && rawSettings !== null
+ ? ((rawSettings as Record<string, unknown>)[field] as
+ | Record<string, unknown>
+ | undefined) ?? {}
+ : {};
+ const paths: Array<[keyof PersistedChatSettings, string]> = [];
+ if (patch.inferenceParams !== undefined) {
+ const global = nested("inferenceParams");
+ for (const field of ["topK", "repetitionPenalty"] as const) {
+ if (!Object.hasOwn(global, field)) {
+ paths.push(["inferenceParams", field]);
+ }
+ }
+ }
+ // Normalizing a differently-cased key writes a new exact-key row. Unfenced,
+ // the subset compare only checks the old spelling, so an exact-key row
+ // another tab added after the confirming read would be overwritten whole.
+ const stored = nested("inferenceParamsByModel");
+ for (const modelId of Object.keys(patch.inferenceParamsByModel ?? {})) {
+ if (!Object.hasOwn(stored, modelId)) {
+ paths.push(["inferenceParamsByModel", modelId]);
+ }
+ }
+ return paths;
+}
+
+function applyLegacyQwenDefaultsAfterPresetChange(
+ ownedGlobalCheckpoint: string | null,
+ migrateOwnedGlobalAlongsideModelMemory: boolean,
+): void {
+ useChatRuntimeStore.setState((state) => {
+ if (
+ !state.settingsHydrated ||
+ state.activePresetSource !== "builtin-default"
+ ) {
+ return state;
+ }
+ const checkpoint = state.params.checkpoint;
+ const includeOwnedGlobal = sameCheckpointIdentity(
+ ownedGlobalCheckpoint,
+ checkpoint,
+ );
+ const localSettings = localQwenMigrationSettings(state);
+ const migration = migrateLegacyQwenDefaults(
+ localSettings,
+ checkpoint,
+ qwenMigrationThinkingOn(localSettings, state),
+ includeOwnedGlobal,
+ migrateOwnedGlobalAlongsideModelMemory,
+ );
+ if (!migration.patch) return state;
+
+ const activeModelId = migration.migratedModelIds.find(
+ (modelId) => sameCheckpointIdentity(modelId, checkpoint),
+ );
+ const activePatch = activeModelId
+ ? migration.patch.inferenceParamsByModel?.[activeModelId]
+ : migration.patch.inferenceParams;
+ if (activePatch) {
+ // The open chat may pin one of these, but a later snapshot-less chat
+ // falls back to the installation copy captured when pairing began. Move
+ // it with the migrated defaults before restoring the thread's params.
+ noteThreadScopedDefaults(activePatch);
+ }
+ return {
+ ...(migration.settings.inferenceParamsByModel
+ ? { paramsByModel: migration.settings.inferenceParamsByModel }
+ : {}),
+ ...(activePatch
+ ? {
+ params: capParamsToLoadedContext(
+ state,
+ restoreThreadScopedParams({
+ ...state.params,
+ ...activePatch,
+ }),
+ ),
+ }
+ : {}),
+ };
+ });
+}
+
+/**
+ * Bring local params back in line after a migration the server accepted while a
+ * local edit was in flight.
+ *
+ * The edit flips provenance to "modified", so the ordinary apply refuses and
+ * the tab keeps generating from values the server no longer holds. Only the
+ * fields the user did not touch are adopted, which is what the per-field
+ * mutation versions captured before the write identify.
+ */
+function adoptMigratedFieldsAfterLocalEdit(
+ patch: PersistedChatSettings,
+ checkpoint: string,
+ versionsBefore: Record<PersistedInferenceParamKey, number>,
+): void {
+ const migratedRow =
+ patch.inferenceParamsByModel?.[checkpoint] ?? patch.inferenceParams;
+ if (migratedRow === undefined) {
+ return;
+ }
+ useChatRuntimeStore.setState((state) => {
+ const nextParams = { ...state.params };
+ let changed = false;
+ for (const [key, value] of Object.entries(migratedRow)) {
+ const field = key as PersistedInferenceParamKey;
+ if (
+ versionsBefore[field] === undefined ||
+ inferenceParamMutationVersions[field] !== versionsBefore[field] ||
+ nextParams[field] === value
+ ) {
+ continue;
+ }
+ (nextParams as Record<string, unknown>)[field] = value;
+ changed = true;
+ }
+ if (!changed) {
+ return state;
+ }
+ const storedRow = state.paramsByModel[checkpoint];
+ return {
+ // As the normal application path does: applying a thread pin advances no
+ // mutation version, so nothing above would have noticed it.
+ params: restoreThreadScopedParams(nextParams),
+ ...(storedRow
+ ? {
+ paramsByModel: {
+ ...state.paramsByModel,
+ [checkpoint]: { ...storedRow, ...migratedRow },
+ },
+ }
+ : {}),
+ };
+ });
+}
+
+async function retryLegacyQwenDefaultsAfterPresetChange(
+ ownedGlobalCheckpoint: string | null,
+ migrateOwnedGlobalAlongsideModelMemory: boolean,
+): Promise<void> {
+ try {
+ // Land the preset selection first so the confirming GET can recognize the
+ // legacy snapshot; a newer edit in another tab fails the fingerprint
+ // safely.
+ await flushPendingChatSettings();
+ // A write outstanding past the flush timeout would reach the backend merge
+ // after this CAS and restore the legacy row. Rearm on its settlement rather
+ // than wait: an external selection gets no later status callback.
+ if (!settingsWritesAreDrained()) {
+ // Bounded: a refused patch is retained and reflushed by each pass, so an
+ // unbounded rearm loops on an unreachable backend. Cleared once writes
+ // drain, so a healthy install never spends it.
+ if (qwenMigrationRearmsWhileBlocked < QWEN_MIGRATION_MAX_REARMS) {
+ qwenMigrationRearmsWhileBlocked += 1;
+ void inflightFlush.catch(() => undefined).then(() => {
+ scheduleLegacyQwenDefaultsRetry(
+ ownedGlobalCheckpoint,
+ migrateOwnedGlobalAlongsideModelMemory,
+ );
+ });
+ }
+ return;
+ }
+ qwenMigrationRearmsWhileBlocked = 0;
+ const state = useChatRuntimeStore.getState();
+ if (
+ !state.settingsHydrated ||
+ state.activePresetSource !== "builtin-default"
+ ) {
+ return;
+ }
+ const checkpoint = state.params.checkpoint;
+ const confirmedRaw = await getChatSettings();
+ const confirmed = sanitizeChatSettings(confirmedRaw);
+ const confirmedState = useChatRuntimeStore.getState();
+ // A model switch during the GET invalidates both the row and the reasoning
+ // mode this retry would persist. The new model schedules its own.
+ if (
+ !confirmedState.settingsHydrated ||
+ confirmedState.activePresetSource !== "builtin-default" ||
+ confirmedState.params.checkpoint !== checkpoint
+ ) {
+ return;
+ }
+ const includeOwnedGlobal = sameCheckpointIdentity(
+ ownedGlobalCheckpoint,
+ checkpoint,
+ );
+ const migration = migrateLegacyQwenDefaults(
+ confirmed,
+ checkpoint,
+ qwenMigrationThinkingOn(confirmed, confirmedState),
+ includeOwnedGlobal,
+ // From the confirming read, as hydration derives it: memory turned on
+ // elsewhere means the global is no longer this checkpoint's to rewrite.
+ migrateOwnedGlobalAlongsideModelMemory &&
+ !qwenMigrationRemembersPerModel(confirmed, confirmedState),
+ );
+ if (!migration.patch) return;
+ if (qwenMigrationHasUnfenceableField(confirmedRaw, confirmed)) return;
+ // Captured before the write: an edit landing mid-flight is the one case
+ // where the server takes the migration and local refuses it.
+ const presetSourceBeforeWrite = activePresetSourceMutationVersion;
+ const paramVersionsBeforeWrite = { ...inferenceParamMutationVersions };
+ const persisted = await savePersistedChatSettingsPatchIfCurrent(
+ confirmed,
+ migration.patch,
+ qwenMigrationExpectedAbsent(confirmedRaw),
+ qwenMigrationExpectedAbsentPaths(confirmedRaw, migration.patch),
+ );
+ // Only now touch local state: applying before persisting would leave this
+ // tab generating with values the server rejected. Revalidated after the
+ // await too, since the checkpoint can move while the response is in flight,
+ // and an external pick gets no callback to schedule another retry.
+ if (
+ persisted.applied &&
+ sameCheckpointIdentity(
+ useChatRuntimeStore.getState().params.checkpoint,
+ checkpoint,
+ )
+ ) {
+ if (activePresetSourceMutationVersion === presetSourceBeforeWrite) {
+ applyLegacyQwenDefaultsAfterPresetChange(
+ ownedGlobalCheckpoint,
+ migrateOwnedGlobalAlongsideModelMemory,
+ );
+ } else if (
+ migration.patch &&
+ useChatRuntimeStore.getState().activePresetSource !== "custom"
+ ) {
+ // "modified" is an ordinary edit and belongs here; a custom preset can
+ // hold a legacy value on purpose and bumps no counter for it.
+ adoptMigratedFieldsAfterLocalEdit(
+ migration.patch,
+ checkpoint,
+ paramVersionsBeforeWrite,
+ );
+ }
+ }
+ } catch {
+ warnSettingsPersistenceFailure();
+ }
+}
+
+let qwenMigrationInFlight: Promise<void> | null = null;
+
+// Same bound as SETTINGS_FLUSH_TIMEOUT_MS, for the same reason.
+const QWEN_MIGRATION_BARRIER_TIMEOUT_MS = 2000;
+
+const QWEN_MIGRATION_MAX_REARMS = 3;
+let qwenMigrationRearmsWhileBlocked = 0;
+
+/**
+ * Settles once a scheduled migration has decided and persisted, so a prompt sent
+ * right after picking a Qwen with a dormant legacy row does not generate from
+ * the values getReplayedParams just put on screen.
+ */
+export async function awaitPendingQwenDefaultsMigration(): Promise<void> {
+ if (qwenMigrationInFlight === null) return;
+ // Bounded like the settings flush: neither request takes an abort signal, so
+ // a wedged backend would hold every send open. Past this the run proceeds.
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ await Promise.race([
+ followPendingQwenDefaultsMigrations(),
+ new Promise<void>((resolve) => {
+ timer = setTimeout(resolve, QWEN_MIGRATION_BARRIER_TIMEOUT_MS);
+ }),
+ ]);
+ } finally {
+ if (timer !== undefined) clearTimeout(timer);
+ }
+}
+
+// Re-read rather than await once: a replacement scheduled while this waits owns
+// the checkpoint the send is about to generate from.
+async function followPendingQwenDefaultsMigrations(): Promise<void> {
+ let pending = qwenMigrationInFlight;
+ while (pending) {
+ await pending;
+ pending = qwenMigrationInFlight;
+ }
+}
+
+let qwenDefaultsRetryScheduled = false;
+let qwenDefaultsRetryOwnedGlobalCheckpoint: string | null = null;
+let qwenDefaultsRetryOwnedGlobalCheckpointConflicted = false;
+let qwenDefaultsRetryMigratesOwnedGlobalAlongsideModelMemory = false;
+
+function scheduleLegacyQwenDefaultsRetry(
+ ownedGlobalCheckpoint: string | null,
+ migrateOwnedGlobalAlongsideModelMemory = ownedGlobalCheckpoint !== null,
+): void {
+ if (ownedGlobalCheckpoint !== null) {
+ if (
+ qwenDefaultsRetryOwnedGlobalCheckpoint !== null &&
+ !sameCheckpointIdentity(
+ qwenDefaultsRetryOwnedGlobalCheckpoint,
+ ownedGlobalCheckpoint,
+ )
+ ) {
+ qwenDefaultsRetryOwnedGlobalCheckpointConflicted = true;
+ } else if (!qwenDefaultsRetryOwnedGlobalCheckpointConflicted) {
+ qwenDefaultsRetryOwnedGlobalCheckpoint = ownedGlobalCheckpoint;
+ }
+ }
+ qwenDefaultsRetryMigratesOwnedGlobalAlongsideModelMemory ||=
+ migrateOwnedGlobalAlongsideModelMemory;
+ if (qwenDefaultsRetryScheduled) {
+ return;
+ }
+ qwenDefaultsRetryScheduled = true;
+ // Published from scheduling time, not from when the microtask runs, or a send
+ // landing in between would find nothing to wait for.
+ let settleMigration: () => void = () => undefined;
+ // Cleared only while the pointer still refers to this retry: the scheduler
+ // frees its slot before the async work ends, so a later retry can replace it.
+ const migration: Promise<void> = new Promise<void>((resolve) => {
+ settleMigration = () => {
+ if (qwenMigrationInFlight === migration) {
+ qwenMigrationInFlight = null;
+ }
+ resolve();
+ };
+ });
+ qwenMigrationInFlight = migration;
+ queueMicrotask(() => {
+ const scheduledOwnedGlobalCheckpoint =
+ qwenDefaultsRetryOwnedGlobalCheckpointConflicted
+ ? null
+ : qwenDefaultsRetryOwnedGlobalCheckpoint;
+ const migrateScheduledOwnedGlobalAlongsideModelMemory =
+ qwenDefaultsRetryMigratesOwnedGlobalAlongsideModelMemory;
+ qwenDefaultsRetryScheduled = false;
+ qwenDefaultsRetryOwnedGlobalCheckpoint = null;
+ qwenDefaultsRetryOwnedGlobalCheckpointConflicted = false;
+ qwenDefaultsRetryMigratesOwnedGlobalAlongsideModelMemory = false;
+ const state = useChatRuntimeStore.getState();
+ if (
+ !state.settingsHydrated ||
+ state.activePresetSource !== "builtin-default"
+ ) {
+ settleMigration();
+ return;
+ }
+ const localSettings = localQwenMigrationSettings(state);
+ const includeOwnedGlobal = sameCheckpointIdentity(
+ scheduledOwnedGlobalCheckpoint,
+ state.params.checkpoint,
+ );
+ const hasLocalCandidate =
+ migrateLegacyQwenDefaults(
+ localSettings,
+ state.params.checkpoint,
+ qwenMigrationThinkingOn(localSettings, state),
+ includeOwnedGlobal,
+ migrateScheduledOwnedGlobalAlongsideModelMemory,
+ ).patch !== null;
+ // A status refresh needs a confirming GET only when the local store still
+ // holds a legacy row. Adoption is the exception: it owns a server snapshot
+ // model defaults already replaced locally, so only the server still has it.
+ const hasOwnedGlobalCandidate =
+ includeOwnedGlobal && isPresenceBumpQwen(state.params.checkpoint);
+ if (!hasLocalCandidate && !hasOwnedGlobalCandidate) {
+ settleMigration();
+ return;
+ }
+ void retryLegacyQwenDefaultsAfterPresetChange(
+ scheduledOwnedGlobalCheckpoint,
+ migrateScheduledOwnedGlobalAlongsideModelMemory,
+ ).finally(settleMigration);
+ });
+}
+
export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
settingsHydrated: false,
threadScopedSettingsPending: false,
@@ -3719,6 +4379,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
// useChatModelRuntime and intentionally NOT persisted here.
params: (() => {
const persistedExternal = loadLastExternalCheckpoint();
+ unownedCheckpointBeforeHydration = persistedExternal;
return persistedExternal
? { ...DEFAULT_INFERENCE_PARAMS, checkpoint: persistedExternal }
: DEFAULT_INFERENCE_PARAMS;
@@ -3909,7 +4570,133 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
settingsHydrationPromise = (async () => {
const hydrationVersions = getSettingsHydrationVersions();
try {
- const { settings, fromServer } = await loadChatSettingsWithLegacyImport();
+ const {
+ settings,
+ fromServer,
+ persisted: settingsArePersisted,
+ } = await loadChatSettingsWithLegacyImport();
+ // Assigned by the confirming read below, so the failure path can prefer
+ // it over the older hydration response.
+ let confirmed: PersistedChatSettings | undefined;
+ // What to hydrate when nothing was migrated. The confirming read is the
+ // newer server truth, but a legacy merge that failed to save exists
+ // only here, and re-reading the server would discard it.
+ const unmigrated = (
+ snapshot: PersistedChatSettings,
+ ): QwenDefaultsMigration => ({
+ settings: settingsArePersisted ? snapshot : settings,
+ patch: null,
+ migratedModelIds: [],
+ });
+ const checkpoint = get().params.checkpoint;
+ const thinkingOn = qwenMigrationThinkingOn(
+ settings,
+ get(),
+ hydrationVersions.scalarSettings.reasoningEnabled,
+ );
+ // A model loaded during the settings GET replaced the one whose global
+ // fallback was saved. Only the model resident at startup can own a
+ // global-only legacy snapshot.
+ const globalBelongsToActiveCheckpoint =
+ !sameCheckpointIdentity(modelLoadedBeforeHydration, checkpoint) &&
+ modelLeftBeforeHydration === null &&
+ !sameCheckpointIdentity(unownedCheckpointBeforeHydration, checkpoint);
+ const remembersPerModel = qwenMigrationRemembersPerModel(
+ settings,
+ get(),
+ hydrationVersions.scalarSettings.rememberParamsPerModel,
+ );
+ let migration = migrateLegacyQwenDefaults(
+ settings,
+ checkpoint,
+ thinkingOn,
+ globalBelongsToActiveCheckpoint,
+ globalBelongsToActiveCheckpoint && !remembersPerModel,
+ );
+ // Neither switch path can schedule the new model's retry from here:
+ // both gate on settingsHydrated, still false.
+ let checkpointMovedDuringConfirm = false;
+ if (fromServer && migration.patch) {
+ try {
+ // Re-read immediately before the write, so the patch derives from
+ // this confirmation rather than the earlier hydration response and
+ // a newer edit from another tab is left untouched.
+ const confirmedRaw = await getChatSettings();
+ confirmed = sanitizeChatSettings(confirmedRaw);
+ const confirmedState = get();
+ // A model switch during the confirming GET invalidates the
+ // checkpoint and mode this migration would persist; the new model
+ // schedules its own retry. The preset can move too: a slider
+ // touched now sets the local source to "modified" but queues its
+ // write behind the debounce, so the server still reads
+ // "builtin-default". Migrating on that stale read would rewrite a
+ // preset the user already modified, so trust the local version.
+ const presetSourceUnchanged =
+ activePresetSourceMutationVersion ===
+ hydrationVersions.presets.activePresetSource &&
+ confirmedState.activePresetSource === "builtin-default";
+ checkpointMovedDuringConfirm =
+ confirmedState.params.checkpoint !== checkpoint;
+ migration =
+ confirmedState.params.checkpoint === checkpoint &&
+ presetSourceUnchanged
+ ? migrateLegacyQwenDefaults(
+ confirmed,
+ checkpoint,
+ qwenMigrationThinkingOn(
+ confirmed,
+ confirmedState,
+ hydrationVersions.scalarSettings.reasoningEnabled,
+ ),
+ globalBelongsToActiveCheckpoint,
+ globalBelongsToActiveCheckpoint &&
+ !qwenMigrationRemembersPerModel(
+ confirmed,
+ confirmedState,
+ hydrationVersions.scalarSettings
+ .rememberParamsPerModel,
+ ),
+ )
+ : unmigrated(confirmed);
+ // migrateLegacyQwenDefaults returns its own input when nothing
+ // migrates, so a read finding no candidate would otherwise replace
+ // an unsaved legacy merge with server-only settings.
+ if (
+ migration.patch === null ||
+ qwenMigrationHasUnfenceableField(confirmedRaw, confirmed)
+ ) {
+ migration = unmigrated(confirmed);
+ }
+ if (migration.patch) {
+ const persisted = await savePersistedChatSettingsPatchIfCurrent(
+ confirmed,
+ migration.patch,
+ qwenMigrationExpectedAbsent(confirmedRaw),
+ qwenMigrationExpectedAbsentPaths(
+ confirmedRaw,
+ migration.patch,
+ ),
+ );
+ migration = {
+ ...migration,
+ settings: persisted.settings,
+ patch: persisted.applied ? migration.patch : null,
+ migratedModelIds: persisted.applied
+ ? migration.migratedModelIds
+ : [],
+ };
+ }
+ } catch {
+ // Best effort, but that cannot mean hydrating values the server
+ // never accepted: the sheet and every request would show migrated
+ // sampling while storage still held the old row, on each start.
+ // Fall back to what was actually read, preferring the confirming
+ // snapshot when it landed, since the first read may already be
+ // stale and backfill would then push this browser's copy over it.
+ migration = unmigrated(confirmed ?? settings);
+ }
+ }
+ const hydratedSettings = migration.settings;
let applied = false;
set((state) => {
if (state.settingsHydrated) {
@@ -3919,24 +4706,32 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
const nextState: Partial<ChatRuntimeStore> = {
settingsHydrated: true,
...getHydratedPresetState(
- settings,
+ hydratedSettings,
state,
hydrationVersions.presets,
),
- ...getHydratedSettingsState(settings, state, hydrationVersions),
+ ...getHydratedSettingsState(
+ hydratedSettings,
+ state,
+ hydrationVersions,
+ ),
};
return nextState;
});
if (applied) {
- cacheHydratedSettings(settings, hydrationVersions);
+ cacheHydratedSettings(hydratedSettings, hydrationVersions);
mirroredSettingsHydrated = true;
// Only an authoritative read says a mirrored field is unset on the
// server. A GET that fell back to legacy storage knows nothing about
// it, and backfilling then pushes this browser's stale values over
// whatever another browser wrote.
- if (fromServer) backfillMirroredSettings(settings);
+ if (fromServer) backfillMirroredSettings(hydratedSettings);
// After the backfill, so a startup edit wins over the stored value.
flushPreHydrationSettings();
+ // Hydrated now, so the model switched to can be repaired.
+ if (checkpointMovedDuringConfirm) {
+ scheduleLegacyQwenDefaultsRetry(null);
+ }
// The previous session's tab-close writes, for the rows that did not exist
// yet when it sent them. A replay of one that did land is refused by its own
// seq, so this cannot revert anything newer.
@@ -3987,7 +4782,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
}),
setModelRequiresTrustRemoteCode: (modelRequiresTrustRemoteCode) =>
set({ modelRequiresTrustRemoteCode }),
- setParams: (params, options) =>
+ setParams: (params, options) => {
set((state) => {
// Mirror setCheckpoint: the local load path can mutate params.checkpoint
// via setParams() before setCheckpoint runs, leaving stale per-turn
@@ -4071,7 +4866,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
} else if (fromModelDefaults && !state.settingsHydrated) {
noteModelDefaultsBeforeHydration(
nextParams.checkpoint,
- checkpointChanged && state.params.checkpoint !== "",
+ options?.migrateOwnedGlobalQwenDefaults === true,
);
}
return {
@@ -4084,7 +4879,20 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
? { contextUsage: null, contextUsageByThreadId: {} }
: {}),
};
- }),
+ });
+ // Startup can hydrate before the server's active model is adopted. Once
+ // status applies its defaults the checkpoint and reasoning mode are known,
+ // so the deferred active-row migration can run.
+ if (options?.fromModelDefaults === true) {
+ const retryState = get();
+ const ownsPersistedGlobal =
+ options.migrateOwnedGlobalQwenDefaults === true;
+ scheduleLegacyQwenDefaultsRetry(
+ ownsPersistedGlobal ? params.checkpoint : null,
+ ownsPersistedGlobal && !retryState.rememberParamsPerModel,
+ );
+ }
+ },
setCustomPresets: (customPresets) =>
set(() => {
customPresetsMutationVersion += 1;
@@ -4097,12 +4905,25 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
saveSettingsPatch({ activePreset });
return { activePreset };
}),
- setActivePresetSource: (activePresetSource) =>
- set(() => {
+ setActivePresetSource: (activePresetSource) => {
+ let returnedToBuiltInDefault = false;
+ set((state) => {
+ returnedToBuiltInDefault =
+ activePresetSource === "builtin-default" &&
+ state.activePresetSource !== "builtin-default";
activePresetSourceMutationVersion += 1;
saveSettingsPatch({ activePresetSource });
return { activePresetSource };
- }),
+ });
+ if (returnedToBuiltInDefault) {
+ // The sheet updates provenance before applying the parameter edit. Defer
+ // a microtask so a final slider move restoring built-in Default has
+ // landed before the migration inspects and flushes it.
+ scheduleLegacyQwenDefaultsRetry(
+ useChatRuntimeStore.getState().params.checkpoint,
+ );
+ }
+ },
setModels: (models) => set({ models }),
setLoras: (loras) => set({ loras, loraInventorySettled: true }),
setThreadRunning: (threadId, running, options) =>
@@ -4238,7 +5059,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
setHfToken: (hfToken) => useHfTokenStore.getState().setToken(hfToken),
setModelsError: (modelsError) => set({ modelsError }),
setLastModelLoadError: (lastModelLoadError) => set({ lastModelLoadError }),
- setCheckpoint: (modelId, ggufVariant, options) =>
+ setCheckpoint: (modelId, ggufVariant, options) => {
+ let scheduleQwenMigration = false;
set((state) => {
// Persist external selections so they survive a refresh. Local ids are
// NOT persisted -- they're re-derived from the backend on mount, and a
@@ -4257,6 +5079,12 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
// Clear stale per-turn usage on model change; the relaxed external-provider
// render gate would otherwise show old counters until the next completion.
const checkpointChanged = state.params.checkpoint !== modelId;
+ // An interactive pick during hydration has no adoption signal either, so
+ // the previous session's global does not become this model's.
+ if (checkpointChanged && !state.settingsHydrated) {
+ unownedCheckpointBeforeHydration = modelId;
+ }
+ scheduleQwenMigration = checkpointChanged && state.settingsHydrated;
// Remember what the outgoing model was running with before replacing it.
// Not for a restore: the model it steps off is the one a background load
// put there, and its load defaults are not settings the user chose.
@@ -4353,7 +5181,17 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
// loop disables Deep Research; a capable one keeps the user's choice.
...(clampsDeepResearch ? { deepResearchEnabled: false } : {}),
};
- }),
+ });
+ // An external pick is the whole story for that model: no load and no status
+ // follows it, so nothing else would ever schedule the migration and the
+ // replayed legacy row would keep being sent until a reload. Never with
+ // ownership, since selecting a model says nothing about whose global the
+ // installation's snapshot is. The scheduler's own dry run makes this cheap
+ // when there is no legacy row to repair.
+ if (scheduleQwenMigration) {
+ scheduleLegacyQwenDefaultsRetry(null);
+ }
+ },
// Re-apply the incoming thread's own usage rather than blanking the bar: a run that finished
// in the background never wrote the visible value, and a still-mounted runtime skips the
// history loader on the way back.
diff --git a/studio/frontend/src/features/chat/utils/chat-settings-storage.ts b/studio/frontend/src/features/chat/utils/chat-settings-storage.ts
index 30bdf943d82..8a93891d2c2 100644
--- a/studio/frontend/src/features/chat/utils/chat-settings-storage.ts
+++ b/studio/frontend/src/features/chat/utils/chat-settings-storage.ts
@@ -4,6 +4,8 @@
import {
getChatSettings,
saveChatSettingsPatch,
+ saveChatSettingsPatchIfCurrent,
+ type ChatSettingsPath,
type PersistedChatPreset,
type PersistedChatSettings,
type PersistedInferenceParams,
@@ -256,7 +258,7 @@ function sanitizeInt(value: unknown, min: number): number | undefined {
: undefined;
}
-function sanitizeChatSettings(value: unknown): PersistedChatSettings {
+export function sanitizeChatSettings(value: unknown): PersistedChatSettings {
if (!isRecord(value)) return {};
const settings: PersistedChatSettings = {};
@@ -464,6 +466,13 @@ export interface LoadedChatSettings {
* as absent would back this browser's stale values over another's.
*/
fromServer: boolean;
+ /**
+ * Whether these values are what the server holds. False when a legacy import
+ * merged local values but failed to save them: the server answered, so
+ * absence is still authoritative, but the merge exists only in this session
+ * and a later re-read would silently drop it.
+ */
+ persisted: boolean;
}
export async function loadChatSettingsWithLegacyImport(): Promise<LoadedChatSettings> {
@@ -475,7 +484,7 @@ export async function loadChatSettingsWithLegacyImport(): Promise<LoadedChatSett
if (isEmptyChatSettings(legacySettings)) {
throw error;
}
- return { settings: legacySettings, fromServer: false };
+ return { settings: legacySettings, fromServer: false, persisted: false };
}
const legacySettings = loadLegacyChatSettings();
@@ -484,7 +493,7 @@ export async function loadChatSettingsWithLegacyImport(): Promise<LoadedChatSett
!isEmptyChatSettings(dbSettings) ||
isEmptyChatSettings(legacySettings)
) {
- return { settings: dbSettings, fromServer: true };
+ return { settings: dbSettings, fromServer: true, persisted: true };
}
try {
return {
@@ -492,16 +501,17 @@ export async function loadChatSettingsWithLegacyImport(): Promise<LoadedChatSett
await saveChatSettingsPatch(legacySettings),
),
fromServer: true,
+ persisted: true,
};
} catch {
// The GET still answered (empty), so absence remains authoritative.
- return { settings: legacySettings, fromServer: true };
+ return { settings: legacySettings, fromServer: true, persisted: false };
}
}
if (isEmptyChatSettings(legacySettings)) {
markLegacySettingsImportDone();
- return { settings: dbSettings, fromServer: true };
+ return { settings: dbSettings, fromServer: true, persisted: true };
}
const mergedSettings = {
@@ -517,9 +527,9 @@ export async function loadChatSettingsWithLegacyImport(): Promise<LoadedChatSett
await saveChatSettingsPatch(mergedSettings),
);
markLegacySettingsImportDone();
- return { settings: savedSettings, fromServer: true };
+ return { settings: savedSettings, fromServer: true, persisted: true };
} catch {
- return { settings: mergedSettings, fromServer: true };
+ return { settings: mergedSettings, fromServer: true, persisted: false };
}
}
@@ -531,3 +541,21 @@ export async function savePersistedChatSettingsPatch(
await saveChatSettingsPatch(sanitizeChatSettings(patch), options),
);
}
+
+export async function savePersistedChatSettingsPatchIfCurrent(
+ expected: PersistedChatSettings,
+ patch: PersistedChatSettings,
+ expectedAbsent: Array<keyof PersistedChatSettings> = [],
+ expectedAbsentPaths: ChatSettingsPath[] = [],
+): Promise<{ settings: PersistedChatSettings; applied: boolean }> {
+ const result = await saveChatSettingsPatchIfCurrent(
+ sanitizeChatSettings(expected),
+ sanitizeChatSettings(patch),
+ expectedAbsent,
+ expectedAbsentPaths,
+ );
+ return {
+ settings: sanitizeChatSettings(result.settings),
+ applied: result.applied,
+ };
+}
diff --git a/studio/frontend/src/features/chat/utils/qwen-defaults-migration.ts b/studio/frontend/src/features/chat/utils/qwen-defaults-migration.ts
new file mode 100644
index 00000000000..cca7fe819a0
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/qwen-defaults-migration.ts
@@ -0,0 +1,265 @@
+// 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 { PersistedChatSettings } from "../api/chat-settings-api";
+import type { PersistedInferenceParams } from "../types/runtime";
+import { isExternalModelId } from "../external-providers";
+import { normalizeModelIdentity } from "../../hub/lib/model-identity";
+import {
+ isOllamaManifestRef,
+ resolveQwenThinkingParams,
+} from "./qwen-sampling-table";
+
+function isOpaqueModelRef(modelId: string): boolean {
+ return isExternalModelId(modelId) || isOllamaManifestRef(modelId);
+}
+
+const LEGACY_QWEN_DEFAULTS = {
+ temperature: 0.6,
+ topP: 0.95,
+ topK: 20,
+ minP: 0.01,
+ repetitionPenalty: 1.0,
+ presencePenalty: 0.0,
+} as const;
+
+const LEGACY_GLOBAL_QWEN_DEFAULTS = {
+ temperature: 0.6,
+ topP: 0.95,
+ minP: 0.01,
+ presencePenalty: 0.0,
+} as const;
+
+const LEGACY_OPTIONAL_GLOBAL_QWEN_DEFAULTS = {
+ topK: 20,
+ repetitionPenalty: 1.0,
+} as const;
+
+/**
+ * The replacement table, read from the same resolver load and the Think toggle
+ * use, so this file cannot drift into a second source of truth. Null whenever
+ * the resolver gives no presencePenalty: a generic Qwen3 row never had the bump,
+ * so it is not ours to rewrite.
+ */
+function currentQwenDefaults(
+ modelId: string,
+ thinkingOn: boolean,
+): PersistedInferenceParams | null {
+ const resolved = resolveQwenThinkingParams(modelId, thinkingOn);
+ if (resolved === null || resolved.presencePenalty === undefined) {
+ return null;
+ }
+ return {
+ temperature: resolved.temperature,
+ topP: resolved.topP,
+ topK: resolved.topK,
+ minP: resolved.minP,
+ presencePenalty: resolved.presencePenalty,
+ };
+}
+
+export function isPresenceBumpQwen(modelId: string): boolean {
+ // The resolver's own answer, not a second predicate: a model that gets the
+ // bump on load is exactly the one whose stale row this repairs.
+ return (
+ resolveQwenThinkingParams(modelId, true)?.presencePenalty !== undefined
+ );
+}
+
+function isLegacyQwenDefaultSnapshot(
+ params: PersistedInferenceParams,
+): boolean {
+ return Object.entries(LEGACY_QWEN_DEFAULTS).every(
+ ([key, value]) => params[key as keyof PersistedInferenceParams] === value,
+ );
+}
+
+function isLegacyGlobalQwenDefaultSnapshot(
+ params: PersistedInferenceParams | undefined,
+): boolean {
+ return (
+ params !== undefined &&
+ Object.entries(LEGACY_GLOBAL_QWEN_DEFAULTS).every(
+ ([key, value]) => params[key as keyof PersistedInferenceParams] === value,
+ ) &&
+ Object.entries(LEGACY_OPTIONAL_GLOBAL_QWEN_DEFAULTS).every(
+ ([key, value]) => {
+ const stored = params[key as keyof PersistedInferenceParams];
+ // Old globals did not always serialize these two, but a present value
+ // must still match, or a customization reads as generated data.
+ return stored === undefined || stored === value;
+ },
+ )
+ );
+}
+
+function changedDefaults(
+ legacy: PersistedInferenceParams,
+ current: PersistedInferenceParams,
+): PersistedInferenceParams {
+ const changed: PersistedInferenceParams = {};
+ for (const [key, value] of Object.entries(current)) {
+ const field = key as keyof PersistedInferenceParams;
+ if (legacy[field] !== value) {
+ (changed as Record<string, unknown>)[key] = value;
+ }
+ }
+ return changed;
+}
+
+function isBuiltInDefault(settings: PersistedChatSettings): boolean {
+ return (
+ (settings.activePreset === undefined ||
+ settings.activePreset === "Default") &&
+ (settings.activePresetSource === undefined ||
+ settings.activePresetSource === "builtin-default")
+ );
+}
+
+export type QwenDefaultsMigration = {
+ settings: PersistedChatSettings;
+ patch: PersistedChatSettings | null;
+ migratedModelIds: string[];
+};
+
+function migrateStoredModelDefaults(
+ stored: Record<string, PersistedInferenceParams> | undefined,
+ activeCheckpoint: string,
+ currentDefaults: PersistedInferenceParams,
+): {
+ migratedModelIds: string[];
+ migratedByModel: Record<string, PersistedInferenceParams>;
+ patchByModel: Record<string, PersistedInferenceParams>;
+} {
+ const migratedModelIds: string[] = [];
+ const migratedByModel: Record<string, PersistedInferenceParams> = {};
+ const patchByModel: Record<string, PersistedInferenceParams> = {};
+ const storedEntries = Object.entries(stored ?? {});
+ // Prefer an exact key when legacy storage holds two spellings; otherwise
+ // normalize the sole case-insensitive match to the checkpoint spelling, which
+ // is how replay indexes the map. normalizeModelIdentity, not toLowerCase: it
+ // preserves case for POSIX paths, which can name two different files. Opaque
+ // ids compare exactly and have no legacy spellings to reconcile.
+ const activeIdentity = normalizeModelIdentity(activeCheckpoint);
+ const activeIsOpaque = isOpaqueModelRef(activeCheckpoint);
+ // Only the sole alias, checked rather than assumed: with two spellings one
+ // may hold the legacy snapshot and the other the user's own sampling, and
+ // insertion order would serve generated defaults over a customization.
+ const aliases = activeIsOpaque
+ ? []
+ : storedEntries.filter(
+ ([modelId]) =>
+ !isOpaqueModelRef(modelId) &&
+ normalizeModelIdentity(modelId) === activeIdentity,
+ );
+ const activeStoredId =
+ storedEntries.find(([modelId]) => modelId === activeCheckpoint)?.[0] ??
+ (aliases.length === 1 ? aliases[0][0] : undefined);
+ for (const [modelId, entry] of storedEntries) {
+ const isActiveCheckpoint = modelId === activeStoredId;
+ if (
+ isActiveCheckpoint &&
+ isPresenceBumpQwen(modelId) &&
+ isLegacyQwenDefaultSnapshot(entry)
+ ) {
+ const normalizedModelId = activeCheckpoint;
+ const migratedEntry = { ...entry, ...currentDefaults };
+ migratedModelIds.push(normalizedModelId);
+ migratedByModel[normalizedModelId] = migratedEntry;
+ patchByModel[normalizedModelId] =
+ modelId === normalizedModelId
+ ? changedDefaults(entry, currentDefaults)
+ : migratedEntry;
+ if (modelId !== normalizedModelId) {
+ // The server merge only sets keys, so the spelling normalized away
+ // survives and a later status naming it would replay the stale row.
+ migratedByModel[modelId] = migratedEntry;
+ patchByModel[modelId] = changedDefaults(entry, currentDefaults);
+ }
+ } else {
+ migratedByModel[modelId] = entry;
+ }
+ }
+ return { migratedModelIds, migratedByModel, patchByModel };
+}
+
+/**
+ * Upgrade the generic-Qwen snapshot Studio used to remember for Qwen3.5/3.6/3.8.
+ * Matching every sampling field leaves a partial override untouched, including
+ * a deliberate presencePenalty=0, and the context-derived maxTokens is kept.
+ * Globals are eligible only when the caller can show they describe the active
+ * checkpoint; a per-model map alone does not prove that.
+ */
+export function migrateLegacyQwenDefaults(
+ settings: PersistedChatSettings,
+ activeCheckpoint: string,
+ thinkingOn: boolean,
+ globalBelongsToActiveCheckpoint = false,
+ migrateOwnedGlobalAlongsideModelMemory = false,
+): QwenDefaultsMigration {
+ // An empty map is no per-model memory, not memory that is empty. Normalized
+ // here, not in the callers: this is exported.
+ const storedRaw = settings.inferenceParamsByModel;
+ const stored =
+ storedRaw !== undefined && Object.keys(storedRaw).length > 0
+ ? storedRaw
+ : undefined;
+ if (!isBuiltInDefault(settings)) {
+ return { settings, patch: null, migratedModelIds: [] };
+ }
+
+ const currentDefaults = currentQwenDefaults(activeCheckpoint, thinkingOn);
+ if (currentDefaults === null) {
+ return { settings, patch: null, migratedModelIds: [] };
+ }
+ const currentGlobalDefaults: PersistedInferenceParams = {
+ temperature: currentDefaults.temperature,
+ topP: currentDefaults.topP,
+ minP: currentDefaults.minP,
+ presencePenalty: currentDefaults.presencePenalty,
+ };
+
+ const { migratedModelIds, migratedByModel, patchByModel } =
+ migrateStoredModelDefaults(stored, activeCheckpoint, currentDefaults);
+
+ const migrateGlobal =
+ (stored === undefined || migrateOwnedGlobalAlongsideModelMemory) &&
+ globalBelongsToActiveCheckpoint &&
+ isPresenceBumpQwen(activeCheckpoint) &&
+ isLegacyGlobalQwenDefaultSnapshot(settings.inferenceParams);
+ const globalChanges = migrateGlobal
+ ? changedDefaults(settings.inferenceParams ?? {}, currentGlobalDefaults)
+ : null;
+ // An already-current global produces {}, which is truthy and would be sent as
+ // an empty patch.
+ const globalPatch =
+ globalChanges && Object.keys(globalChanges).length > 0
+ ? globalChanges
+ : null;
+
+ if (migratedModelIds.length === 0 && !globalPatch) {
+ return { settings, patch: null, migratedModelIds };
+ }
+
+ return {
+ settings: {
+ ...settings,
+ ...(stored ? { inferenceParamsByModel: migratedByModel } : {}),
+ ...(migrateGlobal
+ ? {
+ inferenceParams: {
+ ...settings.inferenceParams,
+ ...currentGlobalDefaults,
+ },
+ }
+ : {}),
+ },
+ patch: {
+ ...(migratedModelIds.length > 0
+ ? { inferenceParamsByModel: patchByModel }
+ : {}),
+ ...(globalPatch ? { inferenceParams: globalPatch } : {}),
+ },
+ migratedModelIds,
+ };
+}
diff --git a/studio/frontend/src/features/chat/utils/qwen-params.ts b/studio/frontend/src/features/chat/utils/qwen-params.ts
index 5a3601984e6..1e3fffffe8e 100644
--- a/studio/frontend/src/features/chat/utils/qwen-params.ts
+++ b/studio/frontend/src/features/chat/utils/qwen-params.ts
@@ -2,34 +2,10 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { useChatRuntimeStore } from "../stores/chat-runtime-store";
-
-export type QwenThinkingParams = {
- temperature: number;
- topP: number;
- topK: number;
- minP: number;
- presencePenalty?: number;
-};
-
-/** Resolve the sampling table shared by model load and the Think toggle. */
-export function resolveQwenThinkingParams(
- checkpoint: string,
- thinkingOn: boolean,
-): QwenThinkingParams | null {
- const normalized = checkpoint.toLowerCase();
- if (!normalized.includes("qwen3")) {
- return null;
- }
-
- const needsPresencePenalty =
- normalized.includes("qwen3.5") ||
- normalized.includes("qwen3.6") ||
- normalized.includes("qwen3.8");
- const base = thinkingOn
- ? { temperature: 0.6, topP: 0.95, topK: 20, minP: 0.0 }
- : { temperature: 0.7, topP: 0.8, topK: 20, minP: 0.0 };
- return needsPresencePenalty ? { ...base, presencePenalty: 1.5 } : base;
-}
+// The table itself lives in qwen-sampling-table.ts, free of store imports, so
+// the defaults migration can read it without a resolver -> store -> migration
+// cycle. Import it from there directly rather than through this module.
+import { resolveQwenThinkingParams } from "./qwen-sampling-table";
/**
* Apply Qwen3-family recommended sampling parameters when the Think toggle
diff --git a/studio/frontend/src/features/chat/utils/qwen-sampling-table.ts b/studio/frontend/src/features/chat/utils/qwen-sampling-table.ts
new file mode 100644
index 00000000000..2f1ca437e41
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/qwen-sampling-table.ts
@@ -0,0 +1,75 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * The single Qwen3 sampling table. Kept free of store imports: qwen-params.ts
+ * imports the store, so the table cannot live there without a cycle. Load, the
+ * Think toggle and the migration then agree by construction.
+ */
+
+import { parseExternalModelId } from "../external-providers";
+
+export type QwenThinkingParams = {
+ temperature: number;
+ topP: number;
+ topK: number;
+ minP: number;
+ presencePenalty?: number;
+};
+
+// Boundary-anchored: "Qwen3.80" and "Qwen3.8B" are a future family and a
+// parameter count, and a substring test would bump both. Any non-alphanumeric
+// ends the family, since a path can separate it with a space as readily as "-".
+const PRESENCE_BUMP_QWEN = /(?:^|[^a-z0-9])qwen3\.(?:5|6|8)(?:$|[^a-z0-9])/;
+
+const OLLAMA_MANIFEST_REF_PREFIX = "ollama-manifest:";
+
+/**
+ * normalizeModelIdentity sees this wrapper rather than the percent-encoded path
+ * inside it and folds the path's case with it, so callers compare these exactly:
+ * two manifests differing only by case are two files.
+ */
+export function isOllamaManifestRef(modelId: string): boolean {
+ return modelId.startsWith(OLLAMA_MANIFEST_REF_PREFIX);
+}
+
+/**
+ * The bare model id, with any wrapper removed. Both wrappers percent-encode, so
+ * "Qwen/Qwen3.8-27B" arrives with its slash as `%2F`, leaving an alphanumeric
+ * "f" against the family segment that the boundary match would reject.
+ */
+function bareModelId(checkpoint: string): string {
+ const external = parseExternalModelId(checkpoint)?.modelId;
+ if (external !== undefined) {
+ return external;
+ }
+ // An Ollama row carries its inventory reference into inference status, quoted
+ // with safe='', so every separator arrives as %2F.
+ if (checkpoint.startsWith(OLLAMA_MANIFEST_REF_PREFIX)) {
+ const ref = checkpoint.slice(OLLAMA_MANIFEST_REF_PREFIX.length);
+ try {
+ return decodeURIComponent(ref);
+ } catch {
+ // A malformed escape is not a reason to lose the whole checkpoint.
+ return ref;
+ }
+ }
+ return checkpoint;
+}
+
+/** Resolve the sampling table shared by model load and the Think toggle. */
+export function resolveQwenThinkingParams(
+ checkpoint: string,
+ thinkingOn: boolean,
+): QwenThinkingParams | null {
+ const normalized = bareModelId(checkpoint).toLowerCase();
+ if (!normalized.includes("qwen3")) {
+ return null;
+ }
+
+ const needsPresencePenalty = PRESENCE_BUMP_QWEN.test(normalized);
+ const base = thinkingOn
+ ? { temperature: 0.6, topP: 0.95, topK: 20, minP: 0.0 }
+ : { temperature: 0.7, topP: 0.8, topK: 20, minP: 0.0 };
+ return needsPresencePenalty ? { ...base, presencePenalty: 1.5 } : base;
+}
diff --git a/studio/frontend/src/features/hub/hub-page.tsx b/studio/frontend/src/features/hub/hub-page.tsx
index da6d8693400..ee382baace6 100644
--- a/studio/frontend/src/features/hub/hub-page.tsx
+++ b/studio/frontend/src/features/hub/hub-page.tsx
@@ -499,6 +499,8 @@ export function ModelsPage() {
applyActiveModelStatusToStore(status, {
previousCheckpoint: previous.checkpoint ?? undefined,
previousGgufVariant: previous.ggufVariant,
+ adoptingExistingServerModel:
+ previous.checkpoint === null || previous.checkpoint === "",
});
},
},
diff --git a/studio/frontend/tests/chat-status-refresh-sequencing.test.ts b/studio/frontend/tests/chat-status-refresh-sequencing.test.ts
index 8f1a1457b79..36678df6e49 100644
--- a/studio/frontend/tests/chat-status-refresh-sequencing.test.ts
+++ b/studio/frontend/tests/chat-status-refresh-sequencing.test.ts
@@ -83,3 +83,10 @@ test("the eviction branch is behind the same guard", () => {
const guardAt = SYNC.indexOf("superseded()");
assert.ok(guardAt !== -1 && guardAt < evictionAt);
});
+
+test("normal startup status adoption owns the resident model's globals", () => {
+ assert.match(
+ SYNC,
+ /adoptingExistingServerModel: selectedCheckpoint === ""/,
+ );
+});
diff --git a/studio/frontend/tests/helpers/store-stubs/settings-http.ts b/studio/frontend/tests/helpers/store-stubs/settings-http.ts
index f2ce1267f97..3f248741a4b 100644
--- a/studio/frontend/tests/helpers/store-stubs/settings-http.ts
+++ b/studio/frontend/tests/helpers/store-stubs/settings-http.ts
@@ -6,9 +6,21 @@
export const settingsHttp = {
settings: {} as Record<string, unknown>,
+ /** Optional one-response-per-GET sequence for stale-read race tests. */
+ getResponses: [] as Array<
+ Record<string, unknown> | Promise<Record<string, unknown>>
+ >,
+ gets: 0,
+ beforeConditionalApply: null as (() => void) | null,
+ /** Status for the conditional route, so a backend without it can be modelled. */
+ conditionalStatus: 200,
puts: [] as Record<string, unknown>[],
+ /** One-shot failures for ordinary PUT ordering/retry tests. */
+ putFailures: [] as Array<{ status: number; detail?: unknown }>,
/** Resolve to let a held GET complete. */
release: null as (() => void) | null,
+ /** Hold an ordinary PUT open, so a write can outlast the flush timeout. */
+ putGate: null as Promise<void> | null,
hold(): void {
settingsHttp.gate = new Promise<void>((resolve) => {
settingsHttp.release = resolve;
@@ -17,18 +29,131 @@ export const settingsHttp = {
gate: null as Promise<void> | null,
};
+function matchesExpected(current: unknown, expected: unknown): boolean {
+ if (expected && typeof expected === "object" && !Array.isArray(expected)) {
+ if (!current || typeof current !== "object" || Array.isArray(current)) {
+ return false;
+ }
+ return Object.entries(expected).every(
+ ([key, value]) =>
+ key in current &&
+ matchesExpected((current as Record<string, unknown>)[key], value),
+ );
+ }
+ return Object.is(current, expected);
+}
+
+function pathExists(current: unknown, path: string[]): boolean {
+ let node = current;
+ for (const segment of path) {
+ if (
+ node == null ||
+ typeof node !== "object" ||
+ Array.isArray(node) ||
+ !(segment in node)
+ ) {
+ return false;
+ }
+ node = (node as Record<string, unknown>)[segment];
+ }
+ return true;
+}
+
+function deepMerge(
+ current: Record<string, unknown>,
+ patch: Record<string, unknown>,
+): Record<string, unknown> {
+ const merged = { ...current };
+ for (const [key, value] of Object.entries(patch)) {
+ const existing = merged[key];
+ merged[key] =
+ existing &&
+ typeof existing === "object" &&
+ !Array.isArray(existing) &&
+ value &&
+ typeof value === "object" &&
+ !Array.isArray(value)
+ ? deepMerge(
+ existing as Record<string, unknown>,
+ value as Record<string, unknown>,
+ )
+ : value;
+ }
+ return merged;
+}
+
+function nextPutFailureResponse(): Response | null {
+ const failure = settingsHttp.putFailures.shift();
+ if (!failure) return null;
+ return {
+ ok: false,
+ status: failure.status,
+ json: async () => ({ detail: failure.detail ?? "temporary failure" }),
+ } as Response;
+}
+
export async function authFetch(
- _url: string,
+ url: string,
init?: { method?: string; body?: string },
): Promise<Response> {
- if (init?.method === "PUT") {
+ let responseSettings = settingsHttp.settings;
+ let applied: boolean | undefined;
+ if (url.endsWith("/compare-and-set") && init?.method === "POST") {
+ if (settingsHttp.conditionalStatus !== 200) {
+ return {
+ ok: false,
+ status: settingsHttp.conditionalStatus,
+ json: async () => ({
+ detail:
+ settingsHttp.conditionalStatus === 405
+ ? "Method Not Allowed"
+ : "Not Found",
+ }),
+ } as Response;
+ }
+ const request = JSON.parse(init.body ?? "{}") as {
+ expected: Record<string, unknown>;
+ expectedAbsent?: string[];
+ expectedAbsentPaths?: string[][];
+ patch: Record<string, unknown>;
+ };
+ settingsHttp.beforeConditionalApply?.();
+ settingsHttp.beforeConditionalApply = null;
+ responseSettings = settingsHttp.settings;
+ applied =
+ (request.expectedAbsent ?? []).every(
+ (key) => !(key in settingsHttp.settings),
+ ) &&
+ (request.expectedAbsentPaths ?? []).every(
+ (path) => !pathExists(settingsHttp.settings, path),
+ ) &&
+ matchesExpected(settingsHttp.settings, request.expected);
+ if (applied) {
+ settingsHttp.puts.push(request.patch);
+ settingsHttp.settings = deepMerge(settingsHttp.settings, request.patch);
+ responseSettings = settingsHttp.settings;
+ }
+ } else if (init?.method === "PUT") {
settingsHttp.puts.push(JSON.parse(init.body ?? "{}"));
- } else if (settingsHttp.gate) {
- await settingsHttp.gate;
+ if (settingsHttp.putGate) await settingsHttp.putGate;
+ const failureResponse = nextPutFailureResponse();
+ if (failureResponse) return failureResponse;
+ } else {
+ if (settingsHttp.gate) {
+ await settingsHttp.gate;
+ }
+ settingsHttp.gets += 1;
+ if (settingsHttp.getResponses.length > 0) {
+ responseSettings = await (settingsHttp.getResponses.shift() ??
+ settingsHttp.settings);
+ }
}
return {
ok: true,
status: 200,
- json: async () => ({ settings: settingsHttp.settings }),
+ json: async () => ({
+ settings: responseSettings,
+ ...(applied !== undefined ? { applied } : {}),
+ }),
} as Response;
}
diff --git a/studio/frontend/tests/mirrored-settings-write-authority.test.ts b/studio/frontend/tests/mirrored-settings-write-authority.test.ts
index 525ddb620a3..dfec781a973 100644
--- a/studio/frontend/tests/mirrored-settings-write-authority.test.ts
+++ b/studio/frontend/tests/mirrored-settings-write-authority.test.ts
@@ -87,13 +87,14 @@ test("hydration backfills only from an authoritative read", () => {
"hydratePersistedSettings: async () => {",
"\n beginModelLoading:",
);
+ // Extra destructured fields are fine; fromServer is the one that gates backfill.
assert.match(
hydrate,
- /const \{ settings, fromServer \} = await loadChatSettingsWithLegacyImport\(\);/,
+ /const \{[\s\S]*?\bsettings,[\s\S]*?\bfromServer,?[\s\S]*?\} = await loadChatSettingsWithLegacyImport\(\);/,
);
assert.match(
hydrate,
- /if \(fromServer\) backfillMirroredSettings\(settings\);/,
+ /if \(fromServer\) backfillMirroredSettings\(hydratedSettings\);/,
);
// An ungated call is the bug: a failed GET would push this browser's stale values.
assert.doesNotMatch(hydrate, /\n\s*backfillMirroredSettings\(settings\);/);
@@ -130,7 +131,7 @@ test("only the legacy-storage fallback is non-authoritative", () => {
// ...and it is the branch that never saw a server answer.
assert.match(
slice(loader, "} catch (error) {", "\n const legacySettings"),
- /return \{ settings: legacySettings, fromServer: false \};/,
+ /return \{ settings: legacySettings, fromServer: false,[^}]*\};/,
);
// Every other exit reports an answered GET, so absence stays meaningful.
assert.ok((loader.match(/fromServer: true/g) ?? []).length >= 4);
diff --git a/studio/frontend/tests/per-model-params-hydration.test.ts b/studio/frontend/tests/per-model-params-hydration.test.ts
index fab48a3c29f..07588d35b31 100644
--- a/studio/frontend/tests/per-model-params-hydration.test.ts
+++ b/studio/frontend/tests/per-model-params-hydration.test.ts
@@ -43,7 +43,10 @@ const STATUS = {
} as never;
/** applyActiveModelStatusToStore's update, which the last test pins. */
-function applyStatus(modelId: string) {
+function applyStatus(
+ modelId: string,
+ { adoptingExistingServerModel = false } = {},
+) {
const store = useChatRuntimeStore.getState();
store.setParams(
mergeBackendRecommendedInference({
@@ -53,7 +56,10 @@ function applyStatus(modelId: string) {
presetSource: store.activePresetSource,
loadedContextLength: STATUS_CONTEXT_LENGTH,
}),
- { fromModelDefaults: true },
+ {
+ fromModelDefaults: true,
+ migrateOwnedGlobalQwenDefaults: adoptingExistingServerModel,
+ },
);
}
@@ -310,7 +316,7 @@ test("the resident model keeps the settings saved for it", async () => {
});
const hydrating = useChatRuntimeStore.getState().hydratePersistedSettings();
- applyStatus(QWEN);
+ applyStatus(QWEN, { adoptingExistingServerModel: true });
settingsHttp.release?.();
await hydrating;
diff --git a/studio/frontend/tests/qwen-defaults-migration-hydration.test.ts b/studio/frontend/tests/qwen-defaults-migration-hydration.test.ts
new file mode 100644
index 00000000000..508e131188a
--- /dev/null
+++ b/studio/frontend/tests/qwen-defaults-migration-hydration.test.ts
@@ -0,0 +1,1217 @@
+// 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 { register } from "node:module";
+import test from "node:test";
+
+import { installLocalStorageFake } from "./helpers/kit.ts";
+
+const { store: localStorageFake } = installLocalStorageFake();
+localStorageFake.set("unsloth_chat_settings_imported_to_studio_db", "true");
+register("./store-settings-resolver.mjs", import.meta.url);
+
+const { settingsHttp } = await import("./helpers/store-stubs/settings-http.ts");
+const {
+ flushPendingChatSettings,
+ noteLoadedModelReasoningMode,
+ useChatRuntimeStore,
+} = await import(
+ "../src/features/chat/stores/chat-runtime-store.ts"
+);
+
+const QWEN38 = "unsloth/Qwen3.8-27B-GGUF";
+const LEGACY_SNAPSHOT = {
+ temperature: 0.6,
+ topP: 0.95,
+ topK: 20,
+ minP: 0.01,
+ repetitionPenalty: 1.0,
+ presencePenalty: 0.0,
+ maxTokens: 8192,
+ systemPrompt: "",
+ systemVariables: "",
+ fastMode: false,
+};
+
+test("hydration replaces and persists the stale Qwen3.8 default snapshot", async () => {
+ settingsHttp.settings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParams: {
+ temperature: 0.6,
+ topP: 0.95,
+ minP: 0.01,
+ presencePenalty: 0.0,
+ maxTokens: 8192,
+ },
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ };
+ settingsHttp.puts.length = 0;
+ useChatRuntimeStore.setState((state) => ({
+ params: {
+ ...state.params,
+ checkpoint: QWEN38,
+ minP: 0,
+ presencePenalty: 1.5,
+ },
+ paramsByModel: {},
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ settingsHydrated: false,
+ }));
+
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ const hydrated = useChatRuntimeStore.getState();
+ assert.equal(hydrated.params.minP, 0);
+ assert.equal(hydrated.params.presencePenalty, 1.5);
+ assert.equal(hydrated.paramsByModel[QWEN38]?.minP, 0);
+ assert.equal(hydrated.paramsByModel[QWEN38]?.presencePenalty, 1.5);
+
+ await new Promise((resolve) => setTimeout(resolve, 600));
+ const migrationPut = settingsHttp.puts.find(
+ (put) =>
+ (put.inferenceParamsByModel as Record<string, unknown> | undefined)?.[
+ QWEN38
+ ] !== undefined,
+ );
+ assert.deepEqual(migrationPut, {
+ inferenceParamsByModel: {
+ [QWEN38]: { minP: 0, presencePenalty: 1.5 },
+ },
+ });
+});
+
+test("active-model adoption retries a migration deferred during hydration", async () => {
+ settingsHttp.getResponses.length = 0;
+ settingsHttp.settings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParams: {
+ temperature: 0.6,
+ topP: 0.95,
+ minP: 0.01,
+ presencePenalty: 0,
+ maxTokens: 8192,
+ },
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ };
+ settingsHttp.puts.length = 0;
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, checkpoint: "" },
+ paramsByModel: {},
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: false,
+ }));
+
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+ assert.equal(
+ useChatRuntimeStore.getState().paramsByModel[QWEN38]?.presencePenalty,
+ 0,
+ );
+
+ useChatRuntimeStore.getState().setCheckpoint(QWEN38);
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ {
+ ...active.params,
+ checkpoint: QWEN38,
+ minP: 0,
+ presencePenalty: 1.5,
+ },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ const migrated = useChatRuntimeStore.getState();
+ assert.equal(migrated.paramsByModel[QWEN38]?.minP, 0);
+ assert.equal(migrated.paramsByModel[QWEN38]?.presencePenalty, 1.5);
+ assert.equal(
+ settingsHttp.puts.some((put) => put.inferenceParams !== undefined),
+ false,
+ );
+ assert.equal(
+ settingsHttp.puts.some(
+ (put) =>
+ (put.inferenceParamsByModel as Record<string, unknown> | undefined)?.[
+ QWEN38
+ ] !== undefined,
+ ),
+ true,
+ );
+});
+
+test("hydration upgrades a global-only non-thinking installation", async () => {
+ settingsHttp.getResponses.length = 0;
+ settingsHttp.settings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ reasoningEnabled: false,
+ inferenceParams: {
+ temperature: 0.6,
+ topP: 0.95,
+ minP: 0.01,
+ presencePenalty: 0.0,
+ maxTokens: 8192,
+ },
+ };
+ settingsHttp.puts.length = 0;
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, checkpoint: QWEN38 },
+ paramsByModel: {},
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningEnabled: true,
+ settingsHydrated: false,
+ }));
+
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ const hydrated = useChatRuntimeStore.getState();
+ assert.equal(hydrated.params.temperature, 0.7);
+ assert.equal(hydrated.params.topP, 0.8);
+ assert.equal(hydrated.params.minP, 0);
+ assert.equal(hydrated.params.presencePenalty, 1.5);
+ assert.deepEqual(
+ settingsHttp.puts.find((put) => put.inferenceParams !== undefined),
+ {
+ inferenceParams: {
+ temperature: 0.7,
+ topP: 0.8,
+ minP: 0,
+ presencePenalty: 1.5,
+ },
+ },
+ );
+});
+
+test("a confirming read preserves a newer edit from another tab", async () => {
+ const newerSnapshot = {
+ ...LEGACY_SNAPSHOT,
+ presencePenalty: 0.4,
+ };
+ const legacySettings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParams: {
+ temperature: 0.6,
+ topP: 0.95,
+ minP: 0.01,
+ presencePenalty: 0.0,
+ maxTokens: 8192,
+ },
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ };
+ const newerSettings = {
+ ...legacySettings,
+ inferenceParamsByModel: { [QWEN38]: newerSnapshot },
+ };
+ settingsHttp.settings = newerSettings;
+ settingsHttp.getResponses = [legacySettings, newerSettings];
+ settingsHttp.puts.length = 0;
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, checkpoint: QWEN38 },
+ paramsByModel: {},
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ settingsHydrated: false,
+ }));
+
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ assert.equal(
+ useChatRuntimeStore.getState().paramsByModel[QWEN38]?.presencePenalty,
+ 0.4,
+ );
+ assert.equal(
+ settingsHttp.puts.some(
+ (put) =>
+ (put.inferenceParamsByModel as Record<string, unknown> | undefined)?.[
+ QWEN38
+ ] !== undefined,
+ ),
+ false,
+ );
+});
+
+test("atomic migration persistence rejects an edit after confirmation", async () => {
+ const legacySettings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ };
+ const newerSettings = {
+ ...legacySettings,
+ inferenceParamsByModel: {
+ [QWEN38]: { ...LEGACY_SNAPSHOT, presencePenalty: 0.4 },
+ },
+ };
+ settingsHttp.settings = legacySettings;
+ settingsHttp.getResponses = [legacySettings, legacySettings];
+ settingsHttp.puts.length = 0;
+ settingsHttp.beforeConditionalApply = () => {
+ settingsHttp.settings = newerSettings;
+ };
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, checkpoint: QWEN38 },
+ paramsByModel: {},
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ settingsHydrated: false,
+ }));
+
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ assert.equal(
+ useChatRuntimeStore.getState().paramsByModel[QWEN38]?.presencePenalty,
+ 0.4,
+ );
+ assert.equal(settingsHttp.puts.length, 0);
+});
+
+test("a confirming read uses the latest reasoning mode", async () => {
+ const thinkingSettings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ reasoningEnabled: true,
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ };
+ const nonThinkingSettings = {
+ ...thinkingSettings,
+ reasoningEnabled: false,
+ };
+ settingsHttp.settings = nonThinkingSettings;
+ settingsHttp.getResponses = [thinkingSettings, nonThinkingSettings];
+ settingsHttp.puts.length = 0;
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, checkpoint: QWEN38 },
+ paramsByModel: {},
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: false,
+ }));
+
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ const hydrated = useChatRuntimeStore.getState();
+ assert.equal(hydrated.reasoningEnabled, false);
+ assert.equal(hydrated.params.temperature, 0.7);
+ assert.equal(hydrated.params.topP, 0.8);
+ assert.deepEqual(
+ settingsHttp.puts.find(
+ (put) =>
+ (put.inferenceParamsByModel as Record<string, unknown> | undefined)?.[
+ QWEN38
+ ] !== undefined,
+ ),
+ {
+ inferenceParamsByModel: {
+ [QWEN38]: {
+ temperature: 0.7,
+ topP: 0.8,
+ minP: 0,
+ presencePenalty: 1.5,
+ },
+ },
+ },
+ );
+});
+
+test("returning from a custom preset retries the guarded migration", async () => {
+ settingsHttp.getResponses.length = 0;
+ settingsHttp.settings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParams: {
+ temperature: 0.6,
+ topP: 0.95,
+ minP: 0.01,
+ presencePenalty: 0.0,
+ maxTokens: 8192,
+ },
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ };
+ settingsHttp.puts.length = 0;
+ useChatRuntimeStore.setState((state) => ({
+ params: {
+ ...state.params,
+ checkpoint: QWEN38,
+ temperature: 0.6,
+ topP: 0.95,
+ minP: 0.01,
+ presencePenalty: 0,
+ },
+ paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ activePreset: "Creative",
+ activePresetSource: "custom",
+ reasoningEnabled: true,
+ settingsHydrated: true,
+ }));
+
+ useChatRuntimeStore.getState().setActivePreset("Default");
+ useChatRuntimeStore.getState().setActivePresetSource("builtin-default");
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ const state = useChatRuntimeStore.getState();
+ assert.equal(state.params.minP, 0);
+ assert.equal(state.params.presencePenalty, 1.5);
+ assert.equal(state.paramsByModel[QWEN38]?.presencePenalty, 1.5);
+ assert.equal(
+ settingsHttp.puts.some(
+ (put) =>
+ (put.inferenceParamsByModel as Record<string, unknown> | undefined)?.[
+ QWEN38
+ ] !== undefined,
+ ),
+ true,
+ );
+});
+
+test("restoring the final modified field retries after the parameter edit", async () => {
+ const modifiedSnapshot = {
+ ...LEGACY_SNAPSHOT,
+ presencePenalty: 0.4,
+ };
+ settingsHttp.getResponses.length = 0;
+ settingsHttp.settings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ };
+ settingsHttp.puts.length = 0;
+ useChatRuntimeStore.setState((state) => ({
+ params: {
+ ...state.params,
+ ...modifiedSnapshot,
+ checkpoint: QWEN38,
+ },
+ paramsByModel: { [QWEN38]: modifiedSnapshot },
+ activePreset: "Default",
+ activePresetSource: "modified",
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: true,
+ }));
+
+ useChatRuntimeStore.getState().setActivePresetSource("builtin-default");
+ useChatRuntimeStore.getState().setParams({
+ ...useChatRuntimeStore.getState().params,
+ presencePenalty: 0,
+ });
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ const state = useChatRuntimeStore.getState();
+ assert.equal(state.params.minP, 0);
+ assert.equal(state.params.presencePenalty, 1.5);
+ assert.equal(state.paramsByModel[QWEN38]?.presencePenalty, 1.5);
+ assert.equal(
+ settingsHttp.puts.some(
+ (put) =>
+ (put.inferenceParamsByModel as Record<string, unknown> | undefined)?.[
+ QWEN38
+ ] !== undefined,
+ ),
+ true,
+ );
+});
+
+test("a model switch during the confirming read leaves the former row untouched", async () => {
+ const legacySettings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ };
+ let releaseConfirmation!: (value: Record<string, unknown>) => void;
+ const confirmation = new Promise<Record<string, unknown>>((resolve) => {
+ releaseConfirmation = resolve;
+ });
+ settingsHttp.settings = legacySettings;
+ settingsHttp.getResponses = [legacySettings, confirmation];
+ settingsHttp.gets = 0;
+ settingsHttp.puts.length = 0;
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, checkpoint: QWEN38 },
+ paramsByModel: {},
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: false,
+ }));
+
+ const hydration = useChatRuntimeStore.getState().hydratePersistedSettings();
+ while (settingsHttp.gets < 2) {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ }
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, checkpoint: "unsloth/Qwen3.6-9B-GGUF" },
+ reasoningEnabled: false,
+ }));
+ releaseConfirmation(legacySettings);
+ await hydration;
+
+ assert.equal(
+ useChatRuntimeStore.getState().paramsByModel[QWEN38]?.presencePenalty,
+ 0,
+ );
+ assert.equal(
+ settingsHttp.puts.some(
+ (put) =>
+ (put.inferenceParamsByModel as Record<string, unknown> | undefined)?.[
+ QWEN38
+ ] !== undefined,
+ ),
+ false,
+ );
+});
+
+test("resident-model adoption migrates a deferred global-only snapshot", async () => {
+ settingsHttp.getResponses.length = 0;
+ settingsHttp.settings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParams: {
+ temperature: 0.6,
+ topP: 0.95,
+ minP: 0.01,
+ presencePenalty: 0,
+ maxTokens: 8192,
+ },
+ };
+ settingsHttp.puts.length = 0;
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: {},
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: true,
+ }));
+
+ const state = useChatRuntimeStore.getState();
+ state.setParams(
+ { ...state.params, minP: 0, presencePenalty: 1.5 },
+ {
+ fromModelDefaults: true,
+ migrateOwnedGlobalQwenDefaults: true,
+ },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ const globalPut = settingsHttp.puts.find(
+ (put) => put.inferenceParams !== undefined,
+ );
+ assert.deepEqual(globalPut?.inferenceParams, {
+ minP: 0,
+ presencePenalty: 1.5,
+ });
+});
+
+test("resident-model adoption does not claim a global beside model memory", async () => {
+ settingsHttp.getResponses.length = 0;
+ settingsHttp.settings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParams: {
+ temperature: 0.6,
+ topP: 0.95,
+ minP: 0.01,
+ presencePenalty: 0,
+ maxTokens: 8192,
+ },
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ };
+ settingsHttp.puts.length = 0;
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: true,
+ }));
+
+ const state = useChatRuntimeStore.getState();
+ state.setParams(
+ { ...state.params, minP: 0, presencePenalty: 1.5 },
+ {
+ fromModelDefaults: true,
+ migrateOwnedGlobalQwenDefaults: true,
+ },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ const persisted = settingsHttp.settings as {
+ inferenceParams?: { minP?: number; presencePenalty?: number };
+ inferenceParamsByModel?: Record<
+ string,
+ { presencePenalty?: number }
+ >;
+ };
+ assert.equal(persisted.inferenceParams?.minP, 0.01);
+ assert.equal(persisted.inferenceParams?.presencePenalty, 0);
+ assert.equal(
+ persisted.inferenceParamsByModel?.[QWEN38]?.presencePenalty,
+ 1.5,
+ );
+});
+
+test("a retry cannot overwrite an edit made after its confirming read", async () => {
+ const legacySettings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ };
+ settingsHttp.getResponses.length = 0;
+ settingsHttp.settings = legacySettings;
+ settingsHttp.puts.length = 0;
+ settingsHttp.beforeConditionalApply = () => {
+ settingsHttp.settings = {
+ ...legacySettings,
+ inferenceParamsByModel: {
+ [QWEN38]: { ...LEGACY_SNAPSHOT, presencePenalty: 0.4 },
+ },
+ };
+ };
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: true,
+ }));
+
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ { ...active.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ assert.equal(settingsHttp.puts.length, 0);
+ assert.equal(
+ (
+ settingsHttp.settings.inferenceParamsByModel as Record<
+ string,
+ Record<string, unknown>
+ >
+ )[QWEN38].presencePenalty,
+ 0.4,
+ );
+});
+
+test("a retry revalidates the checkpoint after its confirming read", async () => {
+ const legacySettings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ };
+ let releaseConfirmation!: (value: Record<string, unknown>) => void;
+ const confirmation = new Promise<Record<string, unknown>>((resolve) => {
+ releaseConfirmation = resolve;
+ });
+ settingsHttp.settings = legacySettings;
+ settingsHttp.getResponses = [confirmation];
+ settingsHttp.gets = 0;
+ settingsHttp.puts.length = 0;
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: true,
+ }));
+
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ { ...active.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ while (settingsHttp.gets < 1) {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ }
+ useChatRuntimeStore.setState((state) => ({
+ params: {
+ ...state.params,
+ checkpoint: "unsloth/Qwen3.6-9B-GGUF",
+ },
+ reasoningEnabled: false,
+ }));
+ releaseConfirmation(legacySettings);
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ assert.equal(settingsHttp.puts.length, 0);
+ assert.equal(
+ (
+ settingsHttp.settings.inferenceParamsByModel as Record<
+ string,
+ Record<string, unknown>
+ >
+ )[QWEN38].presencePenalty,
+ 0,
+ );
+});
+
+test("a retry fences reasoning added after a confirming read", async () => {
+ const legacySettings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ };
+ settingsHttp.getResponses.length = 0;
+ settingsHttp.settings = legacySettings;
+ settingsHttp.puts.length = 0;
+ settingsHttp.beforeConditionalApply = () => {
+ settingsHttp.settings = { ...legacySettings, reasoningEnabled: false };
+ };
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: true,
+ }));
+
+ const state = useChatRuntimeStore.getState();
+ state.setParams(
+ { ...state.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ assert.equal(settingsHttp.puts.length, 0);
+ assert.equal(settingsHttp.settings.reasoningEnabled, false);
+ assert.equal(
+ (
+ settingsHttp.settings.inferenceParamsByModel as Record<
+ string,
+ Record<string, unknown>
+ >
+ )[QWEN38].presencePenalty,
+ 0,
+ );
+});
+
+test("deferred global ownership cannot follow a later checkpoint", async () => {
+ settingsHttp.getResponses.length = 0;
+ settingsHttp.settings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParams: {
+ temperature: 0.6,
+ topP: 0.95,
+ minP: 0.01,
+ presencePenalty: 0,
+ maxTokens: 8192,
+ },
+ };
+ settingsHttp.puts.length = 0;
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: {},
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: true,
+ }));
+
+ const state = useChatRuntimeStore.getState();
+ state.setParams(
+ { ...state.params, minP: 0, presencePenalty: 1.5 },
+ {
+ fromModelDefaults: true,
+ migrateOwnedGlobalQwenDefaults: true,
+ },
+ );
+ useChatRuntimeStore.setState((current) => ({
+ params: {
+ ...current.params,
+ checkpoint: "unsloth/Qwen3.6-9B-GGUF",
+ },
+ reasoningEnabled: false,
+ }));
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ const persisted = settingsHttp.settings as {
+ inferenceParams?: { presencePenalty?: number; minP?: number };
+ };
+ assert.equal(persisted.inferenceParams?.presencePenalty, 0);
+ assert.equal(persisted.inferenceParams?.minP, 0.01);
+});
+
+test("local migration preserves an active thread's sampling override", async () => {
+ settingsHttp.getResponses.length = 0;
+ settingsHttp.settings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ };
+ settingsHttp.puts.length = 0;
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: true,
+ }));
+ const initial = useChatRuntimeStore.getState();
+ initial.setActiveThreadId("thread-with-sampling");
+ initial.applyThreadScopedSettings("thread-with-sampling", {
+ presencePenalty: 0,
+ reasoningEnabled: false,
+ });
+
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ { ...active.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ const migrated = useChatRuntimeStore.getState();
+ assert.equal(migrated.params.presencePenalty, 0);
+ assert.equal(migrated.paramsByModel[QWEN38]?.presencePenalty, 1.5);
+ assert.equal(migrated.paramsByModel[QWEN38]?.temperature, 0.6);
+ assert.equal(migrated.paramsByModel[QWEN38]?.topP, 0.95);
+ migrated.applyThreadScopedSettings(null, {});
+ assert.equal(useChatRuntimeStore.getState().params.minP, 0);
+ assert.equal(useChatRuntimeStore.getState().params.presencePenalty, 1.5);
+ migrated.setActiveThreadId(null);
+});
+
+test("hydration migrates the authoritative global when model memory is off", async () => {
+ settingsHttp.getResponses.length = 0;
+ settingsHttp.settings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: false,
+ inferenceParams: {
+ temperature: 0.6,
+ topP: 0.95,
+ minP: 0.01,
+ presencePenalty: 0,
+ maxTokens: 8192,
+ },
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ };
+ settingsHttp.puts.length = 0;
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, checkpoint: QWEN38 },
+ paramsByModel: {},
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: false,
+ }));
+
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ const hydrated = useChatRuntimeStore.getState();
+ assert.equal(hydrated.rememberParamsPerModel, false);
+ assert.equal(hydrated.params.minP, 0);
+ assert.equal(hydrated.params.presencePenalty, 1.5);
+ assert.deepEqual(
+ settingsHttp.puts.find(
+ (put) =>
+ put.inferenceParams !== undefined &&
+ put.inferenceParamsByModel !== undefined,
+ ),
+ {
+ inferenceParamsByModel: {
+ [QWEN38]: { minP: 0, presencePenalty: 1.5 },
+ },
+ inferenceParams: { minP: 0, presencePenalty: 1.5 },
+ },
+ );
+});
+
+test("a first user model load during hydration does not claim prior globals", async () => {
+ settingsHttp.getResponses.length = 0;
+ settingsHttp.settings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ inferenceParams: {
+ temperature: 0.6,
+ topP: 0.95,
+ minP: 0.01,
+ presencePenalty: 0,
+ maxTokens: 8192,
+ },
+ };
+ settingsHttp.puts.length = 0;
+ settingsHttp.hold();
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, checkpoint: "" },
+ paramsByModel: {},
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: false,
+ }));
+
+ const hydration = useChatRuntimeStore.getState().hydratePersistedSettings();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ const loading = useChatRuntimeStore.getState();
+ loading.setParams(
+ {
+ ...loading.params,
+ checkpoint: QWEN38,
+ minP: 0,
+ presencePenalty: 1.5,
+ },
+ { fromModelDefaults: true },
+ );
+ settingsHttp.release?.();
+ await hydration;
+ settingsHttp.gate = null;
+ settingsHttp.release = null;
+
+ const hydrated = useChatRuntimeStore.getState();
+ assert.equal(hydrated.params.minP, 0);
+ assert.equal(hydrated.params.presencePenalty, 1.5);
+ assert.equal(
+ settingsHttp.puts.some((put) => put.inferenceParams !== undefined),
+ false,
+ );
+});
+
+test("a normalized migration patch stays within the loaded context", async () => {
+ const lowerCaseKey = QWEN38.toLowerCase();
+ settingsHttp.getResponses.length = 0;
+ settingsHttp.settings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParamsByModel: { [lowerCaseKey]: LEGACY_SNAPSHOT },
+ };
+ settingsHttp.puts.length = 0;
+ useChatRuntimeStore.setState((state) => ({
+ params: {
+ ...state.params,
+ ...LEGACY_SNAPSHOT,
+ checkpoint: QWEN38,
+ maxTokens: 4096,
+ },
+ paramsByModel: { [lowerCaseKey]: LEGACY_SNAPSHOT },
+ loadedContextLength: 4096,
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: true,
+ }));
+
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ { ...active.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ const migrated = useChatRuntimeStore.getState();
+ assert.equal(migrated.params.maxTokens, 4096);
+ assert.equal(migrated.paramsByModel[QWEN38]?.presencePenalty, 1.5);
+});
+
+test("deferred adoption migrates the authoritative global when memory is off", async () => {
+ settingsHttp.getResponses.length = 0;
+ settingsHttp.settings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: false,
+ inferenceParams: {
+ temperature: 0.6,
+ topP: 0.95,
+ minP: 0.01,
+ presencePenalty: 0,
+ maxTokens: 8192,
+ },
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ };
+ settingsHttp.puts.length = 0;
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, checkpoint: "" },
+ paramsByModel: {},
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: false,
+ }));
+
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+ const adopting = useChatRuntimeStore.getState();
+ adopting.setParams(
+ {
+ ...adopting.params,
+ checkpoint: QWEN38,
+ minP: 0,
+ presencePenalty: 1.5,
+ },
+ {
+ fromModelDefaults: true,
+ migrateOwnedGlobalQwenDefaults: true,
+ },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ const globalPatch = settingsHttp.puts.find(
+ (put) => put.inferenceParams !== undefined,
+ );
+ assert.deepEqual(globalPatch?.inferenceParams, {
+ minP: 0,
+ presencePenalty: 1.5,
+ });
+});
+
+test("a retry fences optional global fields added after confirmation", async () => {
+ await flushPendingChatSettings();
+ const legacySettings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParams: {
+ temperature: 0.6,
+ topP: 0.95,
+ minP: 0.01,
+ presencePenalty: 0,
+ maxTokens: 8192,
+ },
+ };
+ settingsHttp.getResponses.length = 0;
+ settingsHttp.settings = legacySettings;
+ settingsHttp.puts.length = 0;
+ settingsHttp.beforeConditionalApply = () => {
+ settingsHttp.settings = {
+ ...legacySettings,
+ inferenceParams: { ...legacySettings.inferenceParams, topK: 40 },
+ };
+ };
+ useChatRuntimeStore.setState((state) => ({
+ params: {
+ ...state.params,
+ ...LEGACY_SNAPSHOT,
+ checkpoint: QWEN38,
+ minP: 0,
+ presencePenalty: 1.5,
+ },
+ paramsByModel: {},
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: true,
+ }));
+
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ { ...active.params, minP: 0, presencePenalty: 1.5 },
+ {
+ fromModelDefaults: true,
+ migrateOwnedGlobalQwenDefaults: true,
+ },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ assert.equal(settingsHttp.puts.length, 0);
+ assert.equal(
+ (
+ settingsHttp.settings.inferenceParams as Record<string, unknown>
+ ).topK,
+ 40,
+ );
+ assert.equal(
+ (
+ settingsHttp.settings.inferenceParams as Record<string, unknown>
+ ).presencePenalty,
+ 0,
+ );
+});
+
+test("migration follows the reasoning mode established by the loaded model", async () => {
+ settingsHttp.getResponses.length = 0;
+ settingsHttp.settings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ reasoningEnabled: true,
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ };
+ settingsHttp.puts.length = 0;
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ supportsReasoning: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: false,
+ settingsHydrated: true,
+ }));
+ // An actual load, as the test name says: a status refresh only echoes the
+ // toggle already in the store and must not outrank the persisted one.
+ noteLoadedModelReasoningMode(QWEN38, false, true);
+
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ {
+ ...active.params,
+ temperature: 0.7,
+ topP: 0.8,
+ minP: 0,
+ presencePenalty: 1.5,
+ },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ assert.deepEqual(
+ settingsHttp.puts.find(
+ (put) => put.inferenceParamsByModel !== undefined,
+ )?.inferenceParamsByModel,
+ {
+ [QWEN38]: {
+ temperature: 0.7,
+ topP: 0.8,
+ minP: 0,
+ presencePenalty: 1.5,
+ },
+ },
+ );
+ noteLoadedModelReasoningMode(QWEN38, true);
+});
+
+test("routine model-default refreshes skip migration reads without a candidate", async () => {
+ settingsHttp.getResponses.length = 0;
+ settingsHttp.gets = 0;
+ settingsHttp.puts.length = 0;
+ settingsHttp.settings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ };
+ useChatRuntimeStore.setState((state) => ({
+ params: {
+ ...state.params,
+ checkpoint: QWEN38,
+ temperature: 0.6,
+ topP: 0.95,
+ topK: 20,
+ minP: 0,
+ repetitionPenalty: 1,
+ presencePenalty: 1.5,
+ },
+ paramsByModel: {},
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ settingsHydrated: true,
+ }));
+
+ const qwen = useChatRuntimeStore.getState();
+ qwen.setParams({ ...qwen.params }, { fromModelDefaults: true });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ assert.equal(settingsHttp.gets, 0);
+
+ const llamaCheckpoint = "unsloth/Llama-3.2-3B-Instruct-GGUF";
+ const current = useChatRuntimeStore.getState();
+ current.setParams(
+ { ...current.params, checkpoint: llamaCheckpoint },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ assert.equal(settingsHttp.gets, 0);
+});
+
+// A transient PUT failure must not wedge the migration permanently. Ordering
+// against an undrained write is deliberately not a guarantee: the confirming
+// GET reads whatever the server actually holds, and the compare-and-set is what
+// keeps a decision made from a stale read from landing. See "a preset modified
+// during hydration is not migrated on a stale read".
+test("a failed settings write does not strand the migration", async () => {
+ await flushPendingChatSettings();
+ settingsHttp.getResponses.length = 0;
+ settingsHttp.gets = 0;
+ settingsHttp.puts.length = 0;
+ settingsHttp.putFailures = [{ status: 503 }];
+ settingsHttp.settings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ };
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ activePreset: "Default",
+ activePresetSource: "custom",
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: true,
+ }));
+
+ useChatRuntimeStore.getState().setActivePresetSource("builtin-default");
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ const migrationReached = (): boolean =>
+ settingsHttp.puts.some(
+ (put) =>
+ (put.inferenceParamsByModel as Record<string, unknown> | undefined)?.[
+ QWEN38
+ ] !== undefined,
+ );
+
+ // The 503 leaves the older patch requeued. Reaching the backend merge after
+ // the CAS would restore the legacy row, so the migration has to be the last
+ // write, not merely a write that eventually happens.
+ const putKeys = settingsHttp.puts.map((put) => Object.keys(put).join(","));
+ const migrationIndex = putKeys.findIndex((keys) =>
+ keys.includes("inferenceParamsByModel"),
+ );
+ const lastOrdinary = putKeys.reduce(
+ (last, keys, index) =>
+ keys.includes("inferenceParamsByModel") ? last : index,
+ -1,
+ );
+ assert.ok(migrationIndex > lastOrdinary, "migrated behind an undrained write");
+
+ // Nor stranded: the requeued write settling rearms it in the same pass.
+ settingsHttp.putFailures = [];
+ await flushPendingChatSettings();
+ const qwen = useChatRuntimeStore.getState();
+ qwen.setParams({ ...qwen.params }, { fromModelDefaults: true });
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ assert.equal(migrationReached(), true, "the retry never landed");
+});
diff --git a/studio/frontend/tests/qwen-defaults-migration-safety.test.ts b/studio/frontend/tests/qwen-defaults-migration-safety.test.ts
new file mode 100644
index 00000000000..7974320add6
--- /dev/null
+++ b/studio/frontend/tests/qwen-defaults-migration-safety.test.ts
@@ -0,0 +1,1162 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The migration must never leave this tab showing sampling the server does not
+// have. Each test here failed before the fix it guards.
+
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+import { installLocalStorageFake } from "./helpers/kit.ts";
+
+const { store: localStorageFake } = installLocalStorageFake();
+localStorageFake.set("unsloth_chat_settings_imported_to_studio_db", "true");
+register("./store-settings-resolver.mjs", import.meta.url);
+
+const { settingsHttp } = await import("./helpers/store-stubs/settings-http.ts");
+const {
+ awaitPendingQwenDefaultsMigration,
+ noteLoadedModelReasoningMode,
+ useChatRuntimeStore,
+} = await import(
+ "../src/features/chat/stores/chat-runtime-store.ts"
+);
+
+const QWEN38 = "unsloth/Qwen3.8-27B-GGUF";
+const LEGACY_SNAPSHOT = {
+ temperature: 0.6,
+ topP: 0.95,
+ topK: 20,
+ minP: 0.01,
+ repetitionPenalty: 1.0,
+ presencePenalty: 0.0,
+ maxTokens: 8192,
+ systemPrompt: "",
+ systemVariables: "",
+ fastMode: false,
+};
+
+function resetHttp(settings: Record<string, unknown>): void {
+ settingsHttp.settings = settings;
+ settingsHttp.getResponses.length = 0;
+ settingsHttp.puts.length = 0;
+ settingsHttp.beforeConditionalApply = null;
+ settingsHttp.conditionalStatus = 200;
+ settingsHttp.gate = null;
+ settingsHttp.release = null;
+ settingsHttp.putGate = null;
+}
+
+function seedActiveQwen(): void {
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: true,
+ }));
+}
+
+function serverRow(key = QWEN38): Record<string, unknown> {
+ return (
+ settingsHttp.settings.inferenceParamsByModel as Record<
+ string,
+ Record<string, unknown>
+ >
+ )[key];
+}
+
+const LEGACY_SETTINGS = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+};
+
+test("a rejected retry leaves local sampling on the value the server kept", async () => {
+ resetHttp({ ...LEGACY_SETTINGS });
+ // Another tab commits presencePenalty=0.4 between the confirming GET and the
+ // conditional write, so the compare-and-set is rejected.
+ settingsHttp.beforeConditionalApply = () => {
+ settingsHttp.settings = {
+ ...LEGACY_SETTINGS,
+ inferenceParamsByModel: {
+ [QWEN38]: { ...LEGACY_SNAPSHOT, presencePenalty: 0.4 },
+ },
+ };
+ };
+ seedActiveQwen();
+
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ { ...active.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ assert.equal(settingsHttp.puts.length, 0);
+ assert.equal(serverRow().presencePenalty, 0.4);
+ // The local store must not advertise the rejected values.
+ const after = useChatRuntimeStore.getState();
+ assert.notEqual(after.params.presencePenalty, 1.5);
+ assert.notEqual(
+ (after.paramsByModel[QWEN38] as Record<string, unknown>).presencePenalty,
+ 1.5,
+ );
+});
+
+test("an accepted retry still applies the migration locally", async () => {
+ resetHttp({ ...LEGACY_SETTINGS });
+ seedActiveQwen();
+
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ { ...active.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ assert.equal(settingsHttp.puts.length, 1);
+ assert.equal(serverRow().presencePenalty, 1.5);
+ assert.equal(serverRow().minP, 0);
+ const after = useChatRuntimeStore.getState();
+ assert.equal(after.params.presencePenalty, 1.5);
+ assert.equal(after.params.minP, 0);
+});
+
+test("a backend without the conditional route persists nothing and shows nothing", async () => {
+ resetHttp({ ...LEGACY_SETTINGS });
+ // The desktop app adopts backends above a version floor, so an older one that
+ // never learned this route is a supported install rather than an error.
+ settingsHttp.conditionalStatus = 404;
+ seedActiveQwen();
+
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ { ...active.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ assert.equal(settingsHttp.puts.length, 0);
+ assert.equal(serverRow().presencePenalty, 0);
+ assert.equal(serverRow().minP, 0.01);
+ const after = useChatRuntimeStore.getState();
+ assert.notEqual(after.params.presencePenalty, 1.5);
+});
+
+test("the browser build's 405 is treated the same as an absent route", async () => {
+ resetHttp({ ...LEGACY_SETTINGS });
+ settingsHttp.conditionalStatus = 405;
+ seedActiveQwen();
+
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ { ...active.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ assert.equal(settingsHttp.puts.length, 0);
+ assert.equal(serverRow().presencePenalty, 0);
+ assert.notEqual(useChatRuntimeStore.getState().params.presencePenalty, 1.5);
+});
+
+test("a preset modified during hydration is not migrated on a stale read", async () => {
+ resetHttp({ ...LEGACY_SETTINGS });
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: false,
+ }));
+ settingsHttp.hold();
+ const hydration = useChatRuntimeStore.getState().hydratePersistedSettings();
+ // A slider moves while the settings GET is in flight. Its provenance write
+ // sits behind the debounce, so the server still reads "builtin-default".
+ useChatRuntimeStore.getState().setActivePresetSource("modified");
+ settingsHttp.release?.();
+ await hydration;
+
+ assert.equal(useChatRuntimeStore.getState().activePresetSource, "modified");
+ assert.deepEqual(
+ settingsHttp.puts.filter((put) => "inferenceParamsByModel" in put),
+ [],
+ );
+ assert.equal(serverRow().minP, 0.01);
+ assert.equal(serverRow().presencePenalty, 0);
+});
+
+test("a normalized exact key cannot overwrite a row added after the read", async () => {
+ const lower = QWEN38.toLowerCase();
+ resetHttp({
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParamsByModel: { [lower]: LEGACY_SNAPSHOT },
+ });
+ const newerRow = { temperature: 0.31, presencePenalty: 0.4, maxTokens: 2048 };
+ settingsHttp.beforeConditionalApply = () => {
+ settingsHttp.settings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParamsByModel: {
+ [lower]: LEGACY_SNAPSHOT,
+ [QWEN38]: newerRow,
+ },
+ };
+ };
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: { [lower]: LEGACY_SNAPSHOT },
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: true,
+ }));
+
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ { ...active.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ // The exact-key row the other tab wrote must survive intact, and no
+ // per-model patch may be sent for it at all.
+ assert.deepEqual(serverRow(QWEN38), newerRow);
+ assert.deepEqual(serverRow(lower), LEGACY_SNAPSHOT);
+ assert.deepEqual(
+ settingsHttp.puts.filter((put) => "inferenceParamsByModel" in put),
+ [],
+ );
+});
+
+test("a model id containing slashes stays one absence-fence path segment", async () => {
+ const lower = QWEN38.toLowerCase();
+ resetHttp({
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParamsByModel: { [lower]: LEGACY_SNAPSHOT },
+ });
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: { [lower]: LEGACY_SNAPSHOT },
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: true,
+ }));
+
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ { ...active.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 50));
+
+ // Nothing raced it, so the normalization applies under the exact spelling.
+ assert.equal(serverRow(QWEN38).presencePenalty, 1.5);
+});
+
+test("the loaded model's reasoning mode survives hydration", async () => {
+ // A small Qwen defaults to non-thinking while storage still says thinking.
+ resetHttp({
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ reasoningEnabled: true,
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ });
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: false,
+ settingsHydrated: false,
+ }));
+ noteLoadedModelReasoningMode(QWEN38, false, true);
+
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ const after = useChatRuntimeStore.getState();
+ // The pill and the sampling table have to agree; both follow the load.
+ assert.equal(after.reasoningEnabled, false);
+ assert.equal(after.params.temperature, 0.7);
+ assert.equal(after.params.topP, 0.8);
+ assert.equal(after.params.presencePenalty, 1.5);
+ assert.equal(after.params.minP, 0);
+});
+
+test("a status refresh cannot outrank the installation's persisted reasoning", async () => {
+ // Adoption of a resident model echoes whatever this browser had locally,
+ // which before hydration is a local default, not the installation setting.
+ // Only a load this browser performed may win.
+ resetHttp({
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ reasoningEnabled: false,
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ });
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: false,
+ }));
+ // This browser never loaded QWEN38: clear any load marker left by an earlier
+ // case, then let a status merely report the model (fromLoad defaults false).
+ noteLoadedModelReasoningMode("unsloth/Llama-3.2-3B-Instruct-GGUF", false);
+ noteLoadedModelReasoningMode(QWEN38, true);
+
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ // The server said thinking is off for this installation. It stays off.
+ assert.equal(useChatRuntimeStore.getState().reasoningEnabled, false);
+});
+
+test("the post-load refresh does not drop the load's claim on the mode", async () => {
+ // performLoad marks fromLoad, then awaits refresh(), whose status merge calls
+ // noteLoadedModelReasoningMode again with the default false. Downgrading there
+ // would let hydration replay the previous model's persisted toggle.
+ resetHttp({
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ reasoningEnabled: true,
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ });
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: false,
+ settingsHydrated: false,
+ }));
+ noteLoadedModelReasoningMode(QWEN38, false, true);
+ // The refresh that performLoad awaits, reporting the same model.
+ noteLoadedModelReasoningMode(QWEN38, false);
+
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ const after = useChatRuntimeStore.getState();
+ assert.equal(after.reasoningEnabled, false);
+ assert.equal(after.params.temperature, 0.7);
+ assert.equal(after.params.topP, 0.8);
+});
+
+test("a model without reasoning support is migrated as non-thinking", async () => {
+ // The load-time overlay is gated on supportsReasoning, so a toggle left over
+ // from the previous model must not pick the thinking table for the row.
+ resetHttp({
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ });
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ supportsReasoning: false,
+ settingsHydrated: false,
+ }));
+ // A status reported this checkpoint, and it cannot reason.
+ noteLoadedModelReasoningMode("unsloth/Llama-3.2-3B-Instruct-GGUF", false);
+ useChatRuntimeStore.setState({ reasoningEnabled: true });
+ noteLoadedModelReasoningMode(QWEN38, true);
+
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ assert.equal(serverRow().temperature, 0.7);
+ assert.equal(serverRow().topP, 0.8);
+});
+
+test("an empty stored model map is declined, since it cannot be fenced", async () => {
+ // sanitizeChatSettings drops inferenceParamsByModel: {}, so it lands in
+ // neither expected nor expectedAbsent, and the server matches expected by
+ // recursive subset, where an empty map matches a populated one. Another tab
+ // adding the first row would slip through, so this declines rather than
+ // write unfenced. An absent key is different and stays fenced.
+ resetHttp({
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParams: {
+ temperature: 0.6,
+ topP: 0.95,
+ minP: 0.01,
+ presencePenalty: 0.0,
+ },
+ inferenceParamsByModel: {},
+ });
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: {},
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: false,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: false,
+ }));
+
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ const global = settingsHttp.settings.inferenceParams as Record<string, number>;
+ assert.equal(global.presencePenalty, 0);
+ assert.equal(global.minP, 0.01);
+});
+
+test("case-distinct POSIX paths keep separate reasoning-mode records", async () => {
+ // Two different files on a case-sensitive filesystem. The mode recorded for
+ // one must not gate hydration or pick the migration table for the other.
+ const upper = "/home/u/Models/qwen3.8-27b";
+ const lower = "/home/u/models/qwen3.8-27b";
+ resetHttp({
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ reasoningEnabled: true,
+ inferenceParamsByModel: { [lower]: LEGACY_SNAPSHOT },
+ });
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: lower },
+ paramsByModel: { [lower]: LEGACY_SNAPSHOT },
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: false,
+ supportsReasoning: true,
+ settingsHydrated: false,
+ }));
+ // The load was for the other path entirely.
+ noteLoadedModelReasoningMode(upper, false, true);
+
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ // No record for this checkpoint, so the persisted toggle stands.
+ assert.equal(useChatRuntimeStore.getState().reasoningEnabled, true);
+});
+
+test("a checkpoint switch during the conditional write is not migrated", async () => {
+ // The CAS commits for QWEN38, but the user moves to another Qwen before the
+ // response resolves. Applying then would mark the second model's row migrated
+ // while the server updated only the first.
+ const other = "unsloth/Qwen3.6-9B-GGUF";
+ resetHttp({ ...LEGACY_SETTINGS });
+ settingsHttp.beforeConditionalApply = () => {
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, checkpoint: other },
+ paramsByModel: {
+ ...state.paramsByModel,
+ [other]: { ...LEGACY_SNAPSHOT },
+ },
+ }));
+ };
+ seedActiveQwen();
+
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ { ...active.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 60));
+
+ // The row the user switched to keeps its legacy values locally.
+ const after = useChatRuntimeStore.getState();
+ const otherRow = after.paramsByModel[other] as Record<string, number>;
+ assert.equal(otherRow.presencePenalty, 0);
+ assert.equal(otherRow.minP, 0.01);
+});
+
+test("case-distinct POSIX ownership claims still conflict", async () => {
+ // Two resident-model callbacks enqueue ownership before the microtask runs.
+ // They are different files, so the competing claims must cancel each other
+ // rather than the later one silently replacing the earlier.
+ const upper = "/home/u/Models/qwen3.8-27b";
+ const lower = "/home/u/models/qwen3.8-27b";
+ resetHttp({
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParams: {
+ temperature: 0.6,
+ topP: 0.95,
+ minP: 0.01,
+ presencePenalty: 0.0,
+ },
+ });
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: lower },
+ paramsByModel: {},
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: false,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ supportsReasoning: true,
+ settingsHydrated: true,
+ }));
+
+ const store = useChatRuntimeStore.getState();
+ store.setParams(
+ { ...store.params, checkpoint: upper },
+ { fromModelDefaults: true, migrateOwnedGlobalQwenDefaults: true },
+ );
+ const second = useChatRuntimeStore.getState();
+ second.setParams(
+ { ...second.params, checkpoint: lower },
+ { fromModelDefaults: true, migrateOwnedGlobalQwenDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 60));
+
+ const global = settingsHttp.settings.inferenceParams as Record<
+ string,
+ number
+ >;
+ assert.equal(global.presencePenalty, 0);
+ assert.equal(global.minP, 0.01);
+});
+
+test("selecting an external Qwen migrates its dormant row", async () => {
+ // No load and no status follows an external pick, so setCheckpoint is the
+ // only chance to repair the row it just replayed.
+ const external = `external::openrouter::${encodeURIComponent(
+ "Qwen/Qwen3.8-27B",
+ )}`;
+ resetHttp({
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParamsByModel: { [external]: LEGACY_SNAPSHOT },
+ });
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, checkpoint: "unsloth/Llama-3.2-3B-Instruct-GGUF" },
+ paramsByModel: { [external]: { ...LEGACY_SNAPSHOT } },
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ supportsReasoning: true,
+ settingsHydrated: true,
+ }));
+
+ useChatRuntimeStore.getState().setCheckpoint(external, null);
+ await new Promise((resolve) => setTimeout(resolve, 60));
+
+ const row = serverRow(external);
+ assert.equal(row.presencePenalty, 1.5);
+ assert.equal(row.minP, 0);
+ assert.equal(useChatRuntimeStore.getState().params.presencePenalty, 1.5);
+});
+
+test("the send barrier waits for a migration a model pick just scheduled", async () => {
+ const external = `external::openrouter::${encodeURIComponent(
+ "Qwen/Qwen3.6-9B",
+ )}`;
+ resetHttp({
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParamsByModel: { [external]: LEGACY_SNAPSHOT },
+ });
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, checkpoint: "unsloth/Llama-3.2-3B-Instruct-GGUF" },
+ paramsByModel: { [external]: { ...LEGACY_SNAPSHOT } },
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ supportsReasoning: true,
+ settingsHydrated: true,
+ }));
+
+ useChatRuntimeStore.getState().setCheckpoint(external, null);
+ // What the run does before sending. No sleep: the point is that this alone
+ // is enough, since the row is still legacy the microtask before it. Raced
+ // against a deadline so a regression fails here instead of hanging CI.
+ const settled = await Promise.race([
+ awaitPendingQwenDefaultsMigration().then(() => "settled"),
+ new Promise((resolve) => setTimeout(() => resolve("timeout"), 5000)),
+ ]);
+ assert.equal(settled, "settled", "the barrier never released");
+
+ assert.equal(useChatRuntimeStore.getState().params.presencePenalty, 1.5);
+ assert.equal(serverRow(external).presencePenalty, 1.5);
+});
+
+test("an edit racing the conditional write does not strand local on legacy", async () => {
+ resetHttp({ ...LEGACY_SETTINGS });
+ // The user moves a control after the confirming GET, while the write is out.
+ settingsHttp.beforeConditionalApply = () => {
+ useChatRuntimeStore.getState().setActivePresetSource("modified");
+ };
+ seedActiveQwen();
+
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ { ...active.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 60));
+
+ // The server took the migration, so the tab must not keep generating from the
+ // values it no longer holds.
+ assert.equal(serverRow().presencePenalty, 1.5);
+ const after = useChatRuntimeStore.getState();
+ assert.equal(after.activePresetSource, "modified");
+ assert.equal(after.params.presencePenalty, 1.5);
+ assert.equal(after.params.minP, 0);
+});
+
+test("a decision field that sanitizes away blocks the write", async () => {
+ // An explicit null cannot be asserted as a value or as an absence, so the
+ // migration declines rather than writing unfenced.
+ resetHttp({ ...LEGACY_SETTINGS, activePresetSource: null });
+ seedActiveQwen();
+
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ { ...active.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 60));
+
+ // The row itself, not the queue: an earlier case's debounced PUT can land in
+ // this window and says nothing about whether the migration wrote.
+ assert.equal(serverRow().presencePenalty, 0);
+ assert.equal(serverRow().minP, 0.01);
+});
+
+test("a case-distinct external switch during the write is not migrated", async () => {
+ // Provider-qualified ids are opaque, so these are two different models even
+ // though normalizeModelIdentity would fold them together.
+ const upper = `external::vendor::${encodeURIComponent("Vendor/Qwen3.8-27B")}`;
+ const lower = `external::vendor::${encodeURIComponent("vendor/qwen3.8-27b")}`;
+ resetHttp({
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParamsByModel: {
+ [upper]: LEGACY_SNAPSHOT,
+ [lower]: LEGACY_SNAPSHOT,
+ },
+ });
+ settingsHttp.beforeConditionalApply = () => {
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, checkpoint: lower },
+ }));
+ };
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: upper },
+ paramsByModel: {
+ [upper]: { ...LEGACY_SNAPSHOT },
+ [lower]: { ...LEGACY_SNAPSHOT },
+ },
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ supportsReasoning: true,
+ settingsHydrated: true,
+ }));
+
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ { ...active.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 60));
+
+ // Only the row the write was for; the other model keeps its own values.
+ const lowerRow = useChatRuntimeStore.getState().paramsByModel[lower] as Record<
+ string,
+ number
+ >;
+ assert.equal(lowerRow.presencePenalty, 0);
+ assert.equal(lowerRow.minP, 0.01);
+});
+
+test("an earlier retry settling does not clear a later retry's barrier", async () => {
+ const QWEN36 = "unsloth/Qwen3.6-14B-GGUF";
+ const base = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParamsByModel: {
+ [QWEN38]: { ...LEGACY_SNAPSHOT },
+ [QWEN36]: { ...LEGACY_SNAPSHOT },
+ },
+ };
+ resetHttp({ ...base });
+ // Both confirming GETs are held, so the first retry finishes while the second
+ // is still deciding.
+ const holdGet = (): [Promise<Record<string, unknown>>, () => void] => {
+ let release: () => void = () => undefined;
+ const held = new Promise<Record<string, unknown>>((resolve) => {
+ release = () => resolve(settingsHttp.settings);
+ });
+ return [held, release];
+ };
+ const [firstGet, releaseFirst] = holdGet();
+ const [secondGet, releaseSecond] = holdGet();
+ settingsHttp.getResponses.push(firstGet, secondGet);
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: {
+ [QWEN38]: { ...LEGACY_SNAPSHOT },
+ [QWEN36]: { ...LEGACY_SNAPSHOT },
+ },
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: true,
+ }));
+
+ const first = useChatRuntimeStore.getState();
+ first.setParams(
+ { ...first.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN36 },
+ }));
+ const second = useChatRuntimeStore.getState();
+ second.setParams(
+ { ...second.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ releaseFirst();
+ await new Promise((resolve) => setTimeout(resolve, 30));
+ setTimeout(releaseSecond, 40);
+
+ // A barrier cleared by the wrong retry resolves here with the second row
+ // still legacy; the deadline keeps that a failure rather than a hang.
+ await Promise.race([
+ awaitPendingQwenDefaultsMigration(),
+ new Promise((resolve) => setTimeout(resolve, 5000)),
+ ]);
+ assert.equal(serverRow(QWEN36).presencePenalty, 1.5);
+});
+
+test("the send barrier follows a retry that replaces the one it captured", async () => {
+ const QWEN36 = "unsloth/Qwen3.6-14B-GGUF";
+ const base = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParamsByModel: {
+ [QWEN38]: { ...LEGACY_SNAPSHOT },
+ [QWEN36]: { ...LEGACY_SNAPSHOT },
+ },
+ };
+ resetHttp({ ...base });
+ const holdGet = (): [Promise<Record<string, unknown>>, () => void] => {
+ let release: () => void = () => undefined;
+ const held = new Promise<Record<string, unknown>>((resolve) => {
+ release = () => resolve(settingsHttp.settings);
+ });
+ return [held, release];
+ };
+ const [firstGet, releaseFirst] = holdGet();
+ const [secondGet, releaseSecond] = holdGet();
+ settingsHttp.getResponses.push(firstGet, secondGet);
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: {
+ [QWEN38]: { ...LEGACY_SNAPSHOT },
+ [QWEN36]: { ...LEGACY_SNAPSHOT },
+ },
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: true,
+ }));
+
+ const first = useChatRuntimeStore.getState();
+ first.setParams(
+ { ...first.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ // The send joins here, so it captures the first retry.
+ const barrier = awaitPendingQwenDefaultsMigration();
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN36 },
+ }));
+ const second = useChatRuntimeStore.getState();
+ second.setParams(
+ { ...second.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ releaseFirst();
+ setTimeout(releaseSecond, 60);
+
+ await Promise.race([
+ barrier,
+ new Promise((resolve) => setTimeout(resolve, 5000)),
+ ]);
+ // The checkpoint the send would generate from is the second one.
+ assert.equal(serverRow(QWEN36).presencePenalty, 1.5);
+});
+
+test("a write outlasting the flush timeout rearms the migration", async () => {
+ resetHttp({ ...LEGACY_SETTINGS });
+ let releasePut: () => void = () => undefined;
+ settingsHttp.putGate = new Promise<void>((resolve) => {
+ releasePut = resolve;
+ });
+ seedActiveQwen();
+ // An unrelated setting write, held open past the debounce so it is still on
+ // the wire when the migration tries to land.
+ const before = useChatRuntimeStore.getState();
+ before.setAutoTitle(!before.autoTitle);
+ await new Promise((resolve) => setTimeout(resolve, 600));
+
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ { ...active.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ // Past the 2000 ms flush timeout with the ordinary write still outstanding.
+ await new Promise((resolve) => setTimeout(resolve, 2600));
+ assert.equal(serverRow().presencePenalty, 0);
+
+ releasePut();
+ settingsHttp.putGate = null;
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ await Promise.race([
+ awaitPendingQwenDefaultsMigration(),
+ new Promise((resolve) => setTimeout(resolve, 5000)),
+ ]);
+ assert.equal(serverRow().presencePenalty, 1.5);
+});
+
+test("a status-only reasoning marker does not pick the migration table", async () => {
+ // Status for a resident model lands before the settings GET, so the marker
+ // carries this browser's local default rather than an answer about the model.
+ resetHttp({
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ reasoningEnabled: false,
+ inferenceParamsByModel: { [QWEN38]: LEGACY_SNAPSHOT },
+ });
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: { [QWEN38]: { ...LEGACY_SNAPSHOT } },
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ supportsReasoning: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: true,
+ }));
+ noteLoadedModelReasoningMode(QWEN38, true);
+
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ { ...active.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 60));
+
+ // The persisted toggle is off, so the non-thinking row is what the pill will
+ // hydrate against.
+ assert.equal(serverRow().temperature, 0.7);
+ assert.equal(serverRow().topP, 0.8);
+});
+
+test("a null model map is fenced rather than treated as empty", async () => {
+ // Only a genuinely empty map means "no per-model memory". A null is a key the
+ // row holds, so another tab can replace it with rows this write never saw,
+ // and the compare-and-set asserts neither its value nor its absence.
+ resetHttp({
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParams: { ...LEGACY_SNAPSHOT },
+ inferenceParamsByModel: null,
+ });
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: {},
+ activePreset: "Default",
+ activePresetSource: "custom",
+ rememberParamsPerModel: false,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ supportsReasoning: true,
+ settingsHydrated: true,
+ }));
+
+ useChatRuntimeStore.getState().setActivePresetSource("builtin-default");
+ await new Promise((resolve) => setTimeout(resolve, 80));
+
+ const globals = settingsHttp.settings.inferenceParams as Record<
+ string,
+ number
+ >;
+ assert.equal(globals.presencePenalty, 0);
+ assert.equal(globals.minP, 0.01);
+});
+
+test("per-model memory enabled during the read cancels the global migration", async () => {
+ const OTHER = "unsloth/Llama-3.2-3B-GGUF";
+ // Scheduled while the global snapshot was the active model's to rewrite; the
+ // confirming read shows per-model memory on, so it no longer is.
+ resetHttp({
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ inferenceParams: { ...LEGACY_SNAPSHOT },
+ inferenceParamsByModel: { [OTHER]: { ...LEGACY_SNAPSHOT } },
+ });
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: {},
+ activePreset: "Default",
+ activePresetSource: "custom",
+ rememberParamsPerModel: false,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ supportsReasoning: true,
+ settingsHydrated: true,
+ }));
+
+ useChatRuntimeStore.getState().setActivePresetSource("builtin-default");
+ await new Promise((resolve) => setTimeout(resolve, 80));
+
+ const globals = settingsHttp.settings.inferenceParams as Record<
+ string,
+ number
+ >;
+ assert.equal(globals.presencePenalty, 0);
+ assert.equal(globals.minP, 0.01);
+});
+
+test("a wedged backend does not hold a send open forever", async () => {
+ resetHttp({ ...LEGACY_SETTINGS });
+ // Neither the confirming GET nor the conditional write takes an abort signal.
+ settingsHttp.hold();
+ seedActiveQwen();
+
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ { ...active.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 20));
+
+ const started = Date.now();
+ let timedOut = false;
+ await Promise.race([
+ awaitPendingQwenDefaultsMigration(),
+ new Promise((resolve) => {
+ setTimeout(() => {
+ timedOut = true;
+ resolve(undefined);
+ }, 6000);
+ }),
+ ]);
+ settingsHttp.release?.();
+
+ assert.equal(timedOut, false, "the barrier never released");
+ assert.ok(Date.now() - started < 4000);
+});
+
+test("adopting the startup model clears the unowned pre-hydration mark", async () => {
+ // Status finds a resident Qwen before hydration finishes. setCheckpoint marks
+ // any pre-hydration switch as an interactive pick, and adoption is the signal
+ // that says otherwise, so the global snapshot is still this model's.
+ resetHttp({
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParams: { ...LEGACY_SNAPSHOT },
+ });
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: "" },
+ paramsByModel: {},
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: false,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ supportsReasoning: true,
+ settingsHydrated: false,
+ }));
+ settingsHttp.hold();
+ const hydrating = useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ useChatRuntimeStore.getState().setCheckpoint(QWEN38);
+ const adopting = useChatRuntimeStore.getState();
+ adopting.setParams(
+ { ...adopting.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ { fromModelDefaults: true, migrateOwnedGlobalQwenDefaults: true },
+ );
+
+ settingsHttp.release?.();
+ await hydrating;
+ await new Promise((resolve) => setTimeout(resolve, 60));
+
+ const global = settingsHttp.settings.inferenceParams as Record<
+ string,
+ number
+ >;
+ assert.equal(global.presencePenalty, 1.5);
+});
+
+test("a thread pin survives the race recovery path", async () => {
+ // Applying a thread snapshot advances no installation mutation version, so
+ // nothing in the recovery path would otherwise notice the pin.
+ resetHttp({ ...LEGACY_SETTINGS });
+ seedActiveQwen();
+ useChatRuntimeStore
+ .getState()
+ .applyThreadScopedSettings("thread-1", { presencePenalty: 0.9 });
+ useChatRuntimeStore.setState({ activeThreadId: "thread-1" });
+ // Provenance moves while the conditional write is in flight, which is the
+ // branch that copies migrated fields straight into the live params.
+ settingsHttp.beforeConditionalApply = () => {
+ useChatRuntimeStore.getState().setActivePresetSource("modified");
+ };
+
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ { ...active.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 80));
+
+ assert.equal(
+ useChatRuntimeStore.getState().params.presencePenalty,
+ 0.9,
+ "the open chat's pinned value was replaced by the migrated default",
+ );
+});
+
+test("an unreachable backend does not spin the migration rearm", async () => {
+ resetHttp({ ...LEGACY_SETTINGS });
+ // Every ordinary write is refused, so the patch is retained and each pass
+ // flushes it again.
+ settingsHttp.putFailures = Array.from({ length: 400 }, () => ({
+ status: 503,
+ }));
+ seedActiveQwen();
+ const before = useChatRuntimeStore.getState();
+ before.setAutoTitle(!before.autoTitle);
+
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ { ...active.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 1500));
+
+ assert.ok(
+ settingsHttp.puts.length < 40,
+ `rearmed without bound: ${settingsHttp.puts.length} writes`,
+ );
+ settingsHttp.putFailures = [];
+});
+
+test("a model switch during hydration still gets its own row migrated", async () => {
+ const QWEN36 = "unsloth/Qwen3.6-14B-GGUF";
+ const stored = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParamsByModel: {
+ [QWEN38]: { ...LEGACY_SNAPSHOT },
+ [QWEN36]: { ...LEGACY_SNAPSHOT },
+ },
+ };
+ resetHttp({ ...stored });
+ // The first GET is hydration's own read; the second is the confirming read
+ // taken immediately before the write, and that is the one to hold open.
+ let releaseConfirm: () => void = () => undefined;
+ const confirming = new Promise<Record<string, unknown>>((resolve) => {
+ releaseConfirm = () => resolve(settingsHttp.settings);
+ });
+ settingsHttp.getResponses.push(stored, confirming);
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN38 },
+ paramsByModel: {
+ [QWEN38]: { ...LEGACY_SNAPSHOT },
+ [QWEN36]: { ...LEGACY_SNAPSHOT },
+ },
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ rememberParamsPerModel: true,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ supportsReasoning: true,
+ settingsHydrated: false,
+ }));
+ const hydrating = useChatRuntimeStore.getState().hydratePersistedSettings();
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ // The model moves while the confirming read is out. Neither switch path can
+ // schedule a retry from here, since hydration has not finished.
+ useChatRuntimeStore.setState((state) => ({
+ params: { ...state.params, ...LEGACY_SNAPSHOT, checkpoint: QWEN36 },
+ }));
+ releaseConfirm();
+ await hydrating;
+ await new Promise((resolve) => setTimeout(resolve, 80));
+
+ const row = (
+ settingsHttp.settings.inferenceParamsByModel as Record<
+ string,
+ Record<string, number>
+ >
+ )[QWEN36];
+ assert.equal(row.presencePenalty, 1.5);
+ assert.equal(row.minP, 0);
+});
+
+test("a custom preset chosen mid-write keeps its own legacy-valued fields", async () => {
+ resetHttp({ ...LEGACY_SETTINGS });
+ useChatRuntimeStore.getState().applyThreadScopedSettings(null, {});
+ useChatRuntimeStore.setState({ activeThreadId: null });
+ // A custom preset can hold presencePenalty 0 on purpose. Applying it leaves
+ // that field's value alone, so its mutation counter does not move and the
+ // recovery path would read it as untouched.
+ settingsHttp.beforeConditionalApply = () => {
+ useChatRuntimeStore.getState().setActivePresetSource("custom");
+ };
+ seedActiveQwen();
+
+ const active = useChatRuntimeStore.getState();
+ active.setParams(
+ { ...active.params, minP: 0, presencePenalty: 1.5 },
+ { fromModelDefaults: true },
+ );
+ await new Promise((resolve) => setTimeout(resolve, 80));
+
+ const after = useChatRuntimeStore.getState().params;
+ assert.equal(after.presencePenalty, 0);
+ assert.equal(after.minP, 0.01);
+});
diff --git a/studio/frontend/tests/qwen-defaults-migration.test.ts b/studio/frontend/tests/qwen-defaults-migration.test.ts
new file mode 100644
index 00000000000..10af79a511e
--- /dev/null
+++ b/studio/frontend/tests/qwen-defaults-migration.test.ts
@@ -0,0 +1,467 @@
+// 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 { register } from "node:module";
+import test from "node:test";
+
+// The migration now reads the shared sampling table by extensionless specifier,
+// like the rest of src/, so this test needs the bundler resolver too.
+register("./bundler-resolver.mjs", import.meta.url);
+
+import type { PersistedChatSettings } from "../src/features/chat/api/chat-settings-api.ts";
+const { migrateLegacyQwenDefaults, isPresenceBumpQwen } = await import(
+ "../src/features/chat/utils/qwen-defaults-migration.ts"
+);
+
+const QWEN38 = "unsloth/Qwen3.8-27B-GGUF";
+const LEGACY_SNAPSHOT = {
+ temperature: 0.6,
+ topP: 0.95,
+ topK: 20,
+ minP: 0.01,
+ repetitionPenalty: 1.0,
+ presencePenalty: 0.0,
+ maxTokens: 8192,
+ systemPrompt: "",
+ systemVariables: "",
+ fastMode: false,
+};
+
+function settingsFor(
+ modelId: string,
+ entry: PersistedChatSettings["inferenceParams"] = LEGACY_SNAPSHOT,
+): PersistedChatSettings {
+ return {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParams: {
+ temperature: 0.6,
+ topP: 0.95,
+ minP: 0.01,
+ presencePenalty: 0.0,
+ maxTokens: 8192,
+ },
+ inferenceParamsByModel: { [modelId]: entry },
+ };
+}
+
+test("migrates the complete legacy Qwen3.8 default snapshot", () => {
+ const migrated = migrateLegacyQwenDefaults(
+ settingsFor(QWEN38),
+ QWEN38,
+ true,
+ true,
+ );
+
+ assert.deepEqual(migrated.migratedModelIds, [QWEN38]);
+ assert.equal(
+ migrated.settings.inferenceParamsByModel?.[QWEN38]?.presencePenalty,
+ 1.5,
+ );
+ assert.equal(migrated.settings.inferenceParamsByModel?.[QWEN38]?.minP, 0);
+ assert.equal(migrated.settings.inferenceParams?.presencePenalty, 0);
+ assert.equal(migrated.settings.inferenceParams?.minP, 0.01);
+ assert.deepEqual(migrated.patch, {
+ inferenceParamsByModel: {
+ [QWEN38]: { minP: 0, presencePenalty: 1.5 },
+ },
+ });
+});
+
+test("preserves context-derived token budgets while migrating sampling", () => {
+ for (const maxTokens of [4096, 32768]) {
+ const settings = settingsFor(QWEN38, {
+ ...LEGACY_SNAPSHOT,
+ maxTokens,
+ });
+ const migrated = migrateLegacyQwenDefaults(
+ settings,
+ QWEN38,
+ true,
+ true,
+ );
+
+ assert.equal(
+ migrated.settings.inferenceParamsByModel?.[QWEN38]?.maxTokens,
+ maxTokens,
+ );
+ assert.deepEqual(migrated.patch?.inferenceParamsByModel?.[QWEN38], {
+ minP: 0,
+ presencePenalty: 1.5,
+ });
+ }
+});
+
+test("migrates temperature and top-p for a non-thinking session", () => {
+ const migrated = migrateLegacyQwenDefaults(
+ settingsFor(QWEN38),
+ QWEN38,
+ false,
+ true,
+ );
+
+ assert.equal(
+ migrated.settings.inferenceParamsByModel?.[QWEN38]?.temperature,
+ 0.7,
+ );
+ assert.equal(migrated.settings.inferenceParamsByModel?.[QWEN38]?.topP, 0.8);
+ assert.deepEqual(migrated.patch, {
+ inferenceParamsByModel: {
+ [QWEN38]: {
+ temperature: 0.7,
+ topP: 0.8,
+ minP: 0,
+ presencePenalty: 1.5,
+ },
+ },
+ });
+});
+
+test("also repairs the same auto-generated snapshot for Qwen3.5 and Qwen3.6", () => {
+ for (const modelId of [
+ "unsloth/Qwen3.5-9B-GGUF",
+ "unsloth/Qwen3.6-27B-MTP-GGUF",
+ ]) {
+ const migrated = migrateLegacyQwenDefaults(
+ settingsFor(modelId),
+ modelId,
+ true,
+ );
+ assert.equal(
+ migrated.settings.inferenceParamsByModel?.[modelId]?.presencePenalty,
+ 1.5,
+ );
+ }
+});
+
+test("migrates only the active model when several legacy Qwen rows are saved", () => {
+ const qwen36Small = "unsloth/Qwen3.6-9B-GGUF";
+ const settings = settingsFor(QWEN38);
+ settings.inferenceParamsByModel = {
+ [QWEN38]: LEGACY_SNAPSHOT,
+ [qwen36Small]: LEGACY_SNAPSHOT,
+ };
+
+ const migrated = migrateLegacyQwenDefaults(settings, QWEN38, true);
+
+ assert.deepEqual(migrated.migratedModelIds, [QWEN38]);
+ assert.equal(
+ migrated.settings.inferenceParamsByModel?.[QWEN38]?.presencePenalty,
+ 1.5,
+ );
+ assert.deepEqual(
+ migrated.settings.inferenceParamsByModel?.[qwen36Small],
+ LEGACY_SNAPSHOT,
+ );
+ assert.equal(
+ migrated.patch?.inferenceParamsByModel?.[qwen36Small],
+ undefined,
+ );
+});
+
+test("normalizes a case-insensitive saved key to the active checkpoint", () => {
+ const lowerCaseKey = QWEN38.toLowerCase();
+ const migrated = migrateLegacyQwenDefaults(
+ settingsFor(lowerCaseKey),
+ QWEN38,
+ true,
+ );
+
+ assert.deepEqual(migrated.migratedModelIds, [QWEN38]);
+ assert.equal(
+ migrated.settings.inferenceParamsByModel?.[QWEN38]?.presencePenalty,
+ 1.5,
+ );
+ // The alias is migrated rather than dropped. The server merge only sets keys,
+ // so a spelling removed here would stay legacy there and a later status
+ // naming it would replay the stale row.
+ assert.equal(
+ migrated.settings.inferenceParamsByModel?.[lowerCaseKey]?.presencePenalty,
+ 1.5,
+ );
+ assert.deepEqual(migrated.patch?.inferenceParamsByModel?.[lowerCaseKey], {
+ minP: 0,
+ presencePenalty: 1.5,
+ });
+ assert.deepEqual(
+ migrated.patch?.inferenceParamsByModel?.[QWEN38],
+ {
+ ...LEGACY_SNAPSHOT,
+ minP: 0,
+ presencePenalty: 1.5,
+ },
+ );
+});
+
+test("does not migrate dormant Qwen rows while a non-Qwen model is active", () => {
+ const settings = settingsFor(QWEN38);
+
+ const migrated = migrateLegacyQwenDefaults(
+ settings,
+ "unsloth/Llama-3.2-3B-Instruct-GGUF",
+ true,
+ );
+
+ assert.equal(migrated.patch, null);
+ assert.equal(migrated.settings, settings);
+});
+
+test("preserves an explicit partial presence override", () => {
+ const settings = settingsFor(QWEN38, { presencePenalty: 0.0 });
+ const migrated = migrateLegacyQwenDefaults(settings, QWEN38, true);
+
+ assert.equal(migrated.patch, null);
+ assert.equal(migrated.settings, settings);
+});
+
+test("preserves a customized snapshot", () => {
+ const settings = settingsFor(QWEN38, {
+ ...LEGACY_SNAPSHOT,
+ temperature: 0.7,
+ });
+ const migrated = migrateLegacyQwenDefaults(settings, QWEN38, true);
+
+ assert.equal(migrated.patch, null);
+ assert.equal(migrated.settings, settings);
+});
+
+test("does not migrate generic Qwen3 or a custom preset", () => {
+ const generic = settingsFor("unsloth/Qwen3-8B-GGUF");
+ assert.equal(
+ migrateLegacyQwenDefaults(generic, "unsloth/Qwen3-8B-GGUF", true).patch,
+ null,
+ );
+
+ const custom = {
+ ...settingsFor(QWEN38),
+ activePreset: "Creative",
+ activePresetSource: "custom" as const,
+ };
+ assert.equal(migrateLegacyQwenDefaults(custom, QWEN38, true).patch, null);
+});
+
+test("external checkpoints are decoded before the family is matched", () => {
+ // buildExternalModelId percent-encodes, so a provider-namespaced Qwen arrives
+ // as external::<provider>::Qwen%2FQwen3.8-27B. Matching that raw would put an
+ // alphanumeric "f" against the family segment and drop the presence bump.
+ const encoded = `external::openrouter::${encodeURIComponent("Qwen/Qwen3.8-27B")}`;
+ assert.equal(isPresenceBumpQwen(encoded), true);
+ assert.equal(
+ isPresenceBumpQwen(
+ `external::openrouter::${encodeURIComponent("Qwen/Qwen3-8B")}`,
+ ),
+ false,
+ );
+
+ const settings = settingsFor(encoded);
+ const migrated = migrateLegacyQwenDefaults(settings, encoded, true);
+ assert.equal(
+ migrated.patch?.inferenceParamsByModel?.[encoded]?.presencePenalty,
+ 1.5,
+ );
+});
+
+test("matches presence-bump versions only at model-id boundaries", () => {
+ const future = settingsFor("unsloth/Qwen3.80-27B-GGUF");
+ assert.equal(
+ migrateLegacyQwenDefaults(future, "unsloth/Qwen3.80-27B-GGUF", true).patch,
+ null,
+ );
+});
+
+test("does not infer that globals belong to a newly active Qwen model", () => {
+ const settings = settingsFor(QWEN38);
+ const migrated = migrateLegacyQwenDefaults(settings, QWEN38, true, false);
+
+ assert.equal(migrated.settings.inferenceParams?.presencePenalty, 0);
+ assert.equal(migrated.patch?.inferenceParams, undefined);
+});
+
+test("migrates a global-only legacy install when ownership is established", () => {
+ const settings = settingsFor(QWEN38);
+ settings.inferenceParamsByModel = undefined;
+
+ const migrated = migrateLegacyQwenDefaults(settings, QWEN38, false, true);
+
+ assert.deepEqual(migrated.migratedModelIds, []);
+ assert.equal(migrated.settings.inferenceParams?.temperature, 0.7);
+ assert.equal(migrated.settings.inferenceParams?.topP, 0.8);
+ assert.equal(migrated.settings.inferenceParams?.minP, 0);
+ assert.equal(migrated.settings.inferenceParams?.presencePenalty, 1.5);
+ assert.deepEqual(migrated.patch, {
+ inferenceParams: {
+ temperature: 0.7,
+ topP: 0.8,
+ minP: 0,
+ presencePenalty: 1.5,
+ },
+ });
+});
+
+test("preserves a global-only install's context-derived token budget", () => {
+ const settings = settingsFor(QWEN38);
+ settings.inferenceParamsByModel = undefined;
+ settings.inferenceParams = {
+ ...settings.inferenceParams,
+ maxTokens: 32768,
+ };
+
+ const migrated = migrateLegacyQwenDefaults(settings, QWEN38, true, true);
+
+ assert.equal(migrated.settings.inferenceParams?.maxTokens, 32768);
+ assert.equal(migrated.patch?.inferenceParams?.maxTokens, undefined);
+ assert.equal(migrated.patch?.inferenceParams?.presencePenalty, 1.5);
+});
+
+test("preserves customized optional fields in a global-only snapshot", () => {
+ for (const override of [{ topK: 40 }, { repetitionPenalty: 1.1 }]) {
+ const settings = settingsFor(QWEN38);
+ settings.inferenceParamsByModel = undefined;
+ settings.inferenceParams = {
+ ...settings.inferenceParams,
+ ...override,
+ };
+
+ const migrated = migrateLegacyQwenDefaults(settings, QWEN38, false, true);
+
+ assert.equal(migrated.patch, null);
+ assert.equal(migrated.settings, settings);
+ }
+});
+
+test("leaves global-only settings alone when active ownership is unknown", () => {
+ const settings = settingsFor(QWEN38);
+ settings.inferenceParamsByModel = undefined;
+
+ assert.equal(
+ migrateLegacyQwenDefaults(settings, QWEN38, false, false).patch,
+ null,
+ );
+});
+
+test("is idempotent after the legacy snapshot has been upgraded", () => {
+ const first = migrateLegacyQwenDefaults(settingsFor(QWEN38), QWEN38, true);
+ const second = migrateLegacyQwenDefaults(first.settings, QWEN38, true);
+
+ assert.equal(second.patch, null);
+ assert.deepEqual(second.migratedModelIds, []);
+});
+
+test("an Ollama manifest reference is decoded before the family is matched", () => {
+ // The inventory ref keeps its quote(safe='') encoding all the way into
+ // inference status, so every separator arrives as %2F.
+ const ref = `ollama-manifest:${encodeURIComponent(
+ "/home/u/.ollama/manifests/registry.ollama.ai/library/qwen3.8/latest",
+ )}`;
+ assert.equal(isPresenceBumpQwen(ref), true);
+ assert.equal(
+ isPresenceBumpQwen(
+ `ollama-manifest:${encodeURIComponent(
+ "/home/u/.ollama/manifests/registry.ollama.ai/library/qwen3/latest",
+ )}`,
+ ),
+ false,
+ );
+ // A malformed escape must not lose the checkpoint entirely.
+ assert.equal(isPresenceBumpQwen("ollama-manifest:%E0%A4%A/qwen3.8/latest"), true);
+});
+
+test("POSIX paths differing only by case are not the same model", () => {
+ const active = "/home/u/Models/qwen3.8-27b";
+ const other = "/home/u/models/qwen3.8-27b";
+ const settings = settingsFor(other);
+
+ const migrated = migrateLegacyQwenDefaults(settings, active, true);
+
+ // The other path is a different file on a case-sensitive filesystem, so its
+ // row must not be moved under the active checkpoint.
+ assert.deepEqual(migrated.migratedModelIds, []);
+ assert.equal(migrated.patch, null);
+});
+
+test("a Windows path still folds case", () => {
+ const active = "C:\\Models\\qwen3.8-27b";
+ const settings = settingsFor("c:\\models\\qwen3.8-27b");
+
+ const migrated = migrateLegacyQwenDefaults(settings, active, true);
+
+ assert.deepEqual(migrated.migratedModelIds, [active]);
+});
+
+test("filename and tag delimiters end the family segment", () => {
+ for (const id of [
+ "/models/Qwen3.8.gguf",
+ "qwen3.8:27b",
+ "C:\\models\\Qwen3.6.gguf",
+ ]) {
+ assert.equal(isPresenceBumpQwen(id), true, id);
+ }
+ // The future-version and parameter-count guards still hold.
+ for (const id of ["qwen3.80-27b", "qwen3.8b", "qwen3.85-27b"]) {
+ assert.equal(isPresenceBumpQwen(id), false, id);
+ }
+});
+
+test("external model keys are matched exactly, not normalized", () => {
+ const active = `external::vendor::${encodeURIComponent("Vendor/Qwen3.8-27B")}`;
+ const other = `external::vendor::${encodeURIComponent("vendor/qwen3.8-27b")}`;
+ const migrated = migrateLegacyQwenDefaults(settingsFor(other), active, true);
+
+ // Provider-qualified ids are opaque, so the other row is a different model.
+ assert.deepEqual(migrated.migratedModelIds, []);
+ assert.equal(migrated.patch, null);
+});
+
+test("two aliases normalizing to the active checkpoint are left alone", () => {
+ // One holds the legacy snapshot, the other the user's own sampling. Picking
+ // by insertion order would serve generated defaults over the customization.
+ const settings = settingsFor(QWEN38.toLowerCase());
+ settings.inferenceParamsByModel = {
+ [QWEN38.toLowerCase()]: LEGACY_SNAPSHOT,
+ [QWEN38.toUpperCase()]: { ...LEGACY_SNAPSHOT, temperature: 0.31 },
+ };
+
+ const migrated = migrateLegacyQwenDefaults(settings, QWEN38, true);
+
+ assert.deepEqual(migrated.migratedModelIds, []);
+ assert.equal(migrated.patch, null);
+});
+
+test("two Ollama manifests differing only by path case stay separate", () => {
+ // The ref wraps a percent-encoded absolute path, and two paths differing only
+ // by case are two files on a case-sensitive filesystem.
+ const ref = (path: string): string =>
+ `ollama-manifest:${encodeURIComponent(path)}`;
+ const active = ref("/home/u/.ollama/models/manifests/Qwen3.8/latest");
+ const other = ref("/home/u/.ollama/models/manifests/qwen3.8/latest");
+ const result = migrateLegacyQwenDefaults(
+ {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParamsByModel: {
+ [other]: { ...LEGACY_SNAPSHOT, maxTokens: 4096 },
+ },
+ },
+ active,
+ true,
+ );
+
+ assert.deepEqual(result.migratedModelIds, []);
+ assert.equal(result.patch, null);
+});
+
+test("a space or bracket ends the Qwen family name", () => {
+ // A local path or filename separates the family with whatever the user typed.
+ for (const id of [
+ "/models/Qwen3.8 27B",
+ "/models/Qwen3.8 (instruct)/model.gguf",
+ "C:\\models\\Qwen3.6 14B.gguf",
+ ]) {
+ assert.equal(isPresenceBumpQwen(id), true, id);
+ }
+ // Still a future family and a parameter count, not this one.
+ for (const id of ["/models/Qwen3.80 27B", "/models/Qwen3.8B", "Qwen3.85"]) {
+ assert.equal(isPresenceBumpQwen(id), false, id);
+ }
+});
diff --git a/studio/frontend/tests/qwen-migration-external-restore.test.ts b/studio/frontend/tests/qwen-migration-external-restore.test.ts
new file mode 100644
index 00000000000..16867a2931d
--- /dev/null
+++ b/studio/frontend/tests/qwen-migration-external-restore.test.ts
@@ -0,0 +1,68 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// The restored external pick is browser-local, but chat settings are
+// installation-wide. Seeding the key before the store module loads is the whole
+// point: the store reads it once while building its initial params.
+
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+import { installLocalStorageFake } from "./helpers/kit.ts";
+
+const EXTERNAL_QWEN = `external::openrouter::${encodeURIComponent(
+ "Qwen/Qwen3.8-27B",
+)}`;
+
+const { store: localStorageFake } = installLocalStorageFake();
+localStorageFake.set("unsloth_chat_settings_imported_to_studio_db", "true");
+localStorageFake.set("unsloth_chat_last_external_checkpoint", EXTERNAL_QWEN);
+register("./store-settings-resolver.mjs", import.meta.url);
+
+const { settingsHttp } = await import("./helpers/store-stubs/settings-http.ts");
+const { useChatRuntimeStore } = await import(
+ "../src/features/chat/stores/chat-runtime-store.ts"
+);
+
+test("a restored external checkpoint does not claim the shared global snapshot", async () => {
+ // Another browser wrote this global for some other model. Nothing adopted a
+ // resident model here, so the stale local pick must not migrate it.
+ settingsHttp.settings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParams: {
+ temperature: 0.6,
+ topP: 0.95,
+ minP: 0.01,
+ presencePenalty: 0.0,
+ },
+ };
+ settingsHttp.puts.length = 0;
+
+ assert.equal(
+ useChatRuntimeStore.getState().params.checkpoint,
+ EXTERNAL_QWEN,
+ "the store restored the external pick",
+ );
+ useChatRuntimeStore.setState({
+ rememberParamsPerModel: false,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: false,
+ });
+
+ await useChatRuntimeStore.getState().hydratePersistedSettings();
+
+ const global = settingsHttp.settings.inferenceParams as Record<
+ string,
+ number
+ >;
+ assert.equal(global.presencePenalty, 0);
+ assert.equal(global.minP, 0.01);
+ assert.deepEqual(
+ settingsHttp.puts.filter((put) => "inferenceParams" in put),
+ [],
+ );
+});
+
diff --git a/studio/frontend/tests/qwen-migration-interactive-pick.test.ts b/studio/frontend/tests/qwen-migration-interactive-pick.test.ts
new file mode 100644
index 00000000000..d8a478383fb
--- /dev/null
+++ b/studio/frontend/tests/qwen-migration-interactive-pick.test.ts
@@ -0,0 +1,66 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Its own file because hydratePersistedSettings memoizes its promise for the
+// life of the module, so a second call in an already-hydrated module returns
+// without reading anything and would assert nothing.
+
+import assert from "node:assert/strict";
+import { register } from "node:module";
+import test from "node:test";
+
+import { installLocalStorageFake } from "./helpers/kit.ts";
+
+const { store: localStorageFake } = installLocalStorageFake();
+localStorageFake.set("unsloth_chat_settings_imported_to_studio_db", "true");
+register("./store-settings-resolver.mjs", import.meta.url);
+
+const { settingsHttp } = await import("./helpers/store-stubs/settings-http.ts");
+const { useChatRuntimeStore } = await import(
+ "../src/features/chat/stores/chat-runtime-store.ts"
+);
+
+const EXTERNAL_QWEN = `external::openrouter::${encodeURIComponent(
+ "Qwen/Qwen3.8-27B",
+)}`;
+
+test("an external model picked during hydration does not claim the global", async () => {
+ // setCheckpoint moves the checkpoint at once and records no adoption marker,
+ // so ownership must not fall out of the absence of load markers. The global
+ // here belongs to whatever another browser last used.
+ settingsHttp.settings = {
+ activePreset: "Default",
+ activePresetSource: "builtin-default",
+ inferenceParams: {
+ temperature: 0.6,
+ topP: 0.95,
+ minP: 0.01,
+ presencePenalty: 0.0,
+ },
+ };
+ settingsHttp.puts.length = 0;
+ useChatRuntimeStore.setState({
+ rememberParamsPerModel: false,
+ reasoningAlwaysOn: false,
+ reasoningEnabled: true,
+ settingsHydrated: false,
+ });
+
+ settingsHttp.hold();
+ const hydration = useChatRuntimeStore.getState().hydratePersistedSettings();
+ useChatRuntimeStore.getState().setCheckpoint(EXTERNAL_QWEN);
+ settingsHttp.release?.();
+ await hydration;
+
+ assert.equal(
+ useChatRuntimeStore.getState().params.checkpoint,
+ EXTERNAL_QWEN,
+ "the pick landed",
+ );
+ const global = settingsHttp.settings.inferenceParams as Record<
+ string,
+ number
+ >;
+ assert.equal(global.presencePenalty, 0);
+ assert.equal(global.minP, 0.01);
+});
diff --git a/studio/frontend/tests/qwen38-sampling-defaults.test.ts b/studio/frontend/tests/qwen38-sampling-defaults.test.ts
index 36a689a09f3..8e59a0a888c 100644
--- a/studio/frontend/tests/qwen38-sampling-defaults.test.ts
+++ b/studio/frontend/tests/qwen38-sampling-defaults.test.ts
@@ -11,9 +11,12 @@ import { installLocalStorageFake } from "./helpers/kit.ts";
installLocalStorageFake();
register("./store-settings-resolver.mjs", import.meta.url);
-const { applyQwenThinkingParams, resolveQwenThinkingParams } = await import(
+const { applyQwenThinkingParams } = await import(
"../src/features/chat/utils/qwen-params.ts"
);
+const { resolveQwenThinkingParams } = await import(
+ "../src/features/chat/utils/qwen-sampling-table.ts"
+);
const { useChatRuntimeStore } = await import(
"../src/features/chat/stores/chat-runtime-store.ts"
);