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: carry chat settings across browsers and remote sessions (#8656)

Maheswar Kumarc38daa3b5d5f
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.py
index fa0cb1ead6c..e457963ea10 100644
--- a/studio/backend/routes/chat_history.py
+++ b/studio/backend/routes/chat_history.py
@@ -10,7 +10,7 @@ mixed handlers explicitly send their database transaction through Starlette's th
import asyncio
import sqlite3
-from typing import Annotated, Any, Literal, Optional
+from typing import Annotated, Any, Literal, Optional, Union
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
@@ -18,6 +18,7 @@ from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_valida
from auth.authentication import get_current_subject
from core.inference.llama_server_args import BATCH_MAX, BATCH_MIN, PARALLEL_MAX, PARALLEL_MIN
from loggers import get_logger
+from utils.api_errors import safe_validation_errors
from utils.utils import safe_curated_detail, log_and_http_error
from storage.studio_db import (
ChatMessageConflictError,
@@ -175,7 +176,13 @@ class ChatExportResponse(BaseModel):
class ChatInferenceSettings(BaseModel):
- model_config = ConfigDict(extra = "forbid")
+ # allow_inf_nan: json.loads accepts bare NaN and Infinity, and pydantic takes them
+ # for a float, so `{"temperature": NaN}` used to be stored as a bare NaN token in
+ # value_json. Python reads that back, so the row is never quarantined, while the
+ # response model renders it as null: the value is silently lost and the row is not
+ # valid JSON for any strict reader. Refuse it at the door instead, the way
+ # models/training.py already does for every numeric training field.
+ model_config = ConfigDict(extra = "forbid", allow_inf_nan = False)
temperature: Optional[float] = None
topP: Optional[float] = None
@@ -192,7 +199,7 @@ class ChatInferenceSettings(BaseModel):
class ChatPresetLoadConfig(BaseModel):
- model_config = ConfigDict(extra = "forbid")
+ model_config = ConfigDict(extra = "forbid", allow_inf_nan = False)
customContextLength: Optional[int] = Field(default = None, gt = 0)
maxSeqLength: Optional[float] = None
@@ -229,9 +236,34 @@ class ChatPreset(BaseModel):
loadConfig: Optional[ChatPresetLoadConfig] = None
-class ChatSettingsPayload(BaseModel):
+class ChatRagThreadSource(BaseModel):
+ model_config = ConfigDict(extra = "forbid")
+
+ type: Literal["thread"]
+
+
+class ChatRagKnowledgeBaseSource(BaseModel):
+ model_config = ConfigDict(extra = "forbid")
+
+ type: Literal["kb"]
+ kbId: str = Field(min_length = 1, max_length = 256)
+
+
+class ChatResearchWebsitePolicy(BaseModel):
model_config = ConfigDict(extra = "forbid")
+ # 253 is the maximum length of a DNS name.
+ allowedDomains: list[Annotated[str, Field(max_length = 253)]] = Field(
+ default_factory = list, max_length = 1_000
+ )
+ blockedDomains: list[Annotated[str, Field(max_length = 253)]] = Field(
+ default_factory = list, max_length = 1_000
+ )
+
+
+class ChatSettingsPayload(BaseModel):
+ model_config = ConfigDict(extra = "forbid", allow_inf_nan = False)
+
inferenceParams: Optional[ChatInferenceSettings] = None
customPresets: Optional[list[ChatPreset]] = None
activePreset: Optional[str] = None
@@ -248,6 +280,42 @@ class ChatSettingsPayload(BaseModel):
maxToolCallsPerMessage: Optional[int] = Field(default = None, ge = 1)
toolCallTimeout: Optional[int] = Field(default = None, ge = 1)
+ # Composer and RAG toggles. They describe the installation, not the browser
+ # that set them, so a second browser or a remote session reads them back here
+ # instead of falling back to defaults.
+ reasoningEnabled: Optional[bool] = None
+ toolsEnabled: Optional[bool] = None
+ codeToolsEnabled: Optional[bool] = None
+ imageToolsEnabled: Optional[bool] = None
+ webFetchToolsEnabled: Optional[bool] = None
+ deepResearchEnabled: Optional[bool] = None
+ researchWebsitePolicy: Optional[ChatResearchWebsitePolicy] = None
+ artifactsEnabled: Optional[bool] = None
+ showCanvasMenuItem: Optional[bool] = None
+ mcpEnabledForChat: Optional[bool] = None
+ confirmToolCalls: Optional[bool] = None
+ # "full" (Full access) is session-only by design and never persisted.
+ permissionMode: Optional[Literal["ask", "auto", "off"]] = None
+ ragSource: Optional[
+ Annotated[
+ Union[ChatRagThreadSource, ChatRagKnowledgeBaseSource],
+ Field(discriminator = "type"),
+ ]
+ ] = None
+ ragMode: Optional[Literal["hybrid", "lexical", "dense"]] = None
+ # Matches the ge/le the retrieval endpoint enforces on its own top_k.
+ ragTopK: Optional[int] = Field(default = None, ge = 1, le = 50)
+ ragAutoInject: Optional[Literal["auto", "on", "off"]] = None
+ ragAutoInjectMinScore: Optional[float] = Field(default = None, ge = 0, le = 1)
+ ragOcrScanned: Optional[bool] = None
+ ragCaptionFigures: Optional[bool] = None
+ # Standing load preferences the model-load path reads outside the store.
+ speculativeType: Optional[Literal["auto", "ngram", "off"]] = None
+ gpuMemoryMode: Optional[Literal["auto", "manual"]] = None
+ expandQuantizations: Optional[bool] = None
+ showAllQuantizations: Optional[bool] = None
+ fitOnDeviceOnly: Optional[bool] = None
+
class ChatSettingsResponse(BaseModel):
settings: dict[str, Any]
@@ -1094,7 +1162,12 @@ def put_settings(payload: dict[str, Any], current_subject: str = Depends(get_cur
try:
parsed = ChatSettingsPayload.model_validate(payload)
except ValidationError as exc:
- raise HTTPException(status_code = 400, detail = exc.errors()) from exc
+ # safe_validation_errors, not exc.errors(): the raw errors echo the offending
+ # input, and Starlette's JSONResponse dumps with allow_nan = False, so a
+ # rejected NaN or Infinity made the 400 handler itself unrenderable and the
+ # caller got a 500 for a request the validator had already refused. It also
+ # bounds a multi-megabyte value being quoted back.
+ raise HTTPException(status_code = 400, detail = safe_validation_errors(exc.errors())) from exc
# Atomic read + deep-merge + write in one BEGIN IMMEDIATE so concurrent updates don't clobber.
try:
return ChatSettingsResponse(
diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.py
index bcf59124544..cbd66c353aa 100644
--- a/studio/backend/storage/studio_db.py
+++ b/studio/backend/storage/studio_db.py
@@ -3650,11 +3650,20 @@ def upsert_chat_settings(settings: dict[str, Any]) -> dict[str, Any]:
conn.close()
+# Discriminated unions, not partial patches: merging a `thread` pick into a stored
+# `kb` one keeps `kbId`, which the payload's thread variant forbids.
+_ATOMIC_SETTING_KEYS = frozenset({"ragSource"})
+
+
def _deep_merge_settings(current: dict[str, Any], updates: dict[str, Any]) -> dict[str, Any]:
merged = dict(current)
for key, value in updates.items():
current_value = merged.get(key)
- if isinstance(current_value, dict) and isinstance(value, dict):
+ if (
+ key not in _ATOMIC_SETTING_KEYS
+ and isinstance(current_value, dict)
+ and isinstance(value, dict)
+ ):
merged[key] = _deep_merge_settings(current_value, value)
else:
merged[key] = value
@@ -3670,8 +3679,12 @@ def upsert_chat_settings_merge(updates: dict[str, Any]) -> dict[str, Any]:
try:
conn.execute("BEGIN IMMEDIATE")
current, corrupt = _load_chat_settings_for_merge(conn)
+ # An atomic key carries its whole value, so it repairs a quarantined row
+ # rather than patching a base that is no longer there.
unsafe_partial_keys = [
- key for key, value in updates.items() if key in corrupt and isinstance(value, dict)
+ 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()
diff --git a/studio/backend/tests/test_chat_settings_payload.py b/studio/backend/tests/test_chat_settings_payload.py
new file mode 100644
index 00000000000..6ae5b205457
--- /dev/null
+++ b/studio/backend/tests/test_chat_settings_payload.py
@@ -0,0 +1,199 @@
+# 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 mirrored chat toggles PUT /api/chat/settings accepts.
+
+The payload is extra="forbid" and one bad field 400s the whole save, so these pin
+the contract the client sanitises against before sending.
+"""
+
+import sys
+from pathlib import Path
+
+import pytest
+from pydantic import ValidationError
+
+_BACKEND = Path(__file__).resolve().parents[1]
+if str(_BACKEND) not in sys.path:
+ sys.path.insert(0, str(_BACKEND))
+
+from routes.chat_history import ChatSettingsPayload # noqa: E402
+from storage.studio_db import ( # noqa: E402
+ CorruptSettingsError,
+ _deep_merge_settings,
+ get_connection,
+ upsert_chat_settings_merge,
+)
+
+
+def test_mirrored_settings_round_trip():
+ payload = ChatSettingsPayload.model_validate(
+ {
+ "toolsEnabled": True,
+ "deepResearchEnabled": False,
+ "permissionMode": "ask",
+ "ragSource": {"type": "kb", "kbId": "notes"},
+ "ragMode": "dense",
+ "ragTopK": 12,
+ "ragAutoInject": "on",
+ "ragAutoInjectMinScore": 0.42,
+ "researchWebsitePolicy": {
+ "allowedDomains": ["unsloth.ai"],
+ "blockedDomains": [],
+ },
+ "speculativeType": "ngram",
+ "gpuMemoryMode": "manual",
+ "fitOnDeviceOnly": True,
+ }
+ )
+
+ assert payload.model_dump(exclude_unset = True) == {
+ "toolsEnabled": True,
+ "deepResearchEnabled": False,
+ "permissionMode": "ask",
+ "ragSource": {"type": "kb", "kbId": "notes"},
+ "ragMode": "dense",
+ "ragTopK": 12,
+ "ragAutoInject": "on",
+ "ragAutoInjectMinScore": 0.42,
+ "researchWebsitePolicy": {
+ "allowedDomains": ["unsloth.ai"],
+ "blockedDomains": [],
+ },
+ "speculativeType": "ngram",
+ "gpuMemoryMode": "manual",
+ "fitOnDeviceOnly": True,
+ }
+
+
+def test_thread_rag_source_keeps_its_shape():
+ payload = ChatSettingsPayload.model_validate({"ragSource": {"type": "thread"}})
+ assert payload.model_dump(exclude_unset = True) == {"ragSource": {"type": "thread"}}
+
+
+def test_rag_source_replaces_rather_than_merges():
+ """A thread pick over a stored kb pick must not keep kbId.
+
+ The union's thread variant forbids extra fields, so a merged
+ {"type": "thread", "kbId": ...} is out of contract the moment it is read back.
+ """
+ merged = _deep_merge_settings(
+ {"ragSource": {"type": "kb", "kbId": "notes"}},
+ {"ragSource": {"type": "thread"}},
+ )
+ assert merged["ragSource"] == {"type": "thread"}
+ ChatSettingsPayload.model_validate(merged)
+
+
+def _corrupt_stored_setting(key: str) -> None:
+ conn = get_connection()
+ try:
+ conn.execute("UPDATE chat_settings SET value_json = ? WHERE key = ?", ("{not json", key))
+ conn.commit()
+ finally:
+ conn.close()
+
+
+def test_a_valid_rag_source_repairs_a_corrupt_row():
+ """An atomic key carries its whole value, so it can replace a quarantined row.
+
+ The corrupt-key guard exists because a partial patch would merge onto a base
+ that is no longer there. Applying it to ragSource would 409 the user's pick and
+ leave the selection unsaved.
+ """
+ upsert_chat_settings_merge({"ragSource": {"type": "kb", "kbId": "notes"}})
+ _corrupt_stored_setting("ragSource")
+
+ merged = upsert_chat_settings_merge({"ragSource": {"type": "thread"}})
+ assert merged["ragSource"] == {"type": "thread"}
+
+
+def test_a_partial_patch_onto_a_corrupt_row_still_conflicts():
+ upsert_chat_settings_merge({"inferenceParams": {"temperature": 0.7, "topP": 0.9}})
+ _corrupt_stored_setting("inferenceParams")
+
+ with pytest.raises(CorruptSettingsError):
+ upsert_chat_settings_merge({"inferenceParams": {"temperature": 0.2}})
+
+
+def test_other_nested_settings_still_merge():
+ merged = _deep_merge_settings(
+ {"inferenceParams": {"temperature": 0.7, "topP": 0.9}},
+ {"inferenceParams": {"temperature": 0.2}},
+ )
+ assert merged["inferenceParams"] == {"temperature": 0.2, "topP": 0.9}
+
+
+def test_unset_fields_stay_out_of_the_merge():
+ payload = ChatSettingsPayload.model_validate({"ragTopK": 5})
+ assert payload.model_dump(exclude_unset = True) == {"ragTopK": 5}
+
+
+ "payload",
+ [
+ # Full access disables the sandbox, so it is re-accepted each session.
+ {"permissionMode": "full"},
+ {"ragTopK": 0},
+ {"ragTopK": 51},
+ {"ragAutoInjectMinScore": 2},
+ {"ragMode": "vector"},
+ {"speculativeType": "mtp"},
+ {"gpuMemoryMode": ""},
+ {"ragSource": {"type": "kb"}},
+ {"ragSource": {"type": "kb", "kbId": ""}},
+ {"researchWebsitePolicy": {"allowedDomains": "unsloth.ai"}},
+ {"unknownSetting": True},
+ ],
+)
+def test_out_of_contract_values_are_rejected(payload):
+ with pytest.raises(ValidationError):
+ ChatSettingsPayload.model_validate(payload)
+
+
+# ---------------------------------------------------------------------------
+# Non-finite numbers
+# ---------------------------------------------------------------------------
+#
+# json.loads accepts bare NaN and Infinity, so both reach the payload from any
+# client that is not a browser (JSON.stringify emits null for them). Two things
+# then went wrong, and each needs its own guard.
+
+
[email protected]("value", [float("nan"), float("inf"), float("-inf")])
+ "payload_for",
+ [
+ lambda v: {"ragAutoInjectMinScore": v},
+ lambda v: {"inferenceParams": {"temperature": v}},
+ lambda v: {"customPresets": [{"name": "p", "params": {"topP": v}}]},
+ ],
+)
+def test_non_finite_numbers_are_refused_rather_than_stored(payload_for, value):
+ """A stored NaN is written to value_json as a bare `NaN` token.
+
+ Python reads it back, so the row is never quarantined, and the response model
+ renders it as null: the value is silently lost and the row on disk is not
+ valid JSON for any reader that is not Python.
+ """
+ with pytest.raises(ValidationError):
+ ChatSettingsPayload.model_validate(payload_for(value))
+
+
+def test_the_rejection_detail_can_be_rendered_as_json():
+ """The 400 must be renderable, or the caller gets a 500 instead.
+
+ Starlette's JSONResponse dumps with allow_nan = False, so echoing the
+ offending input back inside `detail` turned a correctly refused request into
+ an unhandled ValueError in the response renderer.
+ """
+ import json
+
+ from fastapi import HTTPException
+
+ from routes.chat_history import put_settings
+
+ with pytest.raises(HTTPException) as excinfo:
+ put_settings({"ragAutoInjectMinScore": float("nan")}, current_subject = "t")
+ assert excinfo.value.status_code == 400
+ json.dumps(excinfo.value.detail, allow_nan = False)
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsx
index 437afd9b836..2c65c1ae3e7 100644
--- a/studio/frontend/src/app/routes/__root.tsx
+++ b/studio/frontend/src/app/routes/__root.tsx
@@ -91,6 +91,18 @@ function PersonalizationSyncMount() {
return null;
}
+// The chat settings are the installation's, and the Models page and the model
+// picker read them too, so hydration cannot wait for ChatPage to mount.
+function ChatSettingsHydrationMount() {
+ const hydratePersistedSettings = useChatRuntimeStore(
+ (state) => state.hydratePersistedSettings,
+ );
+ useEffect(() => {
+ void hydratePersistedSettings();
+ }, [hydratePersistedSettings]);
+ return null;
+}
+
function CredentialBootstrapGate({ children }: { children: ReactNode }) {
const [ready, setReady] = useState(false);
@@ -355,6 +367,7 @@ function RootLayout() {
const content = (
<>
<PersonalizationSyncMount />
+ {!isAuthFlowRoute && <ChatSettingsHydrationMount />}
{!isAuthFlowRoute && <SettingsDialog />}
{/* Opens itself when API traffic arrives; hides on the full monitor page. */}
{!isAuthFlowRoute && <ApiMonitorOverlay />}
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 ab131305255..87bf1129f36 100644
--- a/studio/frontend/src/features/chat/api/chat-settings-api.ts
+++ b/studio/frontend/src/features/chat/api/chat-settings-api.ts
@@ -3,8 +3,19 @@
import { authFetch } from "@/features/auth";
import type { ChatPresetSource } from "../presets/preset-policy";
-import type { ReasoningEffort } from "../stores/chat-runtime-store";
+import type {
+ PermissionMode,
+ RagAutoInject,
+ RagMode,
+ RagSource,
+ ReasoningEffort,
+} from "../stores/chat-runtime-store";
+import type { ResearchWebsitePolicy } from "../types/research";
import type { InferenceParams } from "../types/runtime";
+import {
+ ChatSettingsRequestError,
+ isUnderKeepaliveBudget,
+} from "../utils/settings-retry";
export type PersistedInferenceParams = Partial<
Omit<InferenceParams, "checkpoint">
@@ -30,6 +41,31 @@ export interface PersistedChatSettings {
nudgeToolCalls?: boolean;
maxToolCallsPerMessage?: number;
toolCallTimeout?: number;
+ reasoningEnabled?: boolean;
+ toolsEnabled?: boolean;
+ codeToolsEnabled?: boolean;
+ imageToolsEnabled?: boolean;
+ webFetchToolsEnabled?: boolean;
+ deepResearchEnabled?: boolean;
+ researchWebsitePolicy?: ResearchWebsitePolicy;
+ artifactsEnabled?: boolean;
+ showCanvasMenuItem?: boolean;
+ mcpEnabledForChat?: boolean;
+ confirmToolCalls?: boolean;
+ /** "full" (Full access) is session-only and never leaves the browser. */
+ permissionMode?: Exclude<PermissionMode, "full">;
+ ragSource?: RagSource;
+ ragMode?: RagMode;
+ ragTopK?: number;
+ ragAutoInject?: RagAutoInject;
+ ragAutoInjectMinScore?: number;
+ ragOcrScanned?: boolean;
+ ragCaptionFigures?: boolean;
+ speculativeType?: "auto" | "ngram" | "off";
+ gpuMemoryMode?: "auto" | "manual";
+ expandQuantizations?: boolean;
+ showAllQuantizations?: boolean;
+ fitOnDeviceOnly?: boolean;
}
interface ChatSettingsResponse {
@@ -67,7 +103,16 @@ function parseErrorText(status: number, body: unknown): string {
async function parseJsonOrThrow<T>(response: Response): Promise<T> {
const body = await response.json().catch(() => null);
if (!response.ok) {
- throw new Error(parseErrorText(response.status, body));
+ // Typed, not a bare Error: the settings queue has to tell a server that is
+ // down (keep the patch) from a server that refuses this body (drop the
+ // offending fields), and that decision needs the status and the detail.
+ throw new ChatSettingsRequestError(
+ parseErrorText(response.status, body),
+ response.status,
+ body && typeof body === "object" && "detail" in body
+ ? (body as { detail: unknown }).detail
+ : null,
+ );
}
return body as T;
}
@@ -82,12 +127,19 @@ export async function saveChatSettingsPatch(
patch: PersistedChatSettings,
options: { keepalive?: boolean } = {},
): Promise<PersistedChatSettings> {
+ const body = JSON.stringify(patch);
const response = await authFetch("/api/chat/settings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify(patch),
- // keepalive lets the PUT survive a tab close from the beforeunload flush.
- keepalive: options.keepalive,
+ body,
+ // keepalive lets the PUT survive a tab close from the page-hidden flush,
+ // but only under the Fetch standard's 64 KiB budget for in-flight keepalive
+ // bodies. Over it the request fails immediately in every engine (measured in
+ // Chromium, Firefox and WebKit), and researchWebsitePolicy alone can carry
+ // 2000 domains of 253 characters. Sending without keepalive is a chance
+ // rather than a certain failure, and on the visibilitychange flush -- where
+ // the page is only hidden, not closing -- it simply succeeds.
+ keepalive: options.keepalive ? isUnderKeepaliveBudget(body) : undefined,
});
const data = await parseJsonOrThrow<ChatSettingsResponse>(response);
return data.settings;
diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsx
index 41b86649810..17df1d192c0 100644
--- a/studio/frontend/src/features/chat/chat-page.tsx
+++ b/studio/frontend/src/features/chat/chat-page.tsx
@@ -1885,6 +1885,7 @@ export function ChatPage({
const hydratePersistedSettings = useChatRuntimeStore(
(s) => s.hydratePersistedSettings,
);
+ const settingsHydrated = useChatRuntimeStore((s) => s.settingsHydrated);
const externalProviders = useExternalProvidersStore((s) => s.providers);
const connectionsEnabled = useExternalProvidersStore(
(s) => s.connectionsEnabled,
@@ -2279,7 +2280,10 @@ export function ChatPage({
? (storedWebFetchToolsEnabled ?? false)
: false,
});
- }, [externalProvidersForChat, inferenceParams.checkpoint]);
+ // Reruns once settings hydrate: this normalization reads the stored pills
+ // and clamps them to the model, and hydration refreshes what it reads, so
+ // it has to be the one applied last.
+ }, [externalProvidersForChat, inferenceParams.checkpoint, settingsHydrated]);
const canCompare = useMemo(() => {
return Boolean(inferenceParams.checkpoint) && !isExternalModel;
}, [inferenceParams.checkpoint, isExternalModel]);
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 ab2528dc055..339a0abb340 100644
--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts
@@ -38,6 +38,11 @@ import {
loadChatSettingsWithLegacyImport,
savePersistedChatSettingsPatch,
} from "../utils/chat-settings-storage";
+import {
+ loadShadowOwnsMirroredSetting,
+ normalizeStoredRagAutoInject,
+} from "../utils/mirrored-chat-settings";
+import { retryablePatchAfterFailure } from "../utils/settings-retry";
import {
chatModelLifecycleGate,
type ModelLifecycleLease,
@@ -149,15 +154,7 @@ function loadResearchWebsitePolicy(): ResearchWebsitePolicy {
}
function saveResearchWebsitePolicy(policy: ResearchWebsitePolicy): void {
- if (typeof window === "undefined") return;
- try {
- window.localStorage.setItem(
- CHAT_DEEP_RESEARCH_WEBSITE_POLICY_KEY,
- JSON.stringify(policy),
- );
- } catch {
- // Keep the in-memory setting when storage is unavailable.
- }
+ persistSetting(CHAT_DEEP_RESEARCH_WEBSITE_POLICY_KEY, JSON.stringify(policy));
}
function loadRagSource(): RagSource {
@@ -177,12 +174,7 @@ function loadRagSource(): RagSource {
}
function saveRagSource(value: RagSource): void {
- if (typeof window === "undefined") return;
- try {
- window.localStorage.setItem(CHAT_RAG_SOURCE_KEY, JSON.stringify(value));
- } catch {
- // Ignore storage failures; the default RAG source still works for this session.
- }
+ persistSetting(CHAT_RAG_SOURCE_KEY, JSON.stringify(value));
}
function loadRagMode(): RagMode {
@@ -191,10 +183,9 @@ function loadRagMode(): RagMode {
}
function loadRagAutoInject(): RagAutoInject {
- const raw = loadString(CHAT_RAG_AUTOINJECT_KEY, DEFAULT_RAG_AUTOINJECT);
- if (raw === "auto" || raw === "on" || raw === "off") return raw;
- // Legacy boolean migration: false -> Off, else Auto.
- return raw === "false" ? "off" : "auto";
+ return normalizeStoredRagAutoInject(
+ loadString(CHAT_RAG_AUTOINJECT_KEY, DEFAULT_RAG_AUTOINJECT),
+ );
}
function loadRagTopK(): number {
@@ -330,11 +321,19 @@ function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
+// Discriminated unions, not partial patches: merging a `thread` pick into a
+// stored `kb` one keeps `kbId`, which the backend's thread variant forbids.
+const ATOMIC_SETTING_KEYS = new Set<string>(["ragSource"]);
+
function mergePatch(into: SettingsPatch, more: SettingsPatch): void {
for (const [key, value] of Object.entries(more)) {
const intoAny = into as Record<string, unknown>;
const prev = intoAny[key];
- if (isPlainObject(prev) && isPlainObject(value)) {
+ if (
+ !ATOMIC_SETTING_KEYS.has(key) &&
+ isPlainObject(prev) &&
+ isPlainObject(value)
+ ) {
intoAny[key] = { ...prev, ...value };
} else {
intoAny[key] = value;
@@ -348,17 +347,29 @@ async function flushSettingsPatch(keepalive = false): Promise<void> {
pendingPatch = {};
try {
await savePersistedChatSettingsPatch(patch, { keepalive });
- } catch {
+ } catch (error) {
+ // A rejected patch is NOT requeued as it stands. The endpoint is
+ // extra="forbid" and refuses the whole body on one bad field, so a patch the
+ // server will never accept, requeued forever, makes every later save fail
+ // too and the tab can no longer persist any chat setting. Keep the fields
+ // the server did not name, drop the ones it did, and only reschedule when
+ // the patch actually got smaller so the retry chain is bounded.
+ const { patch: retryable, progressed } = retryablePatchAfterFailure(
+ patch,
+ error,
+ );
const retryPatch: SettingsPatch = {};
- mergePatch(retryPatch, patch);
+ mergePatch(retryPatch, retryable);
mergePatch(retryPatch, pendingPatch);
pendingPatch = retryPatch;
warnSettingsPersistenceFailure();
+ if (progressed && !keepalive && Object.keys(pendingPatch).length > 0) {
+ scheduleSettingsFlush();
+ }
}
}
-function saveSettingsPatch(patch: SettingsPatch): void {
- mergePatch(pendingPatch, patch);
+function scheduleSettingsFlush(): void {
if (pendingTimer !== null) clearTimeout(pendingTimer);
pendingTimer = setTimeout(() => {
pendingTimer = null;
@@ -368,16 +379,38 @@ function saveSettingsPatch(patch: SettingsPatch): void {
}, SETTINGS_DEBOUNCE_MS);
}
-// Best-effort flush of any pending patch on tab close. keepalive lets the PUT
-// outlive the unload; without it the browser cancels the fetch and the user's
-// last slider drag is dropped.
+function saveSettingsPatch(patch: SettingsPatch): void {
+ mergePatch(pendingPatch, patch);
+ scheduleSettingsFlush();
+}
+
+// Best-effort flush of any pending patch when the page is going away. keepalive
+// lets the PUT outlive the unload; without it the browser cancels the fetch and
+// the user's last slider drag is dropped.
+function flushSettingsOnPageHidden(): void {
+ if (pendingTimer !== null) clearTimeout(pendingTimer);
+ // An edit still waiting on hydration is a user edit like any other, and the
+ // tab is going away, so send it rather than let the next session hydrate over it.
+ drainPreHydrationPatch();
+ if (Object.keys(pendingPatch).length === 0) return;
+ inflightFlush = inflightFlush
+ .catch(() => undefined)
+ .then(() => flushSettingsPatch(true));
+}
+
if (typeof window !== "undefined") {
- window.addEventListener("beforeunload", () => {
- if (pendingTimer !== null) clearTimeout(pendingTimer);
- if (Object.keys(pendingPatch).length === 0) return;
- inflightFlush = inflightFlush
- .catch(() => undefined)
- .then(() => flushSettingsPatch(true));
+ window.addEventListener("beforeunload", flushSettingsOnPageHidden);
+ // beforeunload is not the end of a page's life on every platform: mobile
+ // Safari and backgrounded Android tabs are routinely discarded without it, and
+ // a page restored from the back/forward cache never unloaded at all. pagehide
+ // and the hidden transition of visibilitychange are the two the platform does
+ // guarantee, so the debounced patch is normally already gone by the time an
+ // unload would have run. Safe to add rather than replace: the pending patch is
+ // swapped out before the request, so a second call with nothing queued returns
+ // immediately and the two never send the same edit twice.
+ window.addEventListener("pagehide", flushSettingsOnPageHidden);
+ document.addEventListener("visibilitychange", () => {
+ if (document.visibilityState === "hidden") flushSettingsOnPageHidden();
});
}
@@ -385,20 +418,268 @@ function canUseStorage(): boolean {
return typeof window !== "undefined";
}
+function readStorageValue(key: string): string | null {
+ if (!canUseStorage()) return null;
+ try {
+ return localStorage.getItem(key);
+ } catch {
+ return null;
+ }
+}
+
+function writeStorageValue(key: string, raw: string): void {
+ if (!canUseStorage()) return;
+ try {
+ localStorage.setItem(key, raw);
+ } catch {
+ // Keep the in-memory setting when storage is unavailable.
+ }
+}
+
+type MirroredSettingCodec = {
+ encode: (value: unknown) => string;
+ decode: (raw: string) => unknown;
+ /** Value to seed the backend with, for a setting stored under older keys. */
+ readForBackfill?: () => unknown;
+};
+
+const BOOLEAN_SETTING: MirroredSettingCodec = {
+ encode: (value) => (value ? "true" : "false"),
+ decode: (raw) => (raw === "true" ? true : raw === "false" ? false : undefined),
+};
+
+const STRING_SETTING: MirroredSettingCodec = {
+ encode: (value) => String(value),
+ decode: (raw) => raw,
+};
+
+const NUMBER_SETTING: MirroredSettingCodec = {
+ encode: (value) => String(value),
+ decode: (raw) => {
+ const parsed = Number(raw);
+ return Number.isFinite(parsed) ? parsed : undefined;
+ },
+};
+
+const JSON_SETTING: MirroredSettingCodec = {
+ encode: (value) => JSON.stringify(value),
+ decode: (raw) => {
+ try {
+ return JSON.parse(raw) as unknown;
+ } catch {
+ return undefined;
+ }
+ },
+};
+
+const RAG_AUTOINJECT_SETTING: MirroredSettingCodec = {
+ encode: STRING_SETTING.encode,
+ decode: normalizeStoredRagAutoInject,
+};
+
+/**
+ * Settings that describe the installation rather than the browser holding them.
+ * Each entry pairs a localStorage slot with the /api/chat/settings field that
+ * carries it to another browser or a remote session.
+ */
+const MIRRORED_SETTINGS = {
+ reasoningEnabled: {
+ storageKey: CHAT_REASONING_ENABLED_KEY,
+ ...BOOLEAN_SETTING,
+ },
+ toolsEnabled: { storageKey: CHAT_TOOLS_ENABLED_KEY, ...BOOLEAN_SETTING },
+ codeToolsEnabled: {
+ storageKey: CHAT_CODE_TOOLS_ENABLED_KEY,
+ ...BOOLEAN_SETTING,
+ },
+ imageToolsEnabled: {
+ storageKey: CHAT_IMAGE_TOOLS_ENABLED_KEY,
+ ...BOOLEAN_SETTING,
+ },
+ webFetchToolsEnabled: {
+ storageKey: CHAT_WEB_FETCH_TOOLS_ENABLED_KEY,
+ ...BOOLEAN_SETTING,
+ },
+ deepResearchEnabled: {
+ storageKey: CHAT_DEEP_RESEARCH_ENABLED_KEY,
+ ...BOOLEAN_SETTING,
+ },
+ researchWebsitePolicy: {
+ storageKey: CHAT_DEEP_RESEARCH_WEBSITE_POLICY_KEY,
+ ...JSON_SETTING,
+ },
+ artifactsEnabled: {
+ storageKey: CHAT_ARTIFACTS_ENABLED_KEY,
+ ...BOOLEAN_SETTING,
+ },
+ showCanvasMenuItem: {
+ storageKey: CHAT_SHOW_CANVAS_MENU_ITEM_KEY,
+ ...BOOLEAN_SETTING,
+ // A profile predating the visibility flag keeps Canvas shown through an
+ // explicit plus-menu pin, which loadShowCanvasMenuItem reads.
+ readForBackfill: () =>
+ readStorageValue(CHAT_SHOW_CANVAS_MENU_ITEM_KEY) !== null ||
+ readStorageValue(PLUS_MENU_PINS_STORAGE_KEY) !== null
+ ? loadShowCanvasMenuItem()
+ : undefined,
+ },
+ collapseHtmlArtifacts: {
+ storageKey: CHAT_COLLAPSE_HTML_ARTIFACTS_KEY,
+ ...BOOLEAN_SETTING,
+ },
+ allowArtifactNetworkAccess: {
+ storageKey: CHAT_ALLOW_ARTIFACT_NETWORK_ACCESS_KEY,
+ ...BOOLEAN_SETTING,
+ },
+ mcpEnabledForChat: { storageKey: CHAT_MCP_ENABLED_KEY, ...BOOLEAN_SETTING },
+ confirmToolCalls: {
+ storageKey: CHAT_CONFIRM_TOOL_CALLS_KEY,
+ ...BOOLEAN_SETTING,
+ },
+ permissionMode: {
+ storageKey: CHAT_PERMISSION_MODE_KEY,
+ ...STRING_SETTING,
+ // A profile predating permission levels holds only the confirm toggle, and
+ // loadPermissionMode derives the level from it.
+ readForBackfill: () =>
+ readStorageValue(CHAT_PERMISSION_MODE_KEY) !== null ||
+ loadOptionalBool(CHAT_CONFIRM_TOOL_CALLS_KEY) !== null
+ ? loadPermissionMode()
+ : undefined,
+ },
+ ragSource: { storageKey: CHAT_RAG_SOURCE_KEY, ...JSON_SETTING },
+ ragMode: { storageKey: CHAT_RAG_MODE_KEY, ...STRING_SETTING },
+ ragTopK: { storageKey: CHAT_RAG_TOP_K_KEY, ...NUMBER_SETTING },
+ ragAutoInject: {
+ storageKey: CHAT_RAG_AUTOINJECT_KEY,
+ ...RAG_AUTOINJECT_SETTING,
+ },
+ ragAutoInjectMinScore: {
+ storageKey: CHAT_RAG_AUTOINJECT_MIN_SCORE_KEY,
+ ...NUMBER_SETTING,
+ },
+ ragOcrScanned: { storageKey: CHAT_RAG_OCR_KEY, ...BOOLEAN_SETTING },
+ ragCaptionFigures: { storageKey: CHAT_RAG_CAPTION_KEY, ...BOOLEAN_SETTING },
+ speculativeType: { storageKey: CHAT_SPECULATIVE_TYPE_KEY, ...STRING_SETTING },
+ gpuMemoryMode: { storageKey: CHAT_GPU_MEMORY_MODE_KEY, ...STRING_SETTING },
+ expandQuantizations: {
+ storageKey: CHAT_EXPAND_QUANTIZATIONS_KEY,
+ ...BOOLEAN_SETTING,
+ },
+ showAllQuantizations: {
+ storageKey: CHAT_SHOW_ALL_QUANTIZATIONS_KEY,
+ ...BOOLEAN_SETTING,
+ },
+ fitOnDeviceOnly: {
+ storageKey: MODELS_FIT_ON_DEVICE_ONLY_KEY,
+ ...BOOLEAN_SETTING,
+ },
+} satisfies Partial<
+ Record<ScalarSettingKey, { storageKey: string } & MirroredSettingCodec>
+>;
+
+type MirroredSettingKey = keyof typeof MIRRORED_SETTINGS;
+
+const MIRRORED_SETTING_BY_STORAGE_KEY: ReadonlyMap<
+ string,
+ { field: MirroredSettingKey } & MirroredSettingCodec
+> = new Map(
+ Object.entries(MIRRORED_SETTINGS).map(([field, setting]) => [
+ setting.storageKey,
+ { field: field as MirroredSettingKey, ...setting },
+ ]),
+);
+
+let mirroredSettingsHydrated = false;
+let preHydrationPatch: SettingsPatch | null = null;
+
+/**
+ * Send a changed mirrored setting to the backend. An edit made before the
+ * initial GET lands is held rather than dropped: the request would race the
+ * hydrating value, so it is replayed once hydration has applied the server's.
+ * The mutation version is bumped straight away either way, so hydration leaves
+ * a field the user has just set alone.
+ */
+function mirrorSettingToBackend(key: string, raw: string): void {
+ const setting = MIRRORED_SETTING_BY_STORAGE_KEY.get(key);
+ if (!setting) return;
+ const value = setting.decode(raw);
+ if (value === undefined) return;
+ scalarSettingMutationVersions[setting.field] += 1;
+ const patch = { [setting.field]: value } as SettingsPatch;
+ if (!mirroredSettingsHydrated) {
+ preHydrationPatch ??= {};
+ mergePatch(preHydrationPatch, patch);
+ return;
+ }
+ saveSettingsPatch(patch);
+}
+
+/** Move any held startup edits onto the outgoing patch. */
+function drainPreHydrationPatch(): void {
+ if (!preHydrationPatch) return;
+ mergePatch(pendingPatch, preHydrationPatch);
+ preHydrationPatch = null;
+}
+
+/** Replay the edits made while the initial GET was still in flight. */
+function flushPreHydrationSettings(): void {
+ if (!preHydrationPatch) return;
+ const patch = preHydrationPatch;
+ preHydrationPatch = null;
+ saveSettingsPatch(patch);
+}
+
+/**
+ * Write a setting to its localStorage slot and, for the settings mirrored to
+ * /api/chat/settings, to the backend as well. Storage is the synchronous boot
+ * cache; the backend copy is what a second browser or a remote session reads.
+ */
+function persistSetting(key: string, raw: string): void {
+ // Before hydration the cache says nothing about the server's value, so an
+ // explicit write is recorded even where it changes nothing locally. A
+ // constraint write (deep research turning the tool pills off) has to reach
+ // the backend, or hydration restores the toggle it was there to clear.
+ if (!mirroredSettingsHydrated || readStorageValue(key) !== raw) {
+ mirrorSettingToBackend(key, raw);
+ }
+ writeStorageValue(key, raw);
+}
+
+/**
+ * Persist a value a model load applied rather than one the user picked. Before
+ * hydration such a write only reflects this browser's cache, so treating it as
+ * an edit would both block the stored preference from hydrating and replay the
+ * load's default over it. It reaches the cache and waits for the server's.
+ *
+ * `stillCurrent` says the value matches the live store. A load captures its
+ * settings up front and persists them on success, so one that started before
+ * hydration and finished after it would otherwise write the stale capture over
+ * the preference that just arrived.
+ */
+function persistLoadDerivedSetting(
+ key: string,
+ raw: string,
+ stillCurrent: boolean,
+): void {
+ if (!mirroredSettingsHydrated) {
+ writeStorageValue(key, raw);
+ return;
+ }
+ // Dropped outright: the cache now holds the hydrated preference too.
+ if (!stillCurrent) return;
+ persistSetting(key, raw);
+}
+
function loadBool(key: string, fallback: boolean): boolean {
const raw = loadOptionalBool(key);
return raw ?? fallback;
}
export function loadOptionalBool(key: string): boolean | null {
- if (!canUseStorage()) return null;
- try {
- const raw = localStorage.getItem(key);
- if (raw === null) return null;
- return raw === "true";
- } catch {
- return null;
- }
+ const raw = readStorageValue(key);
+ if (raw === null) return null;
+ return raw === "true";
}
/**
@@ -421,12 +702,7 @@ export function resolveToolsEnabledOnLoad(supportsTools: boolean): {
}
function saveBool(key: string, value: boolean): void {
- if (!canUseStorage()) return;
- try {
- localStorage.setItem(key, value ? "true" : "false");
- } catch {
- // ignore
- }
+ persistSetting(key, value ? "true" : "false");
}
// The visibility flag shipped after the menu pins, so when it is absent,
@@ -455,45 +731,26 @@ function loadShowCanvasMenuItem(): boolean {
* off -> "off", i.e. no prompts); fresh installs default to "auto".
*/
function loadPermissionMode(): PermissionMode {
- if (!canUseStorage()) return "auto";
- try {
- const raw = localStorage.getItem(CHAT_PERMISSION_MODE_KEY);
- if (raw === "ask" || raw === "auto" || raw === "off") return raw;
- } catch {
- // ignore
- }
+ const raw = readStorageValue(CHAT_PERMISSION_MODE_KEY);
+ if (raw === "ask" || raw === "auto" || raw === "off") return raw;
const legacyConfirm = loadOptionalBool(CHAT_CONFIRM_TOOL_CALLS_KEY);
if (legacyConfirm === null) return "auto";
return legacyConfirm ? "ask" : "off";
}
function savePermissionMode(mode: PermissionMode): void {
- if (!canUseStorage() || mode === "full") return;
- try {
- localStorage.setItem(CHAT_PERMISSION_MODE_KEY, mode);
- } catch {
- // ignore
- }
+ if (mode === "full") return;
+ persistSetting(CHAT_PERMISSION_MODE_KEY, mode);
}
const INITIAL_PERMISSION_MODE: PermissionMode = loadPermissionMode();
function loadString(key: string, fallback: string): string {
- if (!canUseStorage()) return fallback;
- try {
- return localStorage.getItem(key) ?? fallback;
- } catch {
- return fallback;
- }
+ return readStorageValue(key) ?? fallback;
}
function saveString(key: string, value: string): void {
- if (!canUseStorage()) return;
- try {
- localStorage.setItem(key, value);
- } catch {
- // ignore
- }
+ persistSetting(key, value);
}
// Canonicalises any backend value onto the Speculative Decoding dropdown's
@@ -562,7 +819,11 @@ export function readPersistedSpeculativeType(): string {
// unapplied dropdown edit the user might Reset or abandon before Apply.
export function saveSpeculativeType(value: string | null): void {
if (value && PERSISTED_SPEC_MODES.has(value)) {
- saveString(CHAT_SPECULATIVE_TYPE_KEY, value);
+ persistLoadDerivedSetting(
+ CHAT_SPECULATIVE_TYPE_KEY,
+ value,
+ useChatRuntimeStore.getState().speculativeType === value,
+ );
}
}
@@ -573,7 +834,11 @@ export function readPersistedGpuMemoryMode(): "auto" | "manual" {
}
export function saveGpuMemoryMode(value: "auto" | "manual"): void {
- saveString(CHAT_GPU_MEMORY_MODE_KEY, value);
+ persistLoadDerivedSetting(
+ CHAT_GPU_MEMORY_MODE_KEY,
+ value,
+ useChatRuntimeStore.getState().gpuMemoryMode === value,
+ );
}
/** Persist the GPU Memory mode after a load, but only for a non-diffusion GGUF:
@@ -1350,7 +1615,7 @@ type ChatRuntimeStore = {
type PersistedChatSettings = Awaited<
ReturnType<typeof loadChatSettingsWithLegacyImport>
->;
+>["settings"];
type PersistedInferenceParams = NonNullable<
PersistedChatSettings["inferenceParams"]
>;
@@ -1364,7 +1629,31 @@ type ScalarSettingKey =
| "autoHealToolCalls"
| "nudgeToolCalls"
| "maxToolCallsPerMessage"
- | "toolCallTimeout";
+ | "toolCallTimeout"
+ | "reasoningEnabled"
+ | "toolsEnabled"
+ | "codeToolsEnabled"
+ | "imageToolsEnabled"
+ | "webFetchToolsEnabled"
+ | "deepResearchEnabled"
+ | "researchWebsitePolicy"
+ | "artifactsEnabled"
+ | "showCanvasMenuItem"
+ | "mcpEnabledForChat"
+ | "confirmToolCalls"
+ | "permissionMode"
+ | "ragSource"
+ | "ragMode"
+ | "ragTopK"
+ | "ragAutoInject"
+ | "ragAutoInjectMinScore"
+ | "ragOcrScanned"
+ | "ragCaptionFigures"
+ | "expandQuantizations"
+ | "showAllQuantizations"
+ | "fitOnDeviceOnly"
+ | "speculativeType"
+ | "gpuMemoryMode";
type PresetHydrationVersions = {
customPresets: number;
@@ -1403,6 +1692,30 @@ const SCALAR_SETTING_KEYS = [
"nudgeToolCalls",
"maxToolCallsPerMessage",
"toolCallTimeout",
+ "reasoningEnabled",
+ "toolsEnabled",
+ "codeToolsEnabled",
+ "imageToolsEnabled",
+ "webFetchToolsEnabled",
+ "deepResearchEnabled",
+ "researchWebsitePolicy",
+ "artifactsEnabled",
+ "showCanvasMenuItem",
+ "mcpEnabledForChat",
+ "confirmToolCalls",
+ "permissionMode",
+ "ragSource",
+ "ragMode",
+ "ragTopK",
+ "ragAutoInject",
+ "ragAutoInjectMinScore",
+ "ragOcrScanned",
+ "ragCaptionFigures",
+ "expandQuantizations",
+ "showAllQuantizations",
+ "fitOnDeviceOnly",
+ "speculativeType",
+ "gpuMemoryMode",
] as const satisfies readonly ScalarSettingKey[];
const inferenceParamMutationVersions = Object.fromEntries(
@@ -1428,6 +1741,50 @@ function getSettingsHydrationVersions(): SettingsHydrationVersions {
};
}
+/** Refresh the localStorage cache from the values hydration just applied. */
+function cacheHydratedSettings(
+ settings: PersistedChatSettings,
+ versions: SettingsHydrationVersions,
+): void {
+ for (const [name, setting] of Object.entries(MIRRORED_SETTINGS)) {
+ const field = name as MirroredSettingKey;
+ const value = settings[field];
+ if (value === undefined) continue;
+ if (
+ scalarSettingMutationVersions[field] !== versions.scalarSettings[field]
+ ) {
+ continue;
+ }
+ writeStorageValue(setting.storageKey, setting.encode(value));
+ }
+}
+
+/**
+ * Seed the backend from this browser for mirrored settings it has never stored.
+ * Without it an existing install would keep its preferences local until each
+ * one is next changed.
+ */
+function readStoredSettingValue(
+ setting: { storageKey: string } & MirroredSettingCodec,
+): unknown {
+ const raw = readStorageValue(setting.storageKey);
+ return raw === null ? undefined : setting.decode(raw);
+}
+
+function backfillMirroredSettings(settings: PersistedChatSettings): void {
+ const patch: SettingsPatch = {};
+ for (const [name, setting] of Object.entries(MIRRORED_SETTINGS)) {
+ const field = name as MirroredSettingKey;
+ if (settings[field] !== undefined) continue;
+ const value = setting.readForBackfill
+ ? setting.readForBackfill()
+ : readStoredSettingValue(setting);
+ if (value === undefined) continue;
+ (patch as Record<string, unknown>)[field] = value;
+ }
+ if (hasKeys(patch)) saveSettingsPatch(patch);
+}
+
function setInferenceParam(
params: InferenceParams,
key: PersistedInferenceParamKey,
@@ -1503,6 +1860,23 @@ function getHydratedPresetState(
return nextState;
}
+/**
+ * Whether the active checkpoint is an external model that cannot run deep
+ * research, matching the composer's own rule. An unresolved provider is left
+ * alone: the connection list may not have loaded, and refusing on that would
+ * drop a Codex user's stored preference.
+ */
+function externalCheckpointRefusesDeepResearch(
+ checkpoint: string | null | undefined,
+): boolean {
+ const parsed = parseExternalModelId(checkpoint);
+ if (!parsed) return false;
+ const provider = useExternalProvidersStore
+ .getState()
+ .providers.find((candidate) => candidate.id === parsed.providerId);
+ return provider != null && provider.providerType !== "openai_codex";
+}
+
function getHydratedSettingsState(
settings: PersistedChatSettings,
state: ChatRuntimeStore,
@@ -1522,6 +1896,41 @@ function getHydratedSettingsState(
nextState.params = params;
for (const key of SCALAR_SETTING_KEYS) {
const value = settings[key];
+ // Full access is session-only, so a stored level must not silently drop the
+ // sandbox bypass the user accepted a warning for, and Full access never
+ // confirms a tool call whatever the saved toggle says.
+ if (
+ state.permissionMode === "full" &&
+ (key === "permissionMode" || key === "confirmToolCalls")
+ ) {
+ continue;
+ }
+ // Both describe the running model through a loaded* shadow this loop cannot
+ // set, so skip them while a shadow owns them. With none resident the store
+ // field is what the next load reads and then persists back, so the server's
+ // preference has to land here or the load overwrites it with a default.
+ if (loadShadowOwnsMirroredSetting(key, state)) {
+ continue;
+ }
+ // A load sets this from the model's own capability, and only a load sets
+ // reasoningAlwaysOn, so a stored false would ask a model that cannot stop
+ // thinking to stop thinking.
+ if (
+ key === "reasoningEnabled" &&
+ value === false &&
+ state.reasoningAlwaysOn
+ ) {
+ 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 (
+ key === "deepResearchEnabled" &&
+ value === true &&
+ externalCheckpointRefusesDeepResearch(state.params.checkpoint)
+ ) {
+ continue;
+ }
if (
value !== undefined &&
scalarSettingMutationVersions[key] === versions.scalarSettings[key]
@@ -1713,11 +2122,13 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
settingsHydrationPromise = (async () => {
const hydrationVersions = getSettingsHydrationVersions();
try {
- const settings = await loadChatSettingsWithLegacyImport();
+ const { settings, fromServer } = await loadChatSettingsWithLegacyImport();
+ let applied = false;
set((state) => {
if (state.settingsHydrated) {
return state;
}
+ applied = true;
const nextState: Partial<ChatRuntimeStore> = {
settingsHydrated: true,
...getHydratedPresetState(
@@ -1729,10 +2140,23 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
};
return nextState;
});
+ if (applied) {
+ cacheHydratedSettings(settings, 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);
+ // After the backfill, so a startup edit wins over the stored value.
+ flushPreHydrationSettings();
+ }
} catch {
// Hydrate failed: treat as hydrated-with-defaults so future setParams
// calls reach saveSettingsPatch (which toasts on real network failure).
warnSettingsPersistenceFailure();
+ mirroredSettingsHydrated = true;
+ flushPreHydrationSettings();
set({ settingsHydrated: true });
} finally {
settingsHydrationPromise = null;
@@ -1959,10 +2383,13 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
// stale persisted local id would race the freshly-loaded model. See
// LAST_EXTERNAL_CHECKPOINT_KEY notes.
saveLastExternalCheckpoint(isExternalModelId(modelId) ? modelId : null);
- // Only disarm research for a connection that cannot drive it. Gating on
- // the id prefix alone silently switched it off for capable providers too,
- // forcing the user to re-enable it after every model switch.
- if (isExternalModelId(modelId) && !externalModelSupportsStudioTools(modelId)) {
+ // Only disarm research for a connection that cannot drive it. Gating on the id
+ // prefix alone silently switched it off for capable providers too, and saveBool
+ // now reaches the backend, so that would write the preference off for every
+ // browser on the install. Hoisted because all three writes below share it.
+ const clampsDeepResearch =
+ isExternalModelId(modelId) && !externalModelSupportsStudioTools(modelId);
+ if (clampsDeepResearch) {
saveBool(CHAT_DEEP_RESEARCH_ENABLED_KEY, false);
}
// Clear stale per-turn usage on model change; the relaxed external-provider
@@ -1994,10 +2421,9 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
}
}
const nextGgufVariant = ggufVariant ?? null;
- const nextDeepResearchEnabled =
- isExternalModelId(modelId) && !externalModelSupportsStudioTools(modelId)
- ? false
- : state.deepResearchEnabled;
+ const nextDeepResearchEnabled = clampsDeepResearch
+ ? false
+ : state.deepResearchEnabled;
const queuedSettingsChanged = shouldAdvanceQueuedSettingsEpoch(
{
checkpoint: state.params.checkpoint,
@@ -2038,9 +2464,7 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
: {}),
// Switching to a connection whose provider cannot run Studio's tool
// loop disables Deep Research; a capable one keeps the user's choice.
- ...(isExternalModelId(modelId) && !externalModelSupportsStudioTools(modelId)
- ? { deepResearchEnabled: false }
- : {}),
+ ...(clampsDeepResearch ? { deepResearchEnabled: false } : {}),
};
}),
// Re-apply the incoming thread's own usage rather than blanking the bar: a run that finished
@@ -2298,26 +2722,16 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({
return { showCanvasMenuItem };
}),
setCollapseHtmlArtifacts: (collapseHtmlArtifacts) =>
- set((state) => {
+ set(() => {
saveBool(CHAT_COLLAPSE_HTML_ARTIFACTS_KEY, collapseHtmlArtifacts);
- setScalarSettingVersion(
- "collapseHtmlArtifacts",
- collapseHtmlArtifacts,
- state.collapseHtmlArtifacts,
- );
return { collapseHtmlArtifacts };
}),
setAllowArtifactNetworkAccess: (allowArtifactNetworkAccess) =>
- set((state) => {
+ set(() => {
saveBool(
CHAT_ALLOW_ARTIFACT_NETWORK_ACCESS_KEY,
allowArtifactNetworkAccess,
);
- setScalarSettingVersion(
- "allowArtifactNetworkAccess",
- allowArtifactNetworkAccess,
- state.allowArtifactNetworkAccess,
- );
return { allowArtifactNetworkAccess };
}),
setMcpEnabledForChat: (mcpEnabledForChat) =>
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 48acfdee402..c157db9f37f 100644
--- a/studio/frontend/src/features/chat/utils/chat-settings-storage.ts
+++ b/studio/frontend/src/features/chat/utils/chat-settings-storage.ts
@@ -19,6 +19,10 @@ import {
type Preset,
} from "../presets/preset-policy";
import type { ReasoningEffort } from "../stores/chat-runtime-store";
+import {
+ assignSanitizedMirroredSettings,
+ hasNoMirroredSettings,
+} from "./mirrored-chat-settings";
const AUTO_TITLE_KEY = "unsloth_chat_auto_title";
const AUTO_HEAL_TOOL_CALLS_KEY = "unsloth_auto_heal_tool_calls";
@@ -263,6 +267,7 @@ function sanitizeChatSettings(value: unknown): PersistedChatSettings {
settings.maxToolCallsPerMessage = maxToolCallsPerMessage;
}
if (toolCallTimeout !== undefined) settings.toolCallTimeout = toolCallTimeout;
+ assignSanitizedMirroredSettings(value, settings);
return settings;
}
@@ -321,7 +326,8 @@ export function isEmptyChatSettings(settings: PersistedChatSettings): boolean {
settings.autoHealToolCalls === undefined &&
settings.nudgeToolCalls === undefined &&
settings.maxToolCallsPerMessage === undefined &&
- settings.toolCallTimeout === undefined
+ settings.toolCallTimeout === undefined &&
+ hasNoMirroredSettings(settings)
);
}
@@ -388,7 +394,18 @@ export function loadLegacyChatSettings(): PersistedChatSettings {
return settings;
}
-export async function loadChatSettingsWithLegacyImport(): Promise<PersistedChatSettings> {
+export interface LoadedChatSettings {
+ settings: PersistedChatSettings;
+ /**
+ * The GET answered, so a mirrored field missing from `settings` is missing on
+ * the server too. False when the read fell back to this browser's legacy
+ * storage: nothing is then known about the server, and treating every field
+ * as absent would back this browser's stale values over another's.
+ */
+ fromServer: boolean;
+}
+
+export async function loadChatSettingsWithLegacyImport(): Promise<LoadedChatSettings> {
let dbSettings: PersistedChatSettings;
try {
dbSettings = sanitizeChatSettings(await getChatSettings());
@@ -397,7 +414,7 @@ export async function loadChatSettingsWithLegacyImport(): Promise<PersistedChatS
if (isEmptyChatSettings(legacySettings)) {
throw error;
}
- return legacySettings;
+ return { settings: legacySettings, fromServer: false };
}
const legacySettings = loadLegacyChatSettings();
@@ -406,18 +423,24 @@ export async function loadChatSettingsWithLegacyImport(): Promise<PersistedChatS
!isEmptyChatSettings(dbSettings) ||
isEmptyChatSettings(legacySettings)
) {
- return dbSettings;
+ return { settings: dbSettings, fromServer: true };
}
try {
- return sanitizeChatSettings(await saveChatSettingsPatch(legacySettings));
+ return {
+ settings: sanitizeChatSettings(
+ await saveChatSettingsPatch(legacySettings),
+ ),
+ fromServer: true,
+ };
} catch {
- return legacySettings;
+ // The GET still answered (empty), so absence remains authoritative.
+ return { settings: legacySettings, fromServer: true };
}
}
if (isEmptyChatSettings(legacySettings)) {
markLegacySettingsImportDone();
- return dbSettings;
+ return { settings: dbSettings, fromServer: true };
}
const mergedSettings = {
@@ -433,9 +456,9 @@ export async function loadChatSettingsWithLegacyImport(): Promise<PersistedChatS
await saveChatSettingsPatch(mergedSettings),
);
markLegacySettingsImportDone();
- return savedSettings;
+ return { settings: savedSettings, fromServer: true };
} catch {
- return mergedSettings;
+ return { settings: mergedSettings, fromServer: true };
}
}
diff --git a/studio/frontend/src/features/chat/utils/mirrored-chat-settings.ts b/studio/frontend/src/features/chat/utils/mirrored-chat-settings.ts
new file mode 100644
index 00000000000..4f3c2392a82
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/mirrored-chat-settings.ts
@@ -0,0 +1,187 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Composer, RAG and model-load toggles the chat runtime store mirrors to
+// /api/chat/settings so they follow the installation rather than one browser's
+// localStorage. Every value has to survive a round trip through a browser's
+// storage, so each one is re-validated here before it reaches the backend,
+// which rejects the whole patch on a single out-of-contract field.
+
+import type { PersistedChatSettings } from "../api/chat-settings-api";
+
+const MIRRORED_BOOLEAN_KEYS = [
+ "reasoningEnabled",
+ "toolsEnabled",
+ "codeToolsEnabled",
+ "imageToolsEnabled",
+ "webFetchToolsEnabled",
+ "deepResearchEnabled",
+ "artifactsEnabled",
+ "showCanvasMenuItem",
+ "mcpEnabledForChat",
+ "confirmToolCalls",
+ "ragOcrScanned",
+ "ragCaptionFigures",
+ "expandQuantizations",
+ "showAllQuantizations",
+ "fitOnDeviceOnly",
+] as const satisfies readonly (keyof PersistedChatSettings)[];
+
+const MIRRORED_ENUM_VALUES = {
+ // "full" (Full access) is session-only and never persisted.
+ permissionMode: ["ask", "auto", "off"],
+ ragMode: ["hybrid", "lexical", "dense"],
+ ragAutoInject: ["auto", "on", "off"],
+ speculativeType: ["auto", "ngram", "off"],
+ gpuMemoryMode: ["auto", "manual"],
+} as const satisfies Partial<
+ Record<keyof PersistedChatSettings, readonly string[]>
+>;
+
+// Bounds match the ge/le the backend payload enforces on the same fields.
+const MIRRORED_NUMBER_BOUNDS = {
+ ragTopK: { min: 1, max: 50, integer: true },
+ ragAutoInjectMinScore: { min: 0, max: 1, integer: false },
+} as const satisfies Partial<
+ Record<
+ keyof PersistedChatSettings,
+ { min: number; max: number; integer: boolean }
+ >
+>;
+
+export const MIRRORED_SETTING_KEYS = [
+ ...MIRRORED_BOOLEAN_KEYS,
+ ...(Object.keys(
+ MIRRORED_ENUM_VALUES,
+ ) as (keyof typeof MIRRORED_ENUM_VALUES)[]),
+ ...(Object.keys(
+ MIRRORED_NUMBER_BOUNDS,
+ ) as (keyof typeof MIRRORED_NUMBER_BOUNDS)[]),
+ "researchWebsitePolicy",
+ "ragSource",
+] as const satisfies readonly (keyof PersistedChatSettings)[];
+
+const MAX_RESEARCH_POLICY_DOMAINS = 1000;
+// 253 is the maximum length of a DNS name.
+const MAX_DOMAIN_LENGTH = 253;
+const MAX_RAG_KB_ID_LENGTH = 256;
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value != null && typeof value === "object" && !Array.isArray(value);
+}
+
+function sanitizeDomainList(value: unknown): string[] {
+ if (!Array.isArray(value)) return [];
+ return value
+ .filter(
+ (entry): entry is string =>
+ typeof entry === "string" && entry.length <= MAX_DOMAIN_LENGTH,
+ )
+ .slice(0, MAX_RESEARCH_POLICY_DOMAINS);
+}
+
+function sanitizeResearchWebsitePolicy(
+ value: unknown,
+): PersistedChatSettings["researchWebsitePolicy"] | undefined {
+ if (!isRecord(value)) return undefined;
+ return {
+ allowedDomains: sanitizeDomainList(value.allowedDomains),
+ blockedDomains: sanitizeDomainList(value.blockedDomains),
+ };
+}
+
+function sanitizeRagSource(
+ value: unknown,
+): PersistedChatSettings["ragSource"] | undefined {
+ if (!isRecord(value)) return undefined;
+ if (value.type === "thread") return { type: "thread" };
+ if (
+ value.type === "kb" &&
+ typeof value.kbId === "string" &&
+ value.kbId.length > 0 &&
+ value.kbId.length <= MAX_RAG_KB_ID_LENGTH
+ ) {
+ return { type: "kb", kbId: value.kbId };
+ }
+ return undefined;
+}
+
+function sanitizeBoundedNumber(
+ value: unknown,
+ { min, max, integer }: { min: number; max: number; integer: boolean },
+): number | undefined {
+ if (typeof value !== "number" || !Number.isFinite(value)) return undefined;
+ if (integer && !Number.isInteger(value)) return undefined;
+ return value >= min && value <= max ? value : undefined;
+}
+
+/** Copy the mirrored settings `value` holds in-contract onto `settings`. */
+export function assignSanitizedMirroredSettings(
+ value: Record<string, unknown>,
+ settings: PersistedChatSettings,
+): void {
+ const target = settings as Record<string, unknown>;
+ for (const key of MIRRORED_BOOLEAN_KEYS) {
+ if (typeof value[key] === "boolean") target[key] = value[key];
+ }
+ for (const [key, allowed] of Object.entries(MIRRORED_ENUM_VALUES)) {
+ const candidate = value[key];
+ if (
+ typeof candidate === "string" &&
+ (allowed as readonly string[]).includes(candidate)
+ ) {
+ target[key] = candidate;
+ }
+ }
+ for (const [key, bounds] of Object.entries(MIRRORED_NUMBER_BOUNDS)) {
+ const sanitized = sanitizeBoundedNumber(value[key], bounds);
+ if (sanitized !== undefined) target[key] = sanitized;
+ }
+ const researchWebsitePolicy = sanitizeResearchWebsitePolicy(
+ value.researchWebsitePolicy,
+ );
+ if (researchWebsitePolicy) {
+ settings.researchWebsitePolicy = researchWebsitePolicy;
+ }
+ const ragSource = sanitizeRagSource(value.ragSource);
+ if (ragSource) settings.ragSource = ragSource;
+}
+
+/**
+ * Map a stored RAG auto-inject value onto the three-way control. Storage
+ * predating that control holds "true"/"false", which the backend rejects, so
+ * the migration has to run before a backfill sends the stored value.
+ */
+export function normalizeStoredRagAutoInject(
+ raw: string,
+): "auto" | "on" | "off" {
+ if (raw === "auto" || raw === "on" || raw === "off") return raw;
+ return raw === "false" ? "off" : "auto";
+}
+
+/**
+ * Whether a resident model's own baseline currently owns a mirrored setting.
+ * speculativeType and gpuMemoryMode are each written with a loaded* shadow that
+ * hydration cannot set, so moving the editable half alone while a shadow holds
+ * the other splits the pair. With no shadow the stored preference is the one the
+ * next load reads, and hydration has to apply it or the load sends a default and
+ * persists that default back over the server's value.
+ */
+export function loadShadowOwnsMirroredSetting(
+ key: string,
+ shadows: {
+ loadedSpeculativeType: string | null;
+ loadedGpuMemoryMode: "auto" | "manual" | null;
+ },
+): boolean {
+ if (key === "speculativeType") return shadows.loadedSpeculativeType !== null;
+ if (key === "gpuMemoryMode") return shadows.loadedGpuMemoryMode !== null;
+ return false;
+}
+
+/** Whether `settings` carries none of the mirrored values. */
+export function hasNoMirroredSettings(
+ settings: PersistedChatSettings,
+): boolean {
+ return MIRRORED_SETTING_KEYS.every((key) => settings[key] === undefined);
+}
diff --git a/studio/frontend/src/features/chat/utils/settings-retry.ts b/studio/frontend/src/features/chat/utils/settings-retry.ts
new file mode 100644
index 00000000000..9136f078988
--- /dev/null
+++ b/studio/frontend/src/features/chat/utils/settings-retry.ts
@@ -0,0 +1,118 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Which failed settings writes are worth keeping, and which have to be let go.
+//
+// The settings queue coalesces every change into one patch and requeues it when the
+// PUT fails, which is right for a server that is down and wrong for a server that
+// refuses this patch. /api/chat/settings is extra="forbid" and rejects the WHOLE
+// body on one bad field, so a permanently-rejected value requeued forever rides
+// along with every later save and takes it down too: after one 400 no chat setting
+// can be persisted again for the life of the tab. Measured in Chromium, Firefox and
+// WebKit against a live Studio before this existed.
+//
+// Reachable without a bug on either side, whenever the two versions differ: a new
+// bundle against a rolled-back backend has every mirrored field rejected as
+// extra_forbidden, which is exactly the shape below.
+
+/** A non-2xx answer from the settings endpoint, carrying what the server said. */
+export class ChatSettingsRequestError extends Error {
+ readonly status: number;
+ readonly detail: unknown;
+
+ constructor(message: string, status: number, detail: unknown) {
+ super(message);
+ this.name = "ChatSettingsRequestError";
+ this.status = status;
+ this.detail = detail;
+ }
+}
+
+/**
+ * Whether retrying this failure could ever succeed.
+ *
+ * A network error, a 5xx or a timeout is transient, so the patch is kept. A 4xx is
+ * the server saying this body is wrong; sending it again cannot help. 408 and 429
+ * are the two 4xx that explicitly mean "later", so they stay retryable.
+ */
+export function isTerminalSettingsRejection(error: unknown): boolean {
+ if (!(error instanceof ChatSettingsRequestError)) return false;
+ const { status } = error;
+ if (status === 408 || status === 429) return false;
+ return status >= 400 && status < 500;
+}
+
+/**
+ * The top-level setting names a validation error blames, e.g. `["ragTopK"]`.
+ *
+ * FastAPI answers a pydantic failure with `detail: [{loc: ["ragTopK"], ...}]`. Only
+ * the first element of `loc` is used: a nested failure (`["inferenceParams",
+ * "temperature"]`) means that whole setting is unsendable as it stands, and the
+ * queue works in whole settings.
+ *
+ * An empty result means the field could not be identified, so the caller drops the
+ * patch outright rather than guessing.
+ */
+export function rejectedSettingKeys(detail: unknown): string[] {
+ if (!Array.isArray(detail)) return [];
+ const keys = new Set<string>();
+ for (const entry of detail) {
+ if (entry == null || typeof entry !== "object") continue;
+ const loc = (entry as { loc?: unknown }).loc;
+ if (!Array.isArray(loc) || loc.length === 0) continue;
+ const field = loc[0];
+ if (typeof field === "string" && field.length > 0) keys.add(field);
+ }
+ return [...keys];
+}
+
+/**
+ * The part of `patch` still worth sending after `error`.
+ *
+ * Returns the patch unchanged when the failure is transient. On a terminal
+ * rejection it drops the named fields and keeps the rest, so one bad value cannot
+ * take the other settings in the same coalesced patch with it; when no field can be
+ * named, everything is dropped.
+ *
+ * `progressed` is what makes the retry safe to schedule: it is only true when the
+ * patch got strictly smaller, so a retry loop is bounded by the number of fields.
+ */
+export function retryablePatchAfterFailure<T extends object>(
+ patch: T,
+ error: unknown,
+): { patch: Partial<T>; dropped: string[]; progressed: boolean } {
+ if (!isTerminalSettingsRejection(error)) {
+ return { patch, dropped: [], progressed: false };
+ }
+ const rejected = rejectedSettingKeys(
+ (error as ChatSettingsRequestError).detail,
+ ).filter((key) => key in (patch as Record<string, unknown>));
+ if (rejected.length === 0) {
+ return { patch: {}, dropped: Object.keys(patch), progressed: false };
+ }
+ const kept: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(patch)) {
+ if (!rejected.includes(key)) kept[key] = value;
+ }
+ return {
+ patch: kept as Partial<T>,
+ dropped: rejected,
+ progressed: Object.keys(kept).length > 0,
+ };
+}
+
+// The Fetch standard caps the TOTAL in-flight keepalive body at 64 KiB, and a valid
+// researchWebsitePolicy carries up to 2000 domains of 253 characters, so a settings
+// patch can be an order of magnitude over it. Over the budget the request fails
+// immediately in every engine (measured: "Failed to fetch" in Chromium,
+// "NetworkError" in Firefox, "Load failed" in WebKit), so sending without keepalive
+// is a chance rather than a certain failure -- and on the visibilitychange flush,
+// where the page is only hidden, it simply succeeds.
+const KEEPALIVE_BODY_BUDGET_BYTES = 60 * 1024;
+
+export function isUnderKeepaliveBudget(body: string): boolean {
+ // A JSON body is at least one byte per UTF-16 unit, so this cheap check settles
+ // every ordinary patch without encoding a copy of a large one.
+ if (body.length <= KEEPALIVE_BODY_BUDGET_BYTES / 3) return true;
+ return new TextEncoder().encode(body).byteLength <= KEEPALIVE_BODY_BUDGET_BYTES;
+}
diff --git a/studio/frontend/src/features/rag/components/project-source-dropzone.tsx b/studio/frontend/src/features/rag/components/project-source-dropzone.tsx
index 0eb04d237ce..94ee3240367 100644
--- a/studio/frontend/src/features/rag/components/project-source-dropzone.tsx
+++ b/studio/frontend/src/features/rag/components/project-source-dropzone.tsx
@@ -91,7 +91,7 @@ export async function uploadStagedSources(
if (staged.length === 0) return;
invalidateProjectSources(projectId);
markProjectSourcesPending(projectId);
- const { ocr, caption } = resolveVisionOverrides();
+ const { ocr, caption } = await resolveVisionOverrides();
const documentIds = new Set<string>();
const merged: string[] = [];
for (const entry of staged) {
diff --git a/studio/frontend/src/features/rag/components/use-rag-documents.ts b/studio/frontend/src/features/rag/components/use-rag-documents.ts
index cef0bbd2a0a..b308fdb3399 100644
--- a/studio/frontend/src/features/rag/components/use-rag-documents.ts
+++ b/studio/frontend/src/features/rag/components/use-rag-documents.ts
@@ -296,7 +296,7 @@ export function useRagDocuments(
) => {
const name = itemName(item);
try {
- const { ocr, caption } = resolveVisionOverrides();
+ const { ocr, caption } = await resolveVisionOverrides();
// Leases are short-lived, so mint one per upload rather than at drop time.
const file =
item.kind === "file"
diff --git a/studio/frontend/src/features/rag/components/vision-overrides.ts b/studio/frontend/src/features/rag/components/vision-overrides.ts
index 674484970b7..f2f1f36b6de 100644
--- a/studio/frontend/src/features/rag/components/vision-overrides.ts
+++ b/studio/frontend/src/features/rag/components/vision-overrides.ts
@@ -7,6 +7,18 @@ import {
useChatRuntimeStore,
} from "@/features/chat";
+// Hydration is a network round trip with no deadline of its own: authFetch sets
+// no AbortSignal, so a wedged or unreachable server leaves the promise pending
+// for as long as the socket does. Uploads used to read these overrides
+// synchronously, so waiting forever would be a new way for a drop to hang with
+// nothing on screen. Bound it and take the local values, the way a blocked
+// localStorage already falls through to the backend defaults.
+const HYDRATION_WAIT_MS = 8_000;
+
+function wait(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
function hasLocal(key: string): boolean {
if (typeof window === "undefined") return false;
try {
@@ -21,10 +33,16 @@ function hasLocal(key: string): boolean {
/** Ingest-time vision-pass overrides, sent only once the user has set them;
* otherwise backend env defaults own the policy. Shared by every upload path. */
-export function resolveVisionOverrides(): {
+export async function resolveVisionOverrides(): Promise<{
ocr: boolean | undefined;
caption: boolean | undefined;
-} {
+}> {
+ // These live in the mirrored chat settings, so a fresh browser has to wait for
+ // them: an ingest cannot be undone once its vision passes have run.
+ await Promise.race([
+ useChatRuntimeStore.getState().hydratePersistedSettings(),
+ wait(HYDRATION_WAIT_MS),
+ ]);
const state = useChatRuntimeStore.getState();
return {
ocr: hasLocal(CHAT_RAG_OCR_KEY) ? state.ragOcrScanned : undefined,
diff --git a/studio/frontend/tests/chat-settings-hydration-shadows.test.ts b/studio/frontend/tests/chat-settings-hydration-shadows.test.ts
new file mode 100644
index 00000000000..3295c45f83d
--- /dev/null
+++ b/studio/frontend/tests/chat-settings-hydration-shadows.test.ts
@@ -0,0 +1,138 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// speculativeType and gpuMemoryMode describe the model that is actually running, and every
+// writer sets them together with a loaded* shadow. The settings GET resolves after the
+// first inference status on a cold boot, so hydrating the editable half while a shadow
+// holds the other splits the pair. With nothing resident the opposite is true: the load
+// path reads the store field (use-chat-model-runtime captures stateBeforeUnload), sends it
+// and then persists it back, so a skipped hydration writes the local default over the
+// server's preference. The predicate is tested for real here; the store itself cannot be
+// imported (a .tsx barrel in its graph), so the wiring is pinned against the source.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+import { loadShadowOwnsMirroredSetting } from "../src/features/chat/utils/mirrored-chat-settings.ts";
+
+const store = readFileSync(
+ new URL("../src/features/chat/stores/chat-runtime-store.ts", import.meta.url),
+ "utf8",
+);
+
+function slice(from: string, to: string): string {
+ const start = store.indexOf(from);
+ const end = store.indexOf(to, start + from.length);
+ assert.ok(start !== -1, `not found: ${from}`);
+ assert.ok(end !== -1, `not found: ${to}`);
+ return store.slice(start, end);
+}
+
+const NO_MODEL = {
+ loadedSpeculativeType: null,
+ loadedGpuMemoryMode: null,
+} as const;
+
+// Dropping them instead would make scalarSettingMutationVersions[key] += 1 produce NaN and
+// leave hydration permanently unable to match a version for either key.
+test("both keys stay in the scalar setting list", () => {
+ const keys = slice(
+ "const SCALAR_SETTING_KEYS = [",
+ "] as const satisfies readonly ScalarSettingKey[];",
+ );
+ assert.match(keys, /"speculativeType",/);
+ assert.match(keys, /"gpuMemoryMode",/);
+});
+
+test("a resident model's shadow owns its half of the pair", () => {
+ assert.equal(
+ loadShadowOwnsMirroredSetting("speculativeType", {
+ ...NO_MODEL,
+ loadedSpeculativeType: "mtp",
+ }),
+ true,
+ );
+ assert.equal(
+ loadShadowOwnsMirroredSetting("gpuMemoryMode", {
+ ...NO_MODEL,
+ loadedGpuMemoryMode: "manual",
+ }),
+ true,
+ );
+ // Each key answers for its own shadow only.
+ assert.equal(
+ loadShadowOwnsMirroredSetting("gpuMemoryMode", {
+ ...NO_MODEL,
+ loadedSpeculativeType: "mtp",
+ }),
+ false,
+ );
+});
+
+// The regression: with no shadow, hydration must apply the server's value, or the next
+// load captures the local default and the successful-load persist writes it back.
+test("with nothing resident the stored preference still hydrates", () => {
+ assert.equal(
+ loadShadowOwnsMirroredSetting("speculativeType", NO_MODEL),
+ false,
+ );
+ assert.equal(loadShadowOwnsMirroredSetting("gpuMemoryMode", NO_MODEL), false);
+});
+
+test("every other mirrored setting hydrates unconditionally", () => {
+ for (const key of ["permissionMode", "ragMode", "toolsEnabled"]) {
+ assert.equal(
+ loadShadowOwnsMirroredSetting(key, {
+ loadedSpeculativeType: "mtp",
+ loadedGpuMemoryMode: "manual",
+ }),
+ false,
+ );
+ }
+});
+
+test("hydration defers to the shadow check, not the key name", () => {
+ const hydrate = slice(
+ "function getHydratedSettingsState(",
+ "function setScalarSettingVersion<",
+ );
+ assert.match(hydrate, /loadShadowOwnsMirroredSetting\(key, state\)/);
+ // An unconditional skip is the bug: it strands the server's preference.
+ assert.doesNotMatch(
+ hydrate,
+ /if \(key === "speculativeType" \|\| key === "gpuMemoryMode"\)/,
+ );
+ // The check has to precede the write, or the field moves before anything can stop it.
+ assert.ok(
+ hydrate.indexOf("loadShadowOwnsMirroredSetting") <
+ hydrate.indexOf("[key] = value;"),
+ "the shadow check runs after hydration has already written the field",
+ );
+});
+
+// The load path reads the standing preference from localStorage on a model switch, which
+// cacheHydratedSettings refreshes from the same payload.
+test("the mirrored cache still carries both preferences", () => {
+ const mirrored = slice("const MIRRORED_SETTINGS = {", "\n} satisfies Partial<");
+ assert.match(mirrored, /speculativeType: \{ storageKey: CHAT_SPECULATIVE_TYPE_KEY/);
+ assert.match(mirrored, /gpuMemoryMode: \{ storageKey: CHAT_GPU_MEMORY_MODE_KEY/);
+ assert.match(store, /loadString\(CHAT_SPECULATIVE_TYPE_KEY, "auto"\)/);
+ assert.match(store, /loadString\(CHAT_GPU_MEMORY_MODE_KEY, "auto"\)/);
+});
+
+// saveBool reaches mirrorSettingToBackend, which bumps the version and queues the patch
+// itself, so the sibling mirrored setters call it alone.
+test("the artifact setters bump their setting version once", () => {
+ const setters = slice(
+ "setCollapseHtmlArtifacts: (collapseHtmlArtifacts) =>",
+ "setMcpEnabledForChat: (mcpEnabledForChat) =>",
+ );
+ assert.doesNotMatch(setters, /setScalarSettingVersion/);
+ assert.match(setters, /saveBool\(CHAT_COLLAPSE_HTML_ARTIFACTS_KEY/);
+ assert.match(setters, /saveBool\(\s*CHAT_ALLOW_ARTIFACT_NETWORK_ACCESS_KEY/);
+ assert.match(
+ slice("function mirrorSettingToBackend(", "\n}"),
+ /scalarSettingMutationVersions\[setting\.field\] \+= 1;/,
+ );
+});
diff --git a/studio/frontend/tests/mirrored-chat-settings.test.ts b/studio/frontend/tests/mirrored-chat-settings.test.ts
new file mode 100644
index 00000000000..6aaf5b2fc53
--- /dev/null
+++ b/studio/frontend/tests/mirrored-chat-settings.test.ts
@@ -0,0 +1,132 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Chat toggles used to live only in localStorage, so a second browser or a
+// remote session started from defaults. They now round-trip through
+// /api/chat/settings, and the backend payload is extra="forbid" with literal
+// and range constraints: one out-of-contract field 400s the whole save. These
+// pin what the client is allowed to send and what it accepts back.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import type { PersistedChatSettings } from "../src/features/chat/api/chat-settings-api.ts";
+import {
+ assignSanitizedMirroredSettings,
+ hasNoMirroredSettings,
+ normalizeStoredRagAutoInject,
+} from "../src/features/chat/utils/mirrored-chat-settings.ts";
+
+function sanitized(value: Record<string, unknown>): PersistedChatSettings {
+ const settings: PersistedChatSettings = {};
+ assignSanitizedMirroredSettings(value, settings);
+ return settings;
+}
+
+test("a full set of mirrored settings survives the round trip", () => {
+ const settings = sanitized({
+ toolsEnabled: true,
+ deepResearchEnabled: false,
+ permissionMode: "ask",
+ ragMode: "dense",
+ ragTopK: 12,
+ ragAutoInject: "on",
+ ragAutoInjectMinScore: 0.42,
+ ragSource: { type: "kb", kbId: "notes" },
+ researchWebsitePolicy: {
+ allowedDomains: ["unsloth.ai"],
+ blockedDomains: [],
+ },
+ speculativeType: "ngram",
+ gpuMemoryMode: "manual",
+ fitOnDeviceOnly: true,
+ });
+
+ assert.deepEqual(settings, {
+ toolsEnabled: true,
+ deepResearchEnabled: false,
+ permissionMode: "ask",
+ ragMode: "dense",
+ ragTopK: 12,
+ ragAutoInject: "on",
+ ragAutoInjectMinScore: 0.42,
+ ragSource: { type: "kb", kbId: "notes" },
+ researchWebsitePolicy: {
+ allowedDomains: ["unsloth.ai"],
+ blockedDomains: [],
+ },
+ speculativeType: "ngram",
+ gpuMemoryMode: "manual",
+ fitOnDeviceOnly: true,
+ });
+});
+
+test("a thread RAG source keeps its shape", () => {
+ assert.deepEqual(sanitized({ ragSource: { type: "thread" } }), {
+ ragSource: { type: "thread" },
+ });
+});
+
+// Full access disables the sandbox, so it has to be re-accepted each session.
+test("the full permission mode is never persisted", () => {
+ assert.deepEqual(sanitized({ permissionMode: "full" }), {});
+});
+
+test("values outside the backend contract are dropped, not sent", () => {
+ assert.deepEqual(
+ sanitized({
+ toolsEnabled: "yes",
+ permissionMode: "elevated",
+ ragMode: "vector",
+ ragTopK: 0,
+ ragAutoInjectMinScore: 2,
+ speculativeType: "mtp",
+ gpuMemoryMode: "",
+ ragSource: { type: "kb" },
+ researchWebsitePolicy: "everything",
+ }),
+ {},
+ );
+});
+
+// A stored top K is a slider value; a fractional one would 422 the payload.
+test("a fractional top K is rejected", () => {
+ assert.deepEqual(sanitized({ ragTopK: 7.5 }), {});
+});
+
+test("non-string domains are stripped from the research policy", () => {
+ assert.deepEqual(
+ sanitized({
+ researchWebsitePolicy: {
+ allowedDomains: ["a.example", 42, null],
+ blockedDomains: ["b.example", "x".repeat(300)],
+ },
+ }),
+ {
+ researchWebsitePolicy: {
+ allowedDomains: ["a.example"],
+ blockedDomains: ["b.example"],
+ },
+ },
+ );
+});
+
+// Storage predating the three-way control holds the old booleans. Backfilling one
+// raw would send a value the backend rejects, so the preference never carries.
+test("a legacy RAG auto-inject boolean is migrated before it is sent", () => {
+ assert.equal(normalizeStoredRagAutoInject("false"), "off");
+ assert.equal(normalizeStoredRagAutoInject("true"), "auto");
+ assert.equal(normalizeStoredRagAutoInject("on"), "on");
+ assert.equal(normalizeStoredRagAutoInject("off"), "off");
+ assert.equal(normalizeStoredRagAutoInject("auto"), "auto");
+ assert.equal(normalizeStoredRagAutoInject("nonsense"), "auto");
+});
+
+// The legacy localStorage import runs only against a record with nothing in it,
+// so a server record holding just the mirrored toggles must not read as empty.
+test("a record holding only mirrored settings is not empty", () => {
+ assert.equal(hasNoMirroredSettings({}), true);
+ assert.equal(hasNoMirroredSettings({ autoTitle: true }), true);
+ assert.equal(hasNoMirroredSettings({ ragTopK: 5 }), false);
+ assert.equal(hasNoMirroredSettings({ toolsEnabled: false }), false);
+});
diff --git a/studio/frontend/tests/mirrored-settings-write-authority.test.ts b/studio/frontend/tests/mirrored-settings-write-authority.test.ts
new file mode 100644
index 00000000000..86eee4d50e9
--- /dev/null
+++ b/studio/frontend/tests/mirrored-settings-write-authority.test.ts
@@ -0,0 +1,117 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Two writes that reach every browser on the install now that saveBool and the hydration
+// backfill mirror to /api/chat/settings, so each needs a reason to fire:
+// 1. setCheckpoint's deep-research clamp. Codex runs deep research (thread.tsx exempts
+// openai_codex from researchDisabled, chat-adapter accepts its research requests), so
+// clamping on every external id would turn a Codex user's preference off everywhere.
+// 2. The backfill, which reads "field absent" as "unset on the server". That only holds
+// for a GET that answered; the legacy-storage fallback knows nothing about the server.
+// The store and chat-settings-storage cannot be imported in a bare node test (a .tsx barrel
+// sits in both graphs), so these pin the source the way the sibling store tests do.
+
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import test from "node:test";
+
+function read(path: string): string {
+ return readFileSync(new URL(path, import.meta.url), "utf8");
+}
+
+const store = read("../src/features/chat/stores/chat-runtime-store.ts");
+const storage = read("../src/features/chat/utils/chat-settings-storage.ts");
+
+function slice(source: string, from: string, to: string): string {
+ const start = source.indexOf(from);
+ const end = source.indexOf(to, start + from.length);
+ assert.ok(start !== -1, `not found: ${from}`);
+ assert.ok(end !== -1, `not found: ${to}`);
+ return source.slice(start, end);
+}
+
+const setCheckpoint = () =>
+ slice(
+ store,
+ "setCheckpoint: (modelId, ggufVariant, options) =>",
+ "\n setActiveThreadId:",
+ );
+
+test("selecting a Codex checkpoint keeps deep research", () => {
+ const body = setCheckpoint();
+ // Main settled on externalModelSupportsStudioTools for this; the property under test is
+ // that the clamp is provider-aware and computed once, not which helper answers it.
+ assert.match(
+ body,
+ /const clampsDeepResearch =\s*isExternalModelId\(modelId\) && !externalModelSupportsStudioTools\(modelId\);/,
+ );
+ // Every deep-research write in the setter goes through that one clamp rather than
+ // re-testing the id, which is what switched it off for capable providers.
+ for (const line of body.split("\n")) {
+ if (!/deepResearch/i.test(line)) continue;
+ assert.doesNotMatch(
+ line,
+ /isExternalModelId/,
+ `deep research still clamped on any external id: ${line.trim()}`,
+ );
+ }
+ assert.match(
+ body,
+ /if \(clampsDeepResearch\) \{\s*saveBool\(CHAT_DEEP_RESEARCH_ENABLED_KEY, false\);/,
+ );
+ assert.match(body, /const nextDeepResearchEnabled = clampsDeepResearch/);
+ assert.match(
+ body,
+ /\.\.\.\(clampsDeepResearch \? \{ deepResearchEnabled: false \} : \{\}\)/,
+ );
+});
+
+// The helper resolves the provider and refuses only a known non-Codex one, so an
+// unresolved provider (connection list still loading) never drops the preference.
+test("the clamp exempts Codex and an unresolved provider", () => {
+ const helper = slice(
+ store,
+ "function externalCheckpointRefusesDeepResearch(",
+ "\n}",
+ );
+ assert.match(helper, /if \(!parsed\) return false;/);
+ assert.match(
+ helper,
+ /provider != null && provider\.providerType !== "openai_codex"/,
+ );
+});
+
+test("hydration backfills only from an authoritative read", () => {
+ const hydrate = slice(
+ store,
+ "hydratePersistedSettings: async () => {",
+ "\n beginModelLoading:",
+ );
+ assert.match(
+ hydrate,
+ /const \{ settings, fromServer \} = await loadChatSettingsWithLegacyImport\(\);/,
+ );
+ assert.match(
+ hydrate,
+ /if \(fromServer\) backfillMirroredSettings\(settings\);/,
+ );
+ // An ungated call is the bug: a failed GET would push this browser's stale values.
+ assert.doesNotMatch(hydrate, /\n\s*backfillMirroredSettings\(settings\);/);
+});
+
+test("only the legacy-storage fallback is non-authoritative", () => {
+ const loader = slice(
+ storage,
+ "export async function loadChatSettingsWithLegacyImport(",
+ "\nexport async function savePersistedChatSettingsPatch(",
+ );
+ const nonAuthoritative = loader.match(/fromServer: false/g) ?? [];
+ assert.equal(nonAuthoritative.length, 1);
+ // ...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 \};/,
+ );
+ // 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/settings-retry.test.ts b/studio/frontend/tests/settings-retry.test.ts
new file mode 100644
index 00000000000..17e99efb0e4
--- /dev/null
+++ b/studio/frontend/tests/settings-retry.test.ts
@@ -0,0 +1,158 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// What the settings queue keeps after a failed PUT.
+//
+// The case that matters is the one that used to break the tab: /api/chat/settings
+// is extra="forbid" and rejects the whole body on one bad field, so requeueing a
+// permanently-rejected patch made every later save carry it and fail too. Verified
+// against a live Studio in Chromium, Firefox and WebKit before the fix.
+
+import assert from "node:assert/strict";
+import { test } from "node:test";
+
+import {
+ ChatSettingsRequestError,
+ isTerminalSettingsRejection,
+ isUnderKeepaliveBudget,
+ rejectedSettingKeys,
+ retryablePatchAfterFailure,
+} from "../src/features/chat/utils/settings-retry.ts";
+
+const extraForbidden = (...fields: string[]) =>
+ new ChatSettingsRequestError(
+ "Request failed (400)",
+ 400,
+ fields.map((field) => ({
+ type: "extra_forbidden",
+ loc: [field],
+ msg: "Extra inputs are not permitted",
+ })),
+ );
+
+test("a 4xx is terminal and a 5xx is not", () => {
+ for (const status of [400, 401, 403, 404, 409, 422]) {
+ assert.equal(
+ isTerminalSettingsRejection(
+ new ChatSettingsRequestError("x", status, null),
+ ),
+ true,
+ `${status}`,
+ );
+ }
+ for (const status of [408, 429, 500, 502, 503, 504]) {
+ assert.equal(
+ isTerminalSettingsRejection(
+ new ChatSettingsRequestError("x", status, null),
+ ),
+ false,
+ `${status}`,
+ );
+ }
+});
+
+test("a network failure is not a rejection", () => {
+ assert.equal(isTerminalSettingsRejection(new TypeError("Failed to fetch")), false);
+ assert.equal(isTerminalSettingsRejection(undefined), false);
+});
+
+test("the rejected fields are read out of the pydantic detail", () => {
+ assert.deepEqual(
+ rejectedSettingKeys(extraForbidden("ragTopK", "toolsEnabled").detail).sort(),
+ ["ragTopK", "toolsEnabled"],
+ );
+});
+
+test("a nested failure names the whole setting", () => {
+ const detail = [{ type: "float_parsing", loc: ["inferenceParams", "temperature"] }];
+ assert.deepEqual(rejectedSettingKeys(detail), ["inferenceParams"]);
+});
+
+test("a detail that is not a pydantic list names nothing", () => {
+ assert.deepEqual(rejectedSettingKeys("Cannot apply partial settings patch"), []);
+ assert.deepEqual(rejectedSettingKeys(null), []);
+ assert.deepEqual(rejectedSettingKeys([{ loc: [] }, { loc: [7] }, 3]), []);
+});
+
+test("a transient failure keeps the whole patch", () => {
+ const patch = { ragTopK: 11, toolsEnabled: true };
+ const result = retryablePatchAfterFailure(patch, new TypeError("offline"));
+ assert.deepEqual(result.patch, patch);
+ assert.deepEqual(result.dropped, []);
+ assert.equal(result.progressed, false);
+});
+
+test("a rejected field is dropped and the rest of the patch survives", () => {
+ const patch = { ragTopK: 11, toolsEnabled: true, permissionMode: "ask" };
+ const result = retryablePatchAfterFailure(patch, extraForbidden("ragTopK"));
+ assert.deepEqual(result.patch, { toolsEnabled: true, permissionMode: "ask" });
+ assert.deepEqual(result.dropped, ["ragTopK"]);
+ // Strictly smaller, so the caller may reschedule without looping forever.
+ assert.equal(result.progressed, true);
+});
+
+test("an unattributable rejection drops the patch rather than guessing", () => {
+ const error = new ChatSettingsRequestError("Request failed (400)", 400, "nope");
+ const result = retryablePatchAfterFailure({ ragTopK: 11 }, error);
+ assert.deepEqual(result.patch, {});
+ assert.deepEqual(result.dropped, ["ragTopK"]);
+ assert.equal(result.progressed, false);
+});
+
+test("a rejection naming a field the patch does not hold drops nothing extra", () => {
+ const result = retryablePatchAfterFailure(
+ { ragTopK: 11 },
+ extraForbidden("somethingElse"),
+ );
+ assert.deepEqual(result.patch, {});
+ assert.deepEqual(result.dropped, ["ragTopK"]);
+});
+
+test("the whole-patch rejection of an old backend leaves nothing pending", () => {
+ // A new bundle against a rolled-back backend: every mirrored field is refused,
+ // the supported ones are not, and the retry carries only those.
+ const patch = {
+ autoTitle: true,
+ inferenceParams: { temperature: 0.7 },
+ toolsEnabled: true,
+ permissionMode: "ask",
+ ragTopK: 11,
+ };
+ const result = retryablePatchAfterFailure(
+ patch,
+ extraForbidden("toolsEnabled", "permissionMode", "ragTopK"),
+ );
+ assert.deepEqual(result.patch, {
+ autoTitle: true,
+ inferenceParams: { temperature: 0.7 },
+ });
+ assert.equal(result.progressed, true);
+});
+
+test("retrying is bounded: each round strictly shrinks the patch", () => {
+ let patch: Record<string, unknown> = {
+ a: 1, b: 2, c: 3, autoTitle: true,
+ };
+ const rounds: number[] = [];
+ for (const field of ["a", "b", "c"]) {
+ const result = retryablePatchAfterFailure(patch, extraForbidden(field));
+ patch = result.patch as Record<string, unknown>;
+ rounds.push(Object.keys(patch).length);
+ }
+ assert.deepEqual(rounds, [3, 2, 1]);
+ assert.deepEqual(patch, { autoTitle: true });
+});
+
+// Fetch caps all in-flight keepalive bodies at 64 KiB and a valid
+// researchWebsitePolicy (2000 domains x 253 characters) is far past that, so a patch
+// sent with keepalive over the budget fails immediately -- measured as "Failed to
+// fetch" in Chromium, "NetworkError" in Firefox and "Load failed" in WebKit.
+
+test("the keepalive budget is decided by bytes, not by string length", () => {
+ assert.equal(isUnderKeepaliveBudget(JSON.stringify({ ragTopK: 11 })), true);
+ assert.equal(isUnderKeepaliveBudget("x".repeat(20 * 1024)), true);
+ assert.equal(isUnderKeepaliveBudget("x".repeat(61 * 1024)), false);
+ // A four-byte character is one UTF-16 pair: a length-only check would call this
+ // 44 KiB and send it, and the request would be refused by the browser.
+ assert.equal(isUnderKeepaliveBudget("\u{1f600}".repeat(22 * 1024)), false);
+});
diff --git a/studio/frontend/tsconfig.test.json b/studio/frontend/tsconfig.test.json
index be53907fc7f..e25c1acde65 100644
--- a/studio/frontend/tsconfig.test.json
+++ b/studio/frontend/tsconfig.test.json
@@ -26,5 +26,7 @@
"@/*": ["./src/*"]
}
},
- "include": ["tests"]
+ // The ambient declarations too: a test that reaches a src module pulling in
+ // the dictation adapter needs the SpeechRecognition globals it declares.
+ "include": ["tests", "src/speech-recognition.d.ts"]
}
diff --git a/tests/studio/playwright_chat_ui.py b/tests/studio/playwright_chat_ui.py
index 46cbfb5b12d..5143827f98f 100644
--- a/tests/studio/playwright_chat_ui.py
+++ b/tests/studio/playwright_chat_ui.py
@@ -150,6 +150,44 @@ def exercise_permission_mode_controls(page, shoot):
expect(item).to_be_visible()
item.click()
+ def set_legacy_confirm(legacy_value):
+ page.evaluate(
+ """(legacyValue) => {
+ localStorage.removeItem("unsloth_chat_permission_mode");
+ if (legacyValue === null) {
+ localStorage.removeItem("unsloth_chat_confirm_tool_calls");
+ } else {
+ localStorage.setItem(
+ "unsloth_chat_confirm_tool_calls",
+ legacyValue,
+ );
+ }
+ }""",
+ legacy_value,
+ )
+
+ # The level is an installation setting, mirrored through /api/chat/settings,
+ # so "fresh profile" is no longer "fresh browser": the cross-browser step
+ # runs this block three times against ONE install, and runs two and three
+ # would otherwise open on the level run one left behind. Refuse the
+ # hydrating GET, with no local level either, which is the state a first-ever
+ # browser on a never-configured install is in. Everything up to the end of
+ # the migration loop reads the level, so the whole stretch is held there.
+ def refuse_settings_hydration(route):
+ if route.request.method == "GET":
+ route.fulfill(
+ status = 503,
+ content_type = "application/json",
+ body = json.dumps({"detail": "hydration disabled for this step"}),
+ )
+ else:
+ route.continue_()
+
+ page.route("**/api/chat/settings", refuse_settings_hydration)
+ set_legacy_confirm(None)
+ page.reload(wait_until = "domcontentloaded")
+ expect(pill).to_be_visible()
+
# Fresh profiles default to Approve for me.
expect_mode("Approve for me")
menu = open_menu()
@@ -180,30 +218,36 @@ def exercise_permission_mode_controls(page, shoot):
fail(f"permission pill is clipped in compact layout: {box!r}")
page.set_viewport_size({"width": 1280, "height": 900})
- # Legacy setting migration: true -> ask, false -> off, absent -> auto.
+ # Legacy setting migration: true -> ask, false -> off, absent -> auto. Still
+ # under the refused hydration above: a stored level wins over the local
+ # derivation, so without it the second reload would assert against the level
+ # the first one seeded and read as a migration bug.
migration_cases = (
("true", "Ask for approval"),
("false", "Run automatically"),
(None, "Approve for me"),
)
- for legacy_value, expected_label in migration_cases:
- page.evaluate(
- """(legacyValue) => {
- localStorage.removeItem("unsloth_chat_permission_mode");
- if (legacyValue === null) {
- localStorage.removeItem("unsloth_chat_confirm_tool_calls");
- } else {
- localStorage.setItem(
- "unsloth_chat_confirm_tool_calls",
- legacyValue,
- );
- }
- }""",
- legacy_value,
- )
- page.reload(wait_until = "domcontentloaded")
- expect(pill).to_be_visible()
- expect_mode(expected_label)
+ try:
+ for legacy_value, expected_label in migration_cases:
+ set_legacy_confirm(legacy_value)
+ page.reload(wait_until = "domcontentloaded")
+ expect(pill).to_be_visible()
+ expect_mode(expected_label)
+ finally:
+ page.unroute("**/api/chat/settings", refuse_settings_hydration)
+
+ # The other half of that contract: with a level stored for the install, a
+ # browser holding only the legacy key gets the installation's level back
+ # rather than its own derivation.
+ choose("Ask for approval")
+ expect_mode("Ask for approval")
+ set_legacy_confirm("false")
+ page.reload(wait_until = "domcontentloaded")
+ expect(pill).to_be_visible()
+ expect_mode("Ask for approval")
+ cached = page.evaluate("() => localStorage.getItem('unsloth_chat_permission_mode')")
+ if cached != "ask":
+ fail(f"hydration left the local cache at {cached!r}, expected 'ask'")
choose("Run automatically")
expect_mode("Run automatically")