Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
studio: keep each chat's composer pills and settings with the chat (#8686)
Maheswar Kumar5bb0bc6f7336
diff --git a/.github/workflows/studio-ui-smoke.yml b/.github/workflows/studio-ui-smoke.ymlindex 2c45ae37411..39ebf406165 100644--- a/.github/workflows/studio-ui-smoke.yml+++ b/.github/workflows/studio-ui-smoke.yml@@ -259,6 +259,15 @@ jobs:mkdir -p logs/playwright_extrapython tests/studio/playwright_extra_ui.py+ - name: Per-chat settings persistence (Playwright)+ env:+ BASE_URL: http://127.0.0.1:18894+ STUDIO_NEW_PW: ${{ env.STUDIO_EXTRA_NEW_PW }}+ PW_ART_DIR: logs/playwright_thread_settings+ run: |+ mkdir -p logs/playwright_thread_settings+ python tests/studio/playwright_thread_scoped_settings.py+- name: UI font size scaling regression (Playwright)env:BASE_URL: http://127.0.0.1:18894@@ -432,6 +441,7 @@ jobs:logs/playwrightlogs/playwright-permissions-*logs/playwright_extra+ logs/playwright_thread_settingslogs/playwright_fontscalelogs/playwright_update_bannerlogs/playwright_image_footprintdiff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.pyindex f354f8b1d4f..a5bf80490c5 100644--- a/studio/backend/routes/chat_history.py+++ b/studio/backend/routes/chat_history.py@@ -54,6 +54,7 @@ from storage.studio_db import (upsert_chat_legacy_imports,upsert_chat_message,upsert_chat_settings_merge,+ write_chat_thread_settings,upsert_chat_thread,)@@ -62,6 +63,51 @@ router = APIRouter()logger = get_logger(__name__)+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 ChatThreadSettings(BaseModel):+ """The chat settings captured per thread; a thread storing none uses the global ones."""++ model_config = ConfigDict(extra = "forbid")++ reasoningEnabled: Optional[bool] = None+ reasoningEffort: Optional[+ Literal["none", "minimal", "low", "medium", "high", "max", "xhigh"]+ ] = None+ toolsEnabled: Optional[bool] = None+ codeToolsEnabled: Optional[bool] = None+ imageToolsEnabled: Optional[bool] = None+ webFetchToolsEnabled: Optional[bool] = None+ deepResearchEnabled: Optional[bool] = None+ artifactsEnabled: Optional[bool] = None+ mcpEnabledForChat: Optional[bool] = None+ # "full" (Full access) is session-only and never persisted, per thread or globally.+ permissionMode: Optional[Literal["ask", "auto", "off"]] = None+ ragEnabled: Optional[bool] = 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)++class ChatThread(BaseModel):id: strtitle: str = "New Chat"@@ -76,6 +122,96 @@ class ChatThread(BaseModel):anthropicCodeExecContainerId: Optional[str] = NoneforkedFromThreadId: Optional[str] = NoneforkedFromMessageId: Optional[str] = None+ settings: Optional[ChatThreadSettings] = None+++def thread_from_row(row: dict) -> ChatThread:+ """Build a ChatThread from a DATABASE row, tolerating a snapshot it cannot read.++ `settings` is the first strictly validated nested model Studio builds out of the+ database rather than off the wire, and a stored snapshot outlives the build that+ wrote it: a newer Studio adding a seventeenth setting, widening an enum or+ raising a bound writes a blob this one rejects. Refusing it here 500s the chat on+ open and takes the entire history export with it, since the export validates+ every thread. `_json_loads` already shrugs off JSON that will not parse; JSON+ that parses but postdates this build deserves the same treatment.++ Only the read is forgiving. The wire contract stays strict in both directions, so+ a client still cannot invent a setting, and the row itself is left untouched,+ which means upgrading again restores whatever this build had to drop.+ """+ settings = row.get("settings")+ if isinstance(settings, dict):+ row = {**row, "settings": readable_thread_settings(settings)}+ elif settings is not None:+ row = {**row, "settings": None}+ return ChatThread(**row)+++def readable_thread_settings(settings: dict) -> Optional[dict]:+ """The part of a stored snapshot this build can validate, or None if none of it is."""+ known = {k: v for k, v in settings.items() if k in ChatThreadSettings.model_fields}+ # Drop exactly the fields pydantic names and retry: a version gap usually+ # carries several at once, so removing one guess at a time gives up too early.+ for _ in range(len(known) + 1):+ try:+ ChatThreadSettings.model_validate(known)+ return known+ except ValidationError as exc:+ bad = {str(e["loc"][0]) for e in exc.errors() if e.get("loc")}+ if not bad or not bad & set(known):+ return None+ known = {k: v for k, v in known.items() if k not in bad}+ return None+++def _unreadable_thread_settings(stored: dict) -> dict:+ """The part of a stored snapshot this build cannot validate, and so must not delete.++ An older Studio opening a database a newer one wrote drops the fields it cannot read.+ A blind replacement would make that loss permanent instead of temporary, so a write+ carries forward everything the writer could not have known about: unknown keys, and+ known keys holding values this build rejects.+ """+ readable = readable_thread_settings(stored) or {}+ return {k: v for k, v in stored.items() if k not in readable}+++def _settings_write_from_patch(patch: dict) -> Optional[dict]:+ """Take `settings` / `settingsPatch` out of `patch` and describe the write they ask for.++ `settings` replaces the snapshot, `settingsPatch` applies only the fields it names,+ for a client that knows what changed but not what else the row holds. The result is+ handed to storage rather than executed here: the read, the merge and the guarded+ metadata write all have to be one transaction, or two tabs each build a replacement+ from the same stale row, or a rejected precondition returns 409 having already+ committed the settings.+ """+ replace = "settings" in patch+ merge = "settingsPatch" in patch+ seq = patch.pop("settingsSeq", None)+ writer = patch.pop("settingsWriter", None)+ if not (replace or merge):+ return None+ incoming = patch.pop("settingsPatch", None)+ if merge:+ # A merge is the more specific instruction; sending both is a client bug.+ patch.pop("settings", None)+ else:+ incoming = patch.pop("settings")+ if incoming is None:+ # Clearing is the one instruction that means the whole column. A merge of+ # nothing is not an instruction at all, so it leaves the row alone.+ if replace and not merge:+ return {"clear": True, "seq": seq, "writer": writer}+ return None+ return {+ "merge": incoming if merge else None,+ "replace": None if merge else incoming,+ "seq": seq,+ "writer": writer,+ "keep_unreadable": _unreadable_thread_settings,+ }class ChatThreadPatch(BaseModel):@@ -93,6 +229,16 @@ class ChatThreadPatch(BaseModel):updatedAt: Optional[int] = NoneopenaiCodeExecContainerId: Optional[str] = NoneanthropicCodeExecContainerId: Optional[str] = None+ # Replaces the whole snapshot, except for anything the client could not read.+ settings: Optional[ChatThreadSettings] = None+ # Applies just the fields it names. For the writer that knows what changed but not+ # what else the row holds, which is any write made before the row has been read.+ settingsPatch: Optional[ChatThreadSettings] = None+ # Orders this writer's snapshot writes against its OWN earlier ones, so a keepalive+ # sent on unload cannot be undone by a PATCH the server already had in hand. Never+ # compared across writers: two browsers' counters mean nothing to each other.+ settingsSeq: Optional[int] = None+ settingsWriter: Optional[str] = Noneclass ChatMessage(BaseModel):@@ -237,19 +383,6 @@ class ChatPreset(BaseModel):loadConfig: Optional[ChatPresetLoadConfig] = None-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")@@ -360,7 +493,7 @@ def list_threads(project_id = project_id,include_archived = include_archived,)- return ChatThreadListResponse(threads = [ChatThread(**t) for t in threads])+ return ChatThreadListResponse(threads = [thread_from_row(t) for t in threads])def _missing_project_error(project_id: Optional[str]) -> HTTPException:@@ -381,7 +514,7 @@ def save_thread(payload: ChatThread, current_subject: str = Depends(get_current_if payload.projectId and get_chat_project(payload.projectId) is None:raise _missing_project_error(payload.projectId)try:- return ChatThread(**upsert_chat_thread(payload.model_dump()))+ return thread_from_row(upsert_chat_thread(payload.model_dump()))except ChatThreadDeletedError as exc:raise _deleted_thread_error(payload.id) from excexcept sqlite3.IntegrityError as exc:@@ -397,7 +530,7 @@ def get_thread(thread_id: str, current_subject: str = Depends(get_current_subjecthread = get_chat_thread(thread_id)if thread is None:raise HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")- return ChatThread(**thread)+ return thread_from_row(thread)@router.patch("/threads/{thread_id}", response_model = ChatThread)@@ -414,12 +547,14 @@ def patch_thread(raise HTTPException(status_code = 400, detail = f"{field} cannot be null")if patch.get("projectId") and get_chat_project(patch["projectId"]) is None:raise _missing_project_error(patch["projectId"])+ settings_write = _settings_write_from_patch(patch)try:thread = update_chat_thread(thread_id,patch,expected_title = expected_title,expected_opening_message_id = expected_opening_message_id,+ settings_write = settings_write,)except sqlite3.IntegrityError as exc:# Same race as save_thread: the project can go away before this write lands.@@ -433,7 +568,7 @@ def patch_thread()if thread is None:raise HTTPException(status_code = 404, detail = f"Thread {thread_id} not found")- return ChatThread(**thread)+ return thread_from_row(thread)def _cancel_deleted_research_runs(request: Request, run_ids: list[str]) -> None:@@ -1265,7 +1400,7 @@ def fork_thread(if source.get("openaiCodeExecContainerId") or source.get("anthropicCodeExecContainerId"):warning = "Sandbox starts fresh in fork; files from parent are not carried over."return ChatForkResponse(- thread = ChatThread(**forked),+ thread = thread_from_row(forked),messages = [ChatMessage(**m) for m in messages],containerSnapshotWarning = warning,)@@ -1292,6 +1427,6 @@ def export_history(current_subject: str = Depends(get_current_subject)):version = 1,threadCount = len(threads),projects = [ChatProject(**project) for project in projects],- threads = [ChatThread(**thread) for thread in threads],+ threads = [thread_from_row(thread) for thread in threads],messages = [ChatMessage(**message) for message in messages],)diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex 869b5407788..5381fb421d4 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -367,6 +367,7 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:anthropic_code_exec_container_id TEXT,forked_from_thread_id TEXT,forked_from_message_id TEXT,+ settings_json TEXT,FOREIGN KEY(project_id) REFERENCES chat_projects(id) ON DELETE CASCADE)"""@@ -374,6 +375,18 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:chat_thread_cols = {row[1] for row in conn.execute("PRAGMA table_info(chat_threads)").fetchall()}+ if "settings_json" not in chat_thread_cols:+ conn.execute("ALTER TABLE chat_threads ADD COLUMN settings_json TEXT")+ # Orders one writer's snapshot writes against its own earlier ones. A tab closing+ # sends its last edit keepalive, which can overtake a PATCH already accepted by the+ # server, and no client-side cancel reaches a handler that is already running: the+ # older write has to be refused here. Scoped to the writer that sent it, so two+ # browsers are never ordered against each other; see write_chat_thread_settings.+ # {writer id: highest seq seen from it}. One writer and one seq is not enough: a+ # write from another tab overwrites them, and the delayed request the ordering exists+ # to refuse is then compared against a watermark that is no longer its own.+ if "settings_seqs" not in chat_thread_cols:+ conn.execute("ALTER TABLE chat_threads ADD COLUMN settings_seqs TEXT")if "project_id" not in chat_thread_cols:conn.execute("ALTER TABLE chat_threads ADD COLUMN project_id TEXT")if "openai_code_exec_container_id" not in chat_thread_cols:@@ -1619,9 +1632,9 @@ def _json_loads(value: str | None, fallback):return fallback-def _chat_thread_from_row(row: sqlite3.Row) -> dict:+def _chat_thread_from_row(row: sqlite3.Row, include_settings: bool = True) -> dict:data = dict(row)- return {+ thread = {"id": data["id"],"title": data["title"],"modelType": data["model_type"],@@ -1638,6 +1651,9 @@ def _chat_thread_from_row(row: sqlite3.Row) -> dict:"forkedFromThreadId": data.get("forked_from_thread_id"),"forkedFromMessageId": data.get("forked_from_message_id"),}+ if include_settings:+ thread["settings"] = _json_loads(data.get("settings_json"), None)+ return threaddef _chat_project_from_row(row: sqlite3.Row) -> dict:@@ -1695,8 +1711,8 @@ def upsert_chat_thread(thread: dict) -> dict:conn.execute("""INSERT INTO chat_threads- (id, title, model_type, model_id, pair_id, project_id, archived, created_at, updated_at, openai_code_exec_container_id, anthropic_code_exec_container_id, forked_from_thread_id, forked_from_message_id)- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ (id, title, model_type, model_id, pair_id, project_id, archived, created_at, updated_at, openai_code_exec_container_id, anthropic_code_exec_container_id, forked_from_thread_id, forked_from_message_id, settings_json)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)ON CONFLICT(id) DO UPDATE SETtitle = excluded.title,model_type = excluded.model_type,@@ -1709,7 +1725,9 @@ def upsert_chat_thread(thread: dict) -> dict:openai_code_exec_container_id = excluded.openai_code_exec_container_id,anthropic_code_exec_container_id = excluded.anthropic_code_exec_container_id,forked_from_thread_id = excluded.forked_from_thread_id,- forked_from_message_id = excluded.forked_from_message_id+ forked_from_message_id = excluded.forked_from_message_id,+ -- an absent snapshot keeps the stored one: most writers rebuild the record without it.+ settings_json = COALESCE(excluded.settings_json, chat_threads.settings_json)""",(thread["id"],@@ -1725,6 +1743,7 @@ def upsert_chat_thread(thread: dict) -> dict:thread.get("anthropicCodeExecContainerId"),thread.get("forkedFromThreadId"),thread.get("forkedFromMessageId"),+ json.dumps(thread["settings"]) if thread.get("settings") is not None else None,),)conn.commit()@@ -1741,6 +1760,9 @@ class ChatThreadPreconditionFailed(Exception):# Same order the title migration picks its opening message in.+# Watermarks kept per thread, one per tab that has written its settings.+_MAX_SETTINGS_WRITERS = 32+_OPENING_USER_MESSAGE = """(SELECT id FROM chat_messagesWHERE thread_id = ? AND role = 'user'@@ -1753,6 +1775,7 @@ def update_chat_thread(patch: dict,expected_title: Optional[str] = None,expected_opening_message_id: Optional[str] = None,+ settings_write: Optional[dict] = None,) -> Optional[dict]:"""Patch a thread. With expected_title, the write only lands while the rowstill holds that title, so a concurrent rename wins instead of being lost.@@ -1783,6 +1806,10 @@ def update_chat_thread("forked_from_message_id",patch.get("forkedFromMessageId"),),+ "settings": (+ "settings_json",+ json.dumps(patch["settings"]) if patch.get("settings") is not None else None,+ ),}assignments = []values = []@@ -1790,11 +1817,14 @@ def update_chat_thread(if key in patch:assignments.append(f"{column} = ?")values.append(value)- if not assignments:+ if not assignments and settings_write is None:return get_chat_thread(id)conn = get_connection()try:+ # The snapshot rides in the same transaction as the guarded metadata write, or a+ # rejected precondition returns 409 with the settings change already committed.+ conn.execute("BEGIN IMMEDIATE")# Guards ride in the WHERE clause, so check and write are one statement.where = ["id = ?"]guard: list = [id]@@ -1805,22 +1835,151 @@ def update_chat_thread(where.append(_OPENING_USER_MESSAGE)guard += [id, expected_opening_message_id]guarded = expected_title is not None or expected_opening_message_id is not None- cursor = conn.execute(- f"UPDATE chat_threads SET {', '.join(assignments)} WHERE {' AND '.join(where)}",- (*values, *guard),- )- applied = cursor.rowcount+ applied = 1+ if assignments:+ cursor = conn.execute(+ f"UPDATE chat_threads SET {', '.join(assignments)} WHERE {' AND '.join(where)}",+ (*values, *guard),+ )+ applied = cursor.rowcount+ if guarded and applied == 0:+ conn.rollback()+ if conn.execute("SELECT 1 FROM chat_threads WHERE id = ?", (id,)).fetchone() is None:+ return None+ raise ChatThreadPreconditionFailed(id)+ if settings_write is not None:+ if _write_chat_thread_settings_in_conn(conn, id, **settings_write) is None:+ conn.rollback()+ return Noneconn.commit()row = conn.execute("SELECT * FROM chat_threads WHERE id = ?", (id,)).fetchone()if row is None:return None- if guarded and applied == 0:- raise ChatThreadPreconditionFailed(id)return _chat_thread_from_row(row)finally:conn.close()+def _write_chat_thread_settings_in_conn(+ conn,+ id: str,+ *,+ replace: Optional[dict] = None,+ merge: Optional[dict] = None,+ clear: bool = False,+ seq: Optional[int] = None,+ writer: Optional[str] = None,+ keep_unreadable = None,+) -> Optional[bool]:+ """The snapshot write itself, on a connection whose transaction the caller owns.++ None when the row is gone. True when it wrote, False when an older write from the+ same writer was refused; both leave the caller's transaction usable.++ The all-or-nothing the caller wants is about FAILURE: a rejected metadata+ precondition must not leave the settings committed, and a missing row must write+ nothing. A refusal is not a failure. It means this writer has already landed a newer+ snapshot, so the row holds what the writer wanted either way, and rolling the+ metadata back with it would drop a rename the client sent in the same PATCH and got+ a 200 for.+ """+ row = conn.execute(+ "SELECT settings_json, settings_seqs FROM chat_threads WHERE id = ?",+ (id,),+ ).fetchone()+ if row is None:+ return None+ seqs = _json_loads(row["settings_seqs"], None) if "settings_seqs" in row.keys() else None+ seqs = seqs if isinstance(seqs, dict) else {}+ if seq is not None and writer is not None:+ seen = seqs.get(writer)+ if isinstance(seen, int) and seq <= seen:+ # This writer has already had a newer snapshot stored; this one is the+ # straggler. Held per writer, so a write from another tab in between does+ # not wipe the watermark this comparison depends on.+ return False+ # Re-inserted, not just assigned, so this writer moves to the end and the map+ # stays in least-recently-used order.+ seqs.pop(writer, None)+ seqs[writer] = seq+ # One entry per tab that has ever written, so bound it. Evicted by last use and+ # never by counter: every session starts its own counter at 1, so comparing them+ # across writers would throw out the newest tab and keep long-dead ones, leaving+ # the active writer with no watermark for its own stragglers to be refused by.+ while len(seqs) > _MAX_SETTINGS_WRITERS:+ seqs.pop(next(iter(seqs)))+ stored = _json_loads(row["settings_json"], None)+ stored = stored if isinstance(stored, dict) else {}+ if clear:+ settings_json = None+ else:+ if merge is not None:+ base = stored+ changes = merge+ else:+ base = keep_unreadable(stored) if keep_unreadable else {}+ changes = replace or {}+ settings_json = json.dumps({**base, **changes})+ conn.execute(+ "UPDATE chat_threads SET settings_json = ?, settings_seqs = ? WHERE id = ?",+ (settings_json, json.dumps(seqs) if seqs else None, id),+ )+ return True+++def write_chat_thread_settings(+ id: str,+ *,+ replace: Optional[dict] = None,+ merge: Optional[dict] = None,+ clear: bool = False,+ seq: Optional[int] = None,+ writer: Optional[str] = None,+ keep_unreadable = None,+) -> Optional[dict]:+ """Write a thread's settings snapshot, reading and merging in one transaction.++ Doing the read in the route and the write here lets two requests on the same thread,+ two tabs or a tab closing behind an open one, both turn a partial patch into a full+ replacement built from the same stale snapshot, and the second one lands on top. The+ read, the merge and the write have to be one transaction, so they are.++ `writer` and `seq` order the writes, and only ever against the same writer's own+ earlier ones: a write is dropped when it comes from the writer whose snapshot is+ already stored and carries a seq no newer than it. Two browsers are never compared,+ because their clocks and counters have nothing to do with each other and the one that+ happened to be behind would have every edit silently refused. Within one writer the+ ordering is real, which is the case that needs it: an aborted fetch does not stop a+ handler the server has already started.++ `keep_unreadable(stored) -> dict` names the part of the stored snapshot the caller+ could not read, which a replacement carries forward rather than deleting. Passed in+ rather than imported so this module stays free of the wire models.+ """+ conn = get_connection()+ try:+ # IMMEDIATE takes the write lock up front, so the read below cannot be overtaken.+ conn.execute("BEGIN IMMEDIATE")+ applied = _write_chat_thread_settings_in_conn(+ conn,+ id,+ replace = replace,+ merge = merge,+ clear = clear,+ seq = seq,+ writer = writer,+ keep_unreadable = keep_unreadable,+ )+ if applied is None:+ conn.rollback()+ return None+ conn.commit()+ row = conn.execute("SELECT * FROM chat_threads WHERE id = ?", (id,)).fetchone()+ return _chat_thread_from_row(row) if row is not None else None+ finally:+ conn.close()++def get_chat_thread(id: str) -> Optional[dict]:conn = get_connection()try:@@ -1857,7 +2016,8 @@ def list_chat_threads("ORDER BY COALESCE(updated_at, created_at) DESC, created_at DESC",values,).fetchall()- return [_chat_thread_from_row(row) for row in rows]+ # the snapshot is only read when a thread is opened, so it is left out of the listing.+ return [_chat_thread_from_row(row, include_settings = False) for row in rows]finally:conn.close()@@ -3113,8 +3273,8 @@ def fork_chat_thread(INSERT INTO chat_threads(id, title, model_type, model_id, pair_id, project_id, archived, created_at,openai_code_exec_container_id, anthropic_code_exec_container_id,- forked_from_thread_id, forked_from_message_id)- VALUES (?, ?, ?, ?, ?, ?, 0, ?, NULL, NULL, ?, ?)+ forked_from_thread_id, forked_from_message_id, settings_json)+ VALUES (?, ?, ?, ?, ?, ?, 0, ?, NULL, NULL, ?, ?, ?)""",(new_thread_id,@@ -3126,6 +3286,7 @@ def fork_chat_thread(int(created_at),source_thread_id,branch_message_id,+ src_dict.get("settings_json"),),)fork_messages = []diff --git a/studio/backend/tests/test_chat_thread_settings.py b/studio/backend/tests/test_chat_thread_settings.pynew file mode 100644index 00000000000..6d4ef46b314--- /dev/null+++ b/studio/backend/tests/test_chat_thread_settings.py@@ -0,0 +1,599 @@+# 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 per-thread settings snapshot that makes a chat keep its own modes.++Covers the contract PATCH /api/chat/threads/{id} accepts and the storage rules the+snapshot depends on: writers that rebuild a thread record must not clear it, the thread+listing must not carry it, and a fork must inherit it.+"""++import sqlite3+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 ( # noqa: E402+ ChatThread,+ ChatThreadPatch,+ ChatThreadSettings,+ _settings_write_from_patch,+ thread_from_row,+)+from storage import studio_db # noqa: E402+from utils.paths import studio_db_path # noqa: E402++SETTINGS = {+ "toolsEnabled": True,+ "codeToolsEnabled": False,+ "deepResearchEnabled": False,+ "permissionMode": "auto",+ "ragEnabled": True,+ "ragSource": {"type": "kb", "kbId": "notes"},+ "ragMode": "dense",+ "ragTopK": 12,+ "ragAutoInject": "on",+ "ragAutoInjectMinScore": 0.42,+ "reasoningEffort": "high",+}+++def _reset_studio_db(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "Projects"))+ monkeypatch.setattr(studio_db, "_schema_ready", False)+++def _thread(thread_id: str = "thread-1", **extra) -> dict:+ return {+ "id": thread_id,+ "title": "Test Chat",+ "modelType": "base",+ "modelId": "test-model",+ "pairId": None,+ "archived": False,+ "createdAt": 1_700_000_000_000,+ **extra,+ }+++def test_thread_settings_round_trip():+ settings = ChatThreadSettings.model_validate(SETTINGS)+ assert settings.model_dump(exclude_unset = True) == SETTINGS+++ "field, value",+ [+ # full access disables the sandbox, so it stays session-only per thread too.+ ("permissionMode", "full"),+ ("ragTopK", 51),+ ("ragAutoInjectMinScore", 1.5),+ ("ragMode", "vector"),+ # global-only settings must not reach a thread and silently become per-chat.+ ("gpuMemoryMode", "manual"),+ ("showCanvasMenuItem", True),+ ],+)+def test_thread_settings_rejects_out_of_contract(field, value):+ with pytest.raises(ValidationError):+ ChatThreadSettings.model_validate({field: value})+++def test_thread_settings_survive_a_record_rewrite(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread(settings = SETTINGS))++ # the title autosave and every other writer rebuild the record without the snapshot.+ studio_db.upsert_chat_thread(_thread(title = "Renamed"))++ stored = studio_db.get_chat_thread("thread-1")+ assert stored["title"] == "Renamed"+ assert stored["settings"] == SETTINGS+++def test_thread_settings_patch_replaces_the_snapshot(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread(settings = SETTINGS))++ # ragSource is a discriminated union, so the write replaces: no kb id survives the switch.+ replacement = {"toolsEnabled": False, "ragSource": {"type": "thread"}}+ updated = studio_db.update_chat_thread("thread-1", {"settings": replacement})++ assert updated["settings"] == replacement+ assert studio_db.get_chat_thread("thread-1")["settings"] == replacement+++def test_thread_listing_leaves_out_the_snapshot(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread(settings = SETTINGS))++ listed = studio_db.list_chat_threads()++ assert [row["id"] for row in listed] == ["thread-1"]+ assert "settings" not in listed[0]+++def test_thread_without_a_snapshot_reads_back_null(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread())++ assert studio_db.get_chat_thread("thread-1")["settings"] is None+++def test_fork_inherits_the_snapshot(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread(settings = SETTINGS))+ studio_db.upsert_chat_message(+ {+ "id": "message-1",+ "threadId": "thread-1",+ "parentId": None,+ "role": "user",+ "content": "hello",+ "createdAt": 1_700_000_000_001,+ }+ )++ forked = studio_db.fork_chat_thread(+ source_thread_id = "thread-1",+ branch_message_id = "message-1",+ new_thread_id = "thread-2",+ new_title = "Fork",+ created_at = 1_700_000_000_002,+ id_factory = lambda: "message-2",+ )++ assert forked is not None+ assert studio_db.get_chat_thread("thread-2")["settings"] == SETTINGS+++def test_settings_column_is_added_to_an_existing_database(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ # a database created before this change has no settings_json, and the CREATE TABLE in+ # _ensure_schema never runs for it, so only the ALTER keeps thread writes working.+ db_path = Path(studio_db_path())+ db_path.parent.mkdir(parents = True, exist_ok = True)+ conn = sqlite3.connect(str(db_path))+ try:+ conn.execute(+ """+ CREATE TABLE chat_threads (+ id TEXT NOT NULL PRIMARY KEY,+ title TEXT NOT NULL,+ model_type TEXT NOT NULL,+ model_id TEXT,+ pair_id TEXT,+ archived INTEGER NOT NULL DEFAULT 0,+ created_at INTEGER NOT NULL+ )+ """+ )+ conn.execute(+ """+ CREATE TABLE chat_messages (+ id TEXT NOT NULL PRIMARY KEY,+ thread_id TEXT NOT NULL,+ parent_id TEXT,+ role TEXT NOT NULL,+ content_json TEXT NOT NULL,+ attachments_json TEXT,+ metadata_json TEXT,+ created_at INTEGER NOT NULL+ )+ """+ )+ conn.execute(+ "INSERT INTO chat_threads (id, title, model_type, created_at) VALUES (?, ?, ?, ?)",+ ("thread-1", "Old", "base", 1_700_000_000_000),+ )+ conn.commit()+ finally:+ conn.close()++ assert studio_db.get_chat_thread("thread-1")["settings"] is None+ studio_db.upsert_chat_thread(_thread(settings = SETTINGS))+ assert studio_db.get_chat_thread("thread-1")["settings"] == SETTINGS+++# A snapshot on disk outlives the build that wrote it. A newer Studio adding a+# setting, widening an enum or raising a bound writes a blob this build has never+# seen, and it reaches the response model rather than the request one, so refusing+# it 500s the chat on open and takes the whole history export with it. The wire+# contract stays strict; only the read is forgiving.+ "stored, expected",+ [+ ({"toolsEnabled": True, "voiceModeEnabled": True}, {"toolsEnabled": True}),+ ({"reasoningEffort": "ultra", "toolsEnabled": True}, {"toolsEnabled": True}),+ ({"ragTopK": 999, "toolsEnabled": True}, {"toolsEnabled": True}),+ # several at once, which is what a version gap actually looks like+ (+ {"ragTopK": 999, "reasoningEffort": "ultra", "futureThing": 1, "toolsEnabled": True},+ {"toolsEnabled": True},+ ),+ ({"ragSource": {"type": "web", "url": "x"}, "toolsEnabled": True}, {"toolsEnabled": True}),+ # nothing salvageable, and non-objects+ ({"quantumMode": True}, {}),+ ("hello", None),+ ([1, 2, 3], None),+ ],+)+def test_a_snapshot_from_a_newer_build_still_reads(stored, expected):+ thread = thread_from_row(+ {"id": "t", "title": "T", "modelType": "base", "createdAt": 1, "settings": stored},+ )+ if expected is None:+ assert thread.settings is None+ else:+ assert thread.settings is not None+ assert thread.settings.model_dump(exclude_none = True) == expected+++def test_the_wire_contract_stays_strict():+ # Only rows off disk are forgiven. A client may not invent a setting on either+ # the patch or the full-record POST, which shares the ChatThread model.+ with pytest.raises(ValidationError):+ ChatThreadPatch(settings = {"toolsEnabled": True, "voiceModeEnabled": True})+ with pytest.raises(ValidationError):+ ChatThreadPatch(settings = {"ragTopK": 999})+ with pytest.raises(ValidationError):+ ChatThread(+ id = "t",+ title = "T",+ modelType = "base",+ createdAt = 1,+ settings = {"toolsEnabled": True, "voiceModeEnabled": True},+ )+ with pytest.raises(ValidationError):+ ChatThread(+ id = "t",+ title = "T",+ modelType = "base",+ createdAt = 1,+ settings = {"ragTopK": 999},+ )+++def test_an_unreadable_key_does_not_disturb_the_stored_row(tmp_path, monkeypatch):+ # the row keeps what it had, so upgrading again gets the setting back.+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread())+ studio_db.update_chat_thread("thread-1", {"settings": {"toolsEnabled": True}})+ conn = sqlite3.connect(studio_db_path())+ try:+ conn.execute(+ "UPDATE chat_threads SET settings_json = ? WHERE id = ?",+ ('{"toolsEnabled": true, "voiceModeEnabled": true}', "thread-1"),+ )+ conn.commit()+ finally:+ conn.close()++ row = studio_db.get_chat_thread("thread-1")+ assert thread_from_row(row).settings.toolsEnabled is True++ studio_db.update_chat_thread("thread-1", {"title": "renamed"})+ conn = sqlite3.connect(studio_db_path())+ try:+ raw = conn.execute(+ "SELECT settings_json FROM chat_threads WHERE id = ?", ("thread-1",)+ ).fetchone()[0]+ finally:+ conn.close()+ assert "voiceModeEnabled" in raw+++def _raw_settings(thread_id: str = "thread-1") -> str:+ conn = sqlite3.connect(studio_db_path())+ try:+ return conn.execute(+ "SELECT settings_json FROM chat_threads WHERE id = ?", (thread_id,)+ ).fetchone()[0]+ finally:+ conn.close()+++def _store_raw(payload: str, thread_id: str = "thread-1") -> None:+ conn = sqlite3.connect(studio_db_path())+ try:+ conn.execute("UPDATE chat_threads SET settings_json = ? WHERE id = ?", (payload, thread_id))+ conn.commit()+ finally:+ conn.close()+++def test_a_downgraded_client_cannot_delete_what_it_could_not_read(tmp_path, monkeypatch):+ # The whole point of the lenient read is that upgrading gets the setting back, which+ # only holds if writing in the meantime leaves the unreadable part alone.+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread())+ _store_raw('{"toolsEnabled": true, "voiceModeEnabled": true, "ragTopK": 999}')++ # what this build serves the client: neither the unknown key nor the out-of-range one+ served = thread_from_row(studio_db.get_chat_thread("thread-1")).settings+ assert served.toolsEnabled is True+ assert served.ragTopK is None++ # the client writes back everything it knows about+ patch = {"settings": {"toolsEnabled": False}}+ settings_write = _settings_write_from_patch(patch)+ studio_db.update_chat_thread("thread-1", patch, settings_write = settings_write)++ raw = _raw_settings()+ assert "voiceModeEnabled" in raw+ assert "999" in raw+ assert thread_from_row(studio_db.get_chat_thread("thread-1")).settings.toolsEnabled is False+++def test_a_merge_touches_only_the_fields_it_names(tmp_path, monkeypatch):+ # The unload path knows one pill changed and nothing about the rest of the row.+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread())+ studio_db.update_chat_thread(+ "thread-1", {"settings": {"toolsEnabled": True, "permissionMode": "ask"}}+ )++ payload = ChatThreadPatch(settingsPatch = {"codeToolsEnabled": True})+ patch = payload.model_dump(exclude_unset = True)+ settings_write = _settings_write_from_patch(patch)+ studio_db.update_chat_thread("thread-1", patch, settings_write = settings_write)++ got = thread_from_row(studio_db.get_chat_thread("thread-1")).settings+ assert got.codeToolsEnabled is True+ assert got.toolsEnabled is True+ assert got.permissionMode == "ask"+++def test_a_merge_also_spares_an_unreadable_key(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread())+ _store_raw('{"toolsEnabled": true, "voiceModeEnabled": true}')++ payload = ChatThreadPatch(settingsPatch = {"toolsEnabled": False})+ patch = payload.model_dump(exclude_unset = True)+ settings_write = _settings_write_from_patch(patch)+ studio_db.update_chat_thread("thread-1", patch, settings_write = settings_write)++ assert "voiceModeEnabled" in _raw_settings()+ assert thread_from_row(studio_db.get_chat_thread("thread-1")).settings.toolsEnabled is False+++def test_clearing_still_clears_the_whole_column(tmp_path, monkeypatch):+ # An explicit null is the one instruction that means all of it, unreadable part included.+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread())+ _store_raw('{"toolsEnabled": true, "voiceModeEnabled": true}')++ patch = {"settings": None}+ settings_write = _settings_write_from_patch(patch)+ studio_db.update_chat_thread("thread-1", patch, settings_write = settings_write)++ assert thread_from_row(studio_db.get_chat_thread("thread-1")).settings is None+ assert _raw_settings() in (None, "", "null")+++def test_a_merge_of_nothing_leaves_the_row_alone(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread())+ studio_db.update_chat_thread("thread-1", {"settings": {"toolsEnabled": True}})++ patch = {"title": "renamed", "settingsPatch": None}+ settings_write = _settings_write_from_patch(patch)+ studio_db.update_chat_thread("thread-1", patch, settings_write = settings_write)+ assert "settings" not in patch+ studio_db.update_chat_thread("thread-1", patch)++ got = thread_from_row(studio_db.get_chat_thread("thread-1"))+ assert got.title == "renamed"+ assert got.settings.toolsEnabled is True+++def test_a_merge_is_still_held_to_the_contract():+ with pytest.raises(ValidationError):+ ChatThreadPatch(settingsPatch = {"voiceModeEnabled": True})+ with pytest.raises(ValidationError):+ ChatThreadPatch(settingsPatch = {"ragTopK": 999})+++def test_an_older_write_cannot_overtake_a_newer_one(tmp_path, monkeypatch):+ # The tab-close beacon can pass a PATCH the server has already accepted, and no+ # client-side abort reaches a handler that is already running.+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread())++ studio_db.write_chat_thread_settings(+ "thread-1", replace = {"toolsEnabled": True}, seq = 200, writer = "tab-a"+ )+ # the straggler, carrying what the user had moved away from+ studio_db.write_chat_thread_settings(+ "thread-1", replace = {"toolsEnabled": False}, seq = 100, writer = "tab-a"+ )++ got = thread_from_row(studio_db.get_chat_thread("thread-1")).settings+ assert got.toolsEnabled is True+++def test_the_same_seq_is_not_applied_twice(tmp_path, monkeypatch):+ # keepalive retries can duplicate a request; the second must be a no-op, not a revert.+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread())++ studio_db.write_chat_thread_settings(+ "thread-1", replace = {"toolsEnabled": True}, seq = 500, writer = "tab-a"+ )+ studio_db.write_chat_thread_settings(+ "thread-1", replace = {"toolsEnabled": False}, seq = 500, writer = "tab-a"+ )++ assert thread_from_row(studio_db.get_chat_thread("thread-1")).settings.toolsEnabled is True+++def test_a_write_without_a_seq_still_applies(tmp_path, monkeypatch):+ # Old clients send none, and an unordered write is still better than a dropped one.+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread())++ studio_db.write_chat_thread_settings(+ "thread-1", replace = {"toolsEnabled": True}, seq = 900, writer = "tab-a"+ )+ studio_db.write_chat_thread_settings("thread-1", replace = {"toolsEnabled": False})++ assert thread_from_row(studio_db.get_chat_thread("thread-1")).settings.toolsEnabled is False+++def test_two_merges_of_different_fields_both_survive(tmp_path, monkeypatch):+ # Two tabs, each knowing only its own field. Read-merge-write has to be one+ # transaction or the second one's stale read erases the first one's field.+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread())++ studio_db.write_chat_thread_settings("thread-1", merge = {"toolsEnabled": True})+ studio_db.write_chat_thread_settings("thread-1", merge = {"codeToolsEnabled": True})++ got = thread_from_row(studio_db.get_chat_thread("thread-1")).settings+ assert got.toolsEnabled is True+ assert got.codeToolsEnabled is True+++def test_the_watermark_column_is_added_to_an_existing_database(tmp_path, monkeypatch):+ # Same upgrade path as settings_json: an install that predates the column.+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread())+ conn = sqlite3.connect(studio_db_path())+ try:+ conn.execute("ALTER TABLE chat_threads DROP COLUMN settings_seqs")+ conn.commit()+ finally:+ conn.close()+ monkeypatch.setattr(studio_db, "_schema_ready", False)++ studio_db.write_chat_thread_settings(+ "thread-1", replace = {"toolsEnabled": True}, seq = 1, writer = "tab-a"+ )+ assert thread_from_row(studio_db.get_chat_thread("thread-1")).settings.toolsEnabled is True+++def test_two_browsers_are_never_ordered_against_each_other(tmp_path, monkeypatch):+ # The seq is a client's own counter. Comparing one machine's against another's means+ # the browser whose clock or counter is behind has every edit silently refused, while+ # the server still answers 200 and the user believes it saved.+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread())++ studio_db.write_chat_thread_settings(+ "thread-1", replace = {"toolsEnabled": True}, seq = 9_000, writer = "laptop"+ )+ # a second machine, far behind on the same counter, still gets its edit+ studio_db.write_chat_thread_settings(+ "thread-1", replace = {"toolsEnabled": False}, seq = 12, writer = "desktop"+ )++ assert thread_from_row(studio_db.get_chat_thread("thread-1")).settings.toolsEnabled is False+++def test_a_failed_precondition_does_not_commit_the_settings(tmp_path, monkeypatch):+ # PATCH allows settings and a guarded rename together; a 409 must leave neither.+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread())+ studio_db.update_chat_thread("thread-1", {"settings": {"toolsEnabled": True}})++ with pytest.raises(studio_db.ChatThreadPreconditionFailed):+ studio_db.update_chat_thread(+ "thread-1",+ {"title": "renamed"},+ expected_title = "Not The Current Title",+ settings_write = {"replace": {"toolsEnabled": False}},+ )++ got = thread_from_row(studio_db.get_chat_thread("thread-1"))+ assert got.title == "Test Chat"+ assert got.settings.toolsEnabled is True+++def test_settings_and_a_passing_guard_both_land(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread())++ studio_db.update_chat_thread(+ "thread-1",+ {"title": "renamed"},+ expected_title = "Test Chat",+ settings_write = {"replace": {"toolsEnabled": True}},+ )++ got = thread_from_row(studio_db.get_chat_thread("thread-1"))+ assert got.title == "renamed"+ assert got.settings.toolsEnabled is True+++def test_another_tab_writing_does_not_clear_a_writer_watermark(tmp_path, monkeypatch):+ # The race the ordering exists for: A's newer keepalive lands, B writes, then A's+ # older request finally arrives. With one writer column, B's write has replaced the+ # watermark and A's straggler is no longer compared against its own.+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread())++ studio_db.write_chat_thread_settings(+ "thread-1", merge = {"toolsEnabled": True}, seq = 5, writer = "tab-a"+ )+ studio_db.write_chat_thread_settings(+ "thread-1", merge = {"codeToolsEnabled": True}, seq = 1, writer = "tab-b"+ )+ # tab A's straggler, older than what A already had stored+ studio_db.write_chat_thread_settings(+ "thread-1", merge = {"toolsEnabled": False}, seq = 2, writer = "tab-a"+ )++ got = thread_from_row(studio_db.get_chat_thread("thread-1")).settings+ assert got.toolsEnabled is True+ assert got.codeToolsEnabled is True+++def test_watermarks_do_not_grow_without_bound(tmp_path, monkeypatch):+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread())+ for i in range(studio_db._MAX_SETTINGS_WRITERS + 10):+ studio_db.write_chat_thread_settings(+ "thread-1", merge = {"toolsEnabled": True}, seq = i + 1, writer = f"tab-{i}"+ )++ conn = sqlite3.connect(studio_db_path())+ try:+ raw = conn.execute(+ "SELECT settings_seqs FROM chat_threads WHERE id = ?", ("thread-1",)+ ).fetchone()[0]+ finally:+ conn.close()+ import json as _json++ assert len(_json.loads(raw)) <= studio_db._MAX_SETTINGS_WRITERS+++def test_the_newest_writer_is_not_the_first_evicted(tmp_path, monkeypatch):+ # Every session starts its counter at 1, so evicting by counter throws out the tab+ # that just arrived and keeps long-dead ones, leaving the active writer with no+ # watermark for its own stragglers to be refused by.+ _reset_studio_db(tmp_path, monkeypatch)+ studio_db.upsert_chat_thread(_thread())+ for i in range(studio_db._MAX_SETTINGS_WRITERS):+ studio_db.write_chat_thread_settings(+ "thread-1", merge = {"toolsEnabled": True}, seq = 500 + i, writer = f"old-{i}"+ )+ # a brand new tab, counter starting at 1+ studio_db.write_chat_thread_settings(+ "thread-1", merge = {"toolsEnabled": False}, seq = 1, writer = "fresh"+ )+ # its own straggler must still be refused+ studio_db.write_chat_thread_settings(+ "thread-1", merge = {"toolsEnabled": True}, seq = 1, writer = "fresh"+ )++ got = thread_from_row(studio_db.get_chat_thread("thread-1")).settings+ assert got.toolsEnabled is Falsediff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex d6ee8d3c9a7..75176a19c99 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -125,7 +125,10 @@ import { getExternalReasoningCapabilities } from "@/features/chat/provider-capabimport { useRagToolDisabled } from "@/features/chat/hooks/use-rag-tool-disabled";import { BypassPermissionsMenuItem } from "@/features/chat/bypass-permissions-menu-item";import { PermissionModeComposerPill } from "@/features/chat/permission-mode-select";-import { useChatRuntimeStore } from "@/features/chat/stores/chat-runtime-store";+import {+ settleThreadScopedSettingsForCopy,+ useChatRuntimeStore,+} from "@/features/chat/stores/chat-runtime-store";import { useExternalProvidersStore } from "@/features/chat/stores/external-providers-store";import { saveMarkdownAsProjectSource } from "@/features/rag";import {@@ -2779,6 +2782,11 @@ const Composer: FC<{const [pendingSend, setPendingSend] = useState(false);const pendingSendRef = useRef(false);const waitToastRef = useRef<string | number | null>(null);+ // This chat's own settings are still on their way; a send now would run on the+ // installation defaults showing in their place.+ const threadScopedSettingsPending = useChatRuntimeStore(+ (s) => s.threadScopedSettingsPending,+ );const handleIndexingChange = useCallback((active: boolean) => {indexingActiveRef.current = active;@@ -3180,7 +3188,7 @@ const Composer: FC<{cancelQueuedSendRef.current = cancelQueuedSend;const enqueueSend = useCallback(- (waitingOn: "indexing" | "images" | "audio" = "indexing") => {+ (waitingOn: "indexing" | "images" | "audio" | "settings" = "indexing") => {if (pendingSendRef.current) return;pendingSendRef.current = true;setPendingSend(true);@@ -3189,7 +3197,9 @@ const Composer: FC<{? "Waiting for dropped images": waitingOn === "audio"? "Waiting for dropped audio"- : "Waiting for documents to finish indexing";+ : waitingOn === "settings"+ ? "Loading this chat's settings"+ : "Waiting for documents to finish indexing";waitToastRef.current = toast(title, {description: "Your message will send automatically once they are ready.",duration: Infinity,@@ -3296,6 +3306,15 @@ const Composer: FC<{enqueueSend();return true;}+ // This chat's own settings have been asked for and have not arrived, so the store+ // is showing the installation defaults and the run would be captured with them:+ // a chat stored as "ask" could run tools without asking. Park it like any other+ // wait, so the click still counts and the send fires once the snapshot lands.+ if (threadScopedSettingsPending && !overlay) {+ event.preventDefault();+ enqueueSend("settings");+ return true;+ }return false;},[@@ -3303,6 +3322,7 @@ const Composer: FC<{shouldBlockSend,indexingActive,overlay,+ threadScopedSettingsPending,enqueueSend,parkIfWaitingOnAttachments,],@@ -3319,6 +3339,7 @@ const Composer: FC<{!pendingSend ||!pendingSendRef.current ||indexingActive ||+ threadScopedSettingsPending ||hasMaterializingImageAttachments ||hasMaterializingAudioAttachments) {@@ -3335,6 +3356,7 @@ const Composer: FC<{}, [pendingSend,indexingActive,+ threadScopedSettingsPending,hasMaterializingImageAttachments,hasMaterializingAudioAttachments,aui,@@ -3471,6 +3493,14 @@ const Composer: FC<{parkIfWaitingOnAttachments();return;}+ // Before the queue branch below, not after it: a prompt queued while this chat's+ // own settings are still on their way is snapshotted from the installation+ // defaults on screen, so a chat stored as "ask" would queue as "off".+ if (threadScopedSettingsPending && !overlay) {+ event.preventDefault();+ enqueueSend("settings");+ return;+ }// React may not have rendered threadIsRunning yet when several submits// arrive immediately after a send. The imperative runtime is already@@ -3607,10 +3637,12 @@ const Composer: FC<{disableQueue,hasAttachments,hasPendingAudio,+ enqueueSend,interceptSend,isResearchActive,overlay,parkIfWaitingOnAttachments,+ threadScopedSettingsPending,promptQueueActive,promptQueueThreadIds,preStreamThreadIds,@@ -5960,6 +5992,22 @@ const useForkMessageAction = () => {}setPending(true);try {+ // The fork copies settings_json inside its own transaction, so anything not yet+ // in the row is not in the copy: a pill toggled moments ago and still in the+ // 400ms debounce, or one held because this chat's own read has not landed. The+ // fork would otherwise open on the modes the chat had before, not the ones on+ // screen when it was made.+ try {+ await settleThreadScopedSettingsForCopy(remoteId);+ } catch {+ // The row does not hold what is on screen, so a fork made now would carry the+ // pre-edit modes and look like it had lost the change. Better to say so.+ toast.error("Could not fork this chat", {+ description:+ "Its settings could not be saved, so the fork would not match. Please retry.",+ });+ return;+ }const result = await forkChatThread(remoteId, {messageId,newThreadId: crypto.randomUUID(),diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 1f96c99b215..10b4cd9d0c1 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -122,6 +122,7 @@ import {persistGpuMemoryModeOnLoad,resolveToolsEnabledOnLoad,saveSpeculativeType,+ awaitThreadScopedPairing,useChatRuntimeStore,} from "../stores/chat-runtime-store";import { resolveFitMaxSeqLength, resolveManualAutoCtxPin } from "../presets/preset-policy";@@ -3527,11 +3528,28 @@ export function createOpenAIStreamAdapter(unstable_assistantMessageId,}) {await useChatRuntimeStore.getState().hydratePersistedSettings();+ // Every run reaches here: the composer, Reload, Continue, and send from the edit+ // composer. Waiting for the open chat's own settings in this one place is what+ // keeps the message-level controls from starting a run on the installation+ // defaults that stand in while the read is out, which for a chat stored as "ask"+ // would mean running tools without asking.+ // Bound to this run's own chat: a run for A released by B's pairing ending would+ // resume and read B's settings for A.+ const runThreadId =+ unstable_threadId ?? useChatRuntimeStore.getState().activeThreadId;+ // Refused rather than run on whatever the store holds now: the wait only runs out+ // for a chat the user left mid-read, and the settings on screen are then some+ // other chat's. The run is recoverable by reopening the chat; a message sent with+ // another chat's tools and permission level is not.+ if (!(await awaitThreadScopedPairing(runThreadId))) {+ throw new Error(+ "This chat's settings could not be loaded, so the message was not sent. Reopen the chat and try again.",+ );+ }let runtime = useChatRuntimeStore.getState();// Capture the thread ID once so it stays stable even if the user// switches chats while waiting for model load / auto-load.- const resolvedThreadId =- (unstable_threadId ?? runtime.activeThreadId) || undefined;+ const resolvedThreadId = (runThreadId ?? runtime.activeThreadId) || undefined;const sharedThreadRecordRead = resolvedThreadId? createRetryableSharedRead(() => getStoredChatThreadReadResult(resolvedThreadId),diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex 768d6091eea..23fc26bef67 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -5,7 +5,10 @@ import { authFetch } from "@/features/auth";import { prepareHfTokenForUse } from "@/features/hf-auth";// These helpers are deliberately API-layer-only, not part of their features' public barrels.// eslint-disable-next-line no-restricted-imports-import { disposableTimeoutSignal } from "@/features/hub/lib/abort-signals";+import {+ combineAbortSignals,+ disposableTimeoutSignal,+} from "@/features/hub/lib/abort-signals";// eslint-disable-next-line no-restricted-importsimport { hubTokenHeader } from "@/features/hub/lib/hub-token-header";// eslint-disable-next-line no-restricted-imports@@ -52,11 +55,27 @@ const THREAD_WRITE_TIMEOUT_MS = 30_000;async function threadWriteFetch(input: string,init: RequestInit,+ caller?: AbortSignal,): Promise<Response> {const timeout = disposableTimeoutSignal(THREAD_WRITE_TIMEOUT_MS);+ if (caller === undefined) {+ try {+ return await authFetch(input, { ...init, signal: timeout.signal });+ } finally {+ timeout.dispose();+ }+ }+ // Either reason ends the request. Linked by hand rather than with AbortSignal.any,+ // which Safari only got in 17.4.+ const controller = new AbortController();+ const abort = () => controller.abort();+ if (caller.aborted) abort();+ caller.addEventListener("abort", abort);+ timeout.signal.addEventListener("abort", abort);try {- return await authFetch(input, { ...init, signal: timeout.signal });+ return await authFetch(input, { ...init, signal: controller.signal });} finally {+ caller.removeEventListener("abort", abort);timeout.dispose();}}@@ -757,21 +776,32 @@ export async function deleteChatAttachment(export async function getChatThread(threadId: string,- options: { bounded?: boolean } = {},+ options: { bounded?: boolean; timeoutMs?: number; signal?: AbortSignal } = {},): Promise<ThreadRecord | null> {// Bounded for the delete reconciliation: an unbounded read there would hang the delete that// the write timeout exists to keep moving. Callers on a render path stay unbounded.- const timeout = options.bounded- ? disposableTimeoutSignal(THREAD_WRITE_TIMEOUT_MS)- : null;+ // `timeoutMs` is for a caller with a deadline of its own: the settings pairing gives up+ // on a read long before the write timeout, and without a bound of its own each retry+ // left the previous attempt running against the server it is already struggling to+ // reach. `signal` ends it earlier still, which is what a chat switch wants.+ const timeout =+ options.bounded || options.timeoutMs !== undefined+ ? disposableTimeoutSignal(options.timeoutMs ?? THREAD_WRITE_TIMEOUT_MS)+ : null;+ const combined =+ timeout && options.signal+ ? combineAbortSignals([timeout.signal, options.signal])+ : null;+ const signal = combined?.signal ?? timeout?.signal ?? options.signal;try {const response = await authFetch(`/api/chat/threads/${encodeURIComponent(threadId)}`,- timeout ? { signal: timeout.signal } : undefined,+ signal ? { signal } : undefined,);if (response.status === 404) return null;return parseJsonOrThrow<ThreadRecord>(response);} finally {+ combined?.dispose();timeout?.dispose();}}@@ -805,11 +835,24 @@ export interface UpdateChatThreadOptions {expectedTitle?: string;/** And only while this is still the thread's opening user message. */expectedOpeningMessageId?: string;+ /** Give up on the write; used to stand a superseded settings PATCH down. */+ signal?: AbortSignal;}+/**+ * `settings` replaces the chat's whole snapshot; `settingsPatch` applies only the fields+ * it names, for a writer that knows what changed but not what else the row holds.+ */+export type ChatThreadWritePatch = Partial<ThreadRecord> & {+ settingsPatch?: ThreadRecord["settings"];+ /** Orders a writer's snapshot writes against its own earlier ones, never across tabs. */+ settingsSeq?: number;+ settingsWriter?: string;+};+export async function updateChatThread(threadId: string,- patch: Partial<ThreadRecord>,+ patch: ChatThreadWritePatch,options: UpdateChatThreadOptions = {},): Promise<ThreadRecord> {const body: Record<string, unknown> = { ...patch };@@ -826,6 +869,7 @@ export async function updateChatThread(headers: { "Content-Type": "application/json" },body: JSON.stringify(body),},+ options.signal,);const thread = await parseJsonOrThrow<ThreadRecord>(response);notifyChatHistoryUpdated();diff --git a/studio/frontend/src/features/chat/chat-page.tsx b/studio/frontend/src/features/chat/chat-page.tsxindex 320c6d5940b..75acc49c7bb 100644--- a/studio/frontend/src/features/chat/chat-page.tsx+++ b/studio/frontend/src/features/chat/chat-page.tsx@@ -195,6 +195,7 @@ import {hasGgufSource,isDownloadableHubRepo,loadOptionalBool,+ threadScopedOverride,useChatRuntimeStore,} from "./stores/chat-runtime-store";import { useChatPreferencesStore } from "./stores/chat-preferences-store";@@ -2268,16 +2269,19 @@ export function ChatPage({supportsBuiltinWebSearch &&(provider?.providerType === "anthropic" ||provider?.providerType === "openai");- const storedToolsEnabled = loadOptionalBool(CHAT_TOOLS_ENABLED_KEY);- const storedCodeToolsEnabled = loadOptionalBool(- CHAT_CODE_TOOLS_ENABLED_KEY,- );- const storedImageToolsEnabled = loadOptionalBool(- CHAT_IMAGE_TOOLS_ENABLED_KEY,- );- const storedWebFetchToolsEnabled = loadOptionalBool(- CHAT_WEB_FETCH_TOOLS_ENABLED_KEY,- );+ // the open chat's own pills win, or selecting a model would revert them to the global ones.+ const storedToolsEnabled =+ threadScopedOverride("toolsEnabled") ??+ loadOptionalBool(CHAT_TOOLS_ENABLED_KEY);+ const storedCodeToolsEnabled =+ threadScopedOverride("codeToolsEnabled") ??+ loadOptionalBool(CHAT_CODE_TOOLS_ENABLED_KEY);+ const storedImageToolsEnabled =+ threadScopedOverride("imageToolsEnabled") ??+ loadOptionalBool(CHAT_IMAGE_TOOLS_ENABLED_KEY);+ const storedWebFetchToolsEnabled =+ threadScopedOverride("webFetchToolsEnabled") ??+ loadOptionalBool(CHAT_WEB_FETCH_TOOLS_ENABLED_KEY);// Studio runs Search and Code itself for any provider that advertises the// capability, so a self-hosted connection has no hosted builtin to key off.// Keying the pill state on the hosted flags alone discarded the user's saved@@ -2807,16 +2811,19 @@ export function ChatPage({supportsBuiltinWebSearch &&(selectedProvider?.providerType === "anthropic" ||selectedProvider?.providerType === "openai");- const storedToolsEnabled = loadOptionalBool(CHAT_TOOLS_ENABLED_KEY);- const storedCodeToolsEnabled = loadOptionalBool(- CHAT_CODE_TOOLS_ENABLED_KEY,- );- const storedImageToolsEnabled = loadOptionalBool(- CHAT_IMAGE_TOOLS_ENABLED_KEY,- );- const storedWebFetchToolsEnabled = loadOptionalBool(- CHAT_WEB_FETCH_TOOLS_ENABLED_KEY,- );+ // mirror of the sibling effect: the open chat's own pills win over the global ones.+ const storedToolsEnabled =+ threadScopedOverride("toolsEnabled") ??+ loadOptionalBool(CHAT_TOOLS_ENABLED_KEY);+ const storedCodeToolsEnabled =+ threadScopedOverride("codeToolsEnabled") ??+ loadOptionalBool(CHAT_CODE_TOOLS_ENABLED_KEY);+ const storedImageToolsEnabled =+ threadScopedOverride("imageToolsEnabled") ??+ loadOptionalBool(CHAT_IMAGE_TOOLS_ENABLED_KEY);+ const storedWebFetchToolsEnabled =+ threadScopedOverride("webFetchToolsEnabled") ??+ loadOptionalBool(CHAT_WEB_FETCH_TOOLS_ENABLED_KEY);// Same rule as the selection handler above: a self-hosted connection has// no hosted builtin, so keying the pills on those flags threw away the// user's saved preference every time this ran.diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex acbd40f8b2c..9de0442e88a 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -41,7 +41,9 @@ import {ThreadAutosaveHandle,createOpenAIStreamAdapter,} from "./api/chat-adapter";+import { CHAT_HISTORY_UPDATED_EVENT } from "./api/chat-api";import { getResearchThreadState } from "./api/research-api";+import { sanitizeThreadScopedSettings } from "./utils/thread-scoped-settings";import {ingestResearchUpdate,useResearchRunStore,@@ -60,7 +62,13 @@ import {readOpenDocumentAttachmentContent,} from "./open-document";import { AudioAttachmentAdapter } from "./audio-attachment-adapter";-import { useChatRuntimeStore } from "./stores/chat-runtime-store";+import {+ awaitThreadScopedSettingsWrite,+ beginThreadScopedPairing,+ commitHeldThreadScopedEditsToTheirThread,+ releaseHeldThreadScopedEdits,+ useChatRuntimeStore,+} from "./stores/chat-runtime-store";import { ToolPaneScopeContext, toolPaneScope } from "./tool-output-scope";import {notifyPromptQueueRunFailed,@@ -96,6 +104,7 @@ import {ensureStoredChatThread,getStoredChatMessage,getStoredChatThread,+ getStoredChatThreadReadResult,isExpectedBackgroundChatStorageError,listStoredChatMessages,listStoredChatThreads,@@ -1688,6 +1697,208 @@ function ActiveThreadSync({return null;}+// A thread read that fails leaves the chat unpaired, so it is worth a couple of goes.+const THREAD_READ_RETRY_MS = 1_500;+const THREAD_READ_RETRIES = 2;+// And one that never answers at all has to become a failure, or it holds sends forever.+const THREAD_READ_TIMEOUT_MS = 8_000;++// gated on hydration, or the initial /api/chat/settings response lands after a thread's own values.+function ThreadScopedSettingsSync({+ enabled,+}: { enabled: boolean }): ReactElement | null {+ const activeThreadId = useChatRuntimeStore((state) => state.activeThreadId);+ const settingsHydrated = useChatRuntimeStore(+ (state) => state.settingsHydrated,+ );++ useEffect(() => {+ const { applyThreadScopedSettings } = useChatRuntimeStore.getState();+ // An unsaved chat carries a runtime-made id that no row can exist for, so its read+ // can only 404. Opening a pairing window for it holds every edit behind a round+ // trip that is certain to say "no snapshot", which is how an edit made on a fresh+ // /chat stopped reaching the installation defaults straight away.+ if (isAssistantLocalThreadId(activeThreadId)) {+ applyThreadScopedSettings(null, null);+ return;+ }+ if (!enabled) {+ // Compare panes share one composer between two threads, so there is no single+ // chat whose snapshot could apply: compare runs on the installation defaults and+ // its edits move them, as every chat did before this change. Say so here rather+ // than leaving the module still pointing at the last single chat, whose stored+ // pills a model load would otherwise read back through threadScopedOverride.+ applyThreadScopedSettings(null, null);+ return;+ }+ if (activeThreadId === null) {+ if (settingsHydrated) applyThreadScopedSettings(null, null);+ return;+ }+ // The composer is interactive while /api/chat/settings is still out, so start holding+ // this chat's edits as soon as its id is known. Waiting for hydration to begin the+ // pairing left that window writing edits into the installation defaults instead.+ beginThreadScopedPairing(activeThreadId);+ if (!settingsHydrated) {+ return () => {+ // Hydration finishing re-runs this effect for the same chat, and the held edits are+ // still waiting for that chat's read, so keep holding them. Any other reason to+ // leave means the chat is going away and they belong to it.+ const now = useChatRuntimeStore.getState();+ if (!now.settingsHydrated || now.activeThreadId !== activeThreadId) {+ commitHeldThreadScopedEditsToTheirThread();+ }+ };+ }+ let cancelled = false;+ let paired = false;+ let unpaired = false;+ let defaulted = false;+ let retryTimer: ReturnType<typeof setTimeout> | null = null;+ let retriesLeft = THREAD_READ_RETRIES;+ // One per attempt, aborted when the attempt's deadline passes and when the chat is+ // left. Without it the losing side of the race below stayed open on the server for+ // the full write timeout while the next try opened another.+ const reads = new Set<AbortController>();+ const abortReads = () => {+ for (const read of reads) read.abort();+ reads.clear();+ };++ const sync = () => {+ if (cancelled || paired) return;+ // the composer is live while this read is out, so hold any edit made in the meantime+ // rather than writing it to the installation defaults and then discarding it.+ // Drop to the installation defaults for the duration of the read. Until it lands the+ // store still holds the OUTGOING chat's values, and the composer is usable: a send in+ // that window is captured by snapshotQueuedChatRunSettings and carries the previous+ // chat's permission level and pills, so a chat stored as "ask" could run tools+ // without asking. The defaults are the only honest thing to show for a chat whose+ // own settings are not known yet, and a read that never resolves now leaves those+ // rather than another chat's.+ //+ // The pairing opened above survives this: a drop to the defaults for the chat that is+ // still open and still waiting on its read keeps holding rather than releasing.+ if (!defaulted) {+ defaulted = true;+ applyThreadScopedSettings(null, null);+ }+ beginThreadScopedPairing(activeThreadId);+ // Settle this chat's own PATCH first. Edit a chat, leave, come straight back and the+ // read can overtake the write and return the pre-edit snapshot, which then goes back+ // over the values the user set and is written out again by the next edit.+ const read = new AbortController();+ reads.add(read);+ void awaitThreadScopedSettingsWrite(activeThreadId)+ .then(() =>+ // Bounded, because this read is what holds sends back: an unbounded GET that+ // never settles would park every send in the chat behind "Loading this chat's+ // settings" with nothing to release it, and leave the request open besides.+ // The fetch carries THIS attempt's deadline and its controller, so a stall ends+ // the request rather than leaving it running while the retry opens the next one;+ // the race is the backstop for the rest of the read.+ Promise.race([+ getStoredChatThreadReadResult(activeThreadId, {+ timeoutMs: THREAD_READ_TIMEOUT_MS,+ signal: read.signal,+ }),+ new Promise<never>((_, reject) =>+ setTimeout(+ () => reject(new Error("thread settings read timed out")),+ THREAD_READ_TIMEOUT_MS,+ ),+ ),+ ]),+ )+ .finally(() => {+ reads.delete(read);+ })+ .then(({ thread, cacheable }) => {+ if (cancelled || paired) return;+ // A legacy fallback row means the backend GET FAILED and Dexie answered instead.+ // That is the failure case, not a confirmed missing row: the thread may well+ // have a snapshot on the server, so keep holding and retry rather than+ // releasing this chat's edits into the installation defaults.+ if (thread && !cacheable) {+ retryThreadRead();+ return;+ }+ // a legacy fallback row carries no snapshot, and pinning would overwrite the real one.+ if (!thread) {+ // a new chat's runtime-made id has no row yet, so it stays on the global+ // settings. The answer is in: there is no snapshot to wait for, so an edit+ // held for it is a plain default change and goes out now. Deferring that to a+ // second missing read meant an unsaved chat's click was written to a row that+ // does not exist, or attached to the chat once it was saved.+ releaseHeldThreadScopedEdits();+ if (unpaired) return;+ unpaired = true;+ applyThreadScopedSettings(null, null);+ return;+ }+ paired = true;+ // the response spells every omitted field as null, which is not a value to apply.+ applyThreadScopedSettings(+ activeThreadId,+ thread.settings ? sanitizeThreadScopedSettings(thread.settings) : null,+ );+ })+ // A failed read leaves the installation defaults up (dropped to above), not the+ // outgoing chat's settings, which would otherwise stay live indefinitely. The held+ // edit goes to the chat it was made in.+ .catch(() => retryThreadRead());+ };++ // The read did not answer for this chat. Send what is held to the chat it was made+ // in, then keep the chat paired, or every later edit in it would fall through to the+ // installation defaults for as long as it stays open. A fresh browser with no legacy+ // cache has nothing else to fall back on, so retry a bounded few times.+ const retryThreadRead = () => {+ if (cancelled) return;+ commitHeldThreadScopedEditsToTheirThread();+ if (retryTimer !== null) return;+ if (retriesLeft <= 0) {+ // Out of tries. Staying paired would hold every send behind "Loading this+ // chat's settings" with nothing left to resolve it, so give up openly: the+ // chat runs on the installation defaults, which is what it is already+ // showing, and say so once rather than failing silently.+ applyThreadScopedSettings(null, null);+ releaseHeldThreadScopedEdits();+ toast.error("Could not load this chat's settings", {+ description:+ "It is using the default settings. Reopen the chat to try again.",+ });+ return;+ }+ // Keep the chat paired between tries, or an edit in it would fall through to+ // the installation defaults. A fresh browser with no legacy cache has nothing+ // else to fall back on, so it is worth a few goes.+ beginThreadScopedPairing(activeThreadId);+ retriesLeft -= 1;+ retryTimer = setTimeout(() => {+ retryTimer = null;+ sync();+ }, THREAD_READ_RETRY_MS);+ };++ sync();+ window.addEventListener(CHAT_HISTORY_UPDATED_EVENT, sync);+ return () => {+ cancelled = true;+ if (retryTimer !== null) clearTimeout(retryTimer);+ // Nothing is waiting on these once the chat is gone, and leaving them running is+ // how an outage turned every chat opened during it into three open requests.+ abortReads();+ // switched away mid-read: the edit belongs to the chat it was made in, not to the+ // installation defaults that every other snapshot-less chat follows.+ commitHeldThreadScopedEditsToTheirThread();+ window.removeEventListener(CHAT_HISTORY_UPDATED_EVENT, sync);+ };+ }, [activeThreadId, enabled, settingsHydrated]);++ return null;+}+// Lets the recount read the on-screen branch, not the stored records: an incognito thread stores// none, and a retried thread's newest stored leaf is not what the runtime would send.function ActiveBranchRegistrar({@@ -1977,6 +2188,7 @@ export function ChatRuntimeProvider({!initialThreadId}/>+ <ThreadScopedSettingsSync enabled={modelType === "base" && !pairId} /><ActiveBranchRegistrar enabled={modelType === "base" && !pairId} /><ThreadContextUsageRecount enabled={modelType === "base" && !pairId} /><ThreadBackendAutosave modelType={modelType} pairId={pairId} />diff --git a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts b/studio/frontend/src/features/chat/stores/chat-runtime-store.tsindex 0639cf24ccb..277e1ad9061 100644--- a/studio/frontend/src/features/chat/stores/chat-runtime-store.ts+++ b/studio/frontend/src/features/chat/stores/chat-runtime-store.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+import { authFetch } from "@/features/auth";import { mirrorHfTokenInto, useHfTokenStore } from "@/features/hub";import {cachedPinnableGpuIndexKind,@@ -40,9 +41,18 @@ import {} from "../utils/chat-settings-storage";import {loadShadowOwnsMirroredSetting,+ normalizeStoredPermissionMode,normalizeStoredRagAutoInject,} from "../utils/mirrored-chat-settings";import { retryablePatchAfterFailure } from "../utils/settings-retry";+import {+ THREAD_SCOPED_SETTING_KEYS,+ type ThreadScopedSettingKey,+ type ThreadScopedSettings,+ hasThreadScopedSettings,+ isThreadOwnedSettingKey,+ sanitizeThreadScopedSettings,+} from "../utils/thread-scoped-settings";import {chatModelLifecycleGate,type ModelLifecycleLease,@@ -387,8 +397,31 @@ function saveSettingsPatch(patch: SettingsPatch): void {// 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 {+function flushSettingsOnPageHidden(terminal: boolean): void {if (pendingTimer !== null) clearTimeout(pendingTimer);+ // A captured edit lives only in the debounce, so send it before the tab goes.+ // Only on a terminal event, though: the beacon PATCHes the row directly and a+ // thread whose row has not been created yet answers 404, where the normal path+ // would have created it first. visibilitychange is not terminal (it fires on+ // every tab switch), and the page is still there to await the ensure.+ // Chats whose newest values have just gone out, so an older unsettled snapshot for+ // the same chat is not sent after them: each beacon takes a higher seq than the last,+ // which would make the stale one the winner.+ const sentNewest = new Set<string>();+ const flushedThreadId = threadSettingsWriteThreadId;+ flushThreadScopedSettingsWrite(terminal);+ if (terminal && flushedThreadId !== null) sentNewest.add(flushedThreadId);+ // An edit made while its chat's read was still out lives only in heldThreadScopedEdits,+ // so the flush above does not see it. Effect cleanup is not guaranteed during unload and+ // its ordinary fetch would not outlive the page anyway, so send it from here, keepalive.+ if (terminal) {+ const heldThreadId = pendingPairingThreadId;+ void commitHeldThreadScopedEditsToTheirThread(true);+ if (heldThreadId !== null) sentNewest.add(heldThreadId);+ // And anything an earlier visibilitychange already flushed the normal way, which+ // this event would otherwise leave to a fetch the page is about to cancel.+ beaconUnsettledThreadSettingsWrites(sentNewest);+ }// 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();@@ -399,7 +432,7 @@ function flushSettingsOnPageHidden(): void {}if (typeof window !== "undefined") {- window.addEventListener("beforeunload", flushSettingsOnPageHidden);+ window.addEventListener("beforeunload", () => flushSettingsOnPageHidden(true));// 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@@ -408,9 +441,9 @@ if (typeof window !== "undefined") {// 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);+ window.addEventListener("pagehide", () => flushSettingsOnPageHidden(true));document.addEventListener("visibilitychange", () => {- if (document.visibilityState === "hidden") flushSettingsOnPageHidden();+ if (document.visibilityState === "hidden") flushSettingsOnPageHidden(false);});}@@ -636,14 +669,875 @@ function flushPreHydrationSettings(): void {* 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);+ const mirrored = MIRRORED_SETTING_BY_STORAGE_KEY.get(key);+ const writeGlobal = () => {+ // 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);+ };+ if (mirrored && captureThreadScopedEdit(mirrored.field, writeGlobal)) return;+ writeGlobal();+}++const THREAD_SETTINGS_DEBOUNCE_MS = 400;++/** the thread whose snapshot the store shows, or null on a new chat. */+let threadScopedSettingsThreadId: string | null = null;+/** that thread's stored values, for the load paths that read a setting outside the store. */+let activeThreadScopedSettings: ThreadScopedSettings | null = null;+// captured on the way into a thread: edits made with a chat open must not move the defaults.+let globalThreadScopedDefaults: ThreadScopedSettings | null = null;+let threadSettingsWriteTimer: ReturnType<typeof setTimeout> | null = null;+let threadSettingsWriteThreadId: string | null = null;+// set only when pinning: the values applied on open, not whatever a model-capability effect+// leaves in the store by the time the debounce fires.+let threadSettingsWriteSnapshot: ThreadScopedSettings | null = null;++function readThreadScopedSettings(+ state: ChatRuntimeStore,+): ThreadScopedSettings {+ const source: Record<string, unknown> = {};+ for (const key of THREAD_SCOPED_SETTING_KEYS) {+ source[key] = state[key];+ }+ // drops "full" with it: a stored bypass would come back without the warning dialog.+ return sanitizeThreadScopedSettings(source);+}++// keeps a model load from re-applying the global default over the pills the chat is running with.+export function threadScopedOverride<K extends ThreadScopedSettingKey>(+ key: K,+): ThreadScopedSettings[K] | undefined {+ // activeThreadScopedSettings is only refreshed when the debounce fires, so for the 400ms+ // after an edit it still holds the pre-edit values, and the capture path deliberately+ // wrote nothing to localStorage either. A model load or a status poll landing in that+ // window would read the old value, revert the pill, and then be persisted by the write+ // the edit itself scheduled. The store already holds the edit, so prefer it.+ // A pending PIN carries its own snapshot, which is what the chat is about to be+ // stored as, so that answers instead of the live store. Falling through to+ // activeThreadScopedSettings here reads null, because a chat being pinned had no+ // snapshot to begin with, and the load then puts the global values back over the+ // edit the queued write is about to persist.+ if (+ threadSettingsWriteThreadId !== null &&+ threadSettingsWriteThreadId === threadScopedSettingsThreadId+ ) {+ if (threadSettingsWriteSnapshot !== null) {+ if (threadSettingsWriteSnapshot[key] !== undefined) {+ return threadSettingsWriteSnapshot[key];+ }+ } else {+ const live = readThreadScopedSettings(useChatRuntimeStore.getState());+ if (live[key] !== undefined) return live[key];+ }+ }+ return activeThreadScopedSettings?.[key];+}++/**+ * Fields the user has just set on the open chat, as opposed to ones a model's+ * capabilities moved in the store. The preservations below exist to stop a clamp erasing+ * a stored choice; they must not also undo a choice the user has only now made.+ */+const explicitlyEditedThreadFields = new Set<string>();++/**+ * Fields a provider constraint has moved in the store WITHOUT persisting them. Kimi's+ * builtin web search may not run with thinking, so the composer turns the other pill off+ * with `{ persist: false }`; that write bypasses persistSetting, and so the capture path,+ * on purpose. The value in the store is then the provider's, not the user's, and the+ * next full-snapshot write must not save it over what the chat has stored, or a chat+ * that asked for thinking comes back without it on a model that allows it.+ */+const constraintSuppressedThreadFields = new Set<string>();++/** Both pills of Kimi's search/thinking exclusion; the only non-persisting setters. */+const CONSTRAINT_SUPPRESSIBLE_KEYS = ["reasoningEnabled", "toolsEnabled"] as const;++function noteConstraintSuppressedThreadField(+ field: (typeof CONSTRAINT_SUPPRESSIBLE_KEYS)[number],+): void {+ if (useChatRuntimeStore.getState().activeThreadId === null) return;+ constraintSuppressedThreadFields.add(field);+}++/** Is the stored value the one to keep, rather than the constraint-derived live one? */+function keepsStoredValueUnderConstraint(+ key: (typeof CONSTRAINT_SUPPRESSIBLE_KEYS)[number],+ threadId: string,+ settings: ThreadScopedSettings,+): boolean {+ return (+ threadId === threadScopedSettingsThreadId &&+ constraintSuppressedThreadFields.has(key) &&+ // A choice the user has since made themselves is theirs, constraint or not.+ !explicitlyEditedThreadFields.has(key) &&+ typeof activeThreadScopedSettings?.[key] === "boolean" &&+ settings[key] !== activeThreadScopedSettings[key]+ );+}++// The pills chat-page clamps to the selected model's capabilities.+const CLAMPED_PILL_KEYS = [+ "toolsEnabled",+ "codeToolsEnabled",+ "imageToolsEnabled",+ "webFetchToolsEnabled",+] as const;+type ClampedPillKey = (typeof CLAMPED_PILL_KEYS)[number];++function isSameThreadScopedValue(next: unknown, current: unknown): boolean {+ if (Object.is(next, current)) return true;+ // ragSource is the only object among these, and its variants carry at most a kb id.+ if (isPlainObject(next) && isPlainObject(current)) {+ return next.type === current.type && next.kbId === current.kbId;+ }+ return false;+}++function buildThreadScopedSnapshot(+ threadId: string,+ snapshot: ThreadScopedSettings | null,+): ThreadScopedSettings {+ const settings =+ snapshot ?? readThreadScopedSettings(useChatRuntimeStore.getState());+ // the write replaces the row, and the sanitizer drops a live "full", so without this the+ // level the chat had stored would be erased by any pill toggled under Full access.+ if (+ settings.permissionMode === undefined &&+ threadId === threadScopedSettingsThreadId &&+ activeThreadScopedSettings?.permissionMode !== undefined+ ) {+ settings.permissionMode = activeThreadScopedSettings.permissionMode;+ }+ // Same for deep research, which apply() also holds back (external models and incognito+ // cannot run it). Without this, toggling any other pill in such a chat erases the true+ // it had stored, and it comes back off once the chat is on a local model again.+ //+ // Unless the user just changed it themselves: enabling Search, Code or Images clears+ // deep research deliberately, and restoring it here would ignore that and bring it+ // back, alongside Search, the moment the chat is on a local model again.+ if (+ threadId === threadScopedSettingsThreadId &&+ !explicitlyEditedThreadFields.has("deepResearchEnabled") &&+ activeThreadScopedSettings?.deepResearchEnabled === true &&+ settings.deepResearchEnabled !== true &&+ (externalCheckpointRefusesDeepResearch(+ useChatRuntimeStore.getState().params.checkpoint,+ ) ||+ useChatRuntimeStore.getState().incognito)+ ) {+ settings.deepResearchEnabled = true;+ }+ // And for thinking, which a model that cannot stop thinking forces on in the store.+ // That true is the model's, so persisting it would erase a chat's stored false and+ // leave thinking on once the chat is back on a model where it is optional.+ if (+ threadId === threadScopedSettingsThreadId &&+ !explicitlyEditedThreadFields.has("reasoningEnabled") &&+ activeThreadScopedSettings?.reasoningEnabled === false &&+ settings.reasoningEnabled !== false &&+ useChatRuntimeStore.getState().reasoningAlwaysOn+ ) {+ settings.reasoningEnabled = false;+ }+ // Same again for every pill the model-selection pass in chat-page clamps off in the+ // store without touching the snapshot. The clamp is the model's, not the user's, so it+ // must not erase what the chat had stored; the condition is each pill's own capability+ // rule, which is exactly when the user could not have turned it off themselves.+ if (threadId === threadScopedSettingsThreadId) {+ const live = useChatRuntimeStore.getState();+ const modelLoaded = !!live.params.checkpoint && !live.modelLoading;+ const capable: Record<ClampedPillKey, boolean> = {+ toolsEnabled: live.supportsTools || live.supportsBuiltinWebSearch,+ codeToolsEnabled: live.supportsTools || live.supportsBuiltinCodeExecution,+ imageToolsEnabled: live.supportsBuiltinImageGeneration,+ webFetchToolsEnabled: live.supportsBuiltinWebFetch,+ };+ for (const key of CLAMPED_PILL_KEYS) {+ if (+ modelLoaded &&+ !capable[key] &&+ !explicitlyEditedThreadFields.has(key) &&+ activeThreadScopedSettings?.[key] === true &&+ settings[key] !== true+ ) {+ settings[key] = true;+ }+ }+ }+ // And for the pills a provider constraint moved without persisting them: the store+ // holds the provider's value there, so the chat keeps the one it was stored with.+ if (keepsStoredValueUnderConstraint("reasoningEnabled", threadId, settings)) {+ settings.reasoningEnabled = activeThreadScopedSettings?.reasoningEnabled;+ }+ if (keepsStoredValueUnderConstraint("toolsEnabled", threadId, settings)) {+ settings.toolsEnabled = activeThreadScopedSettings?.toolsEnabled;+ }+ if (threadId === threadScopedSettingsThreadId) {+ activeThreadScopedSettings = settings;+ }+ // Spent: this snapshot has taken them into account, and the next one is about+ // whatever the user does next.+ explicitlyEditedThreadFields.clear();+ return settings;+}++const THREAD_SETTINGS_REPLAY_KEY = "unsloth_chat_thread_settings_replay";+const THREAD_SETTINGS_REPLAY_TIMEOUT_MS = 10_000;++/**+ * Snapshots a terminal event sent but could not confirm, kept where the next session+ * will find them. The beacon cannot await anything: a chat whose row is still being+ * created answers 404 and the edit is gone, and the creation that follows knows nothing+ * about it. Writing the attempt down costs nothing and makes the loss recoverable.+ */+function rememberThreadSettingsForReplay(+ threadId: string,+ body: Record<string, unknown>,+): void {+ if (!canUseStorage()) return;+ try {+ const raw = localStorage.getItem(THREAD_SETTINGS_REPLAY_KEY);+ const pending = raw ? (JSON.parse(raw) as Record<string, unknown>) : {};+ pending[threadId] = body;+ localStorage.setItem(THREAD_SETTINGS_REPLAY_KEY, JSON.stringify(pending));+ } catch {+ // A full or unavailable store just means no replay; the beacon may still land.}- writeStorageValue(key, raw);+}++/**+ * Re-send anything the last session could not confirm. Safe to run always: the seq the+ * body carries is that session's own, so a replay of a write that did land is refused+ * by the server rather than reverting anything newer.+ */+export function replayUnconfirmedThreadSettings(): void {+ // Once per session: it is called from both hydration outcomes, and sending each body+ // twice would race two writes carrying the same seq for the same row.+ if (threadSettingsReplayStarted) return;+ threadSettingsReplayStarted = true;+ if (!canUseStorage()) return;+ let pending: Record<string, unknown> = {};+ try {+ const raw = localStorage.getItem(THREAD_SETTINGS_REPLAY_KEY);+ if (!raw) return;+ pending = JSON.parse(raw) as Record<string, unknown>;+ } catch {+ localStorage.removeItem(THREAD_SETTINGS_REPLAY_KEY);+ return;+ }+ const sent: Promise<unknown>[] = [];+ for (const [threadId, body] of Object.entries(pending)) {+ // Bounded: every settings write in the session waits for these, so a socket that+ // never settles would leave the whole session unable to persist anything.+ const timeout = new AbortController();+ const timer = setTimeout(() => timeout.abort(), THREAD_SETTINGS_REPLAY_TIMEOUT_MS);+ const request = authFetch(`/api/chat/threads/${encodeURIComponent(threadId)}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ signal: timeout.signal,+ })+ .finally(() => clearTimeout(timer))+ // Only an ok response means it landed. authFetch resolves for 404 and 5xx too,+ // and the missing-row case this exists for is exactly the one that 404s, so+ // dropping the entry on any settled promise would throw the edit away for good.+ .then((res) => {+ // Only the body this request carried. A terminal event in THIS session can+ // store a newer body for the same thread while the replay is still out, and+ // that one is unconfirmed by definition: dropping it because an older replay+ // succeeded would leave the newest edit with nothing to recover it from.+ if (res.ok) forgetReplayedThreadSettings(threadId, body);+ })+ .catch(() => undefined);+ sent.push(request);+ }+ // Every snapshot write waits for this. The replay carries the PREVIOUS session's+ // writer id, so the server treats it as unrelated to anything this session sends and+ // will apply it whenever it arrives: on a slow connection a full snapshot from last+ // time could land after an edit made just now and revert it.+ threadSettingsReplaySettled = Promise.all(sent).then(() => undefined);+}++// Resolved once the previous session's unconfirmed writes have been answered.+let threadSettingsReplaySettled: Promise<void> = Promise.resolve();+let threadSettingsReplayStarted = false;++/**+ * Drop one entry, leaving the rest for the next attempt. `expected` narrows that to the+ * exact body the caller sent, for callers whose success says nothing about a newer entry+ * stored since; a caller that has itself just written the row passes nothing, because its+ * values supersede whatever the entry holds.+ */+function forgetReplayedThreadSettings(+ threadId: string,+ expected?: unknown,+): void {+ if (!canUseStorage()) return;+ try {+ const raw = localStorage.getItem(THREAD_SETTINGS_REPLAY_KEY);+ if (!raw) return;+ const pending = JSON.parse(raw) as Record<string, unknown>;+ if (+ expected !== undefined &&+ JSON.stringify(pending[threadId]) !== JSON.stringify(expected)+ ) {+ return;+ }+ delete pending[threadId];+ if (Object.keys(pending).length === 0) {+ localStorage.removeItem(THREAD_SETTINGS_REPLAY_KEY);+ } else {+ localStorage.setItem(THREAD_SETTINGS_REPLAY_KEY, JSON.stringify(pending));+ }+ } catch {+ // Leaving it behind only costs one more replay next time.+ }+}++/**+ * Send the snapshot on tab close. The ensure-then-update chain cannot finish during unload, so+ * the row write goes straight out with keepalive, and what it could not confirm is left for+ * the next session to replay: a thread whose row is still being created answers 404, and the+ * creation that follows would otherwise land without the user's last edit.+ */+function sendThreadScopedSettingsBeacon(+ threadId: string,+ snapshot: ThreadScopedSettings | null,+ merge = false,+): void {+ // A merge carries only what the user touched, for the chat whose own snapshot was+ // never read; sending a replacement built from the defaults on screen would erase+ // the rest of its row. Everything else replaces, as the debounced write does.+ const body = merge+ ? {+ settingsPatch: snapshot,+ settingsSeq: nextThreadSettingsSeq(),+ settingsWriter: threadSettingsWriter,+ }+ : {+ settings: buildThreadScopedSnapshot(threadId, snapshot),+ settingsSeq: nextThreadSettingsSeq(),+ settingsWriter: threadSettingsWriter,+ };+ // The beacon carries the newest values but skips the chain, so an older write would+ // otherwise land after it and put the stale snapshot back. The ticket stands down the+ // ones still queued; the abort ends the one already out, which no ticket can reach.+ takeThreadSettingsWriteTicket(threadId);+ threadSettingsWriteAborts.get(threadId)?.abort();+ rememberThreadSettingsForReplay(threadId, body);+ void authFetch(`/api/chat/threads/${encodeURIComponent(threadId)}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ keepalive: true,+ }).catch(() => undefined);+}++// One chain per thread. The write REPLACES settings_json rather than merging it, so two+// unordered writes do not merge into the newer one, they pick a winner: a slow first+// request landing after a fast second restores the settings the user just moved away from.+const threadSettingsWriteChains = new Map<string, Promise<unknown>>();+// Newest snapshot issued per thread, so a write that is still waiting its turn can tell it+// has been superseded and skip its PATCH rather than reinstate what it captured.+const threadSettingsWriteTickets = new Map<string, number>();++// The request each thread currently has out, so a newer snapshot can stand it down.+const threadSettingsWriteAborts = new Map<string, AbortController>();++/**+ * Stamps each snapshot write so the server can refuse this tab's own older ones, which+ * is the case that needs it: a keepalive sent on unload can be undone by a PATCH the+ * server already had in hand, and no client-side abort reaches that.+ *+ * The id makes the ordering per-tab. A plain counter, and never a clock: comparing one+ * machine's numbers with another's means the browser that happens to be behind has+ * every edit refused while still being told it saved. Across tabs the last write wins,+ * as it did before any of this.+ */+const threadSettingsWriter = crypto.randomUUID();+let lastThreadSettingsSeq = 0;++function nextThreadSettingsSeq(): number {+ lastThreadSettingsSeq += 1;+ return lastThreadSettingsSeq;+}++function takeThreadSettingsWriteTicket(threadId: string): number {+ const ticket = (threadSettingsWriteTickets.get(threadId) ?? 0) + 1;+ threadSettingsWriteTickets.set(threadId, ticket);+ return ticket;+}++/** Resolves true when the snapshot reached the row, so callers can tell it landed. */+function writeThreadScopedSettings(+ threadId: string,+ snapshot: ThreadScopedSettings | null,+): Promise<boolean> {+ // Built now, not inside the chain: the snapshot must describe the store as it is at the+ // moment of the edit, not as it will be once the previous write has finished.+ const settings = buildThreadScopedSnapshot(threadId, snapshot);+ // Stamped with the snapshot, not with the request: the seq has to say when the edit+ // happened, not when its turn in the chain came up.+ const settingsSeq = nextThreadSettingsSeq();+ const ticket = takeThreadSettingsWriteTicket(threadId);+ const previous = threadSettingsWriteChains.get(threadId) ?? Promise.resolve();+ const next = previous+ .catch(() => undefined)+ // Last session's unconfirmed writes go first, or one of them can land on top of+ // this edit: it carries a different writer id, so nothing on the server orders it.+ .then(() => threadSettingsReplaySettled)+ .catch(() => undefined)+ .then(async () => {+ // superseded while queued: sending this would undo the newer snapshot, and the+ // newer one is what the replay entry should be measured against, so this counts+ // as landed for the purposes of the caller.+ if ((threadSettingsWriteTickets.get(threadId) ?? ticket) !== ticket) {+ return true;+ }+ const controller = new AbortController();+ threadSettingsWriteAborts.set(threadId, controller);+ try {+ const { updateStoredChatThread } = await import(+ "../utils/chat-history-storage"+ );+ await updateStoredChatThread(+ threadId,+ { settings, settingsSeq, settingsWriter: threadSettingsWriter },+ { signal: controller.signal },+ );+ // This session's values are now the row's, so a leftover replay entry from the+ // last one would revert them if it were ever retried.+ forgetReplayedThreadSettings(threadId);+ return true;+ } catch {+ // the chat still behaves as edited; only the snapshot for the next visit is lost.+ // An abort lands here too, and that one is deliberate: a newer snapshot won.+ if (!controller.signal.aborted) warnSettingsPersistenceFailure();+ // An abort means a newer write won and is tracked in its place; a real failure+ // means nothing reached the row, and the caller needs to know.+ return controller.signal.aborted;+ } finally {+ if (threadSettingsWriteAborts.get(threadId) === controller) {+ threadSettingsWriteAborts.delete(threadId);+ }+ }+ })+ .finally(() => {+ if (threadSettingsWriteChains.get(threadId) === next) {+ threadSettingsWriteChains.delete(threadId);+ threadSettingsWriteTickets.delete(threadId);+ }+ });+ threadSettingsWriteChains.set(threadId, next);+ return next;+}++/**+ * Settle this chat's snapshot before anything reads it back. A chat edited, left and+ * re-entered has its PATCH in flight, and a GET overtaking it returns the pre-edit+ * snapshot, which then gets applied over the values the user set and written back on the+ * next edit. Pending debounce included, or the read races the timer instead.+ */+export async function settleThreadScopedSettingsForCopy(+ threadId: string,+): Promise<void> {+ // An edit made while this chat's read was still out lives in neither the debounce nor+ // the chain, so settling those alone leaves it behind and the copy takes the old row.+ // Only for a caller that is about to read the row server side: the pairing itself+ // waits on this function's sibling, which must not close the window it just opened.+ if (pendingPairingThreadId === threadId) {+ await commitHeldThreadScopedEditsToTheirThread();+ }+ // A flushed replacement write that failed resolves false rather than throwing, so+ // awaiting the chain alone cannot tell a saved edit from a lost one. The copy is made+ // server side from the row: going ahead on a failed write hands the new chat the+ // pre-edit snapshot and tells the user nothing.+ if (!(await awaitThreadScopedSettingsWrite(threadId))) {+ throw new Error("This chat's settings could not be saved before copying it");+ }+}++/** Resolves false only when a write for this chat is known to have failed. */+export async function awaitThreadScopedSettingsWrite(+ threadId: string,+): Promise<boolean> {+ if (threadSettingsWriteThreadId === threadId) {+ flushThreadScopedSettingsWrite();+ }+ const chain = threadSettingsWriteChains.get(threadId);+ if (chain === undefined) return true;+ // A rejection is the held-edit merge path, which throws on failure.+ const landed = await chain.catch(() => false);+ return landed !== false;+}++function flushThreadScopedSettingsWrite(keepalive = false): void {+ if (threadSettingsWriteTimer !== null) {+ clearTimeout(threadSettingsWriteTimer);+ threadSettingsWriteTimer = null;+ }+ const threadId = threadSettingsWriteThreadId;+ const snapshot = threadSettingsWriteSnapshot;+ threadSettingsWriteThreadId = null;+ threadSettingsWriteSnapshot = null;+ if (threadId === null) return;+ if (keepalive) {+ sendThreadScopedSettingsBeacon(threadId, snapshot);+ return;+ }+ trackUnsettledThreadSettingsWrite(threadId, snapshot);+}++/**+ * Start a normal write and keep its snapshot until it settles.+ *+ * Some browsers fire visibilitychange(hidden) and then pagehide. The first flushes+ * normally and clears the pending snapshot, so the terminal event would find nothing to+ * beacon and a discarded page takes the ordinary fetch with it. Holding the snapshot+ * lets the terminal path send it again, keepalive.+ */+function trackUnsettledThreadSettingsWrite(+ threadId: string,+ snapshot: ThreadScopedSettings | null,+): void {+ // Identity, not value: two ordinary edits both carry a null snapshot, so comparing+ // the value let the first request's settle delete the second one's tracking, and a+ // terminal event then found nothing to resend for a write still in flight.+ const entry: UnsettledThreadSettingsWrite = { snapshot };+ unsettledThreadSettingsWrites.set(threadId, entry);+ void writeThreadScopedSettings(threadId, snapshot).then((landed) => {+ // Only a write that reached the row stops being unsettled. Dropping it on failure+ // left nothing for a terminal event to beacon, so the edit was lost on close and+ // came back reverted, which is the opposite of what this tracking is for.+ if (landed && unsettledThreadSettingsWrites.get(threadId) === entry) {+ unsettledThreadSettingsWrites.delete(threadId);+ }+ });+}++type UnsettledThreadSettingsWrite = { snapshot: ThreadScopedSettings | null };++/** Flushed but not yet acknowledged, so a terminal event can still resend it. */+const unsettledThreadSettingsWrites = new Map<+ string,+ UnsettledThreadSettingsWrite+>();++/**+ * Re-send anything a normal flush has not landed yet, with keepalive.+ *+ * `alreadySent` names the threads the terminal flush has just beaconed. Those carry the+ * newest values, and every beacon takes a higher seq than the last, so re-sending an+ * older unsettled snapshot for the same chat afterwards would make the stale one win.+ */+function beaconUnsettledThreadSettingsWrites(+ alreadySent: ReadonlySet<string>,+): void {+ const unsettled = [...unsettledThreadSettingsWrites];+ unsettledThreadSettingsWrites.clear();+ for (const [threadId, entry] of unsettled) {+ if (alreadySent.has(threadId)) continue;+ sendThreadScopedSettingsBeacon(threadId, entry.snapshot);+ }+}++function scheduleThreadScopedSettingsWrite(+ threadId: string,+ snapshot: ThreadScopedSettings | null = null,+): void {+ if (+ threadSettingsWriteThreadId !== null &&+ threadSettingsWriteThreadId !== threadId+ ) {+ flushThreadScopedSettingsWrite();+ }+ threadSettingsWriteThreadId = threadId;+ threadSettingsWriteSnapshot = snapshot;+ if (threadSettingsWriteTimer !== null) clearTimeout(threadSettingsWriteTimer);+ threadSettingsWriteTimer = setTimeout(() => {+ threadSettingsWriteTimer = null;+ const pendingThreadId = threadSettingsWriteThreadId;+ const pendingSnapshot = threadSettingsWriteSnapshot;+ threadSettingsWriteThreadId = null;+ threadSettingsWriteSnapshot = null;+ if (pendingThreadId !== null) {+ // Tracked the same way a manual flush is: once the timer has fired there is no+ // pending debounce left for a terminal event to find, so without this the write+ // in flight is the only copy and the page teardown cancels it.+ trackUnsettledThreadSettingsWrite(pendingThreadId, pendingSnapshot);+ }+ }, THREAD_SETTINGS_DEBOUNCE_MS);+}++// the chat whose snapshot is in flight, and the edits made before it landed. The store already+// shows them; only the read can say whether they belong to this chat or to the defaults, so they+// wait here. Writing them globally in the meantime moved every other chat's default and was then+// overwritten by the arriving snapshot, so the click both leaked and appeared to do nothing.+let pendingPairingThreadId: string | null = null;+/** The store's thread-scoped values as they stood when the current pairing began. */+let pairingWindowDefaults: ThreadScopedSettings | null = null;+/** and the chat it was sampled for, so a retry does not resample over its own edit. */+let pairingWindowDefaultsThreadId: string | null = null;+let heldThreadScopedEdits: {+ field: string;+ writeGlobal: (() => void) | null;+}[] = [];++/** Start of the window: the read for `threadId` is out but its snapshot has not landed. */+export function beginThreadScopedPairing(threadId: string): void {+ if (pendingPairingThreadId === threadId) return;+ releaseHeldThreadScopedEdits();+ pendingPairingThreadId = threadId;+ // What the installation defaults were before this chat could edit anything. Recorded+ // here because there is nowhere later to recover it from: an edit made during the+ // window overwrites the store, and on the first pairing of a session there is no+ // earlier capture to fall back on.+ //+ // Once per chat, not once per attempt: a retry after a failed read runs with the held+ // edit already in the store, and re-sampling would take that edit for a default.+ if (pairingWindowDefaultsThreadId !== threadId) {+ pairingWindowDefaultsThreadId = threadId;+ // Switching straight from one saved chat to another, the store still holds the+ // OUTGOING chat's values at this point, so it is not a source of defaults. The+ // capture made when that chat was paired is, and it exists whenever a chat is+ // applied. Only with no chat applied does the store itself hold the defaults.+ pairingWindowDefaults =+ threadScopedSettingsThreadId === null+ ? readThreadScopedSettings(useChatRuntimeStore.getState())+ : globalThreadScopedDefaults;+ }+ openThreadScopedPairingGate(threadId);+}++/** Sends are held while this is true; see the field's own note. */+function openThreadScopedPairingGate(threadId: string): void {+ if (!useChatRuntimeStore.getState().threadScopedSettingsPending) {+ useChatRuntimeStore.setState({ threadScopedSettingsPending: true });+ }+ if (!pairingSettledByThreadId.has(threadId)) {+ let resolve!: () => void;+ const promise = new Promise<void>((r) => {+ resolve = r;+ });+ pairingSettledByThreadId.set(threadId, { promise, resolve });+ }+}++/**+ * Release ONE chat's gate. Releasing all of them let a run started for A be freed by B's+ * pairing ending, which is the whole reason these are held per chat; the composer flag+ * is separate, and only tracks whether the chat now on screen is still waiting.+ */+function closeThreadScopedPairingGate(threadId: string | null): void {+ if (threadId !== null) {+ pairingSettledByThreadId.get(threadId)?.resolve();+ pairingSettledByThreadId.delete(threadId);+ }+ const stillWaiting =+ pendingPairingThreadId !== null &&+ pairingSettledByThreadId.has(pendingPairingThreadId);+ if (useChatRuntimeStore.getState().threadScopedSettingsPending !== stillWaiting) {+ useChatRuntimeStore.setState({ threadScopedSettingsPending: stillWaiting });+ }+}++// Per chat, not one for all of them: a run started for A must not be released by B's+// pairing ending, or it resumes and reads B's settings for A's run.+const pairingSettledByThreadId = new Map<+ string,+ { promise: Promise<void>; resolve: () => void }+>();++/**+ * Resolves once `threadId`'s own settings are known, or immediately if they already+ * are. Every run goes through the adapter, so awaiting this there is what stops a+ * Reload, a Continue or an edit-and-send from starting on the installation defaults+ * that stand in while the read is out: a chat stored as "ask" would run as "off".+ * Bounded, so it cannot wait for the life of the tab.+ *+ * Resolves false when the wait ran out. The caller must NOT go ahead on that: the only+ * way to reach it is a chat left mid-read, whose gate is held shut deliberately and+ * whose settings never arrived, so the store now describes some other chat. Running+ * anyway is exactly the mix-up the gate exists to prevent, only 10 seconds later.+ */+export function awaitThreadScopedPairing(+ threadId: string | null | undefined,+): Promise<boolean> {+ if (!threadId) return Promise.resolve(true);+ const gate = pairingSettledByThreadId.get(threadId);+ if (!gate) return Promise.resolve(true);+ return Promise.race([+ gate.promise.then(() => true),+ new Promise<boolean>((resolve) =>+ setTimeout(() => resolve(false), THREAD_PAIRING_WAIT_MS),+ ),+ ]);+}++// Longer than the read can take (THREAD_READ_RETRIES retries, each bounded by+// THREAD_READ_TIMEOUT_MS and spaced THREAD_READ_RETRY_MS apart, then a give-up that+// opens the gate itself), so a slow read never reaches this and a run is only refused+// for a chat whose pairing has genuinely been abandoned.+const THREAD_PAIRING_WAIT_MS = 30_000;++/** The chat turned out to own no snapshot: send the held edits to the defaults, as before. */+export function releaseHeldThreadScopedEdits(): void {+ const held = heldThreadScopedEdits;+ const threadId = pendingPairingThreadId;+ heldThreadScopedEdits = [];+ pendingPairingThreadId = null;+ pairingWindowDefaultsThreadId = null;+ // The answer is in: this chat owns no snapshot, so the defaults ARE its settings and+ // a run waiting on it can go.+ closeThreadScopedPairingGate(threadId);+ for (const edit of held) {+ // Written to the defaults now, so the value hydration held back is history.+ hydratedDefaultsByHeldField.delete(edit.field);+ edit.writeGlobal?.();+ }+}++/**+ * The user left before the read finished. The edit belongs to the chat it was made in, so+ * write it there; replaying it into the installation defaults would move every+ * snapshot-less chat, which is the leak this path exists to prevent.+ *+ * The store still holds the edited values here: the incoming chat's own read has not+ * resolved yet, so nothing has overwritten them. A chat with no row of its own writes+ * nothing (`ensureStoredChatThread` only adopts a record that already exists), which+ * correctly leaves an unsaved chat following the defaults.+ */+export function commitHeldThreadScopedEditsToTheirThread(+ keepalive = false,+): Promise<void> {+ const threadId = pendingPairingThreadId;+ const held = heldThreadScopedEdits;+ heldThreadScopedEdits = [];+ pendingPairingThreadId = null;+ // pairingWindowDefaultsThreadId is deliberately NOT cleared: a failed read commits+ // and then re-pairs the same chat, and the store holds the edit by then, so letting+ // the retry resample would take that edit for the installation default. Leaving for a+ // different chat resamples anyway, because the id no longer matches.+ //+ // The gate is NOT opened here. This runs when the user leaves mid-read, and this+ // chat's snapshot was never loaded, so a run still waiting on it must not be told the+ // settings are known: the store now shows the chat the user moved to.+ closeThreadScopedPairingGate(null);+ if (threadId === null || held.length === 0) return Promise.resolve();+ const changes = heldThreadScopedChanges(held);+ if (keepalive) {+ sendThreadScopedSettingsBeacon(threadId, changes, true);+ return Promise.resolve();+ }+ // Returned rather than fired and forgotten: forking copies settings_json server side,+ // so it has to be able to wait for a held edit to reach the row first.+ return mergeThreadScopedSettingsIntoRow(threadId, changes);+}++/** What the user actually touched, read off the store, which still holds their edits. */+function heldThreadScopedChanges(+ held: { field: string }[],+): ThreadScopedSettings {+ const edited: Record<string, unknown> = {};+ const live = useChatRuntimeStore.getState() as Record<string, unknown>;+ for (const edit of held) edited[edit.field] = live[edit.field];+ return sanitizeThreadScopedSettings(edited);+}++/**+ * PATCH just the fields in `changes`, leaving the rest of the row alone. Used when the+ * store cannot be trusted to describe the chat, which is any time its read has not+ * landed: the store is showing the installation defaults, and a replacement built from+ * those would erase everything the chat had stored that the user did not touch.+ */+async function mergeThreadScopedSettingsIntoRow(+ threadId: string,+ changes: ThreadScopedSettings,+): Promise<void> {+ const settingsSeq = nextThreadSettingsSeq();+ const ticket = takeThreadSettingsWriteTicket(threadId);+ const previous = threadSettingsWriteChains.get(threadId) ?? Promise.resolve();+ const next = previous+ .catch(() => undefined)+ // Last session's unconfirmed writes go first, or one of them can land on top of+ // this edit: it carries a different writer id, so nothing on the server orders it.+ .then(() => threadSettingsReplaySettled)+ .catch(() => undefined)+ .then(async () => {+ if ((threadSettingsWriteTickets.get(threadId) ?? ticket) !== ticket) {+ return;+ }+ try {+ const { updateStoredChatThread } = await import(+ "../utils/chat-history-storage"+ );+ await updateStoredChatThread(threadId, {+ settingsPatch: changes,+ settingsSeq,+ settingsWriter: threadSettingsWriter,+ });+ forgetReplayedThreadSettings(threadId);+ } catch (error) {+ warnSettingsPersistenceFailure();+ // Rethrown as well as toasted: a fork waits on this to know the row holds the+ // edit before the backend copies it, and a resolved promise would let it make+ // a fork carrying the pre-edit snapshot.+ throw error;+ }+ })+ .finally(() => {+ if (threadSettingsWriteChains.get(threadId) === next) {+ threadSettingsWriteChains.delete(threadId);+ threadSettingsWriteTickets.delete(threadId);+ }+ });+ threadSettingsWriteChains.set(threadId, next);+ return next;+}++/**+ * What the server said an installation default is, for fields hydration had to skip+ * because the user had just set them inside a chat whose read was still out. Those edits+ * belong to the chat, so when its pairing window closes the default goes back to the+ * value from before the window, which is this browser's pre-hydration copy. The server's+ * is the authoritative one and lands nowhere else.+ */+const hydratedDefaultsByHeldField = new Map<string, unknown>();++/** Is this field an edit waiting on its chat's read, and so not the installation's to set? */+function isHeldThreadScopedField(field: string): boolean {+ return heldThreadScopedEdits.some((edit) => edit.field === field);+}++// reports whether the edit was taken; with no chat open the caller persists globally as before.+function captureThreadScopedEdit(+ field: string,+ writeGlobal: (() => void) | null = null,+): boolean {+ if (!isThreadOwnedSettingKey(field)) return false;+ const threadId = useChatRuntimeStore.getState().activeThreadId;+ if (threadId === null) return false;+ // both ids: between a switch and its snapshot arriving the store still holds the old values.+ if (threadId === threadScopedSettingsThreadId) {+ explicitlyEditedThreadFields.add(field);+ // Set by the user now, so the chat stores this rather than what it had before a+ // constraint moved the same field.+ constraintSuppressedThreadFields.delete(field);+ scheduleThreadScopedSettingsWrite(threadId);+ return true;+ }+ if (threadId === pendingPairingThreadId) {+ heldThreadScopedEdits.push({ field, writeGlobal });+ return true;+ }+ return false;}/**@@ -686,9 +1580,9 @@ export function loadOptionalBool(key: string): boolean | null {* Resolve the web-search / code-execution pill state to apply when a model* loads. Honors the user's persisted preference so a tool-capable model never* re-enables a pill the user turned off, and never re-disables one they turned- * on. When no preference has been expressed the pills stay off: tool execution- * is opt-in, so the person enables it with a click rather than a tool-capable- * model turning it on for them.+ * on, and the open chat's own state wins over the installation default. When no+ * preference has been expressed the pills stay off: tool execution is opt-in, so+ * the person enables it with a click rather than a model turning it on for them.*/export function resolveToolsEnabledOnLoad(supportsTools: boolean): {toolsEnabled: boolean;@@ -696,8 +1590,14 @@ export function resolveToolsEnabledOnLoad(supportsTools: boolean): {} {if (!supportsTools) return { toolsEnabled: false, codeToolsEnabled: false };return {- toolsEnabled: loadOptionalBool(CHAT_TOOLS_ENABLED_KEY) ?? false,- codeToolsEnabled: loadOptionalBool(CHAT_CODE_TOOLS_ENABLED_KEY) ?? false,+ toolsEnabled:+ threadScopedOverride("toolsEnabled") ??+ loadOptionalBool(CHAT_TOOLS_ENABLED_KEY) ??+ false,+ codeToolsEnabled:+ threadScopedOverride("codeToolsEnabled") ??+ loadOptionalBool(CHAT_CODE_TOOLS_ENABLED_KEY) ??+ false,};}@@ -731,11 +1631,10 @@ function loadShowCanvasMenuItem(): boolean {* off -> "off", i.e. no prompts); fresh installs default to "auto".*/function loadPermissionMode(): PermissionMode {- 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";+ return normalizeStoredPermissionMode(+ readStorageValue(CHAT_PERMISSION_MODE_KEY),+ loadOptionalBool(CHAT_CONFIRM_TOOL_CALLS_KEY),+ );}function savePermissionMode(mode: PermissionMode): void {@@ -1147,6 +2046,12 @@ type ToolStatusEntry = {type ChatRuntimeStore = {settingsHydrated: boolean;+ /**+ * The open chat's own settings have been asked for but have not arrived. The store is+ * showing the installation defaults meanwhile, so a run started now would be captured+ * with them: a chat stored as "ask" could run tools without asking. Sending waits.+ */+ threadScopedSettingsPending: boolean;params: InferenceParams;customPresets: Preset[];activePreset: string;@@ -1522,6 +2427,11 @@ type ChatRuntimeStore = {options?: { trackQueuedSettings?: boolean },) => void;setActiveThreadId: (threadId: string | null) => void;+ /** show `threadId`'s own settings; a null threadId or snapshot restores the global ones. */+ applyThreadScopedSettings: (+ threadId: string | null,+ settings: ThreadScopedSettings | null,+ ) => void;setActiveProjectId: (projectId: string | null) => void;setIncognito: (incognito: boolean) => void;setSettingsPanelOpen: (open: boolean) => void;@@ -1886,6 +2796,22 @@ function externalCheckpointRefusesDeepResearch(return provider != null && provider.providerType !== "openai_codex";}+/**+ * Kimi's $web_search builtin requires thinking disabled, so the composer keeps the two+ * pills mutually exclusive. A restore has to do the same, or a chat stored under another+ * provider sends a combination Kimi rejects.+ */+function isKimiCheckpoint(checkpoint: string | null | undefined): boolean {+ const parsed = parseExternalModelId(checkpoint);+ if (!parsed) return false;+ return (+ useExternalProvidersStore+ .getState()+ .providers.find((candidate) => candidate.id === parsed.providerId)+ ?.providerType === "kimi"+ );+}+function getHydratedSettingsState(settings: PersistedChatSettings,state: ChatRuntimeStore,@@ -1940,6 +2866,22 @@ function getHydratedSettingsState() {continue;}+ // A click made before this response landed is held for the open chat rather than+ // written globally, so it advances no mutation version and the server's value would+ // silently replace it. The user is looking at their click; it wins.+ if (isHeldThreadScopedField(key)) {+ // The click wins in the STORE, but it is the chat's, not the installation's. When+ // the window closes the default has to go back to a value, and the one captured+ // before the window is this browser's pre-hydration copy. Keep the server's here+ // so the restore has the authoritative value to go back to.+ if (+ value !== undefined &&+ scalarSettingMutationVersions[key] === versions.scalarSettings[key]+ ) {+ hydratedDefaultsByHeldField.set(key, value);+ }+ continue;+ }if (value !== undefined &&scalarSettingMutationVersions[key] === versions.scalarSettings[key]@@ -1958,12 +2900,17 @@ function setScalarSettingVersion<K extends ScalarSettingKey>(if (Object.is(value, currentValue)) {return;}- scalarSettingMutationVersions[key] += 1;- saveSettingsPatch({ [key]: value });+ const writeGlobal = () => {+ scalarSettingMutationVersions[key] += 1;+ saveSettingsPatch({ [key]: value });+ };+ if (captureThreadScopedEdit(key, writeGlobal)) return;+ writeGlobal();}export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({settingsHydrated: false,+ threadScopedSettingsPending: false,// Hydrate the last external checkpoint so the external picker survives a// refresh. Local checkpoints are re-derived from the backend in// useChatModelRuntime and intentionally NOT persisted here.@@ -2160,6 +3107,10 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({if (fromServer) backfillMirroredSettings(settings);// After the backfill, so a startup edit wins over the stored value.flushPreHydrationSettings();+ // The previous session's tab-close writes, for the rows that did not exist+ // yet when it sent them. A replay of one that did land is refused by its own+ // seq, so this cannot revert anything newer.+ replayUnconfirmedThreadSettings();}} catch {// Hydrate failed: treat as hydrated-with-defaults so future setParams@@ -2167,6 +3118,10 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({warnSettingsPersistenceFailure();mirroredSettingsHydrated = true;flushPreHydrationSettings();+ // Independent of this endpoint: the tab-close snapshots waiting in storage are+ // rows' own settings, and leaving them unsent because /api/chat/settings was+ // briefly unavailable strands the last session's edit for the whole of this one.+ replayUnconfirmedThreadSettings();set({ settingsHydrated: true });} finally {settingsHydrationPromise = null;@@ -2488,6 +3443,151 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({? (state.contextUsageByThreadId[activeThreadId] ?? null): null,})),+ applyThreadScopedSettings: (threadId, settings) =>+ set((state) => {+ // the pending write belongs to the outgoing thread, so it goes out before the swap.+ flushThreadScopedSettingsWrite();+ // edits made while this chat's snapshot was in flight: keep them and store them on the+ // chat. Anything else and the read would silently undo a click the user already saw.+ const heldFields = new Set<string>();+ if (threadId !== null && threadId === pendingPairingThreadId) {+ for (const edit of heldThreadScopedEdits) heldFields.add(edit.field);+ heldThreadScopedEdits = [];+ pendingPairingThreadId = null;+ // The window is over, so the next visit to this chat samples afresh rather than+ // reusing what the installation defaults were the last time round.+ pairingWindowDefaultsThreadId = null;+ // Its snapshot is now the one in the store, so anything waiting on it can go.+ closeThreadScopedPairingGate(threadId);+ } else if (+ // A drop to the defaults for the chat that is still open and still waiting on its+ // read keeps holding: those edits are that chat's, and releasing them here is the+ // leak this whole path exists to prevent.+ threadId !== null ||+ pendingPairingThreadId === null ||+ pendingPairingThreadId !== state.activeThreadId+ ) {+ releaseHeldThreadScopedEdits();+ }+ // Set from here rather than trusting the calls above: this updater's own return+ // value is merged last, so a `return state` would put the old flag back.+ const pending = pendingPairingThreadId !== null;+ // nothing was overridden while unpaired, so there is nothing to restore.+ if (threadScopedSettingsThreadId === null && threadId === null) {+ return state.threadScopedSettingsPending === pending+ ? state+ : { ...state, threadScopedSettingsPending: pending };+ }+ if (threadScopedSettingsThreadId === null) {+ // A held edit is already in the store but belongs to its chat, not to the+ // installation. Capturing it here would promote it to the default that every+ // snapshot-less chat follows, so take the value from before the window opened.+ // Deleting the key instead leaves it with no fallback at all, and the edited+ // value then stays live into the next chat, which is the same leak.+ const captured = readThreadScopedSettings(state) as Record<+ string,+ unknown+ >;+ const beforeWindow = (pairingWindowDefaults ??+ globalThreadScopedDefaults) as Record<string, unknown> | null;+ for (const field of heldFields) {+ // The server answered for this field while the window was open, and hydration+ // had to skip it. That value is the installation's; the pre-window copy is+ // only what this browser had cached before the answer arrived.+ if (hydratedDefaultsByHeldField.has(field)) {+ captured[field] = hydratedDefaultsByHeldField.get(field);+ } else if (beforeWindow && field in beforeWindow) {+ captured[field] = beforeWindow[field];+ } else {+ delete captured[field];+ }+ hydratedDefaultsByHeldField.delete(field);+ }+ globalThreadScopedDefaults = captured as ThreadScopedSettings;+ }+ threadScopedSettingsThreadId = threadId;+ explicitlyEditedThreadFields.clear();+ // The constraint belongs to the chat it was applied in, and this chat's own+ // provider effects will say so again if it still holds here.+ constraintSuppressedThreadFields.clear();+ const stored = hasThreadScopedSettings(settings)+ ? (settings as ThreadScopedSettings)+ : null;+ activeThreadScopedSettings = stored;+ const nextState: Partial<ChatRuntimeStore> = {};+ const target = nextState as Record<string, unknown>;+ const applied: Record<string, unknown> = {};+ for (const key of THREAD_SCOPED_SETTING_KEYS) {+ // the user set this one while the read was in flight, so it wins over what came back.+ if (heldFields.has(key)) {+ applied[key] = state[key];+ continue;+ }+ // full access was accepted through a warning dialog: a switch must not drop it.+ // The chat is still pinned with the level underneath it, or a chat first opened+ // under full access would store no level at all and follow the installation one+ // forever after, which is the opposite of what pinning on open is for.+ if (key === "permissionMode" && state.permissionMode === "full") {+ const underneath =+ stored?.permissionMode ??+ globalThreadScopedDefaults?.permissionMode ??+ loadPermissionMode();+ if (underneath !== "full") applied[key] = underneath;+ continue;+ }+ // setCheckpoint clears deep research for external models in the store only, so a+ // stored true would come back and fail every send in that chat. openai_codex is the+ // exception the composer already makes, so use the same predicate rather than+ // refusing every external checkpoint.+ if (+ key === "deepResearchEnabled" &&+ (externalCheckpointRefusesDeepResearch(state.params.checkpoint) ||+ state.incognito)+ ) {+ continue;+ }+ // a key the snapshot omits falls back to the defaults, not to the outgoing chat's value.+ const value = stored?.[key] ?? globalThreadScopedDefaults?.[key];+ if (value === undefined) continue;+ applied[key] = value;+ if (!isSameThreadScopedValue(value, state[key])) target[key] = value;+ }+ // Search and Thinking are mutually exclusive on Kimi, and the model-selection effect+ // that enforces it does not rerun on a thread switch. Restoring both, which a chat+ // stored under another provider can hold, would send an unsupported combination, so+ // the restore drops thinking exactly as clicking the Search pill does.+ if (+ isKimiCheckpoint(state.params.checkpoint) &&+ (applied.toolsEnabled ?? state.toolsEnabled) === true &&+ (applied.reasoningEnabled ?? state.reasoningEnabled) === true+ ) {+ applied.reasoningEnabled = false;+ if (state.reasoningEnabled !== false) target.reasoningEnabled = false;+ }+ // pin what the chat shows now, or changing the defaults later would rewrite its modes.+ // A chat that already had a snapshot only needs a write if it is carrying a held edit.+ if (threadId !== null && (stored === null || heldFields.size > 0)) {+ scheduleThreadScopedSettingsWrite(+ threadId,+ stored === null ? sanitizeThreadScopedSettings(applied) : null,+ );+ }+ if (!hasKeys(nextState)) {+ return state.threadScopedSettingsPending === pending+ ? state+ : { ...state, threadScopedSettingsPending: pending };+ }+ if (nextState.permissionMode !== undefined) {+ nextState.confirmToolCalls =+ nextState.permissionMode === "ask" ||+ nextState.permissionMode === "auto";+ }+ return {+ ...nextState,+ threadScopedSettingsPending: pending,+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,+ };+ }),setActiveProjectId: (activeProjectId) => set({ activeProjectId }),setIncognito: (incognito) => {if (incognito) saveBool(CHAT_DEEP_RESEARCH_ENABLED_KEY, false);@@ -2602,6 +3702,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({set((state) => {if (options?.persist !== false) {saveBool(CHAT_REASONING_ENABLED_KEY, reasoningEnabled);+ } else {+ noteConstraintSuppressedThreadField("reasoningEnabled");}return {reasoningEnabled,@@ -2643,6 +3745,8 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({set((state) => {if (options?.persist !== false) {saveBool(CHAT_TOOLS_ENABLED_KEY, toolsEnabled);+ } else {+ noteConstraintSuppressedThreadField("toolsEnabled");}if (toolsEnabled) saveBool(CHAT_DEEP_RESEARCH_ENABLED_KEY, false);return {@@ -2677,7 +3781,9 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({setDeepResearchEnabled: (deepResearchEnabled) =>set((state) => {saveBool(CHAT_DEEP_RESEARCH_ENABLED_KEY, deepResearchEnabled);- const permissionMode = loadPermissionMode();+ // the level this chat carries, or the global one when it carries none.+ const permissionMode =+ threadScopedOverride("permissionMode") ?? loadPermissionMode();if (deepResearchEnabled) {saveBool(CHAT_TOOLS_ENABLED_KEY, false);saveBool(CHAT_IMAGE_TOOLS_ENABLED_KEY, false);@@ -2821,7 +3927,9 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({queuedSettingsEpoch: state.queuedSettingsEpoch + 1,};}- const permissionMode = loadPermissionMode();+ // back to the level this chat carries, or the global one when it carries none.+ const permissionMode =+ threadScopedOverride("permissionMode") ?? loadPermissionMode();return {bypassPermissions,permissionMode,@@ -2869,10 +3977,14 @@ export const useChatRuntimeStore = create<ChatRuntimeStore>((set, get) => ({};}),setRagEnabled: (ragEnabled) =>- set((state) => ({- ragEnabled,- queuedSettingsEpoch: state.queuedSettingsEpoch + 1,- })),+ set((state) => {+ // the only thread-scoped setting with no global slot, so no persist helper reaches it.+ if (ragEnabled !== state.ragEnabled) captureThreadScopedEdit("ragEnabled");+ return {+ ragEnabled,+ queuedSettingsEpoch: state.queuedSettingsEpoch + 1,+ };+ }),setRagSource: (ragSource) =>set((state) => {saveRagSource(ragSource);diff --git a/studio/frontend/src/features/chat/types.ts b/studio/frontend/src/features/chat/types.tsindex 470fe0cbbe6..dc98cb65d94 100644--- a/studio/frontend/src/features/chat/types.ts+++ b/studio/frontend/src/features/chat/types.ts@@ -66,6 +66,10 @@ export interface ThreadRecord {*/forkedFromThreadId?: string | null;forkedFromMessageId?: string | null;+ /** this chat's own settings, applied when it is opened; absent means the global ones. */+ settings?:+ | import("./utils/thread-scoped-settings").ThreadScopedSettings+ | null;}export interface MessageRecord {diff --git a/studio/frontend/src/features/chat/utils/chat-history-storage.ts b/studio/frontend/src/features/chat/utils/chat-history-storage.tsindex 0a6e6764397..62b9b7b3a8d 100644--- a/studio/frontend/src/features/chat/utils/chat-history-storage.ts+++ b/studio/frontend/src/features/chat/utils/chat-history-storage.ts@@ -22,6 +22,7 @@ import {saveChatThread,syncChatMessages,updateChatProject,+ type ChatThreadWritePatch,updateChatThread,} from "../api/chat-api";import { DEXIE_DB_NAME, db } from "../db";@@ -574,6 +575,7 @@ export type StoredChatThreadReadResult = {export async function getStoredChatThreadReadResult(threadId: string,+ options: { bounded?: boolean; timeoutMs?: number; signal?: AbortSignal } = {},): Promise<StoredChatThreadReadResult> {// Incognito threads are never stored, so the lookup can only come back// empty -- short-circuit it instead of doing a Dexie read + backend GET.@@ -586,7 +588,14 @@ export async function getStoredChatThreadReadResult(const legacyThread = await db.threads.get(threadId);let backendThread: ThreadRecord | null;try {- backendThread = await getChatThread(threadId);+ // Bounded for a caller that is gating the UI on this read: an unbounded GET that+ // never answers leaves the request open for the life of the page, and every retry+ // opens another.+ backendThread = await getChatThread(threadId, {+ bounded: options.bounded,+ timeoutMs: options.timeoutMs,+ signal: options.signal,+ });} catch (error) {if (legacyThread && !isChatThreadDeleted(legacyThread.id)) {return { thread: legacyThread, cacheable: false };@@ -618,6 +627,7 @@ export async function getStoredChatThread(export async function ensureStoredChatThread(threadId: string,fallback?: ThreadRecord,+ options: { bounded?: boolean; signal?: AbortSignal } = {},): Promise<ThreadRecord | undefined> {// An incognito thread is never persisted, so there's genuinely nothing// to ensure -- skip the backend round-trips this would otherwise make@@ -630,7 +640,13 @@ export async function ensureStoredChatThread(const legacyThread = fallback ?? (await db.threads.get(threadId));let backendThread: ThreadRecord | null;try {- backendThread = await getChatThread(threadId);+ // Bounded for a caller whose own request carries a deadline: this read runs BEFORE+ // it, so an unbounded one here means neither the caller's signal nor the write+ // timeout ever applies and the write chain behind it never settles.+ backendThread = await getChatThread(threadId, {+ bounded: options.bounded,+ signal: options.signal,+ });} catch (error) {if (!legacyThread || isChatThreadDeleted(legacyThread.id)) {throw error;@@ -913,12 +929,19 @@ export async function saveStoredChatThread(export async function updateStoredChatThread(threadId: string,- patch: Partial<ThreadRecord>,+ patch: ChatThreadWritePatch,+ options: { signal?: AbortSignal } = {},): Promise<ThreadRecord | undefined> {if (isThreadIncognito(threadId)) return undefined;- const thread = await ensureStoredChatThread(threadId);+ // Same bound and same signal as the write it precedes: a stall here left the settings+ // write chain pending for the life of the page, and reopening or forking that chat+ // waits on that chain.+ const thread = await ensureStoredChatThread(threadId, undefined, {+ bounded: true,+ signal: options.signal,+ });if (!thread) return undefined;- return updateChatThread(threadId, patch);+ return updateChatThread(threadId, patch, options);}/** Thread ids whose sandbox still holds files, passed through from the route. */diff --git a/studio/frontend/src/features/chat/utils/mirrored-chat-settings.ts b/studio/frontend/src/features/chat/utils/mirrored-chat-settings.tsindex 4f3c2392a82..0a10a8e2bf5 100644--- a/studio/frontend/src/features/chat/utils/mirrored-chat-settings.ts+++ b/studio/frontend/src/features/chat/utils/mirrored-chat-settings.ts@@ -66,7 +66,7 @@ const MAX_RESEARCH_POLICY_DOMAINS = 1000;const MAX_DOMAIN_LENGTH = 253;const MAX_RAG_KB_ID_LENGTH = 256;-function isRecord(value: unknown): value is Record<string, unknown> {+export function isRecord(value: unknown): value is Record<string, unknown> {return value != null && typeof value === "object" && !Array.isArray(value);}@@ -90,7 +90,7 @@ function sanitizeResearchWebsitePolicy(};}-function sanitizeRagSource(+export function sanitizeRagSource(value: unknown,): PersistedChatSettings["ragSource"] | undefined {if (!isRecord(value)) return undefined;@@ -106,7 +106,7 @@ function sanitizeRagSource(return undefined;}-function sanitizeBoundedNumber(+export function sanitizeBoundedNumber(value: unknown,{ min, max, integer }: { min: number; max: number; integer: boolean },): number | undefined {@@ -179,6 +179,18 @@ export function loadShadowOwnsMirroredSetting(return false;}+// storage predating the level control holds only the confirm toggle: on -> ask, off -> off.+export function normalizeStoredPermissionMode(+ rawMode: string | null,+ legacyConfirm: boolean | null,+): "ask" | "auto" | "off" {+ if (rawMode === "ask" || rawMode === "auto" || rawMode === "off") {+ return rawMode;+ }+ if (legacyConfirm === null) return "auto";+ return legacyConfirm ? "ask" : "off";+}+/** Whether `settings` carries none of the mirrored values. */export function hasNoMirroredSettings(settings: PersistedChatSettings,diff --git a/studio/frontend/src/features/chat/utils/thread-scoped-settings.ts b/studio/frontend/src/features/chat/utils/thread-scoped-settings.tsnew file mode 100644index 00000000000..7b993573abb--- /dev/null+++ b/studio/frontend/src/features/chat/utils/thread-scoped-settings.ts@@ -0,0 +1,147 @@+// 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 chat settings that describe one conversation rather than the installation: the composer+// pills, the permission level and the retrieval controls. Editing one with a chat open writes+// this snapshot onto the thread, and reopening that thread applies it back.++import type {+ PermissionMode,+ RagAutoInject,+ RagMode,+ RagSource,+ ReasoningEffort,+} from "../stores/chat-runtime-store";+import {+ isRecord,+ sanitizeBoundedNumber,+ sanitizeRagSource,+} from "./mirrored-chat-settings.ts";++/** "full" (Full access) is session-only, so a thread never carries it. */+export type ThreadPermissionMode = Exclude<PermissionMode, "full">;++export interface ThreadScopedSettings {+ reasoningEnabled?: boolean;+ reasoningEffort?: ReasoningEffort;+ toolsEnabled?: boolean;+ codeToolsEnabled?: boolean;+ imageToolsEnabled?: boolean;+ webFetchToolsEnabled?: boolean;+ deepResearchEnabled?: boolean;+ artifactsEnabled?: boolean;+ mcpEnabledForChat?: boolean;+ permissionMode?: ThreadPermissionMode;+ ragEnabled?: boolean;+ ragSource?: RagSource;+ ragMode?: RagMode;+ ragTopK?: number;+ ragAutoInject?: RagAutoInject;+ ragAutoInjectMinScore?: number;+}++const THREAD_SCOPED_BOOLEAN_KEYS = [+ "reasoningEnabled",+ "toolsEnabled",+ "codeToolsEnabled",+ "imageToolsEnabled",+ "webFetchToolsEnabled",+ "deepResearchEnabled",+ "artifactsEnabled",+ "mcpEnabledForChat",+ "ragEnabled",+] as const satisfies readonly (keyof ThreadScopedSettings)[];++const THREAD_SCOPED_ENUM_VALUES = {+ reasoningEffort: ["none", "minimal", "low", "medium", "high", "max", "xhigh"],+ permissionMode: ["ask", "auto", "off"],+ ragMode: ["hybrid", "lexical", "dense"],+ ragAutoInject: ["auto", "on", "off"],+} as const satisfies Partial<+ Record<keyof ThreadScopedSettings, readonly string[]>+>;++// bounds match the ge/le PATCH /api/chat/threads/{id} enforces on the same fields.+const THREAD_SCOPED_NUMBER_BOUNDS = {+ ragTopK: { min: 1, max: 50, integer: true },+ ragAutoInjectMinScore: { min: 0, max: 1, integer: false },+} as const satisfies Partial<+ Record<+ keyof ThreadScopedSettings,+ { min: number; max: number; integer: boolean }+ >+>;++export const THREAD_SCOPED_SETTING_KEYS = [+ ...THREAD_SCOPED_BOOLEAN_KEYS,+ ...(Object.keys(+ THREAD_SCOPED_ENUM_VALUES,+ ) as (keyof typeof THREAD_SCOPED_ENUM_VALUES)[]),+ ...(Object.keys(+ THREAD_SCOPED_NUMBER_BOUNDS,+ ) as (keyof typeof THREAD_SCOPED_NUMBER_BOUNDS)[]),+ "ragSource",+] as const satisfies readonly (keyof ThreadScopedSettings)[];++export type ThreadScopedSettingKey =+ (typeof THREAD_SCOPED_SETTING_KEYS)[number];++const THREAD_SCOPED_SETTING_KEY_SET: ReadonlySet<string> = new Set(+ THREAD_SCOPED_SETTING_KEYS,+);++export function isThreadScopedSettingKey(+ key: string,+): key is ThreadScopedSettingKey {+ return THREAD_SCOPED_SETTING_KEY_SET.has(key);+}++// derived on apply, so unstored, but loadPermissionMode falls back to the confirm toggle: writing+// it globally would turn one chat's permission level into every other browser's default.+const THREAD_DERIVED_SETTING_KEYS: ReadonlySet<string> = new Set([+ "confirmToolCalls",+]);++/** whether an edit to `key` belongs to the open chat rather than the installation. */+export function isThreadOwnedSettingKey(key: string): boolean {+ return (+ THREAD_SCOPED_SETTING_KEY_SET.has(key) ||+ THREAD_DERIVED_SETTING_KEYS.has(key)+ );+}++// the patch model is extra="forbid", so one out-of-contract field would 400 the whole write.+export function sanitizeThreadScopedSettings(+ value: unknown,+): ThreadScopedSettings {+ const settings: ThreadScopedSettings = {};+ if (!isRecord(value)) return settings;+ const target = settings as Record<string, unknown>;+ for (const key of THREAD_SCOPED_BOOLEAN_KEYS) {+ if (typeof value[key] === "boolean") target[key] = value[key];+ }+ for (const [key, allowed] of Object.entries(THREAD_SCOPED_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(THREAD_SCOPED_NUMBER_BOUNDS)) {+ const sanitized = sanitizeBoundedNumber(value[key], bounds);+ if (sanitized !== undefined) target[key] = sanitized;+ }+ const ragSource = sanitizeRagSource(value.ragSource);+ if (ragSource) settings.ragSource = ragSource;+ return settings;+}++/** whether `settings` carries any thread-scoped value at all. */+export function hasThreadScopedSettings(+ settings: ThreadScopedSettings | null | undefined,+): boolean {+ if (!settings) return false;+ return THREAD_SCOPED_SETTING_KEYS.some((key) => settings[key] !== undefined);+}diff --git a/studio/frontend/tests/mirrored-chat-settings.test.ts b/studio/frontend/tests/mirrored-chat-settings.test.tsindex 6aaf5b2fc53..313322806bd 100644--- a/studio/frontend/tests/mirrored-chat-settings.test.ts+++ b/studio/frontend/tests/mirrored-chat-settings.test.ts@@ -14,6 +14,7 @@ import type { PersistedChatSettings } from "../src/features/chat/api/chat-settinimport {assignSanitizedMirroredSettings,hasNoMirroredSettings,+ normalizeStoredPermissionMode,normalizeStoredRagAutoInject,} from "../src/features/chat/utils/mirrored-chat-settings.ts";@@ -130,3 +131,24 @@ test("a record holding only mirrored settings is not empty", () => {assert.equal(hasNoMirroredSettings({ ragTopK: 5 }), false);assert.equal(hasNoMirroredSettings({ toolsEnabled: false }), false);});++// Pinned here rather than through the UI: only the first browser to hydrate resolves the level+// from storage, so the mapping can be exercised exactly once per installation.+test("a legacy confirm toggle maps onto the permission level", () => {+ assert.equal(normalizeStoredPermissionMode(null, true), "ask");+ assert.equal(normalizeStoredPermissionMode(null, false), "off");+ assert.equal(normalizeStoredPermissionMode(null, null), "auto");+});++test("a stored permission level wins over the legacy toggle", () => {+ assert.equal(normalizeStoredPermissionMode("off", true), "off");+ assert.equal(normalizeStoredPermissionMode("auto", true), "auto");+ assert.equal(normalizeStoredPermissionMode("ask", false), "ask");+});++// "full" is never stored, so reading one back must not restore the sandbox bypass.+test("an unstorable or unknown level falls through to the derivation", () => {+ assert.equal(normalizeStoredPermissionMode("full", null), "auto");+ assert.equal(normalizeStoredPermissionMode("full", true), "ask");+ assert.equal(normalizeStoredPermissionMode("nonsense", false), "off");+});diff --git a/studio/frontend/tests/thread-scoped-pairing-invariants.test.ts b/studio/frontend/tests/thread-scoped-pairing-invariants.test.tsnew file mode 100644index 00000000000..8947b330966--- /dev/null+++ b/studio/frontend/tests/thread-scoped-pairing-invariants.test.ts@@ -0,0 +1,545 @@+// 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 pairing window is the gap between opening a saved chat and its snapshot arriving.+// Everything in it is racy by nature: the composer is live, the installation defaults are+// on screen, and three async paths (global hydration, the thread read, the debounced+// write) touch the same module state. Each invariant below is one that has actually been+// broken during review, and breaking any of them again either leaks one chat's settings+// into another or loses an edit the user watched happen.+//+// Source assertions rather than a driven store: a .tsx barrel sits in the store's import+// graph, so it cannot be loaded in a bare node test. The sibling store tests do the same.++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 provider = read("../src/features/chat/runtime-provider.tsx");+const composer = read("../src/components/assistant-ui/thread.tsx");++function slice(source: string, from: string, to: string): string {+ const start = source.indexOf(from);+ assert.ok(start !== -1, `not found: ${from}`);+ const end = source.indexOf(to, start + from.length);+ assert.ok(end !== -1, `not found: ${to}`);+ return source.slice(start, end);+}++test("the read waits for this chat's own write before it can be believed", () => {+ // A chat edited, left and re-entered has its PATCH in flight; a GET that overtakes it+ // returns the pre-edit snapshot, which is then applied over what the user set.+ const sync = slice(provider, "const sync = () => {", "// The read did not answer");+ assert.match(sync, /awaitThreadScopedSettingsWrite\(activeThreadId\)/);+ // and the read only happens after it, not alongside+ assert.ok(+ sync.indexOf("awaitThreadScopedSettingsWrite") <+ sync.indexOf("getStoredChatThreadReadResult"),+ "the read is not sequenced after the write",+ );+});++test("running out of read retries ends the pairing rather than parking sends forever", () => {+ // threadScopedSettingsPending gates the composer, so a pairing left open with no retry+ // left holds every send behind a wait that nothing can resolve.+ const retry = slice(provider, "const retryThreadRead = () => {", "\n sync();");+ const exhausted = slice(retry, "if (retriesLeft <= 0) {", "return;");+ assert.match(exhausted, /applyThreadScopedSettings\(null, null\)/);+ assert.match(exhausted, /releaseHeldThreadScopedEdits\(\)/);+ // and it says so, rather than silently running on settings the chat did not choose+ assert.match(exhausted, /toast\.error/);+ // the pairing is only re-opened while tries remain+ const reopen = retry.indexOf("beginThreadScopedPairing");+ assert.ok(+ reopen > retry.indexOf("if (retriesLeft <= 0) {"),+ "pairing is re-opened before the exhaustion check, which leaves it open forever",+ );+});++test("a failed backend read is retried, not treated as a chat with no snapshot", () => {+ // cacheable:false means the GET failed and Dexie answered; releasing here would send+ // the chat's edits to the installation defaults and leave its real snapshot unread.+ const fallback = slice(provider, "if (thread && !cacheable) {", "}");+ assert.match(fallback, /retryThreadRead\(\)/);+});++test("a chat with no row releases its held edits on the first answer", () => {+ // Waiting for a second missing read meant an unsaved chat's click was written to a row+ // that does not exist, or attached to the chat once it was saved.+ const missing = slice(provider, "if (!thread) {", "unpaired = true;");+ assert.match(missing, /releaseHeldThreadScopedEdits\(\)/);+});++test("the defaults are captured when pairing begins, not reconstructed later", () => {+ // An edit during the window overwrites the store, and on the session's first pairing+ // there is no earlier capture to fall back on: the value has to be taken up front.+ const begin = slice(store, "export function beginThreadScopedPairing", "\n}");+ assert.match(begin, /pairingWindowDefaults =/);+ assert.match(begin, /readThreadScopedSettings\(/);+ const capture = slice(+ store,+ "if (threadScopedSettingsThreadId === null) {",+ "globalThreadScopedDefaults = captured",+ );+ assert.match(capture, /pairingWindowDefaults \?\?\s*globalThreadScopedDefaults/);+});++test("dropping to the defaults keeps holding for a chat still awaiting its read", () => {+ // Those edits are that chat's. Releasing them here moves every snapshot-less chat's+ // default, which is the leak the whole hold-and-commit path exists to prevent.+ const guard = slice(+ store,+ " } else if (",+ "releaseHeldThreadScopedEdits();",+ );+ assert.match(guard, /threadId !== null \|\|/);+ assert.match(guard, /pendingPairingThreadId !== state\.activeThreadId/);+});++test("an edit whose chat was never read is sent as a merge, not a replacement", () => {+ // The store is showing the installation defaults, so a full snapshot built from them+ // erases everything the chat had stored that the user did not touch.+ const commit = slice(+ store,+ "export function commitHeldThreadScopedEditsToTheirThread",+ "\n}",+ );+ assert.match(commit, /heldThreadScopedChanges\(held\)/);+ assert.match(commit, /sendThreadScopedSettingsBeacon\(threadId, changes, true\)/);+ const merge = slice(store, "async function mergeThreadScopedSettingsIntoRow", "\n}");+ assert.match(merge, /settingsPatch: changes/);+});++test("hydration does not overwrite a field whose edit is still held", () => {+ // A held edit advances no mutation version, so the server's value would replace it and+ // then be persisted to the thread as if the user had chosen it.+ const loop = slice(store, "for (const key of SCALAR_SETTING_KEYS) {", "return nextState;");+ assert.match(loop, /if \(isHeldThreadScopedField\(key\)\) \{/);+ const held = slice(loop, "if (isHeldThreadScopedField(key)) {", "\n }");+ assert.match(held, /continue;/);+ assert.doesNotMatch(+ held,+ /\(nextState as Record<ScalarSettingKey, unknown>\)\[key\] = value;/,+ "the server's value is applied over the held edit",+ );+});++test("every snapshot write is ordered against the others", () => {+ // Aborting a fetch does not stop a handler the server has already started, so the+ // ordering is enforced server-side and each write has to carry its stamp.+ assert.match(store, /function nextThreadSettingsSeq\(\): number \{/);+ const write = slice(store, "function writeThreadScopedSettings", "\n}");+ assert.match(write, /const settingsSeq = nextThreadSettingsSeq\(\);/);+ assert.match(write, /\{ settings, settingsSeq, settingsWriter/);+ const beacon = slice(store, "function sendThreadScopedSettingsBeacon", "\n}");+ assert.match(beacon, /settingsSeq: nextThreadSettingsSeq\(\)/);+ // the beacon also stands down anything queued and cancels anything already out+ assert.match(beacon, /takeThreadSettingsWriteTicket\(threadId\)/);+ assert.match(beacon, /threadSettingsWriteAborts\.get\(threadId\)\?\.abort\(\)/);+});++test("a normal flush stays resendable until it lands", () => {+ // visibilitychange(hidden) then pagehide: the first flushes normally and clears the+ // pending snapshot, so the terminal event would find nothing to beacon.+ const flush = slice(store, "function flushThreadScopedSettingsWrite", "\n}");+ assert.match(flush, /trackUnsettledThreadSettingsWrite\(threadId, snapshot\)/);+ const track = slice(store, "function trackUnsettledThreadSettingsWrite", "\n}");+ assert.match(track, /unsettledThreadSettingsWrites\.set\(threadId, entry\)/);+ const terminal = slice(store, "function flushSettingsOnPageHidden", "\n}");+ assert.match(terminal, /commitHeldThreadScopedEditsToTheirThread\(true\)/);+ assert.match(terminal, /beaconUnsettledThreadSettingsWrites\(sentNewest\)/);+});++test("a capability clamp never overwrites the preference the chat stored", () => {+ // The clamp is the model's, not the user's. All four pills chat-page clamps go through+ // the same preservation, under each pill's own capability rule.+ const build = slice(store, "function buildThreadScopedSnapshot", "\n}");+ for (const key of [+ "toolsEnabled",+ "codeToolsEnabled",+ "imageToolsEnabled",+ "webFetchToolsEnabled",+ ]) {+ assert.ok(+ store.includes(`"${key}"`) && build.includes("CLAMPED_PILL_KEYS"),+ `${key} is not covered by the clamp preservation`,+ );+ }+ assert.match(build, /modelLoaded &&\s*!capable\[key\] &&/);+});++test("write ordering is per writer, never one browser's counter against another's", () => {+ // Comparing unrelated clients means whichever is behind has every edit refused while+ // the server still answers 200, so the user is told it saved and it did not.+ assert.match(store, /const threadSettingsWriter = crypto\.randomUUID\(\);/);+ const next = slice(store, "function nextThreadSettingsSeq", "\n}");+ assert.doesNotMatch(next, /Date\.now\(\)/, "the seq is a clock again");+ // every write says who it came from, or the server cannot scope the comparison+ for (const site of [+ slice(store, "function sendThreadScopedSettingsBeacon", "\n}"),+ slice(store, "function writeThreadScopedSettings", "\n}"),+ slice(store, "async function mergeThreadScopedSettingsIntoRow", "\n}"),+ ]) {+ assert.match(site, /settingsWriter/);+ }+});++test("a tab-close write that could not be confirmed is replayed next session", () => {+ // A chat whose row is still being created answers 404, and the creation that follows+ // knows nothing about the edit.+ const beacon = slice(store, "function sendThreadScopedSettingsBeacon", "\n}");+ assert.match(beacon, /rememberThreadSettingsForReplay\(threadId, body\)/);+ assert.match(store, /export function replayUnconfirmedThreadSettings/);+ // and something actually calls it on the way back in+ assert.match(store, /replayUnconfirmedThreadSettings\(\);/);+});++test("a model that forces thinking on does not erase a chat's stored preference", () => {+ const build = slice(store, "function buildThreadScopedSnapshot", "\n}");+ assert.match(build, /activeThreadScopedSettings\?\.reasoningEnabled === false/);+ assert.match(build, /reasoningAlwaysOn/);+});++test("compare mode drops the thread-scoped state rather than keeping the last chat's", () => {+ // One composer, two threads: no single snapshot applies, and leaving the module+ // pointing at the last single chat lets a model load read its pills back.+ const disabled = slice(+ provider,+ "// Compare panes share one composer",+ "return;",+ );+ assert.match(disabled, /applyThreadScopedSettings\(null, null\)/);+});++test("a retry does not resample the defaults over the edit it is holding", () => {+ // retryThreadRead commits and re-pairs with the edited value still in the store, so+ // sampling per attempt would take that edit for the installation default.+ const begin = slice(store, "export function beginThreadScopedPairing", "\n}");+ assert.match(begin, /if \(pairingWindowDefaultsThreadId !== threadId\) \{/);+ // and the sample is let go once the window closes, or the next visit reuses it+ assert.match(+ slice(store, "applyThreadScopedSettings: (threadId, settings) =>", "} else if ("),+ /pairingWindowDefaultsThreadId = null;/,+ );+});++test("a pending pin answers the override rather than the null it has stored", () => {+ // A chat being pinned has no snapshot yet, so falling through reads null and a model+ // load puts the global values back over the edit the queued write will persist.+ const override = slice(store, "export function threadScopedOverride", "\n}");+ assert.match(override, /threadSettingsWriteSnapshot\[key\] !== undefined/);+});++test("the prompt queue waits for this chat's settings too, not just a direct send", () => {+ // handleSubmit reaches the queue branch first, and the queued prompt is snapshotted+ // from whatever the store shows at that moment.+ const submit = slice(+ composer,+ "const handleSubmit = useCallback(",+ "startHydratedPromptQueue(",+ );+ assert.match(submit, /threadScopedSettingsPending && !overlay/);+});++test("the defaults sample is never taken from the outgoing chat's values", () => {+ // Switching A -> B, the store still holds A's pills when B's pairing opens, so+ // sampling it would make A's choices the default every snapshot-less chat follows.+ const begin = slice(store, "export function beginThreadScopedPairing", "\n}");+ assert.match(+ begin,+ /threadScopedSettingsThreadId === null\s*\?\s*readThreadScopedSettings\(/,+ );+ assert.match(begin, /:\s*globalThreadScopedDefaults;/);+});++test("the read that gates sends cannot hang forever", () => {+ // The underlying GET has no timeout, and neither the catch nor the retry budget can+ // run for a promise that never settles, so every send stays parked.+ const sync = slice(provider, "const sync = () => {", "// The read did not answer");+ assert.match(sync, /Promise\.race\(\[/);+ assert.match(sync, /THREAD_READ_TIMEOUT_MS/);+});++test("every run waits for the chat's settings, not just the composer", () => {+ // Reload, Continue and send-from-edit never touch handleSubmit; they all reach the+ // adapter, so the wait belongs there.+ const adapter = read("../src/features/chat/api/chat-adapter.ts");+ const run = slice(adapter, "await useChatRuntimeStore.getState().hydratePersistedSettings();", "let runtime =");+ assert.match(run, /await awaitThreadScopedPairing\(runThreadId\)/);+});++test("a replay entry survives a failed replay", () => {+ // authFetch resolves for 404 and 5xx, and the missing-row case this exists for is+ // exactly the one that 404s.+ const replay = slice(store, "export function replayUnconfirmedThreadSettings", "\n}");+ assert.match(replay, /if \(res\.ok\) forgetReplayedThreadSettings\(threadId, body\)/);+ assert.doesNotMatch(+ replay,+ /localStorage\.removeItem\(THREAD_SETTINGS_REPLAY_KEY\);\n if \(!raw\)/,+ "the whole batch is still dropped before it is known to have landed",+ );+});++test("a debounce-fired write is resendable on a terminal event too", () => {+ // Once the timer fires there is no pending debounce left to find, so the in-flight+ // request is the only copy and teardown cancels it.+ const schedule = slice(store, "function scheduleThreadScopedSettingsWrite", "\n}");+ assert.match(schedule, /trackUnsettledThreadSettingsWrite\(pendingThreadId, pendingSnapshot\)/);+});++test("forking settles a held edit, not just the debounce", () => {+ const composerSrc = composer;+ assert.match(composerSrc, /await settleThreadScopedSettingsForCopy\(remoteId\)/);+ const settle = slice(store, "export async function settleThreadScopedSettingsForCopy", "\n}");+ assert.match(settle, /commitHeldThreadScopedEditsToTheirThread\(\)/);+ // and the pairing's own wait must NOT commit, or sync closes the window it just opened+ const await_ = slice(store, "export async function awaitThreadScopedSettingsWrite", "\n}");+ assert.doesNotMatch(await_, /commitHeldThreadScopedEditsToTheirThread/);+});++test("the run's wait is bound to the run's own chat", () => {+ // One promise for all chats meant a run for A was released by B's pairing ending, and+ // then read B's settings for A's run.+ const wait = slice(store, "export function awaitThreadScopedPairing", "\n}");+ assert.match(wait, /threadId: string \| null \| undefined/);+ assert.match(wait, /pairingSettledByThreadId\.get\(threadId\)/);+ const adapter = read("../src/features/chat/api/chat-adapter.ts");+ assert.match(adapter, /await awaitThreadScopedPairing\(runThreadId\)/);+});++test("two unsettled writes for one chat do not cancel each other's tracking", () => {+ // Both ordinary edits carry a null snapshot, so comparing by value let the first+ // request's settle delete the second's entry.+ const track = slice(store, "function trackUnsettledThreadSettingsWrite", "\n}");+ assert.match(track, /const entry: UnsettledThreadSettingsWrite = \{ snapshot \}/);+ assert.match(track, /unsettledThreadSettingsWrites\.get\(threadId\) === entry/);+});++test("a terminal event does not send a stale snapshot after the newest one", () => {+ // Each beacon takes a higher seq than the last, so re-sending an older unsettled+ // snapshot for a chat already flushed would make the stale one win.+ const terminal = slice(store, "function flushSettingsOnPageHidden", "\n}");+ assert.match(terminal, /const sentNewest = new Set<string>\(\)/);+ assert.match(terminal, /beaconUnsettledThreadSettingsWrites\(sentNewest\)/);+ const beacon = slice(store, "function beaconUnsettledThreadSettingsWrites", "\n}");+ assert.match(beacon, /if \(alreadySent\.has\(threadId\)\) continue;/);+});++test("last session's replay is ordered before this session's writes", () => {+ // The replay carries the previous session's writer id, so nothing on the server+ // orders it against an edit made now; on a slow link it can land second and revert it.+ assert.match(store, /let threadSettingsReplaySettled: Promise<void>/);+ const write = slice(store, "function writeThreadScopedSettings", "\n}");+ assert.match(write, /\.then\(\(\) => threadSettingsReplaySettled\)/);+});++test("a retry keeps the defaults snapshot it already took", () => {+ // retryThreadRead commits and re-pairs the same chat, so clearing the id here would+ // let the retry resample the store, which by then holds the held edit.+ const commit = slice(+ store,+ "export function commitHeldThreadScopedEditsToTheirThread",+ "\n}",+ );+ assert.doesNotMatch(commit, /pairingWindowDefaultsThreadId = null;/);+});++test("an explicit clear beats a capability preservation", () => {+ // Enabling Search clears Deep Research deliberately; restoring the stored true would+ // bring it back, alongside Search, once the chat is on a local model again.+ const build = slice(store, "function buildThreadScopedSnapshot", "\n}");+ assert.match(build, /!explicitlyEditedThreadFields\.has\("deepResearchEnabled"\)/);+ const capture = slice(store, "function captureThreadScopedEdit", "\n}");+ assert.match(capture, /explicitlyEditedThreadFields\.add\(field\)/);+});++test("the thread read that gates sends aborts when it times out", () => {+ // `bounded` alone is the 30s WRITE timeout, so the losing side of the race below stayed+ // open while the retry opened the next one. Each attempt carries its own deadline.+ const sync = slice(provider, "const sync = () => {", "// The read did not answer");+ assert.match(sync, /timeoutMs: THREAD_READ_TIMEOUT_MS/);+ assert.match(sync, /signal: read\.signal/);+});++test("a read nobody is waiting for any more is cancelled", () => {+ const effect = slice(provider, "const reads = new Set<AbortController>();", "\n }, [activeThreadId");+ assert.match(effect, /abortReads\(\);/);+ const api = read("../src/features/chat/api/chat-api.ts");+ const get = slice(api, "export async function getChatThread", "\n}");+ assert.match(get, /options\.timeoutMs !== undefined/);+ assert.match(get, /combineAbortSignals\(\[timeout\.signal, options\.signal\]\)/);+});++test("the ensure step in front of a settings write is bounded too", () => {+ // It runs BEFORE the write, so neither the caller's signal nor the write timeout+ // reaches it, and a stall there leaves the whole per-thread chain pending.+ const storage = read("../src/features/chat/utils/chat-history-storage.ts");+ const update = slice(storage, "export async function updateStoredChatThread", "\n}");+ assert.match(update, /ensureStoredChatThread\(threadId, undefined, \{/);+ assert.match(update, /bounded: true/);+ assert.match(update, /signal: options\.signal/);+});++test("a tab-close snapshot is replayed even if global settings fail to hydrate", () => {+ const hydrate = slice(store, "hydratePersistedSettings: async () => {", "beginModelLoading");+ const catchArm = slice(hydrate, "} catch {", "settingsHydrationPromise = null;");+ assert.match(catchArm, /replayUnconfirmedThreadSettings\(\);/);+ // and it must not then run twice+ const replay = slice(store, "export function replayUnconfirmedThreadSettings", "\n}");+ assert.match(replay, /if \(threadSettingsReplayStarted\) return;/);+});++test("a default hydration had to skip is not restored from the pre-hydration copy", () => {+ // The held edit belongs to the chat; when its window closes the installation default+ // goes back to a value, and the server's is the authoritative one.+ assert.match(store, /const hydratedDefaultsByHeldField = new Map<string, unknown>\(\);/);+ const loop = slice(store, "for (const key of SCALAR_SETTING_KEYS) {", "return nextState;");+ assert.match(loop, /hydratedDefaultsByHeldField\.set\(key, value\)/);+ const restore = slice(store, "const beforeWindow = (pairingWindowDefaults ??", "globalThreadScopedDefaults = captured");+ assert.match(restore, /hydratedDefaultsByHeldField\.has\(field\)/);+ assert.ok(+ restore.indexOf("hydratedDefaultsByHeldField.has(field)") <+ restore.indexOf("field in beforeWindow"),+ "the pre-window copy still wins over the server's value",+ );+ const release = slice(store, "export function releaseHeldThreadScopedEdits", "\n}");+ assert.match(release, /hydratedDefaultsByHeldField\.delete\(edit\.field\)/);+});++test("one chat's pairing ending does not release another chat's run", () => {+ // Holding the promises per chat is pointless if every settle resolves all of them,+ // which is what the first attempt at this did.+ const close = slice(store, "function closeThreadScopedPairingGate", "\n}");+ assert.match(close, /pairingSettledByThreadId\.get\(threadId\)\?\.resolve\(\)/);+ assert.doesNotMatch(+ close,+ /for \(const \{ resolve \} of pairingSettledByThreadId\.values\(\)\) resolve\(\)/,+ "every gate is still released at once",+ );+ // leaving mid-read must NOT open the gate: that chat's snapshot never arrived+ const commit = slice(+ store,+ "export function commitHeldThreadScopedEditsToTheirThread",+ "\n}",+ );+ assert.match(commit, /closeThreadScopedPairingGate\(null\)/);+});++test("a run cannot wait on a gate that will never open", () => {+ const wait = slice(store, "export function awaitThreadScopedPairing", "\n}");+ assert.match(wait, /Promise\.race\(\[/);+ assert.match(wait, /THREAD_PAIRING_WAIT_MS/);+});++test("a write that lands clears the replay entry it would otherwise be reverted by", () => {+ // The replay carries the previous session's writer id, so the server will apply it+ // whenever it arrives, including over an edit made since.+ const write = slice(store, "function writeThreadScopedSettings", "\n}");+ assert.match(write, /forgetReplayedThreadSettings\(threadId\)/);+});++test("a failed write stays tracked for the terminal beacon", () => {+ const track = slice(store, "function trackUnsettledThreadSettingsWrite", "\n}");+ assert.match(track, /\.then\(\(landed\) =>/);+ assert.match(track, /if \(landed &&/);+});++test("the replay cannot block the session's writes forever", () => {+ const replay = slice(store, "export function replayUnconfirmedThreadSettings", "\n}");+ assert.match(replay, /THREAD_SETTINGS_REPLAY_TIMEOUT_MS/);+ assert.match(replay, /signal: timeout\.signal/);+});++test("a fork stops when the chat's settings could not be saved", () => {+ const merge = slice(store, "async function mergeThreadScopedSettingsIntoRow", "\n}");+ assert.match(merge, /throw error;/);+ assert.match(composer, /Could not fork this chat/);+});++test("an unsaved chat's edit reaches the installation defaults without a round trip", () => {+ // assistant-ui gives an unsaved thread a `__LOCALID_` id (RemoteThreadListThreadList+ // RuntimeCore), which no row can exist for, so its read can only 404. Holding edits+ // behind that certain-to-fail read is what stopped a pill clicked on a fresh /chat+ // from reaching localStorage straight away, which playwright_chat_ui asserts.+ const effect = slice(+ provider,+ "const { applyThreadScopedSettings } = useChatRuntimeStore.getState();",+ "if (!enabled) {",+ );+ assert.match(effect, /isAssistantLocalThreadId\(activeThreadId\)/);+ assert.match(effect, /applyThreadScopedSettings\(null, null\)/);+});++test("a run whose pairing never settled is refused, not run on another chat's settings", () => {+ // The wait only runs out for a chat left mid-read, whose gate is held shut on purpose;+ // by then the store describes whatever chat the user moved to.+ const wait = slice(store, "export function awaitThreadScopedPairing", "\n}");+ assert.match(wait, /Promise<boolean>/);+ assert.match(wait, /resolve\(false\)/);+ const adapter = read("../src/features/chat/api/chat-adapter.ts");+ assert.match(adapter, /if \(!\(await awaitThreadScopedPairing\(runThreadId\)\)\) \{/);+ assert.match(adapter, /the message was not sent/);+});++test("the pairing wait outlasts the read it is waiting for", () => {+ // Shorter than the read's own budget and an ordinary slow read would fail the send.+ const waitMs = /THREAD_PAIRING_WAIT_MS = ([\d_]+)/.exec(store);+ assert.ok(waitMs, "no pairing wait constant");+ const pairing = Number(waitMs[1].replace(/_/g, ""));+ const readMs = /THREAD_READ_TIMEOUT_MS = ([\d_]+)/.exec(provider);+ const retries = /THREAD_READ_RETRIES = (\d+)/.exec(provider);+ const gap = /THREAD_READ_RETRY_MS = ([\d_]+)/.exec(provider);+ assert.ok(readMs && retries && gap, "no read budget constants");+ const budget =+ (Number(retries[1]) + 1) * Number(readMs[1].replace(/_/g, "")) ++ Number(retries[1]) * Number(gap[1].replace(/_/g, ""));+ assert.ok(+ pairing > budget,+ `pairing wait ${pairing}ms does not outlast the read budget ${budget}ms`,+ );+});++test("a fork does not copy a row whose edit failed to reach it", () => {+ // The replacement write reports failure by resolving false, so awaiting the chain+ // alone cannot tell a saved edit from a lost one.+ const await_ = slice(store, "export async function awaitThreadScopedSettingsWrite", "\n}");+ assert.match(await_, /Promise<boolean>/);+ assert.match(await_, /landed !== false/);+ const settle = slice(store, "export async function settleThreadScopedSettingsForCopy", "\n}");+ assert.match(settle, /if \(!\(await awaitThreadScopedSettingsWrite\(threadId\)\)\) \{/);+ assert.match(settle, /throw new Error/);+});++test("a replay only clears the body it actually sent", () => {+ // A terminal event in this session can store a newer body for the same thread while+ // an older replay is still out; that newer one is unconfirmed by definition.+ const replay = slice(store, "export function replayUnconfirmedThreadSettings", "\n}");+ assert.match(replay, /forgetReplayedThreadSettings\(threadId, body\)/);+ const forget = slice(store, "function forgetReplayedThreadSettings", "\n}");+ assert.match(forget, /JSON\.stringify\(pending\[threadId\]\) !== JSON\.stringify\(expected\)/);+});++test("a provider constraint does not rewrite what the chat stored", () => {+ // Kimi's builtin search may not run with thinking, so the composer moves the other+ // pill with { persist: false } -- which bypasses the capture path on purpose. That+ // value is the provider's, not the user's, and the next snapshot must not save it.+ assert.match(store, /const constraintSuppressedThreadFields = new Set<string>\(\);/);+ const reasoning = slice(store, "setReasoningEnabled: (reasoningEnabled, options)", "\n }),");+ assert.match(reasoning, /noteConstraintSuppressedThreadField\("reasoningEnabled"\)/);+ const tools = slice(store, "setToolsEnabled: (toolsEnabled, options)", "\n }),");+ assert.match(tools, /noteConstraintSuppressedThreadField\("toolsEnabled"\)/);+ const build = slice(store, "function buildThreadScopedSnapshot", "\nconst THREAD_SETTINGS_REPLAY_KEY");+ assert.match(build, /keepsStoredValueUnderConstraint\("reasoningEnabled", threadId, settings\)/);+ assert.match(build, /keepsStoredValueUnderConstraint\("toolsEnabled", threadId, settings\)/);+ // but a choice the user makes themselves still wins, and the flag is the open chat's+ const keeps = slice(store, "function keepsStoredValueUnderConstraint", "\n}");+ assert.match(keeps, /!explicitlyEditedThreadFields\.has\(key\)/);+ const capture = slice(store, "function captureThreadScopedEdit", "\n}");+ assert.match(capture, /constraintSuppressedThreadFields\.delete\(field\)/);+ assert.match(store, /constraintSuppressedThreadFields\.clear\(\);/);+});diff --git a/studio/frontend/tests/thread-scoped-settings.test.ts b/studio/frontend/tests/thread-scoped-settings.test.tsnew file mode 100644index 00000000000..2f2d8a292a4--- /dev/null+++ b/studio/frontend/tests/thread-scoped-settings.test.ts@@ -0,0 +1,137 @@+// 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 snapshot goes out on PATCH /api/chat/threads/{id}, whose model is extra="forbid" with+// literal and range constraints. These pin what the client may send, and what may be per-chat.++import assert from "node:assert/strict";+import test from "node:test";++import {+ THREAD_SCOPED_SETTING_KEYS,+ hasThreadScopedSettings,+ isThreadOwnedSettingKey,+ isThreadScopedSettingKey,+ sanitizeThreadScopedSettings,+} from "../src/features/chat/utils/thread-scoped-settings.ts";++test("a full snapshot survives the round trip", () => {+ const settings = sanitizeThreadScopedSettings({+ reasoningEnabled: true,+ reasoningEffort: "high",+ toolsEnabled: true,+ codeToolsEnabled: false,+ imageToolsEnabled: false,+ webFetchToolsEnabled: true,+ deepResearchEnabled: false,+ artifactsEnabled: true,+ mcpEnabledForChat: false,+ permissionMode: "auto",+ ragEnabled: true,+ ragSource: { type: "kb", kbId: "notes" },+ ragMode: "dense",+ ragTopK: 12,+ ragAutoInject: "on",+ ragAutoInjectMinScore: 0.42,+ });++ assert.deepEqual(settings, {+ reasoningEnabled: true,+ reasoningEffort: "high",+ toolsEnabled: true,+ codeToolsEnabled: false,+ imageToolsEnabled: false,+ webFetchToolsEnabled: true,+ deepResearchEnabled: false,+ artifactsEnabled: true,+ mcpEnabledForChat: false,+ permissionMode: "auto",+ ragEnabled: true,+ ragSource: { type: "kb", kbId: "notes" },+ ragMode: "dense",+ ragTopK: 12,+ ragAutoInject: "on",+ ragAutoInjectMinScore: 0.42,+ });+});++test("full access is dropped rather than stored on the thread", () => {+ // it disables the sandbox, so it is re-accepted through the warning dialog each session.+ assert.deepEqual(+ sanitizeThreadScopedSettings({ permissionMode: "full" }),+ {},+ );+});++test("out-of-contract values are dropped", () => {+ assert.deepEqual(+ sanitizeThreadScopedSettings({+ toolsEnabled: "yes",+ ragMode: "vector",+ ragTopK: 51,+ ragAutoInjectMinScore: 1.5,+ ragSource: { type: "kb" },+ reasoningEffort: "extreme",+ }),+ {},+ );+});++test("settings that describe the installation stay out of the snapshot", () => {+ // these belong to the install, so a chat must not start pinning its own copy of them.+ for (const key of [+ "showCanvasMenuItem",+ "collapseHtmlArtifacts",+ "allowArtifactNetworkAccess",+ "ragOcrScanned",+ "ragCaptionFigures",+ "researchWebsitePolicy",+ "speculativeType",+ "gpuMemoryMode",+ "expandQuantizations",+ "showAllQuantizations",+ "fitOnDeviceOnly",+ "autoTitle",+ ]) {+ assert.equal(isThreadScopedSettingKey(key), false, key);+ }+ assert.deepEqual(+ sanitizeThreadScopedSettings({+ gpuMemoryMode: "manual",+ showCanvasMenuItem: true,+ ragOcrScanned: true,+ }),+ {},+ );+});++test("every thread-scoped key is recognised and non-object input is safe", () => {+ for (const key of THREAD_SCOPED_SETTING_KEYS) {+ assert.equal(isThreadScopedSettingKey(key), true, key);+ }+ assert.deepEqual(sanitizeThreadScopedSettings(null), {});+ assert.deepEqual(sanitizeThreadScopedSettings("toolsEnabled"), {});+ assert.deepEqual(sanitizeThreadScopedSettings([1, 2]), {});+});++test("the legacy confirm toggle is owned by the chat but not stored on it", () => {+ // loadPermissionMode falls back to it, so a per-chat change that wrote it would go global.+ assert.equal(isThreadOwnedSettingKey("confirmToolCalls"), true);+ assert.equal(isThreadScopedSettingKey("confirmToolCalls"), false);+ assert.deepEqual(+ sanitizeThreadScopedSettings({ confirmToolCalls: true }),+ {},+ );+ for (const key of THREAD_SCOPED_SETTING_KEYS) {+ assert.equal(isThreadOwnedSettingKey(key), true, key);+ }+ assert.equal(isThreadOwnedSettingKey("gpuMemoryMode"), false);+});++test("an empty snapshot reads as no snapshot", () => {+ // a thread that stored nothing falls back to the installation settings, as chats did before.+ assert.equal(hasThreadScopedSettings(null), false);+ assert.equal(hasThreadScopedSettings(undefined), false);+ assert.equal(hasThreadScopedSettings({}), false);+ assert.equal(hasThreadScopedSettings({ toolsEnabled: false }), true);+});diff --git a/tests/studio/playwright_thread_scoped_settings.py b/tests/studio/playwright_thread_scoped_settings.pynew file mode 100644index 00000000000..05e702e6514--- /dev/null+++ b/tests/studio/playwright_thread_scoped_settings.py@@ -0,0 +1,456 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Per-chat settings: the composer pills and permission level follow the chat.++Drives two saved chats through the real UI and asserts each keeps its own modes across a+switch and a reload, that a chat's edits leave the installation defaults (and so every new+chat) alone, and that a chat which stored nothing still opens on those defaults.++Needs no model: with nothing loaded the Search and Code pills stay clickable, which is what+lets this run in seconds rather than behind a GGUF download.++ BASE_URL=http://127.0.0.1:18921 STUDIO_NEW_PW=... \+ python tests/studio/playwright_thread_scoped_settings.py+"""++import json+import os+import sys+import time+import uuid+from pathlib import Path++from playwright.sync_api import expect, sync_playwright++BASE = os.environ["BASE_URL"]+NEW = os.environ["STUDIO_NEW_PW"]+ART = Path(os.environ.get("PW_ART_DIR", "logs/playwright"))+ART.mkdir(parents = True, exist_ok = True)++TIMEOUT_MS = int(os.environ.get("STUDIO_UI_TIMEOUT_MS", "30000"))++# The installation-wide slots the per-chat edits below must not touch. The legacy confirm toggle+# is here on purpose: loadPermissionMode falls back to it, so writing it would leak globally.+GLOBAL_KEYS = (+ "unsloth_chat_tools_enabled",+ "unsloth_chat_code_tools_enabled",+ "unsloth_chat_permission_mode",+ "unsloth_chat_confirm_tool_calls",+)++_step = [0]+++def step(message):+ _step[0] += 1+ print(f"[thread-settings] STEP {_step[0]}: {message}", flush = True)+++def fail(message):+ print(f"[thread-settings] FAIL: {message}", flush = True)+ sys.exit(1)+++def shoot(page, name):+ try:+ page.screenshot(path = str(ART / f"thread-settings-{name}.png"), full_page = False)+ except Exception: # noqa: BLE001 - screenshots are diagnostics only+ pass+++def api(+ page,+ path,+ method = "GET",+ body = None,+ token = None,+):+ """Call the backend from the page so the request carries the session cookie."""+ result = page.evaluate(+ """async ([url, method, body, token]) => {+ const headers = { "Content-Type": "application/json" };+ if (token) headers.Authorization = `Bearer ${token}`;+ const response = await fetch(url, {+ method,+ headers,+ body: body === null ? undefined : JSON.stringify(body),+ });+ const text = await response.text();+ let parsed = null;+ try { parsed = JSON.parse(text); } catch { parsed = text; }+ return { status: response.status, body: parsed };+ }""",+ [f"{BASE}{path}", method, body, token],+ )+ if result["status"] >= 400:+ fail(f"{method} {path} returned {result['status']}: {result['body']!r}")+ return result["body"]+++def sign_in(page):+ step("sign in, then land on /chat")+ page.goto(f"{BASE}/change-password", wait_until = "domcontentloaded", timeout = 60_000)+ try:+ page.locator("#new-password").wait_for(state = "visible", timeout = 15_000)+ rotate = True+ except Exception: # noqa: BLE001 - a rerun against the same server is already rotated+ rotate = False+ if rotate:+ page.fill("#new-password", NEW, timeout = TIMEOUT_MS)+ page.fill("#confirm-password", NEW, timeout = TIMEOUT_MS)+ endpoint = "/api/auth/change-password"+ else:+ page.goto(f"{BASE}/login", wait_until = "domcontentloaded", timeout = 60_000)+ page.locator("#password").wait_for(state = "visible", timeout = 60_000)+ page.fill("#password", NEW, timeout = TIMEOUT_MS)+ endpoint = "/api/auth/login"+ with page.expect_response(+ lambda r: endpoint in r.url and r.request.method == "POST",+ timeout = TIMEOUT_MS,+ ) as response_info:+ page.locator('button[type="submit"]').click()+ if response_info.value.status >= 400:+ fail(f"POST {endpoint} returned {response_info.value.status}")+ page.goto(f"{BASE}/chat", wait_until = "domcontentloaded", timeout = 60_000)+ page.locator('button[data-pill-label="Search"]:visible').first.wait_for(+ state = "visible", timeout = 60_000+ )+ return page.evaluate("() => localStorage.getItem('unsloth_auth_token')")+++def seed_thread(page, token, title):+ """Create a saved chat with one message, the state the sidebar and the loader expect."""+ thread_id = str(uuid.uuid4())+ now = int(time.time() * 1000)+ api(+ page,+ "/api/chat/threads",+ method = "POST",+ token = token,+ body = {+ "id": thread_id,+ "title": title,+ "modelType": "base",+ "modelId": "",+ "archived": False,+ "createdAt": now,+ "updatedAt": now,+ },+ )+ api(+ page,+ f"/api/chat/threads/{thread_id}/messages",+ method = "PUT",+ token = token,+ body = {+ "messages": [+ {+ "id": str(uuid.uuid4()),+ "threadId": thread_id,+ "parentId": None,+ "role": "user",+ "content": [{"type": "text", "text": f"seed for {title}"}],+ "createdAt": now,+ }+ ]+ },+ )+ return thread_id+++def stored_settings(page, token, thread_id):+ return api(page, f"/api/chat/threads/{thread_id}", token = token).get("settings")+++def wait_for_stored_settings(page, token, thread_id, key, value):+ """Block until the debounced snapshot write for `thread_id` has landed."""+ deadline = time.monotonic() + 20+ while time.monotonic() < deadline:+ settings = stored_settings(page, token, thread_id)+ if settings and settings.get(key) == value:+ return settings+ page.wait_for_timeout(250)+ fail(f"{thread_id} never stored {key}={value!r}: {stored_settings(page, token, thread_id)!r}")+++def new_chat_in_page(page):+ """Start a new chat from the sidebar, which routes without reloading the document."""+ button = page.locator('[data-sidebar="menu-button"]').filter(has_text = "New Chat").first+ button.wait_for(state = "visible", timeout = TIMEOUT_MS)+ button.click()+ settle(page)+++def open_thread_in_page(page, title):+ """Switch chats the way a user does, without reloading the document."""+ entry = page.locator('[data-testid="recent-thread"]').filter(has_text = title).first+ entry.wait_for(state = "visible", timeout = TIMEOUT_MS)+ entry.click()+ settle(page)+++def open_thread(page, thread_id):+ page.goto(+ f"{BASE}/chat?thread={thread_id}",+ wait_until = "domcontentloaded",+ timeout = 60_000,+ )+ settle(page)+++def unload_any_model(page, token):+ """Leave no model loaded, so the capability-gated pills stay clickable.++ The Search and Code pills are disabled when a model is loaded that cannot run tools+ (`modelLoaded && !(supportsTools || supportsBuiltinWebSearch)`), and this file drives+ both. In CI an earlier step in the same job leaves a small GGUF resident, which has+ no tool support, so every pill click here would time out on a disabled button. With+ nothing loaded the pills are pre-selectable, which is the state this test is about.+ """+ status = page.evaluate(+ """async ({ base, token }) => {+ const res = await fetch(base + "/api/inference/status", {+ headers: { Authorization: "Bearer " + token },+ });+ if (!res.ok) return null;+ return await res.json();+ }""",+ {"base": BASE, "token": token},+ )+ status = status or {}+ loaded = status.get("model_identifier") or (status.get("loaded") or [None])[0]+ if not loaded:+ return+ print(+ f"[thread-settings] unloading {loaded!r} so the pills are not capability-gated", flush = True+ )+ page.evaluate(+ """async ({ base, token, modelPath }) => {+ await fetch(base + "/api/inference/unload", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ Authorization: "Bearer " + token,+ },+ body: JSON.stringify({ model_path: modelPath }),+ });+ }""",+ {"base": BASE, "token": token, "modelPath": loaded},+ )+ page.wait_for_timeout(1500)+++def settle(page):+ """Wait for the composer, then for the thread's snapshot to have been applied."""+ page.locator('button[data-pill-label="Search"]:visible').first.wait_for(+ state = "visible", timeout = TIMEOUT_MS+ )+ # the snapshot arrives on a GET, and the pin write is debounced behind it.+ page.wait_for_timeout(1200)+++def pill(page, label):+ return page.locator(f'button[data-pill-label="{label}"]:visible').first+++def permission_pill(page):+ return page.locator('button[aria-label="Permission level for tool calls"]:visible').first+++def choose_permission(page, label):+ permission_pill(page).click()+ menu = page.get_by_role("menu").last+ expect(menu).to_be_visible()+ menu.get_by_role("menuitem").filter(has_text = label).first.click()+ expect(permission_pill(page)).to_have_attribute("data-pill-label", label)+++def expect_pills(page, where, search, code, permission):+ for label, wanted in (("Search", search), ("Code", code)):+ expect(pill(page, label)).to_have_attribute(+ "data-active", "true" if wanted else "false", timeout = TIMEOUT_MS+ )+ expect(permission_pill(page)).to_have_attribute(+ "data-pill-label", permission, timeout = TIMEOUT_MS+ )+ print(+ f"[thread-settings] {where}: Search={search} Code={code} " f"permission={permission!r}",+ flush = True,+ )+++def read_globals(page):+ return page.evaluate(+ """(keys) => Object.fromEntries(keys.map((k) => [k, localStorage.getItem(k)]))""",+ list(GLOBAL_KEYS),+ )+++def main():+ with sync_playwright() as playwright:+ browser = playwright.chromium.launch(args = ["--no-sandbox", "--disable-dev-shm-usage"])+ context = browser.new_context(viewport = {"width": 1280, "height": 900})+ page = context.new_page()+ page.set_default_timeout(TIMEOUT_MS)+ page_errors = []+ page.on("pageerror", lambda e: page_errors.append(str(e)))++ token = sign_in(page)+ if not token:+ fail("no auth token in localStorage after change-password")+ unload_any_model(page, token)+ page.goto(f"{BASE}/chat", wait_until = "domcontentloaded", timeout = 60_000)++ step("an unsaved chat still edits the installation defaults")+ # plain /chat runs on a runtime-made thread id with no row: treating that as an open+ # chat would stop every toggle made before the first message from persisting at all.+ settle(page)+ pill(page, "Search").click()+ page.wait_for_timeout(600)+ enabled_globals = read_globals(page)+ if enabled_globals["unsloth_chat_tools_enabled"] != "true":+ fail(f"an unsaved chat's edit never reached the defaults: {enabled_globals!r}")+ pill(page, "Search").click()+ page.wait_for_timeout(600)+ disabled_globals = read_globals(page)+ if disabled_globals["unsloth_chat_tools_enabled"] != "false":+ fail(f"toggling back never reached the defaults: {disabled_globals!r}")++ step("pin the installation default every later step compares against")+ # The install is shared, not fresh: the UI workflow boots this server on the same+ # Studio home the chat-ui and cross-browser permission tests have already used, and+ # those leave a permission level behind in the mirrored settings. Every assertion+ # below names a literal level, so the default is set here rather than assumed.+ # No chat is open, so this writes the installation default itself.+ choose_permission(page, "Approve for me")+ print(+ f"[thread-settings] defaults now {read_globals(page)!r}",+ flush = True,+ )++ step("seed two saved chats")+ thread_a = seed_thread(page, token, "Chat A")+ thread_b = seed_thread(page, token, "Chat B")+ print(f"[thread-settings] A={thread_a} B={thread_b}", flush = True)++ step("a chat with no snapshot of its own opens on those defaults")+ open_thread(page, thread_a)+ expect_pills(page, "A on first open", False, False, "Approve for me")+ defaults = read_globals(page)++ step("set Chat A to Search on, Ask for approval")+ pill(page, "Search").click()+ choose_permission(page, "Ask for approval")+ expect_pills(page, "A after editing", True, False, "Ask for approval")+ shoot(page, "01-chat-a-edited")+ wait_for_stored_settings(page, token, thread_a, "toolsEnabled", True)++ step("Chat A's edits leave the installation defaults alone")+ after_edit = read_globals(page)+ if after_edit != defaults:+ fail(+ "editing inside a chat moved the installation defaults: "+ f"{defaults!r} -> {after_edit!r}"+ )++ step("Chat B opens on the defaults, not on Chat A's modes")+ open_thread(page, thread_b)+ expect_pills(page, "B on first open", False, False, "Approve for me")++ step("set Chat B to Code on, Run automatically")+ pill(page, "Code").click()+ choose_permission(page, "Run automatically")+ expect_pills(page, "B after editing", False, True, "Run automatically")+ shoot(page, "02-chat-b-edited")+ wait_for_stored_settings(page, token, thread_b, "codeToolsEnabled", True)++ step("switching back to Chat A restores Chat A's own modes")+ open_thread(page, thread_a)+ expect_pills(page, "A after switching back", True, False, "Ask for approval")++ step("and they survive a full reload")+ page.reload(wait_until = "domcontentloaded")+ settle(page)+ expect_pills(page, "A after reload", True, False, "Ask for approval")+ shoot(page, "03-chat-a-after-reload")++ step("switching back to Chat B restores Chat B's own modes")+ open_thread(page, thread_b)+ expect_pills(page, "B after switching back", False, True, "Run automatically")++ step("and a sidebar switch, with no reload, does the same")+ # The reload-free path is the one users take, and the only one where the store still+ # holds the outgoing chat's values when the incoming snapshot is applied.+ open_thread_in_page(page, "Chat A")+ expect_pills(page, "A after an in-page switch", True, False, "Ask for approval")+ open_thread_in_page(page, "Chat B")+ expect_pills(page, "B after an in-page switch", False, True, "Run automatically")+ shoot(page, "03-in-page-switch")++ step("leaving a chat for a new one restores the installation defaults in place")+ # No reload here either, so the defaults have to come from the captured copy rather+ # than from the store being rebuilt out of localStorage.+ new_chat_in_page(page)+ expect_pills(page, "new chat after an in-page switch", False, False, "Approve for me")++ step("a new chat still starts from the installation defaults")+ page.goto(+ f"{BASE}/chat?new={uuid.uuid4()}",+ wait_until = "domcontentloaded",+ timeout = 60_000,+ )+ settle(page)+ expect_pills(page, "new chat", False, False, "Approve for me")+ shoot(page, "04-new-chat")+ if read_globals(page) != defaults:+ fail("the installation defaults changed at some point during the run")++ step("a chat edited before it had modes of its own keeps the new defaults")+ # no chat is open, so this moves the defaults every snapshot-less chat follows.+ pill(page, "Search").click()+ page.wait_for_timeout(600)+ moved = read_globals(page)+ if moved["unsloth_chat_tools_enabled"] != "true":+ fail(f"a new-chat edit did not reach the defaults: {moved!r}")+ thread_c = seed_thread(page, token, "Chat C")+ open_thread(page, thread_c)+ expect_pills(page, "C on first open", True, False, "Approve for me")++ step("the pinned snapshots reached the backend")+ stored = {+ "A": api(page, f"/api/chat/threads/{thread_a}", token = token).get("settings"),+ "B": api(page, f"/api/chat/threads/{thread_b}", token = token).get("settings"),+ "C": api(page, f"/api/chat/threads/{thread_c}", token = token).get("settings"),+ }+ print(f"[thread-settings] stored={json.dumps(stored, sort_keys = True)}", flush = True)+ if not stored["A"] or stored["A"].get("toolsEnabled") is not True:+ fail(f"Chat A's snapshot did not persist: {stored['A']!r}")+ if stored["A"].get("permissionMode") != "ask":+ fail(f"Chat A stored the wrong permission level: {stored['A']!r}")+ if not stored["B"] or stored["B"].get("codeToolsEnabled") is not True:+ fail(f"Chat B's snapshot did not persist: {stored['B']!r}")+ if stored["B"].get("toolsEnabled") is not False:+ fail(f"Chat B inherited Chat A's Search pill: {stored['B']!r}")+ if stored["B"].get("permissionMode") != "off":+ fail(f"Chat B stored the wrong permission level: {stored['B']!r}")+ if not stored["C"]:+ fail("opening a chat did not pin the modes it was showing")++ step("the thread listing stays free of the snapshot")+ listing = api(page, "/api/chat/threads", token = token)+ for thread in listing.get("threads", []):+ if thread.get("settings") is not None:+ fail(f"thread listing carries a settings snapshot: {thread['id']}")++ if page_errors:+ fail(f"page errors during the run: {page_errors[:3]!r}")++ context.close()+ browser.close()++ print("[thread-settings] PASS", flush = True)+++if __name__ == "__main__":+ main()diff --git a/tests/studio/sim_thread_settings_portability.py b/tests/studio/sim_thread_settings_portability.pynew file mode 100644index 00000000000..7f27f01e8c1--- /dev/null+++ b/tests/studio/sim_thread_settings_portability.py@@ -0,0 +1,265 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Portability checks for the per-chat settings column.++`settings_json` is added to an existing `chat_threads` by an idempotent ALTER, and+every Studio install that upgrades runs it exactly once against a database it has+been writing to for months. The interesting differences between platforms are the+bundled SQLite, the filesystem and the path handling, none of which CI exercises+today: the chat settings tests only ever run on Linux.++Everything here is stdlib plus `storage.studio_db`, so it runs unchanged on+Windows, macOS and Linux.++ python tests/studio/sim_thread_settings_portability.py+"""++import json+import os+import platform+import sqlite3+import sys+import tempfile+import time+import uuid+from pathlib import Path++REPO = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(REPO / "studio" / "backend"))++FAILURES = []+CHECKS = 0+++def check(+ name,+ ok,+ detail = "",+):+ global CHECKS+ CHECKS += 1+ if not ok:+ FAILURES.append(name)+ print(f" [{'PASS' if ok else 'FAIL'}] {name}" + (f" {detail}" if detail else ""), flush = True)+++def fresh_home():+ """A Studio home under a real temp dir, so path handling is the platform's own."""+ home = Path(tempfile.mkdtemp(prefix = "sim8686_"))+ os.environ["UNSLOTH_STUDIO_HOME"] = str(home)+ return home+++def thread_row(title, **extra):+ now = int(time.time() * 1000)+ row = {+ "id": str(uuid.uuid4()),+ "title": title,+ "modelType": "base",+ "modelId": "",+ "archived": False,+ "createdAt": now,+ "updatedAt": now,+ }+ row.update(extra)+ return row+++def main():+ # The Windows console is cp1252 by default, so printing a kbId containing+ # emoji raises UnicodeEncodeError and fails the run for a reason that has+ # nothing to do with what is being tested.+ for stream in (sys.stdout, sys.stderr):+ try:+ stream.reconfigure(encoding = "utf-8", errors = "replace")+ except (AttributeError, ValueError): # pragma: no cover - older stream types+ pass+ print(f"platform : {platform.system()} {platform.release()} ({platform.machine()})")+ print(f"python : {sys.version.split()[0]}")+ print(f"sqlite3 : {sqlite3.sqlite_version}")+ print()++ # ALTER TABLE ADD COLUMN is SQLite 3.2.0 (2005) and COALESCE predates it, so the+ # floor is far below anything shipping today. Assert it rather than assume it.+ major, minor, _ = (int(p) for p in sqlite3.sqlite_version.split("."))+ check(+ "sqlite supports ALTER TABLE ADD COLUMN (>= 3.2)",+ (major, minor) >= (3, 2),+ f"found {sqlite3.sqlite_version}",+ )+ # UPSERT (ON CONFLICT DO UPDATE), which the thread writer uses, needs 3.24.+ check(+ "sqlite supports UPSERT (>= 3.24)",+ (major, minor) >= (3, 24),+ f"found {sqlite3.sqlite_version}",+ )++ print("\n--- upgrade: a database created before the column ---")+ home = fresh_home()+ import storage.studio_db as db # noqa: E402 - after UNSLOTH_STUDIO_HOME is set++ # Build the database with the real schema, populate it the way a months-old+ # install would be, then DROP the new column. Hand-writing the old CREATE TABLE+ # drifts from the real one (it is missing pair_id and everything else the schema+ # step indexes), so this is both more faithful and self-maintaining.+ legacy_ids = []+ for i in range(200):+ row = thread_row(f"legacy {i}")+ db.upsert_chat_thread(row)+ legacy_ids.append(row["id"])+ db_path = Path(db.get_db_path()) if hasattr(db, "get_db_path") else home / "studio.db"++ conn = sqlite3.connect(str(db_path))+ try:+ conn.execute("ALTER TABLE chat_threads DROP COLUMN settings_json")+ conn.commit()+ dropped = True+ except sqlite3.OperationalError as exc:+ # DROP COLUMN is 3.35+. Older SQLite needs the copy-and-rename dance.+ print(f" (DROP COLUMN unavailable: {exc}; rebuilding the table instead)")+ cols = [+ r[1] for r in conn.execute("PRAGMA table_info(chat_threads)") if r[1] != "settings_json"+ ]+ joined = ", ".join(cols)+ conn.executescript(+ f"""CREATE TABLE chat_threads_old AS SELECT {joined} FROM chat_threads;+ DROP TABLE chat_threads;+ ALTER TABLE chat_threads_old RENAME TO chat_threads;"""+ )+ conn.commit()+ dropped = True+ cols = {r[1] for r in conn.execute("PRAGMA table_info(chat_threads)")}+ conn.close()+ check(+ "the fixture really predates the column",+ dropped and "settings_json" not in cols,+ f"columns={len(cols)}",+ )++ db._schema_ready = False # force the migration to run against what we just built+ got = db.get_chat_thread(legacy_ids[0])+ check(+ "a pre-existing thread still reads after the migration",+ got is not None,+ f"title={got.get('title') if got else None!r}",+ )+ check(+ "its settings are absent, not invented",+ got is not None and got.get("settings") in (None, {}),+ f"settings={got.get('settings') if got else None!r}",+ )+ conn = sqlite3.connect(str(db_path))+ cols = {r[1] for r in conn.execute("PRAGMA table_info(chat_threads)")}+ count = conn.execute("SELECT COUNT(*) FROM chat_threads").fetchone()[0]+ conn.close()+ check("the column was added", "settings_json" in cols)+ check("all 200 pre-existing rows survived", count == 200, f"count={count}")++ print("\n--- the migration is idempotent ---")+ for _ in range(3):+ db._schema_ready = False+ db.get_chat_thread(legacy_ids[1])+ check("running the schema step repeatedly is safe", True)++ print("\n--- round trip, including content platforms disagree about ---")+ payloads = {+ "plain": {"toolsEnabled": True, "permissionMode": "ask"},+ "unicode": {"ragSource": {"type": "kb", "kbId": "文書 kb"}},+ "emoji": {"ragSource": {"type": "kb", "kbId": "notes 🧠 v2"}},+ "windows path shaped": {"ragSource": {"type": "kb", "kbId": r"C:\Users\a\kb"}},+ "newlines": {"ragSource": {"type": "kb", "kbId": "a\r\nb"}},+ "float": {"ragAutoInjectMinScore": 0.7},+ "bounds": {"ragTopK": 50},+ "empty": {},+ }+ for name, payload in payloads.items():+ row = thread_row(f"rt {name}")+ db.upsert_chat_thread(row)+ db.update_chat_thread(row["id"], {"settings": payload})+ back = db.get_chat_thread(row["id"]).get("settings")+ if payload == {}:+ check(f"round trip: {name}", back in ({}, None), f"got {back!r}")+ else:+ check(f"round trip: {name}", back == payload, f"got {back!r}")++ print("\n--- a large blob ---")+ row = thread_row("big")+ db.upsert_chat_thread(row)+ big = {"ragSource": {"type": "kb", "kbId": "x" * 200}}+ db.update_chat_thread(row["id"], {"settings": big})+ check("a 200 char kbId round trips", db.get_chat_thread(row["id"]).get("settings") == big)++ print("\n--- the writers that rebuild a row must not clear the snapshot ---")+ row = thread_row("coalesce")+ db.upsert_chat_thread(row)+ db.update_chat_thread(row["id"], {"settings": {"toolsEnabled": True}})+ renamed = dict(row)+ renamed["title"] = "renamed by an autosave"+ db.upsert_chat_thread(renamed)+ after = db.get_chat_thread(row["id"])+ check(+ "a title rewrite leaves the snapshot alone",+ after.get("settings") == {"toolsEnabled": True},+ f"got {after.get('settings')!r}",+ )+ check("and the rewrite did land", after.get("title") == "renamed by an autosave")++ print("\n--- explicit clears ---")+ db.update_chat_thread(row["id"], {"settings": None})+ check(+ "PATCH settings=null clears the column",+ db.get_chat_thread(row["id"]).get("settings") in (None, {}),+ )++ print("\n--- the listing stays free of snapshots ---")+ row = thread_row("listed")+ db.upsert_chat_thread(row)+ db.update_chat_thread(row["id"], {"settings": {"toolsEnabled": True}})+ listed = db.list_chat_threads()+ entries = [t for t in listed if t.get("id") == row["id"]]+ check("the thread is listed", len(entries) == 1)+ check(+ "but carries no snapshot in the listing",+ bool(entries) and not entries[0].get("settings"),+ f"got {entries[0].get('settings') if entries else None!r}",+ )++ print("\n--- corrupt content degrades instead of exploding ---")+ row = thread_row("corrupt")+ db.upsert_chat_thread(row)+ conn = sqlite3.connect(str(db_path))+ conn.execute("UPDATE chat_threads SET settings_json = ? WHERE id = ?", ('{"nope', row["id"]))+ conn.commit()+ conn.close()+ try:+ got = db.get_chat_thread(row["id"])+ check(+ "unparseable JSON reads as no snapshot",+ got.get("settings") in (None, {}),+ f"got {got.get('settings')!r}",+ )+ except Exception as exc: # noqa: BLE001 - that would be the finding+ check("unparseable JSON reads as no snapshot", False, f"{type(exc).__name__}: {exc}")++ print("\n--- WAL, which is what a running Studio uses ---")+ conn = sqlite3.connect(str(db_path))+ mode = conn.execute("PRAGMA journal_mode").fetchone()[0]+ conn.close()+ row = thread_row("wal")+ db.upsert_chat_thread(row)+ db.update_chat_thread(row["id"], {"settings": {"codeToolsEnabled": True}})+ check(+ f"writes work under journal_mode={mode}",+ db.get_chat_thread(row["id"]).get("settings") == {"codeToolsEnabled": True},+ )++ print(f"\n{CHECKS - len(FAILURES)}/{CHECKS} passed")+ if FAILURES:+ print("FAILED: " + ", ".join(FAILURES))+ return 1+ return 0+++if __name__ == "__main__":+ sys.exit(main())