Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

studio: preserve gguf settings across chat switches (#9562)

Maheswar Kumar2785f01c7ff2
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.py
index 8ef2a679333..bc48a249d0d 100644
--- a/studio/backend/routes/chat_history.py
+++ b/studio/backend/routes/chat_history.py
@@ -132,6 +132,7 @@ class ChatThread(BaseModel):
title: str = "New Chat"
modelType: Literal["base", "lora", "model1", "model2"]
modelId: str = ""
+ modelGgufVariant: Optional[str] = None
pairId: Optional[str] = None
projectId: Optional[str] = None
archived: bool = False
@@ -241,6 +242,7 @@ class ChatThreadPatch(BaseModel):
expectedOpeningMessageId: Optional[str] = None
modelType: Optional[Literal["base", "lora", "model1", "model2"]] = None
modelId: Optional[str] = None
+ modelGgufVariant: Optional[str] = None
pairId: Optional[str] = None
projectId: Optional[str] = None
archived: Optional[bool] = None
diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.py
index e2b30c5d56c..74664097da5 100644
--- a/studio/backend/storage/studio_db.py
+++ b/studio/backend/storage/studio_db.py
@@ -382,6 +382,7 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
title TEXT NOT NULL,
model_type TEXT NOT NULL,
model_id TEXT,
+ model_gguf_variant TEXT,
pair_id TEXT,
project_id TEXT,
archived INTEGER NOT NULL DEFAULT 0,
@@ -401,6 +402,8 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
}
if "settings_json" not in chat_thread_cols:
conn.execute("ALTER TABLE chat_threads ADD COLUMN settings_json TEXT")
+ if "model_gguf_variant" not in chat_thread_cols:
+ conn.execute("ALTER TABLE chat_threads ADD COLUMN model_gguf_variant TEXT")
# Orders one writer's snapshot writes against its own earlier ones. A tab closing
# sends its last edit keepalive, which can overtake a PATCH already accepted by the
# server, and no client-side cancel reaches a handler that is already running: the
@@ -1680,6 +1683,7 @@ def _chat_thread_from_row(row: sqlite3.Row, include_settings: bool = True) -> di
"title": data["title"],
"modelType": data["model_type"],
"modelId": data.get("model_id") or "",
+ "modelGgufVariant": data.get("model_gguf_variant") or None,
"pairId": data.get("pair_id") or None,
"projectId": data.get("project_id") or None,
"archived": bool(data["archived"]),
@@ -1752,11 +1756,16 @@ def upsert_chat_thread(thread: dict) -> dict:
conn.execute(
"""
INSERT INTO chat_threads
- (id, title, model_type, model_id, pair_id, project_id, archived, created_at, updated_at, openai_code_exec_container_id, anthropic_code_exec_container_id, forked_from_thread_id, forked_from_message_id, settings_json)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ (id, title, model_type, model_id, model_gguf_variant, pair_id, project_id, archived, created_at, updated_at, openai_code_exec_container_id, anthropic_code_exec_container_id, forked_from_thread_id, forked_from_message_id, settings_json)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
title = excluded.title,
model_type = excluded.model_type,
+ model_gguf_variant = CASE
+ WHEN excluded.model_id = chat_threads.model_id
+ THEN COALESCE(excluded.model_gguf_variant, chat_threads.model_gguf_variant)
+ ELSE excluded.model_gguf_variant
+ END,
model_id = excluded.model_id,
pair_id = excluded.pair_id,
project_id = excluded.project_id,
@@ -1775,6 +1784,7 @@ def upsert_chat_thread(thread: dict) -> dict:
thread.get("title") or "New Chat",
thread["modelType"],
thread.get("modelId") or "",
+ thread.get("modelGgufVariant"),
thread.get("pairId"),
thread.get("projectId"),
1 if thread.get("archived") else 0,
@@ -1826,6 +1836,7 @@ def update_chat_thread(
"title": ("title", patch.get("title")),
"modelType": ("model_type", patch.get("modelType")),
"modelId": ("model_id", patch.get("modelId")),
+ "modelGgufVariant": ("model_gguf_variant", patch.get("modelGgufVariant")),
"pairId": ("pair_id", patch.get("pairId")),
"projectId": ("project_id", patch.get("projectId")),
"archived": ("archived", 1 if patch.get("archived") else 0),
@@ -3419,16 +3430,17 @@ def fork_chat_thread(
conn.execute(
"""
INSERT INTO chat_threads
- (id, title, model_type, model_id, pair_id, project_id, archived, created_at,
+ (id, title, model_type, model_id, model_gguf_variant, pair_id, project_id, archived, created_at,
openai_code_exec_container_id, anthropic_code_exec_container_id,
forked_from_thread_id, forked_from_message_id, settings_json)
- VALUES (?, ?, ?, ?, ?, ?, 0, ?, NULL, NULL, ?, ?, ?)
+ VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, NULL, NULL, ?, ?, ?)
""",
(
new_thread_id,
new_title,
src_dict["model_type"],
src_dict.get("model_id") or "",
+ src_dict.get("model_gguf_variant"),
None, # pairId: forks always standalone (compare-mode disabled v1)
src_dict.get("project_id"),
int(created_at),
diff --git a/studio/backend/tests/test_chat_history_routes.py b/studio/backend/tests/test_chat_history_routes.py
index 883062c61fc..aa5c0cdd1a3 100644
--- a/studio/backend/tests/test_chat_history_routes.py
+++ b/studio/backend/tests/test_chat_history_routes.py
@@ -186,6 +186,21 @@ def test_save_thread_distinguishes_a_tombstone_from_an_unknown_id(monkeypatch):
assert exc_info.value.detail == "Thread thread-1 was deleted"
+def test_chat_thread_payload_carries_gguf_variant():
+ thread = chat_history.ChatThread(
+ id = "thread-1",
+ title = "GGUF chat",
+ modelType = "base",
+ modelId = "unsloth/Qwen3-GGUF",
+ modelGgufVariant = "Q6_K",
+ createdAt = 1,
+ )
+ patch = chat_history.ChatThreadPatch(modelGgufVariant = "Q8_0")
+
+ assert thread.model_dump()["modelGgufVariant"] == "Q6_K"
+ assert patch.model_dump(exclude_unset = True) == {"modelGgufVariant": "Q8_0"}
+
+
def test_clear_history_fences_pending_thread_ids(monkeypatch):
captured: list[str] = []
captured_operation_ids: list[str | None] = []
diff --git a/studio/backend/tests/test_chat_history_storage.py b/studio/backend/tests/test_chat_history_storage.py
index 0f333823580..4df2bcedd41 100644
--- a/studio/backend/tests/test_chat_history_storage.py
+++ b/studio/backend/tests/test_chat_history_storage.py
@@ -205,6 +205,22 @@ def test_chat_thread_updated_at_survives_thread_resave(tmp_path, monkeypatch):
assert studio_db.get_chat_thread("thread-1")["updatedAt"] == 1_700_000_000_500
+def test_chat_thread_preserves_gguf_variant(tmp_path, monkeypatch):
+ _reset_studio_db(tmp_path, monkeypatch)
+ thread = {**_thread(), "modelGgufVariant": "Q6_K"}
+
+ assert studio_db.upsert_chat_thread(thread)["modelGgufVariant"] == "Q6_K"
+ studio_db.upsert_chat_thread(_thread())
+ assert studio_db.get_chat_thread("thread-1")["modelGgufVariant"] == "Q6_K"
+
+ updated = studio_db.update_chat_thread("thread-1", {"modelGgufVariant": "Q8_0"})
+ assert updated is not None
+ assert updated["modelGgufVariant"] == "Q8_0"
+
+ replacement = {**_thread(), "modelId": "other-model"}
+ assert studio_db.upsert_chat_thread(replacement)["modelGgufVariant"] is None
+
+
def test_list_chat_threads_orders_by_last_activity(tmp_path, monkeypatch):
_reset_studio_db(tmp_path, monkeypatch)
older = _thread("thread-old")
@@ -282,6 +298,7 @@ def test_chat_threads_updated_at_migration_backfills_from_messages(tmp_path, mon
assert studio_db.get_chat_thread("thread-with-msgs")["updatedAt"] == 1_700_000_002_000
assert studio_db.get_chat_thread("thread-empty")["updatedAt"] == 1_700_000_050_000
assert studio_db.get_chat_thread("thread-fork")["updatedAt"] == 1_700_000_100_000
+ assert studio_db.get_chat_thread("thread-with-msgs")["modelGgufVariant"] is None
def test_chat_projects_delete_cascades_threads_and_messages(tmp_path, monkeypatch):
@@ -650,7 +667,12 @@ def _msg(mid: str, parent: str | None, t: int) -> dict:
def test_fork_chat_thread_copies_ancestry_with_fresh_ids(tmp_path, monkeypatch):
_reset_studio_db(tmp_path, monkeypatch)
studio_db.upsert_chat_thread(
- {**_thread("src"), "title": "Original", "openaiCodeExecContainerId": "cnt-x"}
+ {
+ **_thread("src"),
+ "title": "Original",
+ "modelGgufVariant": "Q6_K",
+ "openaiCodeExecContainerId": "cnt-x",
+ }
)
# Linear chain: m1 -> m2 -> m3. Plus a sibling m4 off m2 (should NOT
# be copied since we fork at m3).
@@ -682,6 +704,7 @@ def test_fork_chat_thread_copies_ancestry_with_fresh_ids(tmp_path, monkeypatch):
assert forked["id"] == "fork-1"
assert forked["forkedFromThreadId"] == "src"
assert forked["forkedFromMessageId"] == "m3"
+ assert forked["modelGgufVariant"] == "Q6_K"
# Container ids reset on fork.
assert forked["openaiCodeExecContainerId"] is None
diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsx
index 51a6ae678be..0c8351c8980 100644
--- a/studio/frontend/src/components/assistant-ui/thread.tsx
+++ b/studio/frontend/src/components/assistant-ui/thread.tsx
@@ -3557,6 +3557,7 @@ const Composer: FC<{
projectId: projectIdAtQueueStart,
incognito: incognitoAtQueueStart,
modelId: runSettingsAtQueueStart.params.checkpoint ?? "",
+ modelGgufVariant: runSettingsAtQueueStart.activeGgufVariant,
createdAt: Date.now(),
});
}
@@ -3586,6 +3587,7 @@ const Composer: FC<{
// before any later navigation or compatibility check can observe it.
await updateStoredChatThread(remoteId, {
modelId: runSettingsAtQueueStart.params.checkpoint ?? "",
+ modelGgufVariant: runSettingsAtQueueStart.activeGgufVariant,
});
shouldCorrectPersistedModel = false;
if (
@@ -4088,6 +4090,7 @@ const Composer: FC<{
projectId: projectScope,
incognito: chatStateAtSend.incognito,
modelId: chatStateAtSend.params.checkpoint ?? "",
+ modelGgufVariant: chatStateAtSend.activeGgufVariant,
createdAt: Date.now(),
});
aui.composer().send();
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.ts
index c44e510a483..5437e208e88 100644
--- a/studio/frontend/src/features/chat/api/chat-adapter.ts
+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts
@@ -63,6 +63,7 @@ import {
import { readThreadCreationClaim } from "../utils/chat-thread-creation-claim";
import {
consumeQueuedChatRunSettings,
+ shouldPersistResolvedQueuedModel,
snapshotQueuedChatRunSettings,
} from "../utils/queued-chat-run-settings";
import {
@@ -2147,6 +2148,7 @@ function isAutoLoadableGgufVariant(variant: GgufVariantDetail | null): boolean {
type QueuedResolvedModelRuntime = {
checkpoint: string;
+ activeGgufVariant: string | null;
supportsTools: boolean;
supportsReasoning: boolean;
reasoningAlwaysOn: boolean;
@@ -2293,6 +2295,7 @@ function queuedResolvedModelFromStore(
);
return {
checkpoint: state.params.checkpoint,
+ activeGgufVariant: state.activeGgufVariant,
supportsTools: state.supportsTools,
supportsReasoning: state.supportsReasoning,
reasoningAlwaysOn: state.reasoningAlwaysOn,
@@ -3788,6 +3791,7 @@ async function resolveQueuedEmptyLocalModel(
blockedByTrustRemoteCode: false,
modelRuntime: {
checkpoint,
+ activeGgufVariant: status.gguf_variant ?? null,
supportsTools: status.supports_tools ?? false,
supportsReasoning: status.supports_reasoning ?? false,
reasoningAlwaysOn: status.reasoning_always_on ?? false,
@@ -3945,7 +3949,10 @@ export function createOpenAIStreamAdapter(
const queuedRunSettings =
consumeQueuedChatRunSettings(resolvedThreadId);
let queuedEmptyModelRuntime: QueuedResolvedModelRuntime | null = null;
- const persistResolvedQueuedModel = async (modelId: string) => {
+ const persistResolvedQueuedModel = async (
+ modelId: string,
+ modelGgufVariant: string | null,
+ ) => {
if (
!queuedRunSettings ||
queuedRunSettings.params.checkpoint ||
@@ -3954,11 +3961,14 @@ export function createOpenAIStreamAdapter(
) {
return;
}
- try {
- await updateStoredChatThread(resolvedThreadId, { modelId });
- } catch (error) {
- throw error;
+ const storedThread = await readThreadRecord?.();
+ if (!shouldPersistResolvedQueuedModel(storedThread)) {
+ return;
}
+ await updateStoredChatThread(resolvedThreadId, {
+ modelId,
+ modelGgufVariant,
+ });
};
if (queuedRunSettings) {
runtime = { ...runtime, ...queuedRunSettings };
@@ -4028,6 +4038,10 @@ export function createOpenAIStreamAdapter(
queuedEmptyModelRuntime?.checkpoint ??
liveRuntime.params.checkpoint,
},
+ activeGgufVariant:
+ queuedEmptyModelRuntime !== null
+ ? queuedEmptyModelRuntime.activeGgufVariant
+ : liveRuntime.activeGgufVariant,
supportsTools:
queuedEmptyModelRuntime?.supportsTools ??
liveRuntime.supportsTools,
@@ -4075,7 +4089,10 @@ export function createOpenAIStreamAdapter(
const userMessageParentId =
userMessageIndex > 0 ? messages[userMessageIndex - 1]!.id : null;
const { params } = runtime;
- await persistResolvedQueuedModel(params.checkpoint);
+ await persistResolvedQueuedModel(
+ params.checkpoint,
+ runtime.activeGgufVariant,
+ );
const selectedCheckpoint = params.checkpoint.trim();
const researchExternalSelection = parseExternalModelId(selectedCheckpoint);
const researchExternalProvider = researchExternalSelection
@@ -4375,6 +4392,10 @@ export function createOpenAIStreamAdapter(
queuedEmptyModelRuntime?.checkpoint ??
liveRuntime.params.checkpoint,
},
+ activeGgufVariant:
+ queuedEmptyModelRuntime !== null
+ ? queuedEmptyModelRuntime.activeGgufVariant
+ : liveRuntime.activeGgufVariant,
supportsTools:
queuedEmptyModelRuntime?.supportsTools ??
liveRuntime.supportsTools,
@@ -4414,7 +4435,10 @@ export function createOpenAIStreamAdapter(
}
: liveRuntime;
const { params } = runtime;
- await persistResolvedQueuedModel(params.checkpoint);
+ await persistResolvedQueuedModel(
+ params.checkpoint,
+ runtime.activeGgufVariant,
+ );
const sandboxSessionId = await resolveSandboxSessionId(
resolvedThreadId,
readThreadRecord,
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.ts
index 1bba081a951..7011c789a16 100644
--- a/studio/frontend/src/features/chat/api/chat-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-api.ts
@@ -52,6 +52,11 @@ export const CHAT_HISTORY_UPDATED_EVENT = "unsloth-chat-history-updated";
export { CHAT_HISTORY_REVISION_KEY } from "../utils/chat-history-revision";
export const CHAT_PROJECTS_UPDATED_EVENT = "unsloth-chat-projects-updated";
+export type ChatHistoryUpdatedDetail = {
+ thread?: ThreadRecord;
+ coalesce?: boolean;
+};
+
// bounds the request itself so a wedged socket cannot stall every reader waiting on the write
const THREAD_WRITE_TIMEOUT_MS = 30_000;
@@ -118,14 +123,16 @@ export class GenerationLengthError extends Error {
* `coalesce` is for the per-chunk streaming path alone: it holds the cross-tab write until
* the writes stop. Structural changes must not use it.
*/
-export function notifyChatHistoryUpdated(options?: {
- coalesce?: boolean;
-}): void {
+export function notifyChatHistoryUpdated(
+ detail: ChatHistoryUpdatedDetail = {},
+): void {
if (typeof window !== "undefined") {
- const coalesce = options?.coalesce === true;
+ const coalesce = detail.coalesce === true;
// detail lets a listener tell a chunk save from a structural change (isCoalescedHistoryEvent)
window.dispatchEvent(
- new CustomEvent(CHAT_HISTORY_UPDATED_EVENT, { detail: { coalesce } }),
+ new CustomEvent<ChatHistoryUpdatedDetail>(CHAT_HISTORY_UPDATED_EVENT, {
+ detail: { ...detail, coalesce },
+ }),
);
// The event above is same-document; a storage write is what crosses.
publishChatHistoryRevision(coalesce);
@@ -847,7 +854,7 @@ export async function saveChatThread(
throw new ChatThreadDeletedError(parseErrorText(response.status, body));
}
const savedThread = await parseJsonOrThrow<ThreadRecord>(response);
- notifyChatHistoryUpdated();
+ notifyChatHistoryUpdated({ thread: savedThread });
return savedThread;
}
@@ -899,7 +906,7 @@ export async function updateChatThread(
options.signal,
);
const thread = await parseJsonOrThrow<ThreadRecord>(response);
- if (options.notify !== false) notifyChatHistoryUpdated();
+ if (options.notify !== false) notifyChatHistoryUpdated({ thread });
return thread;
}
@@ -926,7 +933,7 @@ export async function forkChatThread(
messages: MessageRecord[];
containerSnapshotWarning: string | null;
}>(response);
- notifyChatHistoryUpdated();
+ notifyChatHistoryUpdated({ thread: data.thread });
return data;
}
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index 8ce297bc645..a39a992d296 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -138,7 +138,10 @@ import {
ResearchActivitySheet,
} from "./components/research-activity-panel";
import { ChatModelNotice } from "./components/chat-model-notice";
-import { chatModelSwitchMeta } from "./components/chat-model-notice-switch";
+import {
+ chatModelSwitchMeta,
+ type ChatModelSwitchTarget,
+} from "./components/chat-model-notice-switch";
import { ContextUsageBar } from "./components/context-usage-bar";
import { ModelLoadInlineStatus } from "./components/model-load-status";
import { ProjectSwitcher } from "./components/project-switcher";
@@ -205,13 +208,12 @@ import {
CHAT_TOOLS_ENABLED_KEY,
CHAT_WEB_FETCH_TOOLS_ENABLED_KEY,
PENDING_CHAT_ATTACHMENT_KEY,
- hasGgufSource,
- isDownloadableHubRepo,
loadOptionalBool,
readPendingAttachmentTargetClaim,
threadScopedOverride,
useChatRuntimeStore,
} from "./stores/chat-runtime-store";
+import { wantsDownloadManagerStaging } from "./utils/model-download-staging";
import { useChatPreferencesStore } from "./stores/chat-preferences-store";
import { useResearchRunStore } from "./stores/research-run-store";
import { useExternalProvidersStore } from "./stores/external-providers-store";
@@ -2736,14 +2738,8 @@ export function ChatPage({
const stageOrLoad = useCallback(
async (selection: SelectedModelInput) => {
const store = useChatRuntimeStore.getState();
- const wantManagerDownload =
- isDownloadableHubRepo(selection) && !selection.isDownloaded;
+ const wantManagerStaging = wantsDownloadManagerStaging(selection);
if (store.modelLoading) {
- const wantBackgroundDownload =
- wantManagerDownload ||
- (selection.source === "hub" &&
- hasGgufSource(selection) &&
- !selection.isDownloaded);
const isLoadingThisPick =
!!loadingModel &&
normalizeModelRef(loadingModel.id) ===
@@ -2753,7 +2749,7 @@ export function ChatPage({
toast.info("This model is already loading", {
description: "It's downloading as part of the load in progress.",
});
- } else if (wantBackgroundDownload) {
+ } else if (wantManagerStaging) {
const outcome = await downloadManager.requestStart({
kind: DOWNLOAD_KIND.MODEL,
repoId: selection.id,
@@ -2784,12 +2780,7 @@ export function ChatPage({
}
return;
}
- const wantManagerStage =
- wantManagerDownload ||
- (selection.source === "hub" &&
- hasGgufSource(selection) &&
- !selection.isDownloaded);
- if (wantManagerStage) {
+ if (wantManagerStaging) {
setPendingHubAutoLoad((current) =>
current &&
current.selection.id === selection.id &&
@@ -3027,7 +3018,8 @@ export function ChatPage({
const handleCheckpointChange = useCallback(
(
value: string,
- meta?: ModelSelectorChangeMeta,
+ // Partial: the switch-back carries only what the resolver cannot recover.
+ meta?: Partial<ModelSelectorChangeMeta>,
) => {
const store = useChatRuntimeStore.getState();
const currentCheckpoint = store.params.checkpoint;
@@ -3665,10 +3657,10 @@ export function ChatPage({
// `/api/models/list` nor the external ids, so without it the switch loads on
// different arguments than the menu would.
const handleSwitchBackToChatModel = useCallback(
- (modelId: string) => {
+ (target: ChatModelSwitchTarget) => {
handleCheckpointChange(
- modelId,
- chatModelSwitchMeta(modelId, loraModels),
+ target.modelId,
+ chatModelSwitchMeta(target, loraModels),
);
},
[handleCheckpointChange, loraModels],
@@ -4135,6 +4127,7 @@ export function ChatPage({
<ChatModelNotice
threadId={view.threadId ?? newChatThreadId ?? undefined}
checkpoint={inferenceParams.checkpoint}
+ activeGgufVariant={activeGgufVariant}
selectableModelIds={selectableModelIds}
onSwitch={handleSwitchBackToChatModel}
/>
diff --git a/studio/frontend/src/features/chat/components/chat-model-notice-switch.ts b/studio/frontend/src/features/chat/components/chat-model-notice-switch.ts
index c8a2489ee23..2e20ef740b0 100644
--- a/studio/frontend/src/features/chat/components/chat-model-notice-switch.ts
+++ b/studio/frontend/src/features/chat/components/chat-model-notice-switch.ts
@@ -5,40 +5,127 @@ import type {
LoraModelOption,
ModelSelectorChangeMeta,
} from "@/features/model-picker/components/model-selector/types";
+import {
+ ggufQuantLabel,
+ normalizeGgufVariantIdentity,
+} from "../../model-picker/model-config/model-identity";
+import { resolveOnlyRememberedGgufVariant } from "../../model-picker/model-config/per-model-config";
+
+export type ChatModelSwitchTarget = {
+ modelId: string;
+ ggufVariant?: string | null;
+};
+
+type ChatModelThreadSnapshot = {
+ id: string;
+ modelId?: string | null;
+ modelGgufVariant?: string | null;
+};
+
+export function resolveChatModelSwitchTarget(
+ target: ChatModelSwitchTarget,
+): ChatModelSwitchTarget {
+ if (target.ggufVariant) {
+ return target;
+ }
+ const remembered = resolveOnlyRememberedGgufVariant(target.modelId);
+ const basename = target.modelId.replace(/\\/g, "/").split("/").pop() ?? "";
+ if (
+ !remembered ||
+ normalizeGgufVariantIdentity(ggufQuantLabel(`${basename}.gguf`)) !==
+ normalizeGgufVariantIdentity(remembered.ggufVariant)
+ ) {
+ return target;
+ }
+ return { ...target, ggufVariant: remembered.ggufVariant };
+}
+
+function chatModelSwitchTargetFromThread(
+ thread: ChatModelThreadSnapshot | null | undefined,
+): ChatModelSwitchTarget | null {
+ return thread?.modelId
+ ? resolveChatModelSwitchTarget({
+ modelId: thread.modelId,
+ ggufVariant: thread.modelGgufVariant ?? null,
+ })
+ : null;
+}
+
+function sameSwitchTarget(
+ a: ChatModelSwitchTarget | null,
+ b: ChatModelSwitchTarget | null,
+): boolean {
+ return (
+ (a?.modelId ?? null) === (b?.modelId ?? null) &&
+ (a?.ggufVariant ?? null) === (b?.ggufVariant ?? null)
+ );
+}
+
+export function createChatModelHistoryReader(
+ threadId: string,
+ onModel: (model: ChatModelSwitchTarget | null) => void,
+) {
+ let disposed = false;
+ let updateSeen = false;
+ // undefined until the first emit, so an opening read of null still reaches the caller.
+ let emitted: ChatModelSwitchTarget | null | undefined;
+ const emit = (model: ChatModelSwitchTarget | null): void => {
+ if (emitted !== undefined && sameSwitchTarget(emitted, model)) {
+ return;
+ }
+ emitted = model;
+ onModel(model);
+ };
+ return {
+ applyInitial(thread: ChatModelThreadSnapshot | null | undefined): void {
+ if (disposed || updateSeen) {
+ return;
+ }
+ emit(chatModelSwitchTargetFromThread(thread));
+ },
+ // every history event for this thread lands here, renames and archives included,
+ // so the model is compared before a new object is handed to the caller.
+ applyUpdate(thread: ChatModelThreadSnapshot): void {
+ if (disposed || thread.id !== threadId) {
+ return;
+ }
+ updateSeen = true;
+ emit(chatModelSwitchTargetFromThread(thread));
+ },
+ dispose(): void {
+ disposed = true;
+ },
+ };
+}
/**
- * The picker metadata a "Switch back" has to carry, or undefined when the id
- * needs none.
- *
- * `handleCheckpointChange` is the picker's handler, and the picker never calls
- * it with the id alone. For a Hub row or an external model the id is enough:
- * `selectModel` finds the row in `/api/models/list` (which carries `isGguf`) or
- * `isExternalModelId` routes it. A local / fine-tuned row is in neither, so
- * with no metadata `isGguf` resolves false and the /load request drops
- * `n_parallel`, `n_batch`, `n_ubatch` and `llama_extra_args` and sizes the
- * context down the transformers path -- a different load from the one the same
- * model gets when picked from the menu.
+ * The picker metadata a "Switch back" has to carry, or undefined when the id needs none.
*
- * Mirrors what the picker itself supplies for these rows, field for field:
- * `localDirectGgufMeta` for a single .gguf file, and the fine-tuned list's own
- * `selectionMeta` for everything else.
+ * A local / fine-tuned row is in neither `/api/models/list` nor the external ids, so with
+ * no metadata `isGguf` resolves false and the /load request drops the llama.cpp flags. A
+ * Hub repo resolves itself, and a synthesized `source: "hub"` would only route an on-disk
+ * model into the download manager, so just the variant travels. The remembered config
+ * stays off both branches: `stageOrLoad` already falls back to `rememberedConfigFor`.
*/
export function chatModelSwitchMeta(
- modelId: string,
+ target: ChatModelSwitchTarget,
loraModels: readonly LoraModelOption[],
-): ModelSelectorChangeMeta | undefined {
- const row = loraModels.find((model) => model.id === modelId);
- if (!row) return undefined;
+): Partial<ModelSelectorChangeMeta> | undefined {
+ const resolvedTarget = resolveChatModelSwitchTarget(target);
+ const row = loraModels.find((model) => model.id === resolvedTarget.modelId);
+ const ggufVariant = resolvedTarget.ggufVariant || undefined;
+ if (!row) {
+ return ggufVariant ? { ggufVariant } : undefined;
+ }
const isLocal = row.source === "local";
return {
source: isLocal ? "local" : row.source === "exported" ? "exported" : "lora",
- // A local folder is not an adapter, and neither is a merged or GGUF export.
+ // local folders and merged or gguf exports are not adapters.
isLora:
!isLocal && row.exportType !== "merged" && row.exportType !== "gguf",
- // Already on disk: without this the load shows a download progress bar for
- // a model that has nothing to download.
+ // every row here is already on disk.
isDownloaded: true,
- // Set only by chatLocalModelOptions, and only for a single .gguf file.
- isGguf: row.isGguf === true,
+ isGguf: row.isDirectGguf === true || Boolean(ggufVariant),
+ ...(ggufVariant ? { ggufVariant } : {}),
};
}
diff --git a/studio/frontend/src/features/chat/components/chat-model-notice.tsx b/studio/frontend/src/features/chat/components/chat-model-notice.tsx
index edbeed30af4..ccf8c192f3c 100644
--- a/studio/frontend/src/features/chat/components/chat-model-notice.tsx
+++ b/studio/frontend/src/features/chat/components/chat-model-notice.tsx
@@ -4,19 +4,22 @@
import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
+import { ggufVariantsMatch } from "@/features/hub";
+import {
+ CHAT_HISTORY_UPDATED_EVENT,
+ type ChatHistoryUpdatedDetail,
+} from "../api/chat-api";
import { compareModelDisplayName } from "../lib/external-model-label";
import { getStoredChatThread } from "../utils/chat-history-storage";
+import {
+ type ChatModelSwitchTarget,
+ createChatModelHistoryReader,
+} from "./chat-model-notice-switch";
-/**
- * The model a saved chat was started on, read once per chat.
- *
- * Every thread row has carried `modelId` since long before this notice, so an
- * existing chat knows its model without any migration. A chat with no row yet
- * (a New Chat that has not been sent) answers null and shows nothing.
- */
+/** reads the saved chat's starting model and waits for queued initialization. */
export function useChatCreatedModel(
threadId: string | undefined,
-): string | null {
+): ChatModelSwitchTarget | null {
// Keyed by the chat it was read for, not a bare value. Clearing it in the
// effect is a frame late: the effect is passive, so the first render for the
// incoming chat has already committed with the outgoing chat's model, which
@@ -24,24 +27,28 @@ export function useChatCreatedModel(
// only for a matching key makes that render impossible rather than brief.
const [read, setRead] = useState<{
threadId: string;
- modelId: string | null;
+ model: ChatModelSwitchTarget | null;
} | null>(null);
useEffect(() => {
if (!threadId) return;
- let cancelled = false;
+ const reader = createChatModelHistoryReader(threadId, (model) =>
+ setRead({ threadId, model }),
+ );
+ const onHistoryUpdated = (event: Event): void => {
+ const updatedThread = (event as CustomEvent<ChatHistoryUpdatedDetail>)
+ .detail?.thread;
+ if (updatedThread) reader.applyUpdate(updatedThread);
+ };
+ window.addEventListener(CHAT_HISTORY_UPDATED_EVENT, onHistoryUpdated);
void getStoredChatThread(threadId)
- .then((thread) => {
- if (!cancelled) setRead({ threadId, modelId: thread?.modelId || null });
- })
- .catch(() => {
- // A failed read is not worth a message: the notice is an offer, not a
- // gate, and the chat runs on whatever is loaded either way.
- });
+ .then((thread) => reader.applyInitial(thread))
+ .catch(() => undefined);
return () => {
- cancelled = true;
+ reader.dispose();
+ window.removeEventListener(CHAT_HISTORY_UPDATED_EVENT, onHistoryUpdated);
};
}, [threadId]);
- return read && read.threadId === threadId ? read.modelId : null;
+ return read && read.threadId === threadId ? read.model : null;
}
type ChatModelNoticeProps = {
@@ -49,9 +56,10 @@ type ChatModelNoticeProps = {
threadId: string | undefined;
/** The model the composer will actually send to. */
checkpoint: string;
+ activeGgufVariant: string | null;
/** Every model that can be selected right now, by id. */
selectableModelIds: ReadonlySet<string>;
- onSwitch: (modelId: string) => void;
+ onSwitch: (target: ChatModelSwitchTarget) => void;
};
/**
@@ -64,15 +72,23 @@ type ChatModelNoticeProps = {
export function ChatModelNotice({
threadId,
checkpoint,
+ activeGgufVariant,
selectableModelIds,
onSwitch,
}: ChatModelNoticeProps) {
- const createdModelId = useChatCreatedModel(threadId);
- if (!createdModelId || createdModelId === checkpoint) return null;
+ const createdModel = useChatCreatedModel(threadId);
+ if (!createdModel) return null;
+ if (
+ createdModel.modelId === checkpoint &&
+ (createdModel.ggufVariant == null ||
+ ggufVariantsMatch(createdModel.ggufVariant, activeGgufVariant))
+ ) {
+ return null;
+ }
// A model that has since been deleted, or a connection that is gone: the
// switch could not be honoured, and saying so on every open is just noise.
- if (!selectableModelIds.has(createdModelId)) return null;
- const label = compareModelDisplayName(createdModelId);
+ if (!selectableModelIds.has(createdModel.modelId)) return null;
+ const label = compareModelDisplayName(createdModel.modelId);
return (
// Positioned, not in flow. The chat header is `absolute ... z-40` with an
// opaque `bg-background`, so an in-flow sibling starts at y=0 UNDER it and
@@ -90,7 +106,7 @@ export function ChatModelNotice({
variant="ghost"
size="sm"
className="ml-auto h-6 shrink-0 px-2 text-ui-12"
- onClick={() => onSwitch(createdModelId)}
+ onClick={() => onSwitch(createdModel)}
>
Switch back
</Button>
diff --git a/studio/frontend/src/features/chat/local-model-options.ts b/studio/frontend/src/features/chat/local-model-options.ts
index 71e789ba5c2..4ed02f1293f 100644
--- a/studio/frontend/src/features/chat/local-model-options.ts
+++ b/studio/frontend/src/features/chat/local-model-options.ts
@@ -49,6 +49,8 @@ export function chatLocalModelOptions(
continue;
}
seen.add(model.id);
+ const isDirectGguf =
+ model.source === "ollama" || model.path.toLowerCase().endsWith(".gguf");
options.push({
id: model.id,
name:
@@ -58,11 +60,8 @@ export function chatLocalModelOptions(
baseModel: baseModelLabel(model.source),
updatedAt: model.updated_at ?? undefined,
source: "local" as const,
- isGguf:
- model.source === "ollama" || model.path.toLowerCase().endsWith(".gguf")
- ? true
- : undefined,
- isDirectGguf: model.source === "ollama" ? true : undefined,
+ isGguf: isDirectGguf ? true : undefined,
+ isDirectGguf: isDirectGguf ? true : undefined,
});
}
return options;
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsx
index 4900a214c39..9676139a876 100644
--- a/studio/frontend/src/features/chat/runtime-provider.tsx
+++ b/studio/frontend/src/features/chat/runtime-provider.tsx
@@ -698,6 +698,7 @@ export async function ensureThreadRecord({
projectId,
incognito,
modelId,
+ modelGgufVariant,
createdAt,
}: {
threadId: string;
@@ -708,6 +709,7 @@ export async function ensureThreadRecord({
incognito?: boolean;
/** Snapshot from the send this row belongs to, so retries cannot adopt a later checkpoint. */
modelId?: string;
+ modelGgufVariant?: string | null;
/** Snapshot from the send this row belongs to, so retries retain its original creation time. */
createdAt?: number;
}): Promise<void> {
@@ -720,6 +722,10 @@ export async function ensureThreadRecord({
const runtimeStateAtInit = useChatRuntimeStore.getState();
const incognitoAtInit = incognito ?? runtimeStateAtInit.incognito;
const modelIdAtInit = modelId ?? runtimeStateAtInit.params.checkpoint ?? "";
+ const modelGgufVariantAtInit =
+ modelGgufVariant !== undefined
+ ? modelGgufVariant
+ : runtimeStateAtInit.activeGgufVariant;
const createdAtInit = createdAt ?? Date.now();
// Fresh assistant-ui threads are local ids. Temporary chats can skip the
// history list entirely so a storage outage cannot block the first send.
@@ -745,6 +751,7 @@ export async function ensureThreadRecord({
title: "New Chat",
modelType,
modelId: modelIdAtInit,
+ modelGgufVariant: modelGgufVariantAtInit,
pairId,
projectId: projectId ?? null,
archived: false,
@@ -831,6 +838,9 @@ function createStudioDbAdapter(
const modelIdAtInit = claim
? claim.modelId
: (runtimeStateAtInit.params.checkpoint ?? "");
+ const modelGgufVariantAtInit = claim
+ ? claim.modelGgufVariant
+ : runtimeStateAtInit.activeGgufVariant;
const createdAtInit = claim ? claim.createdAt : Date.now();
const projectIdAtInit = claim ? claim.projectId : projectId;
trackStoredChatThreadRecord(threadId, () =>
@@ -841,6 +851,7 @@ function createStudioDbAdapter(
projectId: projectIdAtInit,
incognito: incognitoAtInit,
modelId: modelIdAtInit,
+ modelGgufVariant: modelGgufVariantAtInit,
createdAt: createdAtInit,
}),
);
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 8124e0e9586..c8ceec5a970 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -2367,43 +2367,14 @@ export function loadedGpuMemoryFields(resp: {
};
}
-/** A pick is a GGUF: HF variant, native file, or a direct local .gguf. */
-export function hasGgufSource(x: {
- ggufVariant?: string;
- nativePathToken?: string;
- isGguf?: boolean;
-}): boolean {
- return (
- x.ggufVariant != null || x.nativePathToken != null || x.isGguf === true
- );
-}
-
-/** A local-disk model id: Unix absolute (/), relative (./ ../), tilde (~/),
- * Windows drive (C:\) or UNC (\\server). Shared so the loader and the
- * hub-repo predicate classify ids identically. */
-export function isLocalModelPath(id: string): boolean {
- return /^(\/|\.{1,2}[\\/]|~[\\/]|[A-Za-z]:[\\/]|\\\\)/.test(id);
-}
-
-/** An uncached HF hub repo we can download as a full snapshot (non-GGUF
- * safetensors / MLX). Excludes GGUF sources, local paths, native files, LoRA,
- * and external provider models so none are mis-routed into a snapshot. */
-export function isDownloadableHubRepo(x: {
- id: string;
- source?: string;
- isLora?: boolean;
- ggufVariant?: string;
- nativePathToken?: string;
- isGguf?: boolean;
-}): boolean {
- return (
- x.source === "hub" &&
- !hasGgufSource(x) &&
- x.isLora !== true &&
- x.nativePathToken == null &&
- !isLocalModelPath(x.id)
- );
-}
+// re-exported here so every existing importer keeps its path; defined in a leaf module
+// that a test can load without pulling the whole store in.
+export {
+ hasGgufSource,
+ isDownloadableHubRepo,
+ isLocalModelPath,
+ wantsDownloadManagerStaging,
+} from "../utils/model-download-staging";
type ContextUsageSnapshot = {
promptTokens: number;
diff --git a/studio/frontend/src/features/chat/types.ts b/studio/frontend/src/features/chat/types.ts
index dc98cb65d94..63b3aec3ccb 100644
--- a/studio/frontend/src/features/chat/types.ts
+++ b/studio/frontend/src/features/chat/types.ts
@@ -32,6 +32,7 @@ export interface ThreadRecord {
title: string;
modelType: ModelType;
modelId?: string;
+ modelGgufVariant?: string | null;
pairId?: string;
projectId?: string | null;
archived: boolean;
diff --git a/studio/frontend/src/features/chat/utils/chat-thread-creation-claim.ts b/studio/frontend/src/features/chat/utils/chat-thread-creation-claim.ts
index 44e68a9dfe2..8b6e49de1ef 100644
--- a/studio/frontend/src/features/chat/utils/chat-thread-creation-claim.ts
+++ b/studio/frontend/src/features/chat/utils/chat-thread-creation-claim.ts
@@ -21,6 +21,7 @@ export type ThreadCreationClaim = {
projectId: string | null;
incognito: boolean;
modelId: string;
+ modelGgufVariant: string | null;
createdAt: number;
};
@@ -78,6 +79,7 @@ export function readThreadCreationClaim(
projectId: claim.projectId,
incognito: claim.incognito,
modelId: claim.modelId,
+ modelGgufVariant: claim.modelGgufVariant,
createdAt: claim.createdAt,
};
}
diff --git a/studio/frontend/src/features/chat/utils/model-download-staging.ts b/studio/frontend/src/features/chat/utils/model-download-staging.ts
new file mode 100644
index 00000000000..36f12ded1be
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/model-download-staging.ts
@@ -0,0 +1,56 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/** A pick is a GGUF: HF variant, native file, or a direct local .gguf. */
+export function hasGgufSource(x: {
+ ggufVariant?: string;
+ nativePathToken?: string;
+ isGguf?: boolean;
+}): boolean {
+ return (
+ x.ggufVariant != null || x.nativePathToken != null || x.isGguf === true
+ );
+}
+
+/** A local-disk model id: Unix absolute (/), relative (./ ../), tilde (~/),
+ * Windows drive (C:\) or UNC (\\server). Shared so the loader and the
+ * hub-repo predicate classify ids identically. */
+export function isLocalModelPath(id: string): boolean {
+ return /^(\/|\.{1,2}[\\/]|~[\\/]|[A-Za-z]:[\\/]|\\\\)/.test(id);
+}
+
+/** An uncached HF hub repo we can download as a full snapshot (non-GGUF
+ * safetensors / MLX). Excludes GGUF sources, local paths, native files, LoRA,
+ * and external provider models so none are mis-routed into a snapshot. */
+export function isDownloadableHubRepo(x: {
+ id: string;
+ source?: string;
+ isLora?: boolean;
+ ggufVariant?: string;
+ nativePathToken?: string;
+ isGguf?: boolean;
+}): boolean {
+ return (
+ x.source === "hub" &&
+ !hasGgufSource(x) &&
+ x.isLora !== true &&
+ x.nativePathToken == null &&
+ !isLocalModelPath(x.id)
+ );
+}
+
+/** A pick the Hub download manager must fetch first: an uncached snapshot repo, or a Hub
+ * GGUF whose quant is not on disk. Everything else loads directly, so a caller that
+ * cannot prove a Hub pick is missing must leave `source` unset. */
+export function wantsDownloadManagerStaging(x: {
+ id: string;
+ source?: string;
+ isLora?: boolean;
+ ggufVariant?: string;
+ nativePathToken?: string;
+ isGguf?: boolean;
+ isDownloaded?: boolean;
+}): boolean {
+ if (x.isDownloaded) return false;
+ return isDownloadableHubRepo(x) || (x.source === "hub" && hasGgufSource(x));
+}
diff --git a/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts b/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts
index 06b02e54ad5..fcc08bb2cad 100644
--- a/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts
+++ b/studio/frontend/src/features/chat/utils/queued-chat-run-settings.ts
@@ -1,9 +1,10 @@
// 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 { useChatRuntimeStore } from "../stores/chat-runtime-store";
+import type { useChatRuntimeStore } from "../stores/chat-runtime-store";
const QUEUED_SETTING_KEYS = [
+ "activeGgufVariant",
"supportsTools",
"supportsReasoning",
"reasoningAlwaysOn",
@@ -69,6 +70,13 @@ export function snapshotQueuedChatRunSettings(
return snapshot;
}
+/** A queued send may only fill in the model of a row that was written without one. */
+export function shouldPersistResolvedQueuedModel(
+ storedThread: { modelId?: string | null } | null | undefined,
+): boolean {
+ return Boolean(storedThread && !storedThread.modelId);
+}
+
export function registerQueuedChatRunSettings(
threadIds: string[],
settings: QueuedChatRunSettings,
diff --git a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts b/studio/frontend/src/features/model-picker/model-config/per-model-config.ts
index c289a212d3a..a27fb23ad7f 100644
--- a/studio/frontend/src/features/model-picker/model-config/per-model-config.ts
+++ b/studio/frontend/src/features/model-picker/model-config/per-model-config.ts
@@ -983,6 +983,41 @@ function loadPerModelConfig(
return normalize(map[key]);
}
+export function resolveOnlyRememberedGgufVariant(
+ modelId: string,
+): { ggufVariant: string; config: PerModelConfig } | null {
+ const map = readMap();
+ const variants = new Map<string, string>();
+ const normalizedModelId = normalizeModelIdentity(modelId);
+ for (const key of Object.keys(map)) {
+ const storedModelId = modelIdFromStorageKey(key);
+ const ggufVariant = ggufVariantFromStorageKey(key);
+ if (
+ !storedModelId ||
+ !ggufVariant ||
+ normalizeModelIdentity(storedModelId) !== normalizedModelId
+ ) {
+ continue;
+ }
+ const normalizedVariant = normalizeGgufVariantIdentity(ggufVariant);
+ if (normalizedVariant) {
+ variants.set(normalizedVariant, ggufVariant);
+ }
+ }
+ if (variants.size !== 1) {
+ return null;
+ }
+ const ggufVariant = variants.values().next().value;
+ if (!ggufVariant) {
+ return null;
+ }
+ const key = findConfigKeyForModelVariant(map, modelId, ggufVariant);
+ if (!key || storedConfigVersion(map[key]) > STORAGE_SCHEMA_VERSION) {
+ return null;
+ }
+ return { ggufVariant, config: normalize(map[key]) };
+}
+
export function isDefaultConfig(config: PerModelConfig): boolean {
return (
config.customContextLength == null &&
diff --git a/studio/frontend/tests/chat-remembers-its-model.test.ts b/studio/frontend/tests/chat-remembers-its-model.test.ts
index 71ffc24a610..3cfd0d987ff 100644
--- a/studio/frontend/tests/chat-remembers-its-model.test.ts
+++ b/studio/frontend/tests/chat-remembers-its-model.test.ts
@@ -11,8 +11,29 @@ import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
-import { chatModelSwitchMeta } from "../src/features/chat/components/chat-model-notice-switch.ts";
-import { chatLocalModelOptions } from "../src/features/chat/local-model-options.ts";
+import {
+ installLocalStorageFake,
+ registerBundlerResolver,
+} from "./helpers/kit.ts";
+
+registerBundlerResolver();
+const { store } = installLocalStorageFake();
+const {
+ chatModelSwitchMeta,
+ createChatModelHistoryReader,
+ resolveChatModelSwitchTarget,
+} = await import("../src/features/chat/components/chat-model-notice-switch.ts");
+const { chatLocalModelOptions } = await import(
+ "../src/features/chat/local-model-options.ts"
+);
+const { DEFAULT_PER_MODEL_CONFIG, resolveInitialConfig, savePerModelConfig } =
+ await import("../src/features/model-picker/model-config/per-model-config.ts");
+const { shouldPersistResolvedQueuedModel } = await import(
+ "../src/features/chat/utils/queued-chat-run-settings.ts"
+);
+const { wantsDownloadManagerStaging } = await import(
+ "../src/features/chat/utils/model-download-staging.ts"
+);
function read(path: string): string {
return readFileSync(new URL(path, import.meta.url), "utf8");
@@ -20,11 +41,34 @@ function read(path: string): string {
const notice = read("../src/features/chat/components/chat-model-notice.tsx");
const page = read("../src/features/chat/chat-page.tsx");
+const runtimeProvider = read("../src/features/chat/runtime-provider.tsx");
+const adapter = read("../src/features/chat/api/chat-adapter.ts");
+const chatApi = read("../src/features/chat/api/chat-api.ts");
+const types = read("../src/features/chat/types.ts");
const thread = read("../src/components/assistant-ui/thread.tsx");
const researchPanel = read(
"../src/features/chat/components/research-activity-panel.tsx",
);
const artifact = read("../src/features/chat/artifacts/artifact-surface.tsx");
+const switchSource = read(
+ "../src/features/chat/components/chat-model-notice-switch.ts",
+);
+
+/** The selection handleCheckpointChange builds from the meta, mirrored field for field. */
+function switchBackSelection(
+ target: { modelId: string; ggufVariant?: string | null },
+ rows: Parameters<typeof chatModelSwitchMeta>[1] = [],
+) {
+ const meta = chatModelSwitchMeta(target, rows);
+ return {
+ id: target.modelId,
+ source: meta?.source,
+ isLora: meta?.isLora,
+ ggufVariant: meta?.ggufVariant,
+ isDownloaded: meta?.isDownloaded,
+ isGguf: meta?.isGguf,
+ };
+}
function slice(source: string, from: string, to: string): string {
const start = source.indexOf(from);
@@ -41,19 +85,21 @@ test("the notice never switches a model on its own", () => {
// Opening a chat must not evict what is resident: a local load is multi-gigabyte.
assert.doesNotMatch(notice, /loadModel|setCheckpoint/);
// The only way out of it is the button.
- assert.match(notice, /onClick=\{\(\) => onSwitch\(createdModelId\)\}/);
+ assert.match(notice, /onClick=\{\(\) => onSwitch\(createdModel\)\}/);
});
test("the notice stays quiet when it has nothing to offer", () => {
const body = notice.slice(notice.indexOf("export function ChatModelNotice"));
- // no stamp, already on it, or a model that has since gone away
+ // no stamp, already on the exact pick, or a model that has since gone away
+ assert.match(body, /if \(!createdModel\) return null;/);
+ assert.match(body, /createdModel\.modelId === checkpoint/);
assert.match(
body,
- /if \(!createdModelId \|\| createdModelId === checkpoint\) return null;/,
+ /ggufVariantsMatch\(createdModel\.ggufVariant, activeGgufVariant\)/,
);
assert.match(
body,
- /if \(!selectableModelIds\.has\(createdModelId\)\) return null;/,
+ /if \(!selectableModelIds\.has\(createdModel\.modelId\)\) return null;/,
);
});
@@ -67,11 +113,49 @@ test("switching chats does not show the outgoing chat's model", () => {
notice.indexOf("export function useChatCreatedModel"),
notice.indexOf("type ChatModelNoticeProps"),
);
- assert.match(hook, /setRead\(\{ threadId, modelId:/);
- assert.match(hook, /return read && read\.threadId === threadId \? read\.modelId : null;/);
- // and a read that resolves after the chat changed is dropped
- assert.match(hook, /if \(!cancelled\) setRead/);
- assert.match(hook, /cancelled = true;/);
+ assert.match(
+ hook,
+ /return read && read\.threadId === threadId \? read\.model : null;/,
+ );
+ assert.match(hook, /detail\?\.thread/);
+ assert.match(hook, /reader\.applyUpdate\(updatedThread\)/);
+ assert.match(hook, /reader\.applyInitial\(thread\)/);
+ assert.match(hook, /reader\.dispose\(\)/);
+ assert.match(
+ hook,
+ /addEventListener\(CHAT_HISTORY_UPDATED_EVENT, onHistoryUpdated\)/,
+ );
+ assert.match(
+ hook,
+ /removeEventListener\(CHAT_HISTORY_UPDATED_EVENT, onHistoryUpdated\)/,
+ );
+ assert.match(
+ chatApi,
+ /notifyChatHistoryUpdated\(\{ thread: savedThread \}\)/,
+ );
+ assert.match(chatApi, /notifyChatHistoryUpdated\(\{ thread \}\)/);
+});
+
+test("a thread update wins over an older initial model read", () => {
+ const seen: unknown[] = [];
+ const reader = createChatModelHistoryReader("thread-1", (model) => {
+ seen.push(model);
+ });
+ reader.applyUpdate({
+ id: "thread-1",
+ modelId: "resolved-model",
+ modelGgufVariant: "Q6_K",
+ });
+ reader.applyInitial({
+ id: "thread-1",
+ modelId: "interim-model",
+ modelGgufVariant: "Q8_0",
+ });
+ reader.applyUpdate({ id: "another-thread", modelId: "unrelated-model" });
+ assert.deepEqual(seen, [{ modelId: "resolved-model", ggufVariant: "Q6_K" }]);
+ reader.dispose();
+ reader.applyUpdate({ id: "thread-1", modelId: "late-model" });
+ assert.equal(seen.length, 1);
});
test("the notice is wired to the picker's own handler, not a private path", () => {
@@ -85,7 +169,7 @@ test("the notice is wired to the picker's own handler, not a private path", () =
"const inventoryRefreshStartedRef",
);
assert.match(wrapper, /handleCheckpointChange\(/);
- assert.match(wrapper, /chatModelSwitchMeta\(modelId, loraModels\)/);
+ assert.match(wrapper, /chatModelSwitchMeta\(target, loraModels\)/);
assert.match(page, /selectableModelIds=\{selectableModelIds\}/);
// Offered only for a real saved chat, in the single-chat view.
assert.match(page, /view\.mode === "single" && \(\s*<ChatModelNotice/);
@@ -260,6 +344,61 @@ test("a chat started as New Chat gets the notice once its row exists", () => {
assert.match(notice, /threadId=\{view\.threadId \?\? newChatThreadId \?\? undefined\}/);
});
+test("a chat thread keeps the GGUF variant it started on", () => {
+ assert.match(types, /modelGgufVariant\?: string \| null;/);
+ const creator = slice(
+ runtimeProvider,
+ "export async function ensureThreadRecord",
+ "function createStudioDbAdapter",
+ );
+ assert.match(creator, /modelGgufVariantAtInit/);
+ assert.match(creator, /modelGgufVariant: modelGgufVariantAtInit/);
+ const initialize = slice(
+ runtimeProvider,
+ "initialize(threadId",
+ "async rename",
+ );
+ assert.match(initialize, /runtimeStateAtInit\.activeGgufVariant/);
+ assert.match(initialize, /modelGgufVariant: modelGgufVariantAtInit/);
+});
+
+test("a queued empty-model send backfills its resolved GGUF variant", () => {
+ const persistence = slice(
+ adapter,
+ "const persistResolvedQueuedModel",
+ "if (queuedRunSettings)",
+ );
+ assert.match(persistence, /modelGgufVariant: string \| null/);
+ assert.match(persistence, /modelGgufVariant,/);
+ assert.match(persistence, /shouldPersistResolvedQueuedModel/);
+ assert.match(adapter, /activeGgufVariant: state\.activeGgufVariant/);
+ assert.match(adapter, /activeGgufVariant: status\.gguf_variant \?\? null/);
+ assert.match(
+ adapter,
+ /queuedEmptyModelRuntime !== null[\s\S]{0,100}queuedEmptyModelRuntime\.activeGgufVariant[\s\S]{0,80}liveRuntime\.activeGgufVariant/,
+ );
+ assert.match(adapter, /params\.checkpoint,\s*runtime\.activeGgufVariant/);
+ const queuedSettings = read(
+ "../src/features/chat/utils/queued-chat-run-settings.ts",
+ );
+ assert.match(queuedSettings, /"activeGgufVariant"/);
+ assert.match(thread, /modelGgufVariant: runSettingsAtQueueStart\.activeGgufVariant/);
+});
+
+test("queued model backfill changes only a fresh empty thread row", () => {
+ assert.equal(shouldPersistResolvedQueuedModel({ modelId: "" }), true);
+ assert.equal(
+ shouldPersistResolvedQueuedModel({ modelId: "original-model" }),
+ false,
+ );
+ assert.equal(shouldPersistResolvedQueuedModel(undefined), false);
+ // The caller has already returned on a queued checkpoint four lines earlier.
+ assert.match(
+ slice(adapter, "const persistResolvedQueuedModel", "if (queuedRunSettings)"),
+ /queuedRunSettings\.params\.checkpoint \|\|/,
+ );
+});
+
// The switch back is the picker's handler, so it has to arrive carrying what the picker
// itself would have put on it. A local or fine-tuned row is in neither /api/models/list
// nor the external ids, so with the bare id selectModel resolves isGguf false and the
@@ -267,12 +406,13 @@ test("a chat started as New Chat gets the notice once its row exists", () => {
// context down the transformers path.
test("switching back to a single-file local GGUF still loads as a GGUF", () => {
- const meta = chatModelSwitchMeta("/models/qwen3-4b-q4.gguf", [
+ const meta = chatModelSwitchMeta({ modelId: "/models/qwen3-4b-q4.gguf" }, [
{
id: "/models/qwen3-4b-q4.gguf",
name: "qwen3-4b-q4",
source: "local",
isGguf: true,
+ isDirectGguf: true,
},
]);
assert.deepEqual(meta, {
@@ -298,23 +438,213 @@ test("a single .gguf file carries its format out of the local inventory", () =>
assert.equal(option.isGguf, true);
});
-test("a GGUF directory is not claimed as a GGUF, since its quant is unknown", () => {
- // That row expands in the picker to pick a variant, and a chat row records only
- // modelId. Sending llama-server flags for a quant nobody chose is worse than the
- // plain switch.
+test("a saved GGUF variant is carried back exactly", () => {
+ store.clear();
+ const modelId = "/models/Qwen3-4B-GGUF";
+ assert.deepEqual(
+ chatModelSwitchMeta({ modelId, ggufVariant: "Q6_K" }, [
+ {
+ id: modelId,
+ name: "Qwen3-4B-GGUF",
+ source: "local",
+ isGguf: true,
+ },
+ ]),
+ {
+ source: "local",
+ isLora: false,
+ isDownloaded: true,
+ isGguf: true,
+ ggufVariant: "Q6_K",
+ },
+ );
+ assert.deepEqual(
+ chatModelSwitchMeta(
+ { modelId: "unsloth/Qwen3-4B-GGUF", ggufVariant: "Q8_0" },
+ [],
+ ),
+ { ggufVariant: "Q8_0" },
+ );
+});
+
+test("switching back to a hub GGUF loads it instead of staging a download", () => {
+ store.clear();
+ // stageOrLoad routes a pick with source "hub" and no isDownloaded through the download
+ // manager. Two of requestStart's outcomes, conflict and busy, toast and return without
+ // loading, so a switch back that lands there silently does nothing.
+ const selection = switchBackSelection({
+ modelId: "unsloth/Qwen3-4B-GGUF",
+ ggufVariant: "Q8_0",
+ });
+ assert.equal(wantsDownloadManagerStaging(selection), false);
+ // and the variant, the one thing no resolver can recover, still travels
+ assert.equal(selection.ggufVariant, "Q8_0");
+ // A pick the picker itself marks as a hub row still stages, so nothing else moved.
+ assert.equal(
+ wantsDownloadManagerStaging({
+ id: "unsloth/Qwen3-4B-GGUF",
+ source: "hub",
+ ggufVariant: "Q8_0",
+ }),
+ true,
+ );
+ // The selection mapping above and the predicate under test are the page's own.
+ const built = slice(page, "const selection = {", "await stageOrLoad(selection);");
+ for (const field of [
+ "source: meta?.source",
+ "isLora: meta?.isLora",
+ "ggufVariant: meta?.ggufVariant",
+ "isGguf: meta?.isGguf",
+ ]) {
+ assert.ok(built.includes(field), `selection lost ${field}`);
+ }
+ assert.match(built, /isDownloaded: meta\?\.isDownloaded \|\| isSameLoadedModel/);
+ assert.match(
+ page,
+ /const wantManagerStaging = wantsDownloadManagerStaging\(selection\);/,
+ );
+});
+
+test("a history update that leaves the model alone is not re-emitted", () => {
+ // Every CHAT_HISTORY_UPDATED_EVENT for the thread reaches applyUpdate, renames and
+ // archives included, and a fresh object each time re-renders the notice for nothing.
+ const seen: unknown[] = [];
+ const reader = createChatModelHistoryReader("thread-1", (model) => {
+ seen.push(model);
+ });
+ reader.applyInitial({
+ id: "thread-1",
+ modelId: "model-a",
+ modelGgufVariant: "Q6_K",
+ });
+ reader.applyUpdate({
+ id: "thread-1",
+ modelId: "model-a",
+ modelGgufVariant: "Q6_K",
+ });
+ reader.applyUpdate({
+ id: "thread-1",
+ modelId: "model-a",
+ modelGgufVariant: "Q6_K",
+ });
+ assert.equal(seen.length, 1);
+ reader.applyUpdate({
+ id: "thread-1",
+ modelId: "model-a",
+ modelGgufVariant: "Q8_0",
+ });
+ assert.equal(seen.length, 2);
+ reader.dispose();
+});
+
+test("a legacy GGUF directory recovers its sole saved variant and context", () => {
+ store.clear();
+ const modelId = String.raw`N:\AI Models\Qwen\Qwen3.6-40B-Q6_K`;
+ assert.ok(
+ savePerModelConfig(modelId, "Q6_K", {
+ ...DEFAULT_PER_MODEL_CONFIG,
+ customContextLength: 32768,
+ }),
+ );
+ const [option] = chatLocalModelOptions([
+ {
+ id: modelId,
+ display_name: "Qwen3.6-40B-Q6_K",
+ path: modelId,
+ source: "custom",
+ model_format: "gguf",
+ },
+ ]);
+ assert.equal(option.isDirectGguf, undefined);
+ const target = resolveChatModelSwitchTarget({ modelId });
+ assert.equal(target.ggufVariant?.toLowerCase(), "q6_k");
+ const meta = chatModelSwitchMeta(target, [option]);
+ assert.equal(meta?.isGguf, true);
+ assert.equal(meta?.ggufVariant?.toLowerCase(), "q6_k");
+ // The variant is the key the saved 32768 is filed under; stageOrLoad does the lookup.
+ assert.equal(
+ resolveInitialConfig(modelId, target.ggufVariant ?? undefined).config
+ .customContextLength,
+ 32768,
+ );
+});
+
+test("a legacy GGUF directory does not guess between saved variants", () => {
+ store.clear();
+ const modelId = "/models/Qwen3-4B-GGUF";
+ for (const variant of ["Q4_K_M", "Q8_0"]) {
+ assert.ok(
+ savePerModelConfig(modelId, variant, {
+ ...DEFAULT_PER_MODEL_CONFIG,
+ customContextLength: 32768,
+ }),
+ );
+ }
const [option] = chatLocalModelOptions([
{
- id: "/models/Qwen3-4B-GGUF",
+ id: modelId,
display_name: "Qwen3-4B-GGUF",
- path: "/models/Qwen3-4B-GGUF",
+ path: modelId,
source: "models_dir",
model_format: "gguf",
},
]);
- assert.equal(option.isGguf, undefined);
+ const meta = chatModelSwitchMeta({ modelId }, [option]);
+ assert.equal(meta?.isGguf, false);
+ assert.equal(meta?.ggufVariant, undefined);
+ assert.equal(meta?.config, undefined);
+});
+
+test("a legacy GGUF directory does not infer a quant from config alone", () => {
+ store.clear();
+ const modelId = "/models/Qwen3-4B-GGUF";
+ assert.ok(
+ savePerModelConfig(modelId, "Q6_K", {
+ ...DEFAULT_PER_MODEL_CONFIG,
+ customContextLength: 32768,
+ }),
+ );
+ assert.equal(resolveChatModelSwitchTarget({ modelId }).ggufVariant, undefined);
+});
+
+test("the switch back leaves the remembered config to stageOrLoad", () => {
+ store.clear();
+ const modelId = "/models/qwen3-4b-q4.gguf";
+ assert.ok(
+ savePerModelConfig(modelId, null, {
+ ...DEFAULT_PER_MODEL_CONFIG,
+ customContextLength: 32768,
+ }),
+ );
+ const selection = switchBackSelection({ modelId }, [
+ {
+ id: modelId,
+ name: "qwen3-4b-q4",
+ source: "local",
+ isGguf: true,
+ isDirectGguf: true,
+ },
+ ]);
+ // A config on the meta would duplicate the lookup stageOrLoad already does.
+ assert.doesNotMatch(
+ slice(switchSource, "import type {", "export type ChatModelSwitchTarget"),
+ /resolveInitialConfig/,
+ );
+ const stage = slice(page, "const stageOrLoad = useCallback", "useRepoDownload(");
+ assert.match(stage, /selection\.config \?\? rememberedConfigFor\(selection\)/);
+ const remembered = slice(
+ page,
+ "const rememberedConfigFor = useCallback",
+ "const isExternalModel",
+ );
+ assert.match(
+ remembered,
+ /resolveInitialConfig\(selection\.id, selection\.ggufVariant\)/,
+ );
assert.equal(
- chatModelSwitchMeta("/models/Qwen3-4B-GGUF", [option])?.isGguf,
- false,
+ resolveInitialConfig(selection.id, selection.ggufVariant).config
+ .customContextLength,
+ 32768,
);
});
@@ -329,13 +659,13 @@ test("switching back to a fine-tuned row mirrors the picker's own metadata", ()
exportType: "merged" as const,
},
];
- assert.deepEqual(chatModelSwitchMeta("run-1", adapters), {
+ assert.deepEqual(chatModelSwitchMeta({ modelId: "run-1" }, adapters), {
source: "lora",
isLora: true,
isDownloaded: true,
isGguf: false,
});
- assert.deepEqual(chatModelSwitchMeta("run-2", adapters), {
+ assert.deepEqual(chatModelSwitchMeta({ modelId: "run-2" }, adapters), {
source: "exported",
isLora: false,
isDownloaded: true,
@@ -347,6 +677,12 @@ test("a Hub or external id is still switched on the id alone", () => {
// Those two resolve without help: /api/models/list carries isGguf, and
// isExternalModelId routes the rest. Inventing a "local" source for them would
// send them down the wrong branch of handleCheckpointChange.
- assert.equal(chatModelSwitchMeta("unsloth/Qwen3-4B-GGUF", []), undefined);
- assert.equal(chatModelSwitchMeta("openai:gpt-5-mini", []), undefined);
+ assert.equal(
+ chatModelSwitchMeta({ modelId: "unsloth/Qwen3-4B-GGUF" }, []),
+ undefined,
+ );
+ assert.equal(
+ chatModelSwitchMeta({ modelId: "openai:gpt-5-mini" }, []),
+ undefined,
+ );
});
diff --git a/tests/studio/test_multi_chat_prompt_queue_contract.py b/tests/studio/test_multi_chat_prompt_queue_contract.py
index e56f2fbb134..eb4099807f7 100644
--- a/tests/studio/test_multi_chat_prompt_queue_contract.py
+++ b/tests/studio/test_multi_chat_prompt_queue_contract.py
@@ -428,7 +428,16 @@ def test_queued_settings_are_thread_scoped_without_cross_chat_fallback():
assert "getInferenceStatus().catch(() => null)" not in lifecycle
assert "const status = await getInferenceStatus();" in lifecycle
assert "options?.abortSignal?.throwIfAborted()" in CHAT_ADAPTER
- assert CHAT_ADAPTER.count("await persistResolvedQueuedModel(params.checkpoint)") >= 2
+ assert (
+ len(
+ re.findall(
+ r"await persistResolvedQueuedModel\(\s*params\.checkpoint,"
+ r"\s*runtime\.activeGgufVariant,\s*\)",
+ CHAT_ADAPTER,
+ )
+ )
+ >= 2
+ )
assert "notifyQueuedRunFailed" not in CHAT_ADAPTER
assert "pendingSettings.length === 1" not in QUEUED_SETTINGS
assert "entry.threadIds.has(threadId)" in QUEUED_SETTINGS