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
Persist chat pins across clients of the same Unsloth server (#15293)
Lee Jackson71dd6d20a5c2
diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.ymlindex 6c964f94a28..c8b61da8e71 100644--- a/.github/workflows/studio-frontend-ci.yml+++ b/.github/workflows/studio-frontend-ci.yml@@ -22,6 +22,9 @@ on:- 'tests/studio/playwright_chat_autoscroll.py'- 'tests/studio/playwright_research_freeze.py'- 'tests/studio/playwright_research_review.py'+ - 'tests/studio/playwright_pinned_chat_persistence.py'+ - 'studio/backend/routes/chat_history.py'+ - 'studio/backend/storage/studio_db.py'- 'tests/studio/playwright_heavy_thread.py'- 'tests/studio/probe_dismiss_guard.py'- 'tests/studio/playwright_nonmodal_menus.py'@@ -64,6 +67,9 @@ on:- 'tests/studio/playwright_chat_autoscroll.py'- 'tests/studio/playwright_research_freeze.py'- 'tests/studio/playwright_research_review.py'+ - 'tests/studio/playwright_pinned_chat_persistence.py'+ - 'studio/backend/routes/chat_history.py'+ - 'studio/backend/storage/studio_db.py'- 'tests/studio/playwright_heavy_thread.py'- 'tests/studio/probe_dismiss_guard.py'- 'tests/studio/playwright_nonmodal_menus.py'@@ -481,6 +487,13 @@ jobs:working-directory: ${{ github.workspace }}run: python3 tests/studio/playwright_research_freeze.py+ - name: Browser regression for pinned chat persistence+ working-directory: ${{ github.workspace }}+ timeout-minutes: 3+ run: |+ python3 -m pip install fastapi httpx pyjwt argon2-cffi cryptography huggingface_hub python-multipart structlog+ python3 tests/studio/playwright_pinned_chat_persistence.py+# A gate, not a measurement. The released and streamdown variants are positive controls# that MUST flicker: a run where neither collapses means the detector stopped seeing, not# that the flicker stopped. Chromium only on a PR, the engine whose content-visibilitydiff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.pyindex 88f8cff3383..ed240e2c979 100644--- a/studio/backend/routes/chat_history.py+++ b/studio/backend/routes/chat_history.py@@ -22,6 +22,7 @@ from pydantic import (ValidationError,field_serializer,field_validator,+ model_validator,)from auth.authentication import get_current_subject@@ -43,6 +44,8 @@ from utils.account_context import is_owner_contextfrom utils.utils import safe_curated_detail, log_and_http_errorfrom storage.studio_db import (ChatForkActiveGenerationError,+ MAX_PINNED_CHAT_IDS,+ MAX_PINNED_CHAT_ID_LENGTH,ChatMessageConflictError,ChatMessageProtectedError,ChatThreadDeletedError,@@ -66,6 +69,7 @@ from storage.studio_db import (get_chat_attachment,get_chat_project,get_chat_thread,+ get_chat_pins,get_chat_message,next_message_created_at,list_chat_attachments_page,@@ -83,6 +87,7 @@ from storage.studio_db import (remap_chat_thread_document_ids,set_chat_project_working_folder,ProjectWorkingFolderConflictError,+ migrate_chat_pins,sync_chat_messages,update_chat_project,update_chat_thread,@@ -521,6 +526,10 @@ class ChatResearchMcpSource(BaseModel):class ChatSettingsPayload(BaseModel):model_config = ConfigDict(extra = "forbid", allow_inf_nan = False)+ # Sidebar IDs (incl. comparison pair IDs), not thread rows. Omitted = no change; [] unpins all.+ pinnedChatIds: list[+ Annotated[str, Field(strict = True, min_length = 1, max_length = MAX_PINNED_CHAT_ID_LENGTH)]+ ] = Field(default_factory = list, max_length = MAX_PINNED_CHAT_IDS)inferenceParams: Optional[ChatInferenceSettings] = None# Deep-merged per key so patching one model keeps the others.inferenceParamsByModel: Optional[dict[str, ChatInferenceSettings]] = None@@ -592,6 +601,15 @@ class ChatSettingsPayload(BaseModel):contextPolicy: Optional[Literal["inherit", "checkpoint", "rolling"]] = NonecompactionHeadroomRatio: Optional[float] = Field(default = None, ge = 0.0, le = 0.9)+ @field_validator("pinnedChatIds")+ @classmethod+ def _unique_pinned_chat_ids(cls, value: list[str]) -> list[str]:+ if any(0xD800 <= ord(character) <= 0xDFFF for id in value for character in id):+ raise ValueError("pinnedChatIds must contain valid Unicode")+ if len(value) != len(set(value)):+ raise ValueError("pinnedChatIds must not contain duplicate IDs")+ return value+@field_validator("researchModelTimeoutSeconds", "maxToolCallsPerMessage", mode = "before")@classmethoddef _not_a_boolean(cls, value: Any) -> Any:@@ -620,6 +638,40 @@ class ConditionalChatSettingsPayload(BaseModel):expectedAbsent: list[str] = Field(default_factory = list)expectedAbsentPaths: list[list[str]] = Field(default_factory = list)patch: ChatSettingsPayload+ operationId: Optional[Annotated[str, Field(strict = True, min_length = 1, max_length = 128)]] = None+ # Explicit unpins can predate importing the corresponding legacy thread.+ unpinnedChatIds: list[+ Annotated[str, Field(strict = True, min_length = 1, max_length = MAX_PINNED_CHAT_ID_LENGTH)]+ ] = Field(default_factory = list, max_length = MAX_PINNED_CHAT_IDS)++ # Queued pins this unpin superseded: acknowledged here so a delayed one is never applied.+ cancelledOperationIds: list[+ Annotated[str, Field(strict = True, min_length = 1, max_length = 128)]+ ] = Field(default_factory = list, max_length = MAX_PINNED_CHAT_IDS)++ @field_validator("unpinnedChatIds", "cancelledOperationIds")+ @classmethod+ def _unique_unpinned_ids(cls, value: list[str]) -> list[str]:+ return ChatSettingsPayload._unique_pinned_chat_ids(value)++ @field_validator("operationId")+ @classmethod+ def _valid_operation_id(cls, value: Optional[str]) -> Optional[str]:+ if value is not None and any(0xD800 <= ord(character) <= 0xDFFF for character in value):+ raise ValueError("operationId must contain valid Unicode")+ return value++ @model_validator(mode = "after")+ def _operation_is_pin_only(self):+ if (+ self.operationId is not None+ or "unpinnedChatIds" in self.model_fields_set+ or "cancelledOperationIds" in self.model_fields_set+ ) and self.patch.model_fields_set != {"pinnedChatIds"}:+ raise ValueError("Pin operation metadata requires a pinnedChatIds-only patch")+ if set(self.unpinnedChatIds).intersection(self.patch.pinnedChatIds):+ raise ValueError("An unpinned chat ID cannot also be pinned in the same patch")+ return self@field_validator("expectedAbsent")@classmethod@@ -645,6 +697,23 @@ class ConditionalChatSettingsResponse(ChatSettingsResponse):applied: bool+class ChatPinsResponse(BaseModel):+ pinnedIds: list[str] = Field(default_factory = list)+++class ChatPinsMigrationRequest(BaseModel):+ model_config = ConfigDict(extra = "forbid")++ ids: list[+ Annotated[str, Field(strict = True, min_length = 1, max_length = MAX_PINNED_CHAT_ID_LENGTH)]+ ] = Field(max_length = MAX_PINNED_CHAT_IDS)++ @field_validator("ids")+ @classmethod+ def _unique_ids(cls, value: list[str]) -> list[str]:+ return ChatSettingsPayload._unique_pinned_chat_ids(value)++class ChatMessagesBatchRequest(BaseModel):threadIds: list[str]@@ -1837,6 +1906,20 @@ async def clear_history(}[email protected]("/pins", response_model = ChatPinsResponse, response_model_exclude_unset = True)+def get_pins(current_subject: str = Depends(get_current_subject)):+ pins = get_chat_pins()+ return ChatPinsResponse() if pins is None else ChatPinsResponse(pinnedIds = pins)++[email protected]("/pins/migrate", response_model = ChatPinsResponse, response_model_exclude_unset = True)+def migrate_pins(+ payload: ChatPinsMigrationRequest, current_subject: str = Depends(get_current_subject)+):+ pins = migrate_chat_pins(payload.ids)+ return ChatPinsResponse() if pins is None else ChatPinsResponse(pinnedIds = pins)++@router.get("/settings", response_model = ChatSettingsResponse)def get_settings(current_subject: str = Depends(get_current_subject)):return ChatSettingsResponse(settings = list_chat_settings())@@ -1857,6 +1940,9 @@ def compare_and_set_settings(parsed.patch.model_dump(exclude_unset = True),parsed.expectedAbsent,parsed.expectedAbsentPaths,+ operation_id = parsed.operationId,+ unpinned_chat_ids = parsed.unpinnedChatIds,+ cancelled_operation_ids = parsed.cancelledOperationIds,)return ConditionalChatSettingsResponse(settings = settings, applied = applied)except CorruptSettingsError as exc:diff --git a/studio/backend/storage/studio_db.py b/studio/backend/storage/studio_db.pyindex ddf4ea47b84..6ebe7d3cf01 100644--- a/studio/backend/storage/studio_db.py+++ b/studio/backend/storage/studio_db.py@@ -723,6 +723,10 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:)""")+ # Sidebar IDs (incl. comparison pair IDs), so no foreign key to one thread row.+ conn.execute("CREATE TABLE IF NOT EXISTS chat_pin_tombstones (id TEXT NOT NULL PRIMARY KEY)")+ conn.execute("CREATE TABLE IF NOT EXISTS chat_pin_deletions (id TEXT NOT NULL PRIMARY KEY)")+ conn.execute("CREATE TABLE IF NOT EXISTS chat_pin_operations (id TEXT NOT NULL PRIMARY KEY)")conn.execute("""CREATE TABLE IF NOT EXISTS app_settings (@@ -2807,6 +2811,25 @@ def lift_chat_thread_tombstones(thread_ids: Iterable[str]) -> None:def _tombstone_chat_threads(conn: sqlite3.Connection, thread_ids: Iterable[str]) -> None:+ thread_ids = set(thread_ids)+ # Recorded apart from unpins so a queued pin never waits forever on a deleted comparison.+ pairs = {+ row["pair_id"]+ for row in conn.execute("SELECT id, pair_id FROM chat_threads WHERE pair_id IS NOT NULL")+ if row["id"] in thread_ids and row["pair_id"]+ }+ deleted_pairs = {+ pair+ for pair in pairs+ if all(+ row["id"] in thread_ids+ for row in conn.execute("SELECT id FROM chat_threads WHERE pair_id = ?", (pair,))+ )+ }+ conn.executemany(+ "INSERT OR IGNORE INTO chat_pin_deletions (id) VALUES (?)",+ [(id,) for id in thread_ids | deleted_pairs],+ )deleted_at = int(datetime.now(timezone.utc).timestamp() * 1000)conn.executemany("""@@ -2908,6 +2931,7 @@ def delete_chat_threads_with_active_runs(ids: list[str]) -> tuple[list[str], listry:conn.execute("BEGIN IMMEDIATE")active = delete_chat_threads_in(conn, ids)+ _load_chat_pins_in_conn(conn, repair = True, remember_removed = True)conn.commit()return activeexcept Exception:@@ -3055,6 +3079,7 @@ def clear_chat_history_with_replay_status(_tombstone_chat_threads(conn, sorted(set(additional_thread_ids) | set(removed)))conn.execute("DELETE FROM chat_attachment_tombstones")conn.execute("DELETE FROM chat_threads")+ _load_chat_pins_in_conn(conn, repair = True, remember_removed = True)_mark_chat_attachment_inventory_clean(conn)if operation_id is not None:conn.execute(@@ -3361,6 +3386,7 @@ def delete_chat_project(id: str, delete_files: bool = False) -> Optional[dict]:_tombstone_chat_threads(conn, thread_ids)conn.execute("DELETE FROM chat_threads WHERE project_id = ?", (id,))conn.execute("DELETE FROM chat_projects WHERE id = ?", (id,))+ _load_chat_pins_in_conn(conn, repair = True, remember_removed = True)_mark_chat_attachment_inventory_clean(conn)conn.commit()if delete_files:@@ -5517,6 +5543,158 @@ def upsert_app_setting_map_entry(conn.close()+_CHAT_PINS_KEY = "pinnedChatIds"+MAX_PINNED_CHAT_IDS = 10_000+MAX_PINNED_CHAT_ID_LENGTH = 512+++def _normalized_chat_pin_ids(value: Any) -> list[str]:+ if not isinstance(value, list):+ return []+ return list(+ dict.fromkeys(+ item+ for item in value+ if isinstance(item, str)+ and 0 < len(item) <= MAX_PINNED_CHAT_ID_LENGTH+ and not any(0xD800 <= ord(character) <= 0xDFFF for character in item)+ )+ )+++def _existing_chat_pin_ids(conn: sqlite3.Connection, ids: list[str]) -> list[str]:+ """Keep sidebar IDs that still have a thread, including archived comparisons."""+ present: set[str] = set()+ chunk_size = _SQLITE_IN_CHUNK_SIZE // 2+ for start in range(0, len(ids), chunk_size):+ chunk = ids[start : start + chunk_size]+ placeholders = ",".join("?" for _ in chunk)+ rows = conn.execute(+ f"""SELECT id FROM chat_threads+ WHERE id IN ({placeholders}) AND (pair_id IS NULL OR pair_id = '')+ UNION SELECT pair_id AS id FROM chat_threads WHERE pair_id IN ({placeholders})""",+ (*chunk, *chunk),+ ).fetchall()+ present.update(row["id"] for row in rows)+ return [id for id in ids if id in present][:MAX_PINNED_CHAT_IDS]+++def _store_chat_pins_in_conn(conn: sqlite3.Connection, ids: list[str]) -> None:+ conn.execute(+ """INSERT INTO chat_settings (key, value_json, updated_at) VALUES (?, ?, ?)+ ON CONFLICT(key) DO UPDATE SET+ value_json = excluded.value_json, updated_at = excluded.updated_at""",+ (_CHAT_PINS_KEY, json.dumps(ids), datetime.now(timezone.utc).isoformat()),+ )+++def _load_chat_pins_in_conn(+ conn: sqlite3.Connection,+ *,+ repair: bool = False,+ remember_removed: bool = False,+) -> tuple[Optional[list[str]], bool]:+ """None means genuinely absent; malformed data becomes a recoverable empty list."""+ row = conn.execute(+ "SELECT value_json FROM chat_settings WHERE key = ?", (_CHAT_PINS_KEY,)+ ).fetchone()+ if row is None:+ return None, False+ value = _json_loads(row["value_json"], None)+ normalized = _normalized_chat_pin_ids(value)+ pins = _existing_chat_pin_ids(conn, normalized)+ dirty = value != pins+ if repair and dirty:+ if value != normalized:+ # Retain the damaged value for recovery; never quarantine an ordinary orphan.+ conn.execute(+ """INSERT INTO chat_settings_quarantine+ (key, value_json, reason, quarantined_at) VALUES (?, ?, ?, ?)""",+ (+ _CHAT_PINS_KEY,+ row["value_json"],+ "invalid_chat_pins",+ datetime.now(timezone.utc).isoformat(),+ ),+ )+ if remember_removed:+ remaining = set(pins)+ conn.executemany(+ "INSERT OR IGNORE INTO chat_pin_tombstones (id) VALUES (?)",+ [(id,) for id in normalized if id not in remaining],+ )+ _store_chat_pins_in_conn(conn, pins)+ return pins, dirty+++def get_chat_pins() -> Optional[list[str]]:+ conn = get_connection(_CONTENDED_BUSY_TIMEOUT_SECONDS)+ try:+ pins, dirty = _load_chat_pins_in_conn(conn)+ if dirty:+ # Re-read under the write lock so a pin committed since the first read survives.+ conn.execute("BEGIN IMMEDIATE")+ pins, _ = _load_chat_pins_in_conn(conn, repair = True)+ conn.commit()+ return pins+ except Exception:+ conn.rollback()+ raise+ finally:+ conn.close()+++def migrate_chat_pins(ids: list[str]) -> Optional[list[str]]:+ conn = get_connection(_CONTENDED_BUSY_TIMEOUT_SECONDS)+ try:+ conn.execute("BEGIN IMMEDIATE")+ current, _ = _load_chat_pins_in_conn(conn, repair = True)+ incoming = _existing_chat_pin_ids(conn, _normalized_chat_pin_ids(ids))+ blocked: set[str] = set()+ for start in range(0, len(incoming), _SQLITE_IN_CHUNK_SIZE):+ chunk = incoming[start : start + _SQLITE_IN_CHUNK_SIZE]+ placeholders = ",".join("?" for _ in chunk)+ blocked.update(+ row["id"]+ for row in conn.execute(+ f"SELECT id FROM chat_pin_tombstones WHERE id IN ({placeholders})", chunk+ )+ )+ present = set(current or [])+ additions = [id for id in incoming if id not in present and id not in blocked]+ pins = [*(current or []), *additions][:MAX_PINNED_CHAT_IDS]+ if pins != (current or []):+ _store_chat_pins_in_conn(conn, pins)+ current = pins+ conn.commit()+ return current+ except Exception:+ conn.rollback()+ raise+ finally:+ conn.close()+++def _record_chat_pin_change(+ conn: sqlite3.Connection,+ previous: Any,+ ids: list[str],+ explicit_unpins: Iterable[str] = (),+) -> None:+ old = set(_normalized_chat_pin_ids(previous))+ present = set(ids)+ # An unpin can predate legacy import creating the row; record it though it removes nothing.+ removed = (old - present) | set(explicit_unpins)+ conn.executemany(+ "INSERT OR IGNORE INTO chat_pin_tombstones (id) VALUES (?)",+ [(id,) for id in removed],+ )+ # Only an explicit pin write clears an unpin; migration never calls this helper.+ conn.executemany(+ "DELETE FROM chat_pin_tombstones WHERE id = ?", [(id,) for id in ids if id not in old]+ )++def list_chat_settings() -> dict[str, Any]:conn = get_connection()try:@@ -5603,6 +5781,8 @@ def upsert_chat_settings_merge(updates: dict[str, Any]) -> dict[str, Any]:conn = get_connection()try:conn.execute("BEGIN IMMEDIATE")+ if _CHAT_PINS_KEY in updates:+ _load_chat_pins_in_conn(conn, repair = True)current, corrupt = _load_chat_settings_for_merge(conn)# An atomic key carries its whole value, so it repairs a quarantined row without a base.unsafe_partial_keys = [@@ -5616,6 +5796,12 @@ def upsert_chat_settings_merge(updates: dict[str, Any]) -> dict[str, Any]:raise CorruptSettingsError(f"Cannot apply partial settings patch to corrupt key(s): {keys}")+ if _CHAT_PINS_KEY in updates:+ updates = {+ **updates,+ _CHAT_PINS_KEY: _existing_chat_pin_ids(conn, updates[_CHAT_PINS_KEY]),+ }+ _record_chat_pin_change(conn, current.get(_CHAT_PINS_KEY), updates[_CHAT_PINS_KEY])merged = _merge_settings_updates(current, updates)now = datetime.now(timezone.utc).isoformat()conn.executemany(@@ -5666,6 +5852,9 @@ def upsert_chat_settings_merge_if_current(updates: dict[str, Any],expected_absent: Iterable[str] = (),expected_absent_paths: Iterable[Iterable[str]] = (),+ operation_id: Optional[str] = None,+ unpinned_chat_ids: Iterable[str] = (),+ cancelled_operation_ids: Iterable[str] = (),) -> tuple[dict[str, Any], bool]:"""Atomically merge ``updates`` only if ``expected`` still matches. Expected is a recursive subsetso legacy keys omitted by the current client do not prevent a guarded migration. Any field the@@ -5674,7 +5863,19 @@ def upsert_chat_settings_merge_if_current(conn = get_connection(_CONTENDED_BUSY_TIMEOUT_SECONDS)try:conn.execute("BEGIN IMMEDIATE")+ if _CHAT_PINS_KEY in updates:+ _load_chat_pins_in_conn(conn, repair = True)current, corrupt = _load_chat_settings_for_merge(conn)+ if (+ operation_id is not None+ and conn.execute(+ "SELECT 1 FROM chat_pin_operations WHERE id = ?", (operation_id,)+ ).fetchone()+ is not None+ ):+ # A replay after a lost response: acknowledge, never re-apply over a newer unpin.+ conn.commit()+ return current, Truematches_expected = _chat_settings_match_expected(current, expected)has_new_expected_field = any(key in current for key in expected_absent)has_new_expected_path = any(@@ -5698,6 +5899,34 @@ def upsert_chat_settings_merge_if_current(# Skip empty patches or updated_at is rewritten, which reads as a settings change.conn.commit()return current, True+ if _CHAT_PINS_KEY in updates:+ requested = updates[_CHAT_PINS_KEY]+ existing = _existing_chat_pin_ids(conn, requested)+ missing = set(requested) - set(existing)+ # A chat still awaiting legacy import: leave unacknowledged so the journal retries.+ deleted = set()+ chunk_size = _SQLITE_IN_CHUNK_SIZE // 2+ for start in range(0, len(requested), chunk_size):+ chunk = requested[start : start + chunk_size]+ placeholders = ",".join("?" for _ in chunk)+ deleted.update(+ row["id"]+ for row in conn.execute(+ f"SELECT id FROM chat_pin_deletions WHERE id IN ({placeholders}) "+ f"UNION SELECT id FROM chat_thread_tombstones WHERE id IN ({placeholders})",+ (*chunk, *chunk),+ )+ )+ if missing - deleted:+ conn.commit()+ return current, False+ updates = {+ **updates,+ _CHAT_PINS_KEY: existing,+ }+ _record_chat_pin_change(+ conn, current.get(_CHAT_PINS_KEY), updates[_CHAT_PINS_KEY], unpinned_chat_ids+ )merged = _merge_settings_updates(current, updates)now = datetime.now(timezone.utc).isoformat()conn.executemany(@@ -5710,6 +5939,12 @@ def upsert_chat_settings_merge_if_current(""",[(key, json.dumps(value), now) for key, value in merged.items()],)+ if operation_id is not None:+ conn.execute("INSERT INTO chat_pin_operations (id) VALUES (?)", (operation_id,))+ conn.executemany(+ "INSERT OR IGNORE INTO chat_pin_operations (id) VALUES (?)",+ [(id,) for id in cancelled_operation_ids],+ )conn.commit()return merged, Trueexcept CorruptSettingsError:diff --git a/studio/backend/tests/test_pinned_chat_settings.py b/studio/backend/tests/test_pinned_chat_settings.pynew file mode 100644index 00000000000..c7aff5940af--- /dev/null+++ b/studio/backend/tests/test_pinned_chat_settings.py@@ -0,0 +1,626 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Ordered sidebar pins persist across clients through the shared settings API."""++import json+import sqlite3+import threading+from concurrent.futures import ThreadPoolExecutor++import pytest+from fastapi import HTTPException+from fastapi import FastAPI+from fastapi.testclient import TestClient+from pydantic import ValidationError++from routes import chat_history+from storage import studio_db+++def _save_if_current(+ expected,+ pins,+ *,+ expected_absent = False,+ operation_id = None,+ unpinned_ids = (),+ cancelled_operation_ids = (),+):+ return chat_history.compare_and_set_settings(+ {+ "expected": expected,+ "expectedAbsent": ["pinnedChatIds"] if expected_absent else [],+ "patch": {"pinnedChatIds": pins},+ "operationId": operation_id,+ "unpinnedChatIds": list(unpinned_ids),+ "cancelledOperationIds": list(cancelled_operation_ids),+ },+ current_subject = "test-user",+ )+++def _seed(+ *ids,+ pair_id = None,+ archived = False,+ project_id = None,+):+ for id in ids:+ studio_db.upsert_chat_thread(+ {+ "id": id,+ "title": id,+ "modelType": "base",+ "createdAt": 1,+ "pairId": pair_id,+ "archived": archived,+ "projectId": project_id,+ }+ )+++def _pins():+ return chat_history.get_pins(current_subject = "test-user").model_dump(exclude_unset = True)+++def _migrate(ids):+ return chat_history.migrate_pins(+ chat_history.ChatPinsMigrationRequest(ids = ids), current_subject = "test-user"+ ).model_dump(exclude_unset = True)+++def test_pin_payload_distinguishes_omitted_from_explicitly_empty():+ assert chat_history.ChatSettingsPayload().model_dump(exclude_unset = True) == {}+ assert chat_history.ChatSettingsPayload(pinnedChatIds = []).model_dump(exclude_unset = True) == {+ "pinnedChatIds": []+ }+++def test_new_pin_waits_for_a_visible_legacy_thread_to_finish_importing():+ first = _save_if_current({}, ["late-import"], expected_absent = True, operation_id = "pin-late")+ assert not first.applied+ conn = studio_db.get_connection()+ try:+ assert (+ conn.execute("SELECT 1 FROM chat_pin_operations WHERE id = 'pin-late'").fetchone()+ is None+ )+ finally:+ conn.close()+ _seed("late-import")+ retry = _save_if_current({}, ["late-import"], expected_absent = True, operation_id = "pin-late")+ assert retry.applied+ assert retry.settings["pinnedChatIds"] == ["late-import"]+++def test_a_deleted_comparison_pin_is_acknowledged_without_blocking_later_pins():+ _seed("left", "right", pair_id = "deleted-pair")+ _seed("keep")+ studio_db.delete_chat_threads_with_active_runs(["left", "right"])+ deleted = _save_if_current(+ {}, ["deleted-pair"], expected_absent = True, operation_id = "stale-pair"+ )+ assert deleted.applied+ assert deleted.settings["pinnedChatIds"] == []+ later = _save_if_current({"pinnedChatIds": []}, ["keep"], operation_id = "next-pin")+ assert later.applied+ assert later.settings["pinnedChatIds"] == ["keep"]+++def test_pin_intent_for_a_chat_deleted_before_upgrade_does_not_block_the_queue():+ _seed("deleted-before-upgrade")+ studio_db.delete_chat_threads_with_active_runs(["deleted-before-upgrade"])+ conn = studio_db.get_connection()+ try:+ conn.execute("DELETE FROM chat_pin_deletions")+ conn.commit()+ finally:+ conn.close()+ saved = _save_if_current(+ {}, ["deleted-before-upgrade"], expected_absent = True, operation_id = "old-pin"+ )+ assert saved.applied+ assert saved.settings["pinnedChatIds"] == []+++ "pins",+ [+ None,+ "chat-1",+ [None],+ [True],+ [42],+ [""],+ ["x" * 513],+ [chr(0xD800)],+ ["a", "a"],+ [str(i) for i in range(10_001)],+ ],+ ids = [+ "null",+ "not-list",+ "null-id",+ "boolean-id",+ "number-id",+ "empty-id",+ "long-id",+ "invalid-unicode",+ "duplicate",+ "too-many",+ ],+)+def test_invalid_pins_do_not_overwrite_saved_state(pins):+ _seed("keep")+ chat_history.put_settings({"pinnedChatIds": ["keep"]}, current_subject = "test-user")++ with pytest.raises(ValidationError):+ chat_history.ChatSettingsPayload.model_validate({"pinnedChatIds": pins})+ with pytest.raises(HTTPException) as error:+ chat_history.put_settings({"pinnedChatIds": pins}, current_subject = "test-user")++ assert error.value.status_code == 400+ assert studio_db.list_chat_settings()["pinnedChatIds"] == ["keep"]+++def test_ordered_chat_and_comparison_pins_round_trip_through_sqlite(monkeypatch):+ # A comparison's sidebar ID is its pair ID, not either underlying thread ID.+ pins = ["comparison-pair", "ordinary-thread", "another-thread"]+ _seed("left", "right", pair_id = "comparison-pair")+ _seed("ordinary-thread", "another-thread")+ chat_history.put_settings({"pinnedChatIds": pins}, current_subject = "test-user")+ chat_history.put_settings({"autoTitle": False}, current_subject = "test-user")++ conn = studio_db.get_connection()+ try:+ row = conn.execute(+ "SELECT value_json FROM chat_settings WHERE key = ?", ("pinnedChatIds",)+ ).fetchone()+ assert json.loads(row["value_json"]) == pins+ finally:+ conn.close()++ # Reinitialize storage and read through a separate request, as another browser does.+ studio_db.reset_schema_state_for_tests()+ saved = chat_history.get_settings(current_subject = "another-client").settings+ assert saved == {"autoTitle": False, "pinnedChatIds": pins}+++def test_legacy_migration_only_claims_an_absent_pin_setting():+ _seed("legacy-pin", "different-browser-pin")+ chat_history.put_settings({"autoTitle": False}, current_subject = "test-user")+ assert "pinnedChatIds" not in chat_history.get_settings(current_subject = "test-user").settings++ migrated = _save_if_current({}, ["legacy-pin"], expected_absent = True)+ assert migrated.applied is True+ assert migrated.settings == {"autoTitle": False, "pinnedChatIds": ["legacy-pin"]}++ stale_migration = _save_if_current({}, ["different-browser-pin"], expected_absent = True)+ assert stale_migration.applied is False+ assert stale_migration.settings["pinnedChatIds"] == ["legacy-pin"]+++def test_explicit_empty_pins_prevent_legacy_browser_resurrection():+ _seed("legacy-pin")+ migrated = _save_if_current({}, ["legacy-pin"], expected_absent = True)+ cleared = _save_if_current({"pinnedChatIds": migrated.settings["pinnedChatIds"]}, [])+ assert cleared.applied is True++ stale_migration = _save_if_current({}, ["legacy-pin"], expected_absent = True)+ assert stale_migration.applied is False+ assert stale_migration.settings["pinnedChatIds"] == []+ assert chat_history.get_settings(current_subject = "test-user").settings["pinnedChatIds"] == []++[email protected]("field", ["expected", "patch"])+def test_compare_and_set_rejects_null_pins(field):+ _seed("keep")+ chat_history.put_settings({"pinnedChatIds": ["keep"]}, current_subject = "test-user")+ payload = {"expected": {"pinnedChatIds": ["keep"]}, "patch": {"pinnedChatIds": []}}+ payload[field] = {"pinnedChatIds": None}+ with pytest.raises(HTTPException) as error:+ chat_history.compare_and_set_settings(payload, current_subject = "test-user")+ assert error.value.status_code == 400+ assert studio_db.list_chat_settings()["pinnedChatIds"] == ["keep"]+++def test_stale_pin_write_rebases_without_resurrecting_an_unpinned_chat():+ _seed("a", "b", "c")+ chat_history.put_settings({"pinnedChatIds": ["a", "b"]}, current_subject = "test-user")+ old_snapshot = {"pinnedChatIds": ["a", "b"]}+ assert _save_if_current(old_snapshot, ["b"]).applied is True++ # Another browser pins c using the state it read before a was unpinned.+ stale = _save_if_current(old_snapshot, ["c", "a", "b"])+ assert stale.applied is False+ assert stale.settings["pinnedChatIds"] == ["b"]++ current = stale.settings["pinnedChatIds"]+ rebased = _save_if_current({"pinnedChatIds": current}, ["c", *current])+ assert rebased.applied is True+ assert studio_db.list_chat_settings()["pinnedChatIds"] == ["c", "b"]+++def test_concurrent_pin_writers_conflict_then_rebase_without_lost_pins():+ _seed("a", "b")+ chat_history.put_settings({"pinnedChatIds": []}, current_subject = "test-user")+ barrier = threading.Barrier(2)++ def pin_from_empty_snapshot(chat_id):+ barrier.wait(timeout = 5)+ return chat_id, _save_if_current({"pinnedChatIds": []}, [chat_id])++ with ThreadPoolExecutor(max_workers = 2) as pool:+ results = list(pool.map(pin_from_empty_snapshot, ["a", "b"]))++ assert sum(result.applied for _, result in results) == 1+ winner = next(chat_id for chat_id, result in results if result.applied)+ loser, rejected = next((chat_id, result) for chat_id, result in results if not result.applied)+ assert rejected.settings["pinnedChatIds"] == [winner]++ current = rejected.settings["pinnedChatIds"]+ rebased = _save_if_current({"pinnedChatIds": current}, [loser, *current])+ assert rebased.applied is True+ assert studio_db.list_chat_settings()["pinnedChatIds"] == [loser, winner]+++def test_pin_read_and_empty_migration_leave_absent_state_absent():+ assert _pins() == {}+ assert _migrate([]) == {}+ assert _migrate(["not-yet-imported"]) == {}+ assert "pinnedChatIds" not in studio_db.list_chat_settings()+ _seed("not-yet-imported")+ assert _migrate(["not-yet-imported"]) == {"pinnedIds": ["not-yet-imported"]}+++def test_distinct_browser_migrations_merge_without_reordering_existing_pins():+ _seed("a", "b", "c")+ assert _migrate(["a", "b"]) == {"pinnedIds": ["a", "b"]}+ assert _migrate(["c", "b"]) == {"pinnedIds": ["a", "b", "c"]}+ assert _migrate(["b", "a"]) == {"pinnedIds": ["a", "b", "c"]}++[email protected]("method", ["put", "cas"])+def test_migration_cannot_resurrect_unpins_and_explicit_repin_is_allowed(method, monkeypatch):+ _seed("a", "b", "c")+ _migrate(["a", "b"])+ if method == "put":+ chat_history.put_settings({"pinnedChatIds": ["a"]}, current_subject = "test-user")+ else:+ assert _save_if_current({"pinnedChatIds": ["a", "b"]}, ["a"]).applied+ studio_db.reset_schema_state_for_tests()+ assert _migrate(["b", "c"]) == {"pinnedIds": ["a", "c"]}+ assert _save_if_current({"pinnedChatIds": ["a", "c"]}, ["b", "a", "c"]).applied+ assert _pins() == {"pinnedIds": ["b", "a", "c"]}+ conn = studio_db.get_connection()+ try:+ assert conn.execute("SELECT id FROM chat_pin_tombstones WHERE id = 'b'").fetchone() is None+ finally:+ conn.close()+++def test_noop_and_migration_preserve_unpin_tombstones():+ _seed("a", "b")+ _migrate(["a", "b"])+ assert _save_if_current({"pinnedChatIds": ["a", "b"]}, ["a"]).applied+ assert _save_if_current({"pinnedChatIds": ["a"]}, ["a"]).applied+ assert _migrate(["b"]) == {"pinnedIds": ["a"]}+++def test_deleting_threads_prunes_single_and_comparison_pins_atomically():+ _seed("single")+ _seed("left", "right", pair_id = "pair")+ _seed("archived", archived = True)+ assert _migrate(["single", "pair", "archived", "left", "missing"]) == {+ "pinnedIds": ["single", "pair", "archived"]+ }+ studio_db.delete_chat_threads(["single", "left"])+ # Read raw settings to prove deletion itself pruned, without relying on GET repair.+ assert studio_db.list_chat_settings()["pinnedChatIds"] == ["pair", "archived"]+ studio_db.delete_chat_threads(["right"])+ assert studio_db.list_chat_settings()["pinnedChatIds"] == ["archived"]+ assert _migrate(["pair", "single"]) == {"pinnedIds": ["archived"]}+++def test_project_deletion_and_clear_all_prune_pin_state():+ studio_db.upsert_chat_project(+ {"id": "project", "name": "Project", "createdAt": 1, "updatedAt": 1}+ )+ _seed("project-chat", project_id = "project")+ _seed("other-chat")+ _migrate(["project-chat", "other-chat"])+ studio_db.delete_chat_project("project")+ assert studio_db.list_chat_settings()["pinnedChatIds"] == ["other-chat"]+ studio_db.clear_chat_history()+ assert studio_db.list_chat_settings()["pinnedChatIds"] == []+++def test_orphan_pins_do_not_exhaust_capacity_and_stale_cas_can_rebase():+ _seed("new-chat")+ orphaned = [f"deleted-{i}" for i in range(studio_db.MAX_PINNED_CHAT_IDS)]+ studio_db.upsert_chat_settings({"pinnedChatIds": orphaned})+ # Expected state can still name old IDs: normalization returns a conflict, not a lost update.+ stale = _save_if_current({"pinnedChatIds": orphaned}, ["new-chat"])+ assert not stale.applied+ assert stale.settings["pinnedChatIds"] == []+ assert _save_if_current({"pinnedChatIds": []}, ["new-chat"]).applied+ assert _pins() == {"pinnedIds": ["new-chat"]}+++ "raw,expected",+ [+ ("{bad-json", []),+ ("null", []),+ ('"wrong-shape"', []),+ ('{"a":true}', []),+ ('["a",null,true,"a","missing",""]', ["a"]),+ (json.dumps(["a", chr(0xD800)]), ["a"]),+ ],+)+def test_targeted_get_repairs_corrupt_pin_state_and_preserves_unrelated_settings(raw, expected):+ _seed("a", "b")+ studio_db.upsert_chat_settings({"autoTitle": False, "pinnedChatIds": []})+ conn = studio_db.get_connection()+ try:+ conn.execute("UPDATE chat_settings SET value_json = ? WHERE key = 'pinnedChatIds'", (raw,))+ conn.commit()+ finally:+ conn.close()+ assert _pins() == {"pinnedIds": expected}+ assert studio_db.list_chat_settings() == {"autoTitle": False, "pinnedChatIds": expected}+ assert _save_if_current({"pinnedChatIds": expected}, ["b", *expected]).applied+ conn = studio_db.get_connection()+ try:+ assert (+ conn.execute(+ "SELECT value_json FROM chat_settings_quarantine WHERE key = 'pinnedChatIds'"+ ).fetchone()[0]+ == raw+ )+ finally:+ conn.close()+++def test_healthy_targeted_get_neither_writes_nor_loads_unrelated_settings(monkeypatch):+ _seed("a")+ _migrate(["a"])+ studio_db.upsert_chat_settings({"customPresets": ["x" * 100_000]})+ statements = []+ original = studio_db.get_connection++ def traced_connection(*args, **kwargs):+ conn = original(*args, **kwargs)+ conn.set_trace_callback(statements.append)+ return conn++ monkeypatch.setattr(studio_db, "get_connection", traced_connection)+ assert _pins() == {"pinnedIds": ["a"]}+ assert all(sql.lstrip().upper().startswith("SELECT") for sql in statements)+ settings_reads = [sql for sql in statements if "FROM chat_settings" in sql]+ assert len(settings_reads) == 1 and "WHERE key = 'pinnedChatIds'" in settings_reads[0]+++def test_operation_replay_acknowledges_without_reversing_a_later_unpin(monkeypatch):+ _seed("a")+ assert _save_if_current({}, ["a"], expected_absent = True, operation_id = "pin-1").applied+ assert _save_if_current({"pinnedChatIds": ["a"]}, [], operation_id = "unpin-2").applied+ studio_db.reset_schema_state_for_tests()+ replay = _save_if_current({}, ["a"], expected_absent = True, operation_id = "pin-1")+ assert replay.applied+ assert replay.settings["pinnedChatIds"] == []+ assert _migrate(["a"]) == {"pinnedIds": []}+ assert set(studio_db.list_chat_settings()) == {"pinnedChatIds"}+++def test_conflicting_operation_is_not_acknowledged_until_rebased():+ _seed("a", "b")+ _migrate(["a"])+ stale = _save_if_current({"pinnedChatIds": []}, ["b"], operation_id = "pin-b")+ assert not stale.applied+ saved = _save_if_current({"pinnedChatIds": ["a"]}, ["b", "a"], operation_id = "pin-b")+ assert saved.applied and saved.settings["pinnedChatIds"] == ["b", "a"]+++ "patch", [{}, {"autoTitle": False}, {"pinnedChatIds": [], "autoTitle": False}]+)+def test_operation_ids_cannot_acknowledge_unrelated_settings(patch):+ with pytest.raises(HTTPException) as error:+ chat_history.compare_and_set_settings(+ {"expected": {}, "patch": patch, "operationId": "op"}, current_subject = "test-user"+ )+ assert error.value.status_code == 400+++def test_concurrent_legacy_migration_and_unpin_never_resurrects_the_unpin():+ _seed("a", "b")+ _migrate(["a"])+ barrier = threading.Barrier(2)++ def migrate():+ barrier.wait(timeout = 5)+ return _migrate(["a", "b"])++ def unpin():+ barrier.wait(timeout = 5)+ snapshot = ["a"]+ for _ in range(3):+ reply = _save_if_current(+ {"pinnedChatIds": snapshot}, [id for id in snapshot if id != "a"]+ )+ if reply.applied:+ return+ snapshot = reply.settings["pinnedChatIds"]+ raise AssertionError("Unpin could not rebase")++ with ThreadPoolExecutor(max_workers = 2) as pool:+ a, b = pool.submit(migrate), pool.submit(unpin)+ a.result()+ b.result()+ assert _pins() == {"pinnedIds": ["b"]}+ assert _migrate(["a"]) == {"pinnedIds": ["b"]}+++def test_pin_endpoints_serialize_absence_and_never_expose_other_settings():+ app = FastAPI()+ app.include_router(chat_history.router, prefix = "/api/chat")+ app.dependency_overrides[chat_history.get_current_subject] = lambda: "test-user"+ _seed("a")+ studio_db.upsert_chat_settings({"autoTitle": False})+ with TestClient(app) as client:+ assert client.get("/api/chat/pins").json() == {}+ assert client.post("/api/chat/pins/migrate", json = {"ids": ["a"]}).json() == {+ "pinnedIds": ["a"]+ }+ assert client.get("/api/chat/pins").json() == {"pinnedIds": ["a"]}+ assert client.post("/api/chat/pins/migrate", json = {"ids": None}).status_code == 422+++def test_concurrent_browser_migrations_preserve_both_pin_lists():+ _seed("a", "b")+ barrier = threading.Barrier(2)++ def migrate(id):+ barrier.wait(timeout = 5)+ return _migrate([id])++ with ThreadPoolExecutor(max_workers = 2) as pool:+ list(pool.map(migrate, ["a", "b"]))+ assert set(_pins()["pinnedIds"]) == {"a", "b"}+++def test_failed_pin_write_rolls_back_tombstone_and_operation_ack():+ _seed("a")+ _migrate(["a"])+ conn = studio_db.get_connection()+ try:+ conn.execute("""CREATE TRIGGER fail_pin_write BEFORE UPDATE ON chat_settings+ WHEN NEW.key = 'pinnedChatIds'+ BEGIN SELECT RAISE(ABORT, 'test write failure'); END""")+ conn.commit()+ finally:+ conn.close()+ with pytest.raises(sqlite3.IntegrityError):+ _save_if_current(+ {"pinnedChatIds": ["a"]},+ [],+ operation_id = "failed-unpin",+ unpinned_ids = ["not-yet-imported"],+ )+ assert _pins() == {"pinnedIds": ["a"]}+ conn = studio_db.get_connection()+ try:+ assert conn.execute("SELECT id FROM chat_pin_tombstones").fetchall() == []+ assert conn.execute("SELECT id FROM chat_pin_operations").fetchall() == []+ finally:+ conn.close()+++def test_bad_unicode_pin_does_not_prevent_deleting_a_chat():+ _seed("a")+ studio_db.upsert_chat_settings({"pinnedChatIds": ["a", chr(0xD800)]})+ studio_db.delete_chat_threads(["a"])+ assert studio_db.get_chat_thread("a") is None+ assert studio_db.list_chat_settings()["pinnedChatIds"] == []+++def test_explicit_unpin_before_thread_import_blocks_legacy_resurrection():+ assert _migrate(["late-thread"]) == {}+ unpinned = _save_if_current(+ {},+ [],+ expected_absent = True,+ operation_id = "unpin-before-import",+ unpinned_ids = ["late-thread"],+ )+ assert unpinned.applied and unpinned.settings["pinnedChatIds"] == []+ _seed("late-thread")+ assert _migrate(["late-thread"]) == {"pinnedIds": []}++ # A deliberate new pin can undo the unpin. Replaying the old acknowledgement+ # cannot add its tombstone again or undo the later explicit choice.+ assert _save_if_current(+ {"pinnedChatIds": []}, ["late-thread"], operation_id = "repin-later"+ ).applied+ replay = _save_if_current(+ {},+ [],+ expected_absent = True,+ operation_id = "unpin-before-import",+ unpinned_ids = ["late-thread"],+ )+ assert replay.applied and replay.settings["pinnedChatIds"] == ["late-thread"]+ conn = studio_db.get_connection()+ try:+ assert (+ conn.execute("SELECT id FROM chat_pin_tombstones WHERE id = 'late-thread'").fetchone()+ is None+ )+ finally:+ conn.close()+++def test_conflicting_explicit_unpin_does_not_leave_a_tombstone():+ _seed("existing")+ _migrate(["existing"])+ rejected = _save_if_current({"pinnedChatIds": []}, [], unpinned_ids = ["late-thread"])+ assert not rejected.applied+ _seed("late-thread")+ assert _migrate(["late-thread"]) == {"pinnedIds": ["existing", "late-thread"]}+++ "patch,unpinned",+ [+ ({"pinnedChatIds": ["a"]}, ["a"]),+ ({"autoTitle": False}, ["a"]),+ ({"autoTitle": False}, []),+ ({"pinnedChatIds": []}, None),+ ({"pinnedChatIds": []}, "a"),+ ({"pinnedChatIds": []}, ["a", "a"]),+ ({"pinnedChatIds": []}, [chr(0xD800)]),+ ],+)+def test_invalid_or_contradictory_explicit_unpins_are_rejected(patch, unpinned):+ with pytest.raises(HTTPException) as error:+ chat_history.compare_and_set_settings(+ {"expected": {}, "patch": patch, "unpinnedChatIds": unpinned},+ current_subject = "test-user",+ )+ assert error.value.status_code == 400+ assert studio_db.list_chat_settings() == {}++[email protected]("operation_id", [chr(0xD800), "op-" + chr(0xDFFF)])+def test_invalid_unicode_operation_id_is_rejected_before_sqlite(operation_id):+ with pytest.raises(HTTPException) as error:+ _save_if_current({}, [], expected_absent = True, operation_id = operation_id)+ assert error.value.status_code == 400+ assert studio_db.list_chat_settings() == {}+++def test_a_delayed_pin_an_unpin_cancelled_is_acknowledged_without_applying():+ _seed("chat")+ _save_if_current({}, [], expected_absent = True)+ unpin = _save_if_current(+ {"pinnedChatIds": []},+ [],+ operation_id = "unpin-op",+ unpinned_ids = ["chat"],+ cancelled_operation_ids = ["pin-op"],+ )+ assert unpin.applied+ delayed = _save_if_current({"pinnedChatIds": []}, ["chat"], operation_id = "pin-op")+ assert delayed.applied+ assert _pins() == {"pinnedIds": []}+++def test_cancelled_operation_ids_require_a_pin_only_patch():+ with pytest.raises(HTTPException) as error:+ chat_history.compare_and_set_settings(+ {"expected": {}, "patch": {"autoTitle": False}, "cancelledOperationIds": ["op"]},+ current_subject = "test-user",+ )+ assert error.value.status_code == 400diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.tsindex 4d297245fd2..0013b1f53ba 100644--- a/studio/frontend/scripts/check-bundle-budget.ts+++ b/studio/frontend/scripts/check-bundle-budget.ts@@ -426,8 +426,12 @@ export const BUDGET = {// Cosmos3 video families (#14554): +466 B raw / +218 B transfer. Raised by that.// Lookup-table pricing (#14465): +1,517 B raw / +470 B transfer on top of the lines above (measured merged with// 4db3eaeb55, Node 24, 99 chunks).- transferBytes: 2_101_185,- rawBytes: 6_973_555,+ // Chat pins synced through the server (#15293): the sync runtime is a lazy chunk, but the modules it shares+ // with startup code (chat-settings-api, sidebar-organization-keys) split into their own eager chunks, plus the+ // mount hook and store wiring: +3,074 B raw / +2,025 B transfer (6,958,762 -> 6,961,836 B raw, 2,099,260 ->+ // 2,101,285 B transfer against 9c397197e0, Node 24, 106 -> 109 chunks). Raised by that growth.+ transferBytes: 2_103_210,+ rawBytes: 6_976_629,};// Chunk count is not budgeted: splitting a page out raises it while lowering bytes.diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsxindex 2c8793f63fc..711c1918559 100644--- a/studio/frontend/src/app/routes/__root.tsx+++ b/studio/frontend/src/app/routes/__root.tsx@@ -28,6 +28,7 @@ import {StopRunningChatsDialog,useOpeningFolder,useChatRuntimeStore,+ usePinnedChatsSync,} from "@/features/chat";import { useExportRuntimeLifecycle } from "@/features/export";import { FIND_SCOPE_ATTRIBUTE, FindInPage } from "@/features/find-in-page";@@ -196,6 +197,7 @@ function HubSourceNoticeMount() {// Models page and picker read chat settings too, so hydration cannot wait for ChatPage.function ChatSettingsHydrationMount() {+ usePinnedChatsSync();const hydratePersistedSettings = useChatRuntimeStore((state) => state.hydratePersistedSettings,);diff --git a/studio/frontend/src/features/chat/api/chat-pins-api.ts b/studio/frontend/src/features/chat/api/chat-pins-api.tsnew file mode 100644index 00000000000..b307669788a--- /dev/null+++ b/studio/frontend/src/features/chat/api/chat-pins-api.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++import { authFetch } from "@/features/auth";+import {+ getChatSettings,+ saveChatSettingsPatchIfCurrent,+} from "./chat-settings-api";+import { ChatSettingsRequestError } from "../utils/settings-retry";+import {+ type PinOperation,+ PinnedChatsValidationError,+ validatePinnedIds,+} from "../utils/pinned-chats-sync";++/** Scoped to one auth session; every refresh probes for a backend upgrade. */+export function createChatPinsApi(sessionSignal: AbortSignal) {+ let supportsOperationId = false;++ async function bounded<T>(+ run: (signal: AbortSignal) => Promise<T>,+ ): Promise<T> {+ // The supported WebKit floor lacks AbortSignal.any; release listener and timer per request.+ const controller = new AbortController();+ const abort = () => controller.abort();+ sessionSignal.addEventListener("abort", abort);+ if (sessionSignal.aborted) abort();+ const timer = setTimeout(abort, 10_000);+ try {+ return await run(controller.signal);+ } finally {+ clearTimeout(timer);+ sessionSignal.removeEventListener("abort", abort);+ }+ }++ async function request(+ path: string,+ ids?: string[],+ ): Promise<string[] | undefined> {+ return bounded(async (signal) => {+ const response = await authFetch(path, {+ signal,+ ...(ids === undefined+ ? {}+ : {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ ids }),+ }),+ });+ const data: unknown = await response.json().catch((error: unknown) => {+ // A 200 whose body was cut off is a transport failure to retry, not an invalid answer.+ if (signal.aborted || response.ok) throw error;+ return null;+ });+ if (!response.ok) {+ const detail =+ data && typeof data === "object" && "detail" in data+ ? data.detail+ : null;+ throw new ChatSettingsRequestError(+ `Unable to sync pinned chats (${response.status})`,+ response.status,+ detail,+ );+ }+ if (!data || typeof data !== "object" || Array.isArray(data))+ throw new PinnedChatsValidationError("Invalid pinned chats response");+ supportsOperationId = true;+ return validatePinnedIds(+ "pinnedIds" in data ? data.pinnedIds : undefined,+ );+ });+ }++ function missingRoute(error: unknown): boolean {+ return (+ error instanceof ChatSettingsRequestError &&+ (error.status === 404 || error.status === 405)+ );+ }++ async function compareAndSet(+ expected: string[] | undefined,+ next: string[],+ operation?: PinOperation,+ ) {+ const result = await bounded((signal) =>+ saveChatSettingsPatchIfCurrent(+ expected === undefined ? {} : { pinnedChatIds: expected },+ { pinnedChatIds: next },+ expected === undefined ? ["pinnedChatIds"] : [],+ [],+ {+ signal,+ requireSupport: true,+ operationId: supportsOperationId+ ? (operation?.serverId ?? operation?.operationId)+ : undefined,+ unpinnedChatIds:+ supportsOperationId && operation && !operation.pinned+ ? operation.ids+ : undefined,+ cancelledOperationIds: supportsOperationId+ ? operation?.cancels+ : undefined,+ },+ ),+ );+ return {+ applied: result.applied,+ pinnedIds: validatePinnedIds(result.settings?.pinnedChatIds),+ };+ }++ return {+ async load(): Promise<string[] | undefined> {+ try {+ return await request("/api/chat/pins");+ } catch (error) {+ if (!missingRoute(error)) throw error;+ supportsOperationId = false;+ return validatePinnedIds(+ (await bounded((signal) => getChatSettings({ signal })))+ .pinnedChatIds,+ );+ }+ },+ async migrateLegacy(ids: string[]): Promise<string[] | undefined> {+ try {+ return await request("/api/chat/pins/migrate", ids);+ } catch (error) {+ if (!missingRoute(error)) throw error;+ supportsOperationId = false;+ const current = validatePinnedIds(+ (await bounded((signal) => getChatSettings({ signal })))+ .pinnedChatIds,+ );+ // A backend with the setting but no tombstones cannot merge stale browser lists.+ if (current !== undefined) return current;+ return (await compareAndSet(undefined, ids)).pinnedIds;+ }+ },+ compareAndSet,+ };+}diff --git a/studio/frontend/src/features/chat/api/chat-settings-api.ts b/studio/frontend/src/features/chat/api/chat-settings-api.tsindex 8351e5bb5f7..a97526096ff 100644--- a/studio/frontend/src/features/chat/api/chat-settings-api.ts+++ b/studio/frontend/src/features/chat/api/chat-settings-api.ts@@ -15,10 +15,7 @@ import type {ResearchMcpSource,ResearchWebsitePolicy,} from "../types/research";-import type {- InferenceParams,- PersistedInferenceParams,-} from "../types/runtime";+import type { PersistedInferenceParams } from "../types/runtime";import {ChatSettingsRequestError,isUnderKeepaliveBudget,@@ -33,6 +30,8 @@ export interface PersistedChatPreset {}export interface PersistedChatSettings {+ /** Ordered sidebar chat/pair IDs, shared by clients of this installation. */+ pinnedChatIds?: string[];inferenceParams?: PersistedInferenceParams;inferenceParamsByModel?: Record<string, PersistedInferenceParams>;/** Outgoing only: per model id, keys of the entry above the server drops before merging the rest. */@@ -138,8 +137,10 @@ async function parseJsonOrThrow<T>(response: Response): Promise<T> {return body as T;}-export async function getChatSettings(): Promise<PersistedChatSettings> {- const response = await authFetch("/api/chat/settings");+export async function getChatSettings(+ options: { signal?: AbortSignal } = {},+): Promise<PersistedChatSettings> {+ const response = await authFetch("/api/chat/settings", options);const data = await parseJsonOrThrow<ChatSettingsResponse>(response);return data.settings;}@@ -165,8 +166,16 @@ export async function saveChatSettingsPatchIfCurrent(patch: PersistedChatSettings,expectedAbsent: Array<keyof PersistedChatSettings> = [],expectedAbsentPaths: ChatSettingsPath[] = [],+ options: {+ signal?: AbortSignal;+ requireSupport?: boolean;+ operationId?: string;+ unpinnedChatIds?: string[];+ cancelledOperationIds?: string[];+ } = {},): Promise<{ settings: PersistedChatSettings; applied: boolean }> {const response = await authFetch("/api/chat/settings/compare-and-set", {+ signal: options.signal,method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({@@ -174,10 +183,20 @@ export async function saveChatSettingsPatchIfCurrent(expectedAbsent,expectedAbsentPaths,patch,+ ...(options.operationId ? { operationId: options.operationId } : {}),+ ...(options.unpinnedChatIds+ ? { unpinnedChatIds: options.unpinnedChatIds }+ : {}),+ ...(options.cancelledOperationIds?.length+ ? { cancelledOperationIds: options.cancelledOperationIds }+ : {}),}),});// 404 (--api-only) or 405 (browser SPA catch-all) means an older backend: report not applied.- if (response.status === 404 || response.status === 405) {+ if (+ !options.requireSupport &&+ (response.status === 404 || response.status === 405)+ ) {return { settings: expected, applied: false };}return parseJsonOrThrow<ConditionalChatSettingsResponse>(response);diff --git a/studio/frontend/src/features/chat/hooks/use-pinned-chats-sync.ts b/studio/frontend/src/features/chat/hooks/use-pinned-chats-sync.tsnew file mode 100644index 00000000000..aaf45598555--- /dev/null+++ b/studio/frontend/src/features/chat/hooks/use-pinned-chats-sync.ts@@ -0,0 +1,88 @@+// 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 { useEffect } from "react";+import {+ AUTH_SESSION_CLEARED_EVENT,+ AUTH_SESSION_STORED_EVENT,+ AUTH_SESSION_MARK_KEY,+ AUTH_TOKEN_KEY,+ hasAuthToken,+} from "@/features/auth";+import {+ PIN_JOURNAL_PREFIX,+ discardUnboundPinEdits,+} from "../stores/pinned-chats-store";++// Loaded on mount, not at startup: the sync runtime would push the eager bundle over budget.+let runtime: Promise<typeof import("../sync-pinned-chats")> | undefined;+const loadRuntime = () =>+ (runtime ??= import("../sync-pinned-chats").catch((error: unknown) => {+ // Browsers refetch a failed dynamic import, so the next focus/online/poll retries it.+ runtime = undefined;+ throw error;+ }));++/** Keep pins current across clients, and discard in-flight work at session boundaries. */+export function usePinnedChatsSync(): void {+ useEffect(() => {+ let sessionMark = localStorage.getItem(AUTH_SESSION_MARK_KEY);+ const refresh = () => {+ if (hasAuthToken() && document.visibilityState === "visible") {+ void loadRuntime()+ .then((sync) => {+ const refreshed = sync.refreshPinnedChats();+ // Its synchronous scope() may have just backfilled the mark of a pre-mark session.+ sessionMark = localStorage.getItem(AUTH_SESSION_MARK_KEY);+ return refreshed;+ })+ .catch(() => undefined);+ sessionMark = localStorage.getItem(AUTH_SESSION_MARK_KEY);+ }+ };+ const reconcileSession = () => {+ // Synchronous, so a runtime that fails to load cannot carry edits into the next session.+ discardUnboundPinEdits();+ void loadRuntime()+ .then((sync) => sync.resetPinnedChats({ clearPending: true }))+ .catch(() => undefined);+ sessionMark = localStorage.getItem(AUTH_SESSION_MARK_KEY);+ refresh();+ };+ const onStorage = (event: StorageEvent) => {+ if (event.key?.startsWith(PIN_JOURNAL_PREFIX)) refresh();+ if (+ event.key === null ||+ event.key === AUTH_SESSION_MARK_KEY ||+ event.key === AUTH_TOKEN_KEY+ ) {+ const nextMark = localStorage.getItem(AUTH_SESSION_MARK_KEY);+ if (nextMark !== sessionMark || !hasAuthToken()) reconcileSession();+ }+ };+ window.addEventListener(AUTH_SESSION_CLEARED_EVENT, reconcileSession);+ window.addEventListener(AUTH_SESSION_STORED_EVENT, reconcileSession);+ window.addEventListener("storage", onStorage);+ window.addEventListener("focus", refresh);+ window.addEventListener("online", refresh);+ document.addEventListener("visibilitychange", refresh);+ const timer = window.setInterval(refresh, 30_000);+ refresh();+ return () => {+ window.clearInterval(timer);+ window.removeEventListener(AUTH_SESSION_CLEARED_EVENT, reconcileSession);+ window.removeEventListener(AUTH_SESSION_STORED_EVENT, reconcileSession);+ window.removeEventListener("storage", onStorage);+ window.removeEventListener("focus", refresh);+ window.removeEventListener("online", refresh);+ document.removeEventListener("visibilitychange", refresh);+ const clearPending =+ !hasAuthToken() ||+ localStorage.getItem(AUTH_SESSION_MARK_KEY) !== sessionMark;+ if (clearPending) discardUnboundPinEdits();+ void loadRuntime()+ .then((sync) => sync.resetPinnedChats({ clearPending }))+ .catch(() => undefined);+ };+ }, []);+}diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex b894e805205..bcf3578f616 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -215,6 +215,7 @@ export {type SectionLanding,} from "./hooks/use-section-drag";export { usePinnedChatsStore } from "./stores/pinned-chats-store";+export { usePinnedChatsSync } from "./hooks/use-pinned-chats-sync";export { usePinnedProjectsStore } from "./stores/pinned-projects-store";export {applyManualOrder,diff --git a/studio/frontend/src/features/chat/stores/pinned-chats-store.ts b/studio/frontend/src/features/chat/stores/pinned-chats-store.tsindex e44257abaf2..e80ef6d6346 100644--- a/studio/frontend/src/features/chat/stores/pinned-chats-store.ts+++ b/studio/frontend/src/features/chat/stores/pinned-chats-store.ts@@ -2,52 +2,95 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { create } from "zustand";-import { persist } from "zustand/middleware";-// Kept in localStorage, not the chat DB; new pins are prepended so the newest pin sorts first.-export interface PinnedChatsState {+// Here, not in the journal, so the startup hook can read it without loading the sync runtime.+export const PIN_JOURNAL_PREFIX = "unsloth_chat_pin_journal:";++export interface PinnedChatsActions {+ setPinned: (ids: string[], pinned: boolean) => void;+}++export interface PinnedChatsState extends PinnedChatsActions {+ /** Stable chat IDs (or pair IDs for comparisons), in manual pin order. */pinnedIds: string[];togglePin: (id: string) => void;unpin: (id: string) => void;- setPinned: (ids: string[], pinned: boolean) => void;}-export const usePinnedChatsStore = create<PinnedChatsState>()(- persist(- (set) => ({- pinnedIds: [],- togglePin: (id) =>- set((state) => ({- pinnedIds: state.pinnedIds.includes(id)- ? state.pinnedIds.filter((x) => x !== id)- : [id, ...state.pinnedIds],- })),- unpin: (id) =>- set((state) => ({- pinnedIds: state.pinnedIds.filter((x) => x !== id),- })),- setPinned: (ids, pinned) =>- set((state) => {- if (!pinned) {- const dropping = new Set(ids);- return {- pinnedIds: state.pinnedIds.filter((id) => !dropping.has(id)),- };- }- const additions = ids.filter((id) => !state.pinnedIds.includes(id));- if (additions.length === 0) return state;- return { pinnedIds: [...additions, ...state.pinnedIds] };- }),- }),- {- name: "unsloth_pinned_chats",- merge: (persisted, current) => {- const saved = persisted as Partial<PinnedChatsState> | undefined;- return {- ...current,- pinnedIds: Array.isArray(saved?.pinnedIds) ? saved.pinnedIds : [],- };- },- },- ),-);+let actions: PinnedChatsActions | null = null;++// Edits made before the lazy runtime binds; they survive a reload. Memory when storage is absent.+const UNBOUND_KEY = "unsloth_chat_pin_unbound";+let unboundMemory: Array<[string[], boolean]> = [];++function readUnbound(): Array<[string[], boolean]> {+ try {+ if (typeof localStorage === "undefined") return unboundMemory;+ const saved: unknown = JSON.parse(localStorage.getItem(UNBOUND_KEY) ?? "[]");+ return Array.isArray(saved)+ ? saved.filter(+ (entry): entry is [string[], boolean] =>+ Array.isArray(entry) &&+ Array.isArray(entry[0]) &&+ entry[0].every((id: unknown) => typeof id === "string") &&+ typeof entry[1] === "boolean",+ )+ : [];+ } catch {+ return unboundMemory;+ }+}++function writeUnbound(edits: Array<[string[], boolean]>): void {+ unboundMemory = edits;+ try {+ if (typeof localStorage === "undefined") return;+ if (edits.length) localStorage.setItem(UNBOUND_KEY, JSON.stringify(edits));+ else localStorage.removeItem(UNBOUND_KEY);+ } catch {+ // Storage full or blocked: the edit still reaches the runtime if it binds this session.+ }+}++/** Sign-out: drop edits made before the runtime bound and the pins they showed. */+export function discardUnboundPinEdits(): void {+ writeUnbound([]);+ usePinnedChatsStore.setState({ pinnedIds: [] });+}++/** Bind persistence at runtime without pulling API/auth modules into this state store. */+export function setPinnedChatsActions(next: PinnedChatsActions | null): void {+ actions = next;+ if (!next) return;+ const queued = readUnbound();+ writeUnbound([]);+ for (const [ids, pinned] of queued) next.setPinned(ids, pinned);+}++export const usePinnedChatsStore = create<PinnedChatsState>((set, get) => ({+ pinnedIds: [],+ togglePin: (id) => get().setPinned([id], !get().pinnedIds.includes(id)),+ unpin: (id) => get().setPinned([id], false),+ setPinned: (ids, pinned) => {+ if (actions) {+ actions.setPinned(ids, pinned);+ return;+ }+ writeUnbound([...readUnbound(), [ids, pinned]]);+ set((state) => {+ if (!pinned) {+ const dropping = new Set(ids);+ const next = state.pinnedIds.filter((id) => !dropping.has(id));+ return next.length === state.pinnedIds.length+ ? state+ : { pinnedIds: next };+ }+ const additions = [...new Set(ids)].filter(+ (id) => !state.pinnedIds.includes(id),+ );+ return additions.length === 0+ ? state+ : { pinnedIds: [...additions, ...state.pinnedIds] };+ });+ },+}));diff --git a/studio/frontend/src/features/chat/sync-pinned-chats.ts b/studio/frontend/src/features/chat/sync-pinned-chats.tsnew file mode 100644index 00000000000..2430f3393c2--- /dev/null+++ b/studio/frontend/src/features/chat/sync-pinned-chats.ts@@ -0,0 +1,118 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { toast } from "sonner";+import { AUTH_SESSION_MARK_KEY, hasAuthToken } from "@/features/auth";+import { getApiBase, isTauri } from "@/lib/api-base";+import { createNavigationNonce } from "@/lib/navigation-nonce";+import { createChatPinsApi } from "./api/chat-pins-api";+import {+ discardUnboundPinEdits,+ setPinnedChatsActions,+ usePinnedChatsStore,+} from "./stores/pinned-chats-store";+import {+ preserveFallbackPins,+ readLegacyPinnedChatIds,+} from "./utils/legacy-pinned-chats";+import { createPinnedChatsJournal } from "./utils/pinned-chats-journal";+import { createPinnedChatsSync } from "./utils/pinned-chats-sync";+import { createPinnedChatsTransport } from "./utils/pinned-chats-transport";+import { isRetryablePinError } from "./utils/settings-retry";+import { onChatThreadsDeleted } from "./utils/chat-thread-tombstones";++function scope(): string {+ // Desktop's backend port changes between launches of the same installation.+ const server = isTauri+ ? window.location.origin+ : getApiBase() || window.location.origin;+ let mark = localStorage.getItem(AUTH_SESSION_MARK_KEY);+ if (!mark) {+ // Pre-mark sessions get one on token refresh, stranding the journal: set it now.+ mark = createNavigationNonce();+ localStorage.setItem(AUTH_SESSION_MARK_KEY, mark);+ }+ return `${server}|${mark}`;+}++function createRuntime(sessionScope: string) {+ const controller = new AbortController();+ const journal = createPinnedChatsJournal(localStorage, sessionScope);+ const legacy = readLegacyPinnedChatIds(localStorage);+ // Re-sent every refresh: legacy import may create rows later; tombstones keep unpins.+ const readLegacy = () => legacy;+ const api = createChatPinsApi(controller.signal);+ const transport = createPinnedChatsTransport({+ ...api,+ migrateLegacy: (ids) =>+ api.migrateLegacy([...new Set([...ids, ...readLegacy()])]),+ readLegacy,+ readFallback: journal.readFallback,+ writeFallback: journal.writeFallback,+ onUnsupported: () =>+ toast.info(+ "This server saves pins in this browser. They will sync after the server is updated.",+ { id: "pinned-chats-compatibility" },+ ),+ });+ const sync = createPinnedChatsSync({+ ...transport,+ readLegacy,+ readPending: journal.readPending,+ writePending: journal.writePending,+ isRetryable: isRetryablePinError,+ publish: (pinnedIds) => usePinnedChatsStore.setState({ pinnedIds }),+ onError: () =>+ toast.error("Could not sync pinned chats. Try again when connected.", {+ id: "pinned-chats-sync-error",+ }),+ });+ // Every delete path unpins what it removed, so a never-imported comparison's pin cannot block.+ const stopWatchingDeletes = onChatThreadsDeleted((threadIds, pairIds) => {+ const pinned = new Set(usePinnedChatsStore.getState().pinnedIds);+ const removed = [...threadIds, ...pairIds].filter((id) => pinned.has(id));+ if (removed.length > 0) void sync.setPinned(removed, false).catch(() => undefined);+ });+ setPinnedChatsActions({+ setPinned: (ids, pinned) => {+ void sync.setPinned(ids, pinned).catch(() => undefined);+ },+ });+ return {+ scope: sessionScope,+ refresh: sync.refresh,+ reset(clearPending: boolean) {+ controller.abort();+ stopWatchingDeletes();+ transport.reset();+ sync.reset();+ setPinnedChatsActions(null);+ if (clearPending) {+ preserveFallbackPins(localStorage, journal.readFallback);+ journal.clear();+ }+ },+ };+}++let runtime: ReturnType<typeof createRuntime> | undefined;++export async function refreshPinnedChats(): Promise<void> {+ if (!hasAuthToken()) return;+ const sessionScope = scope();+ if (runtime?.scope !== sessionScope) {+ runtime?.reset(true);+ runtime = createRuntime(sessionScope);+ }+ await runtime.refresh();+}++/** Unmount retains durable work; sign-out/account changes explicitly discard it. */+export function resetPinnedChats({+ clearPending = false,+}: { clearPending?: boolean } = {}): void {+ const previous = runtime;+ runtime = undefined;+ previous?.reset(clearPending);+ if (clearPending) discardUnboundPinEdits();+}diff --git a/studio/frontend/src/features/chat/utils/clear-all-chats.ts b/studio/frontend/src/features/chat/utils/clear-all-chats.tsindex c0c91829811..d1b6c9fbd2e 100644--- a/studio/frontend/src/features/chat/utils/clear-all-chats.ts+++ b/studio/frontend/src/features/chat/utils/clear-all-chats.ts@@ -2,6 +2,7 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import { useChatRuntimeStore } from "../stores/chat-runtime-store";+import { usePinnedChatsStore } from "../stores/pinned-chats-store";import { chatHistoryClearBoundary } from "./chat-history-clear-boundary";import { clearStoredChats, countStoredChats } from "./chat-history-storage";import { requestPromptQueueStop } from "./prompt-queue-boundary";@@ -23,5 +24,14 @@ export async function clearAllChats(options: { deleteFiles?: boolean } = {}) {stopChatThread(threadId);}requestPromptQueueStop();- return await clearStoredChats(options);+ // Snapshot first: a chat another client creates and pins mid-clear survives it.+ const pinnedBefore = usePinnedChatsStore.getState().pinnedIds;+ const result = await clearStoredChats(options);+ if (result.backend === "cleared") {+ // Unpin what was cleared, so a never-imported comparison's queued pin cannot block later saves.+ const failed = new Set(result.failedThreadIds);+ const removed = pinnedBefore.filter((id) => !failed.has(id));+ if (removed.length > 0) usePinnedChatsStore.getState().setPinned(removed, false);+ }+ return result;}diff --git a/studio/frontend/src/features/chat/utils/legacy-pinned-chats.ts b/studio/frontend/src/features/chat/utils/legacy-pinned-chats.tsnew file mode 100644index 00000000000..d52950b81e8--- /dev/null+++ b/studio/frontend/src/features/chat/utils/legacy-pinned-chats.ts@@ -0,0 +1,67 @@+// 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 { SIDEBAR_ORGANIZATION_STORAGE_KEY } from "../stores/sidebar-organization-keys.ts";+import { isValidPinId } from "./pinned-chats-sync.ts";++function ids(value: unknown): string[] {+ if (!Array.isArray(value)) {+ return [];+ }+ return [...new Set(value.filter(isValidPinId))].slice(0, 10_000);+}++/** Read the old browser-only pins once the server confirms it has no pin state. */+export function readLegacyPinnedChatIds(+ storage: Pick<Storage, "getItem">,+): string[] {+ try {+ const saved = JSON.parse(storage.getItem("unsloth_pinned_chats") ?? "null");+ const pinned = ids(saved?.state?.pinnedIds);+ if (saved?.state?.manualOrderIncluded === true) {+ return pinned;+ }+ let order: string[] = [];+ try {+ const organization = JSON.parse(+ storage.getItem(SIDEBAR_ORGANIZATION_STORAGE_KEY) ?? "null",+ );+ order = ids(organization?.state?.manualOrder?.pinned);+ } catch {+ // A damaged sidebar preference must not discard otherwise valid pins.+ }+ const rank = new Map(order.map((id, index) => [id, index]));+ // Match the old sidebar: newly pinned (unranked) chats lead the dragged rows.+ return pinned.sort((a, b) => (rank.get(a) ?? -1) - (rank.get(b) ?? -1));+ } catch {+ return [];+ }+}++/** Older servers: keep the full order in one browser write, read back as-is. */+export function writeLocalPinnedChatIds(+ storage: Pick<Storage, "setItem">,+ pinnedIds: string[],+): void {+ storage.setItem(+ "unsloth_pinned_chats",+ JSON.stringify({+ state: { pinnedIds, manualOrderIncluded: true },+ version: 0,+ }),+ );+}++/** Sign-out clears the session-scoped journal; keep what an older backend saved only there. */+export function preserveFallbackPins(+ storage: Pick<Storage, "setItem">,+ readFallback: () => { pinnedIds: string[] } | undefined,+): void {+ try {+ const saved = readFallback();+ if (saved) writeLocalPinnedChatIds(storage, saved.pinnedIds);+ } catch {+ // A damaged journal holds nothing worth keeping.+ }+}+diff --git a/studio/frontend/src/features/chat/utils/pinned-chats-journal.ts b/studio/frontend/src/features/chat/utils/pinned-chats-journal.tsnew file mode 100644index 00000000000..97d33fdee52--- /dev/null+++ b/studio/frontend/src/features/chat/utils/pinned-chats-journal.ts@@ -0,0 +1,169 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import {+ type PinOperation,+ applyPinOperation,+ validatePinOperation,+ validatePinnedIds,+} from "./pinned-chats-sync.ts";+import type { PinnedChatsFallbackState } from "./pinned-chats-transport.ts";+import { PIN_JOURNAL_PREFIX } from "../stores/pinned-chats-store.ts";+import { createNavigationNonce } from "../../../lib/navigation-nonce.ts";++export { PIN_JOURNAL_PREFIX };++interface Entry {+ operation?: PinOperation;+ baseIds?: string[];+ order: number;+}++/** One immutable key per intent prevents tabs from overwriting each other's queues. */+export function createPinnedChatsJournal(storage: Storage, scope: string) {+ const prefix = `${PIN_JOURNAL_PREFIX}${encodeURIComponent(scope)}:`;+ const seedKey = `${prefix}fallback:seed:${createNavigationNonce()}`;+ const observed = { pending: new Set<string>(), fallback: new Set<string>() };+ let lastOrder = 0;++ function keys(kind: "pending" | "fallback"): string[] {+ const start = `${prefix}${kind}:`;+ const result: string[] = [];+ for (let i = 0; i < storage.length; i += 1) {+ const key = storage.key(i);+ if (key?.startsWith(start)) {+ result.push(key);+ }+ }+ return result;+ }++ function read(kind: "pending" | "fallback"): [string, Entry][] {+ const result: [string, Entry][] = [];+ for (const key of keys(kind)) {+ const raw = storage.getItem(key);+ if (raw === null) {+ continue;+ }+ const value = JSON.parse(raw) as Entry;+ if (!(value && Number.isFinite(value.order))) {+ throw new Error("Invalid saved pin change");+ }+ if (kind === "pending" || value.operation !== undefined) {+ value.operation = validatePinOperation(value.operation);+ }+ if (kind === "fallback") {+ value.baseIds = validatePinnedIds(value.baseIds);+ if (!value.baseIds) {+ throw new Error("Invalid saved pin state");+ }+ }+ observed[kind].add(key);+ lastOrder = Math.max(lastOrder, value.order);+ result.push([key, value]);+ }+ return result.sort(+ ([a, x], [b, y]) => x.order - y.order || a.localeCompare(b),+ );+ }++ function write(+ kind: "pending" | "fallback",+ operations: PinOperation[],+ baseIds?: string[],+ ): void {+ const keep = new Set<string>();+ const keyOf = (operation: PinOperation) =>+ `${prefix}${kind}:${operation.operationId}`;+ const storedOrder = (key: string): number | undefined => {+ const raw = storage.getItem(key);+ if (raw === null) return undefined;+ const order = (JSON.parse(raw) as Entry).order;+ return Number.isFinite(order) ? order : undefined;+ };+ let previous: number | undefined;+ operations.forEach((operation, index) => {+ validatePinOperation(operation);+ const key = keyOf(operation);+ let order = storedOrder(key);+ if (order === undefined) {+ // Seen here and gone now: another tab acknowledged or cancelled it. Never recreate it.+ if (observed[kind].has(key)) return;+ // A trimmed pin keeps its slot: it must replay before the unpin fencing its server ID.+ let next: number | undefined;+ for (const later of operations.slice(index + 1)) {+ next = storedOrder(keyOf(later));+ if (next !== undefined) break;+ }+ order =+ next === undefined+ ? Math.max(Date.now(), lastOrder + 1, (previous ?? 0) + 1)+ : previous === undefined+ ? next - 1+ : (previous + next) / 2;+ lastOrder = Math.max(lastOrder, order);+ storage.setItem(key, JSON.stringify({ operation, baseIds, order }));+ }+ previous = order;+ keep.add(key);+ });+ // A fallback seed is needed even before the first offline mutation.+ if (+ kind === "fallback" &&+ baseIds !== undefined &&+ operations.length === 0+ ) {+ const key = seedKey;+ keep.add(key);+ lastOrder = Math.max(Date.now(), lastOrder + 1);+ storage.setItem(key, JSON.stringify({ baseIds, order: lastOrder }));+ }+ // Only acknowledge entries seen here: another tab may have appended one mid-request.+ for (const key of observed[kind]) {+ if (!keep.has(key)) {+ storage.removeItem(key);+ }+ }+ observed[kind] = keep;+ }++ return {+ readPending(): PinOperation[] {+ return read("pending").flatMap(([, value]) =>+ value.operation ? [value.operation] : [],+ );+ },+ writePending(operations: PinOperation[]): void {+ write("pending", operations);+ },+ readFallback(): PinnedChatsFallbackState | undefined {+ const entries = read("fallback");+ if (entries.length === 0) {+ return undefined;+ }+ const baseIds = [+ ...new Set(entries.flatMap(([, value]) => value.baseIds ?? [])),+ ];+ validatePinnedIds(baseIds);+ const operations = entries.flatMap(([, value]) =>+ value.operation ? [value.operation] : [],+ );+ return {+ baseIds,+ operations,+ pinnedIds: operations.reduce(applyPinOperation, baseIds),+ };+ },+ writeFallback(state: PinnedChatsFallbackState | undefined): void {+ write("fallback", state?.operations ?? [], state?.baseIds);+ },+ clear(): void {+ for (const kind of ["pending", "fallback"] as const) {+ for (const key of keys(kind)) {+ storage.removeItem(key);+ }+ observed[kind].clear();+ }+ },+ };+}diff --git a/studio/frontend/src/features/chat/utils/pinned-chats-sync.ts b/studio/frontend/src/features/chat/utils/pinned-chats-sync.tsnew file mode 100644index 00000000000..0ab09a71a9b--- /dev/null+++ b/studio/frontend/src/features/chat/utils/pinned-chats-sync.ts@@ -0,0 +1,447 @@+// 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 { createNavigationNonce } from "../../../lib/navigation-nonce.ts";++export type PinOperation = {+ operationId: string;+ kind: "pin";+ ids: string[];+ pinned: boolean;+ /** Queued pins this unpin superseded; the server acknowledges them without applying. */+ cancels?: string[];+ /** Server replay ID when it differs from the journal's: a trimmed intent keeps its original's. */+ serverId?: string;+};++export interface PinnedChatsSyncOptions {+ load: () => Promise<string[] | undefined>;+ compareAndSet: (+ expected: string[] | undefined,+ next: string[],+ operation?: PinOperation,+ ) => Promise<{ pinnedIds: string[] | undefined; applied: boolean }>;+ readLegacy: () => string[];+ migrateLegacy?: (ids: string[]) => Promise<string[] | undefined>;+ readPending?: () => PinOperation[];+ writePending?: (operations: PinOperation[]) => void;+ isRetryable?: (error: unknown) => boolean;+ publish: (ids: string[]) => void;+ onError?: (error: unknown) => void;+}++export class PinnedChatsValidationError extends Error {}++export function isValidPinId(value: unknown): value is string {+ if (typeof value !== "string" || value.length === 0 || value.length > 512) {+ return false;+ }+ // JSON can contain lone UTF-16 surrogates, which cannot be stored as UTF-8.+ for (let index = 0; index < value.length; index += 1) {+ const code = value.charCodeAt(index);+ if (code >= 0xd800 && code <= 0xdbff) {+ const next = value.charCodeAt(++index);+ if (!(next >= 0xdc00 && next <= 0xdfff)) {+ return false;+ }+ } else if (code >= 0xdc00 && code <= 0xdfff) {+ return false;+ }+ }+ return true;+}++export function validatePinnedIds(value: unknown): string[] | undefined {+ if (value === undefined) {+ return undefined;+ }+ if (+ !Array.isArray(value) ||+ value.length > 10_000 ||+ !value.every(isValidPinId) ||+ new Set(value).size !== value.length+ ) {+ throw new PinnedChatsValidationError("Invalid pinned chats response");+ }+ return value.slice();+}++export function validatePinOperation(value: unknown): PinOperation {+ if (!value || typeof value !== "object") {+ throw new PinnedChatsValidationError("Invalid pending pin operation");+ }+ const operation = value as Partial<PinOperation>;+ if (!isValidPinId(operation.operationId)) {+ throw new PinnedChatsValidationError("Invalid pending pin operation");+ }+ if (operation.kind === "pin" && typeof operation.pinned === "boolean") {+ const ids = validatePinnedIds(operation.ids);+ const cancels = validatePinnedIds(operation.cancels);+ const serverId =+ operation.serverId === undefined || isValidPinId(operation.serverId)+ ? operation.serverId+ : null;+ if (ids && serverId !== null) {+ return {+ kind: "pin",+ operationId: operation.operationId,+ ids,+ pinned: operation.pinned,+ ...(cancels?.length ? { cancels } : {}),+ ...(serverId ? { serverId } : {}),+ };+ }+ }+ throw new PinnedChatsValidationError("Invalid pending pin operation");+}++/** Apply relative intent to the latest state, without reviving missing rows. */+export function applyPinOperation(+ ids: string[],+ operation: PinOperation,+): string[] {+ const selected = new Set(operation.ids);+ if (!operation.pinned) {+ return ids.filter((id) => !selected.has(id));+ }+ const present = new Set(ids);+ return [...operation.ids.filter((id) => !present.has(id)), ...ids];+}++/** A durable FIFO of pin intents, rebased when another client writes first. */+export function createPinnedChatsSync(options: PinnedChatsSyncOptions) {+ let generation = 0;+ let loaded = false;+ let confirmed: string[] | undefined;+ let pending: PinOperation[] = [];+ let queue: Promise<void> = Promise.resolve();+ let refreshing: Promise<void> | undefined;+ const scheduled = new Map<string, Promise<void>>();+ // A response arrived, but removing its journal entry may still need retrying.+ const acknowledged = new Set<string>();++ function publish() {+ options.publish(pending.reduce(applyPinOperation, confirmed ?? []));+ }++ function persist(operations: PinOperation[]): void {+ options.writePending?.(operations.map(validatePinOperation));+ }++ function restore(): void {+ if (!options.readPending) {+ return;+ }+ const saved = options.readPending();+ if (!Array.isArray(saved) || saved.length > 10_000) {+ throw new PinnedChatsValidationError("Invalid pending pin operations");+ }+ const operations = saved.map(validatePinOperation);+ // The journal is the queue, in its order: a missing intent was acknowledged/cancelled elsewhere.+ const next = [+ ...new Map(operations.map((entry) => [entry.operationId, entry])).values(),+ ];+ const changed =+ next.length !== pending.length ||+ next.some((entry, index) => entry.operationId !== pending[index]?.operationId);+ if (changed) {+ pending = next;+ publish();+ }+ }++ function rejected(error: unknown): Promise<void> {+ options.onError?.(error);+ return Promise.reject(error);+ }++ function enqueue(task: (epoch: number) => Promise<void>): Promise<void> {+ const epoch = generation;+ const result = queue.then(async () => {+ if (epoch !== generation) {+ return;+ }+ try {+ await task(epoch);+ } catch (error) {+ if (epoch !== generation) {+ return;+ }+ options.onError?.(error);+ throw error;+ }+ });+ queue = result.catch(() => undefined);+ return result;+ }++ async function mergeLegacy(+ ids: string[] | undefined,+ epoch: number,+ ): Promise<string[] | undefined> {+ const legacy = validatePinnedIds([...new Set(options.readLegacy())]) ?? [];+ if (legacy.length === 0) {+ return ids;+ }+ let result: string[] | undefined;+ if (options.migrateLegacy) {+ result = await options.migrateLegacy(legacy);+ } else if (ids === undefined) {+ // No merge endpoint: never claim an empty setting before importing legacy pins.+ result = (await options.compareAndSet(undefined, legacy)).pinnedIds;+ } else {+ return ids;+ }+ if (epoch !== generation) {+ return ids;+ }+ // The backend can leave the setting absent when every legacy ID is orphaned.+ return validatePinnedIds(result);+ }++ async function hydrate(epoch: number, force = false): Promise<void> {+ if (loaded && !force) {+ return;+ }+ const ids = validatePinnedIds(await options.load());+ if (epoch !== generation) {+ return;+ }+ const migrated = await mergeLegacy(ids, epoch);+ if (epoch !== generation) {+ return;+ }+ confirmed = migrated;+ loaded = true;+ publish();+ }++ function finish(operation: PinOperation): void {+ const remaining = pending.filter(+ (entry) => entry.operationId !== operation.operationId,+ );+ persist(remaining);+ pending = remaining;+ acknowledged.delete(operation.operationId);+ publish();+ }++ async function writeOperation(+ operation: PinOperation,+ epoch: number,+ ): Promise<void> {+ for (let attempt = 0; attempt < 8; attempt += 1) {+ if (epoch !== generation) {+ return;+ }+ try {+ // A rebase must not resend an intent another tab cancelled during the last attempt.+ restore();+ } catch {+ // An unreadable journal keeps the in-memory queue.+ }+ if (!pending.some((entry) => entry.operationId === operation.operationId)) {+ return;+ }+ const next =+ validatePinnedIds(applyPinOperation(confirmed ?? [], operation)) ?? [];+ const result = await options.compareAndSet(+ confirmed?.slice(),+ next,+ operation,+ );+ if (epoch !== generation) {+ return;+ }+ if (!result || typeof result.applied !== "boolean") {+ throw new PinnedChatsValidationError("Invalid pinned chats response");+ }+ const ids = validatePinnedIds(result.pinnedIds);+ if (result.applied && ids === undefined) {+ throw new PinnedChatsValidationError("Invalid pinned chats response");+ }+ confirmed = ids;+ if (result.applied) {+ acknowledged.add(operation.operationId);+ finish(operation);+ return;+ }+ publish();+ }+ throw new Error(+ "Pinned chats changed in another browser. Please try again.",+ );+ }++ async function recover(+ operation: PinOperation,+ error: unknown,+ epoch: number,+ ): Promise<void> {+ const retryable =+ !(error instanceof PinnedChatsValidationError) &&+ (options.isRetryable?.(error) ?? true);+ if (!(retryable || acknowledged.has(operation.operationId))) {+ // A rejected intent cannot succeed on retry; later valid intents may proceed.+ acknowledged.add(operation.operationId);+ finish(operation);+ }+ loaded = false;+ try {+ const ids = validatePinnedIds(await options.load());+ if (epoch !== generation) {+ return;+ }+ confirmed = ids;+ loaded = ids !== undefined;+ } catch {+ // Keep the last confirmed state and the durable optimistic intents.+ }+ if (epoch === generation) {+ publish();+ }+ }++ async function execute(+ operation: PinOperation,+ epoch: number,+ ): Promise<void> {+ try {+ // Another tab may have cancelled this intent while an earlier one was in flight.+ restore();+ } catch {+ // An unreadable journal keeps the in-memory queue.+ }+ if (!pending.some((entry) => entry.operationId === operation.operationId)) {+ return;+ }+ if (pending[0]?.operationId !== operation.operationId) {+ throw new Error("An earlier pin change is still waiting to save.");+ }+ try {+ if (acknowledged.has(operation.operationId)) {+ finish(operation);+ return;+ }+ await hydrate(epoch);+ await writeOperation(operation, epoch);+ } catch (error) {+ if (epoch !== generation) {+ return;+ }+ await recover(operation, error, epoch);+ throw error;+ }+ }++ function schedulePending(): Promise<void>[] {+ return pending.map((operation) => {+ const existing = scheduled.get(operation.operationId);+ if (existing) {+ return existing;+ }+ const result = enqueue((epoch) => execute(operation, epoch));+ scheduled.set(operation.operationId, result);+ const clear = () => {+ if (scheduled.get(operation.operationId) === result) {+ scheduled.delete(operation.operationId);+ }+ };+ void result.then(clear, clear);+ return result;+ });+ }++ function mutate(intent: Omit<PinOperation, "operationId">): Promise<void> {+ try {+ restore();+ let operation = validatePinOperation({+ ...intent,+ operationId: createNavigationNonce(),+ });+ // An unpin strips its chats from earlier queued pins, so an unplaceable pin cannot block.+ const cancelled = new Set(operation.pinned ? [] : operation.ids);+ const superseded: string[] = [];+ const kept = pending.flatMap((entry) => {+ if (!entry.pinned) return [entry];+ const ids = entry.ids.filter((id) => !cancelled.has(id));+ if (ids.length === entry.ids.length) return [entry];+ const serverId = entry.serverId ?? entry.operationId;+ // Another tab may already have sent it: the unpin fences its ID on the server.+ superseded.push(serverId);+ // New journal ID (entries are immutable), same server ID; it runs before the fencing unpin.+ return ids.length === 0+ ? []+ : [{ ...entry, ids, operationId: createNavigationNonce(), serverId }];+ });+ if (superseded.length > 0) {+ // An original and its trimmed replacement can coexist after a partial journal write.+ operation = validatePinOperation({ ...operation, cancels: [...new Set(superseded)] });+ }+ const next = [...kept, operation];+ if (next.length > 10_000) {+ throw new PinnedChatsValidationError("Too many pending pin changes");+ }+ // Persist before presenting success in the UI; navigation may happen immediately.+ persist(next);+ pending = next;+ publish();+ schedulePending();+ const result = scheduled.get(operation.operationId);+ if (!result) {+ throw new Error("Pin operation was not scheduled");+ }+ return result;+ } catch (error) {+ return rejected(error);+ }+ }++ return {+ refresh(): Promise<void> {+ if (refreshing) {+ return refreshing;+ }+ try {+ restore();+ } catch (error) {+ return rejected(error);+ }+ const hydration = enqueue((epoch) => hydrate(epoch, true));+ const operations = schedulePending();+ const result = Promise.allSettled([hydration, ...operations]).then(+ (results) => {+ const failure = results.find((entry) => entry.status === "rejected");+ if (failure?.status === "rejected") {+ throw failure.reason;+ }+ },+ );+ refreshing = result;+ const clear = () => {+ if (refreshing === result) {+ refreshing = undefined;+ }+ };+ void result.then(clear, clear);+ return result;+ },+ setPinned(ids: string[], pinned: boolean): Promise<void> {+ return mutate({ kind: "pin", ids: [...new Set(ids)], pinned });+ },+ reset({ clearPending = false }: { clearPending?: boolean } = {}): void {+ generation += 1;+ loaded = false;+ confirmed = undefined;+ pending = [];+ queue = Promise.resolve();+ refreshing = undefined;+ scheduled.clear();+ acknowledged.clear();+ publish();+ if (clearPending) {+ persist([]);+ }+ },+ };+}diff --git a/studio/frontend/src/features/chat/utils/pinned-chats-transport.ts b/studio/frontend/src/features/chat/utils/pinned-chats-transport.tsnew file mode 100644index 00000000000..faea8233be8--- /dev/null+++ b/studio/frontend/src/features/chat/utils/pinned-chats-transport.ts@@ -0,0 +1,293 @@+// 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 { ChatSettingsRequestError } from "./settings-retry.ts";++import {+ applyPinOperation,+ PinnedChatsValidationError,+ validatePinnedIds,+ validatePinOperation,+ type PinOperation,+} from "./pinned-chats-sync.ts";++export interface PinnedChatsFallbackState {+ baseIds: string[];+ pinnedIds: string[];+ operations: PinOperation[];+}++interface PinnedChatsTransportOptions {+ load: () => Promise<string[] | undefined>;+ compareAndSet: (+ expected: string[] | undefined,+ next: string[],+ operation?: PinOperation,+ ) => Promise<{ pinnedIds: string[] | undefined; applied: boolean }>;+ migrateLegacy?: (ids: string[]) => Promise<string[] | undefined>;+ readLegacy: () => string[];+ readFallback: () => PinnedChatsFallbackState | undefined;+ writeFallback: (state: PinnedChatsFallbackState | undefined) => void;+ onUnsupported?: () => void;+}++class ReplayConflictError extends Error {}++const PIN_OPERATION_FIELDS = new Set([+ "operationId",+ "unpinnedChatIds",+ "cancelledOperationIds",+]);++function isUnsupported(error: unknown): boolean {+ if (!(error instanceof ChatSettingsRequestError)) return false;+ if (error.status === 404 || error.status === 405) return true;+ if (+ error.status !== 400 ||+ !Array.isArray(error.detail) ||+ !error.detail.length+ ) {+ return false;+ }+ let rejectsPinField = false;+ const onlyUnsupportedPins = error.detail.every((entry: unknown) => {+ if (!entry || typeof entry !== "object") return false;+ const { type, loc, msg } = entry as {+ type?: unknown;+ loc?: unknown;+ msg?: unknown;+ };+ if (!Array.isArray(loc)) return false;+ if (type === "extra_forbidden" && loc.at(-1) === "pinnedChatIds") {+ rejectsPinField = true;+ return true;+ }+ // A backend downgraded since support was probed also rejects this client's operation metadata.+ if (+ type === "extra_forbidden" &&+ loc.length === 1 &&+ PIN_OPERATION_FIELDS.has(String(loc[0]))+ ) {+ return true;+ }+ // Older backends also reject the migration's expectedAbsent naming the new field.+ return (+ type === "value_error" &&+ loc.length === 1 &&+ loc[0] === "expectedAbsent" &&+ msg === "Value error, Unknown chat settings field(s): pinnedChatIds"+ );+ });+ return onlyUnsupportedPins && rejectsPinField;+}++/** Drop pins a later entry unpins; that unpin fences each dropped pin's server ID. */+function compactReplay(operations: PinOperation[]): PinOperation[] {+ const unpinFor = new Map<string, PinOperation & { cancels: string[] }>();+ const kept: PinOperation[] = [];+ for (const operation of [...operations].reverse()) {+ if (!operation.pinned) {+ const fence = { ...operation, cancels: [...(operation.cancels ?? [])] };+ operation.ids.forEach((id) => unpinFor.set(id, fence));+ kept.push(fence);+ continue;+ }+ const fenceId = operation.ids.find((id) => unpinFor.has(id));+ if (fenceId === undefined) {+ kept.push(operation);+ continue;+ }+ const serverId = operation.serverId ?? operation.operationId;+ unpinFor.get(fenceId)!.cancels.push(serverId);+ const ids = operation.ids.filter((id) => !unpinFor.has(id));+ // Same server ID, replayed before the fence: an already-committed copy is just acknowledged.+ if (ids.length > 0) kept.push({ ...operation, ids, serverId });+ }+ return kept+ .reverse()+ .map(({ cancels, ...operation }) =>+ cancels?.length ? { ...operation, cancels: [...new Set(cancels)] } : operation,+ );+}++function sameIds(left: string[] | undefined, right: string[]): boolean {+ return left !== undefined && left.length === right.length &&+ left.every((id, index) => id === right[index]);+}++/** Older servers use a durable local journal which is replayed after upgrade. */+export function createPinnedChatsTransport(options: PinnedChatsTransportOptions) {+ let localOnly = false;+ let generation = 0;+ let lastRemote: string[] | undefined;+ let recoveredOnLoad = false;++ function assertCurrent(epoch: number): void {+ if (epoch !== generation) throw new Error("Pinned chat session changed");+ }++ function readFallback(): PinnedChatsFallbackState | undefined {+ const state = options.readFallback();+ if (state === undefined) return undefined;+ if (!state || !Array.isArray(state.operations) || state.operations.length > 10_000)+ throw new PinnedChatsValidationError("Invalid local pin journal");+ const baseIds = validatePinnedIds(state.baseIds);+ const pinnedIds = validatePinnedIds(state.pinnedIds);+ const operations = state.operations.map(validatePinOperation);+ if (!baseIds || !pinnedIds || new Set(operations.map((op) => op.operationId)).size !== operations.length)+ throw new PinnedChatsValidationError("Invalid local pin journal");+ return { baseIds, pinnedIds, operations };+ }++ function fallback(error: unknown, epoch: number, expected?: string[]): PinnedChatsFallbackState {+ assertCurrent(epoch);+ if (!isUnsupported(error)) throw error;+ let state = readFallback();+ if (!state) {+ const baseIds = validatePinnedIds(expected ?? lastRemote ?? options.readLegacy())!;+ state = { baseIds, pinnedIds: baseIds.slice(), operations: [] };+ // Failure to save the recovery record must not be reported as a local save.+ options.writeFallback(state);+ }+ if (!localOnly) {+ localOnly = true;+ options.onUnsupported?.();+ }+ return state;+ }++ function validateResult(result: { pinnedIds: string[] | undefined; applied: boolean }) {+ if (!result || typeof result.applied !== "boolean")+ throw new PinnedChatsValidationError("Invalid pinned chats response");+ const pinnedIds = validatePinnedIds(result.pinnedIds);+ if (result.applied && pinnedIds === undefined)+ throw new PinnedChatsValidationError("Invalid pinned chats response");+ return { pinnedIds, applied: result.applied };+ }++ async function remoteMigration(ids: string[], current: string[] | undefined, epoch: number) {+ if (options.migrateLegacy) {+ const migrated = validatePinnedIds(await options.migrateLegacy(ids));+ assertCurrent(epoch);+ // No valid legacy IDs may remain after pruning deleted chats.+ return migrated;+ }+ if (current !== undefined) return current;+ if (!ids.length) return current;+ const result = validateResult(await options.compareAndSet(undefined, ids));+ assertCurrent(epoch);+ if (result.pinnedIds === undefined)+ throw new PinnedChatsValidationError("Invalid pin migration response");+ return result.pinnedIds;+ }++ async function recover(state: PinnedChatsFallbackState, current: string[] | undefined, epoch: number) {+ current = await remoteMigration(state.baseIds, current, epoch);+ for (const operation of compactReplay(state.operations)) {+ let applied = false;+ for (let attempt = 0; attempt < 8; attempt += 1) {+ assertCurrent(epoch);+ const next = validatePinnedIds(applyPinOperation(current ?? [], operation))!;+ const result = validateResult(await options.compareAndSet(current, next, operation));+ assertCurrent(epoch);+ current = result.pinnedIds;+ if (result.applied) {+ applied = true;+ break;+ }+ }+ if (!applied) throw new ReplayConflictError("Pinned chats changed in another browser. Please try again.");+ }+ assertCurrent(epoch);+ // Cleared only once every write is acknowledged; the server deduplicates a retried replay.+ options.writeFallback(undefined);+ localOnly = false;+ lastRemote = current?.slice();+ recoveredOnLoad = true;+ return current;+ }++ function localCompareAndSet(expected: string[] | undefined, next: string[], operation?: PinOperation) {+ const state = readFallback();+ if (!state) throw new Error("Local pinned chats are unavailable");+ // A pin another tab's unpin already fenced arrived late: acknowledge it, never apply it.+ const replayId = operation && (operation.serverId ?? operation.operationId);+ if (replayId && state.operations.some((entry) => entry.cancels?.includes(replayId)))+ return { pinnedIds: state.pinnedIds, applied: true };+ const existing = operation && state.operations.some((entry) => entry.operationId === operation.operationId);+ if (!existing && !sameIds(expected, state.pinnedIds))+ return { pinnedIds: state.pinnedIds, applied: false };+ if (!existing && !operation && !sameIds(next, state.pinnedIds))+ throw new PinnedChatsValidationError("A local pin change requires an operation");+ const operations = existing || !operation+ ? state.operations : [...state.operations, validatePinOperation(operation)];+ if (operations.length > 10_000)+ throw new PinnedChatsValidationError("Too many pending pin changes");+ const pinnedIds = existing || !operation+ ? state.pinnedIds : validatePinnedIds(applyPinOperation(state.pinnedIds, operation))!;+ options.writeFallback({ ...state, pinnedIds, operations });+ return { pinnedIds, applied: true };+ }++ return {+ async load(): Promise<string[] | undefined> {+ const epoch = generation;+ recoveredOnLoad = false;+ const state = readFallback();+ try {+ const current = validatePinnedIds(await options.load());+ assertCurrent(epoch);+ if (current !== undefined) lastRemote = current.slice();+ if (state) return await recover(state, current, epoch);+ return current;+ } catch (error) {+ assertCurrent(epoch);+ const transient = error instanceof TypeError ||+ (error as { unslothTransportFailure?: unknown })?.unslothTransportFailure === true ||+ (error instanceof Error && ["AbortError", "TimeoutError"].includes(error.name)) ||+ (error instanceof ChatSettingsRequestError &&+ (error.status >= 500 || error.status === 429 || error.status === 408));+ // A refused replay keeps the saved view, so a later unpin can compact that pin away.+ if (state && (transient || error instanceof ReplayConflictError)) return state.pinnedIds;+ return fallback(error, epoch).pinnedIds;+ }+ },+ async migrateLegacy(ids: string[]): Promise<string[] | undefined> {+ const epoch = generation;+ const state = readFallback();+ if (state) return state.pinnedIds;+ // load() just replayed the baseline and offline changes; reimporting would duplicate them.+ if (recoveredOnLoad) return lastRemote?.slice();+ try {+ const current = await remoteMigration(validatePinnedIds(ids)!, lastRemote, epoch);+ assertCurrent(epoch);+ lastRemote = current?.slice();+ return current;+ } catch (error) {+ return fallback(error, epoch).pinnedIds;+ }+ },+ async compareAndSet(expected: string[] | undefined, next: string[], operation?: PinOperation) {+ validatePinnedIds(expected);+ validatePinnedIds(next);+ if (operation) validatePinOperation(operation);+ if (readFallback()) return localCompareAndSet(expected, next, operation);+ const epoch = generation;+ try {+ const result = validateResult(await options.compareAndSet(expected, next, operation));+ assertCurrent(epoch);+ lastRemote = result.pinnedIds?.slice();+ return result;+ } catch (error) {+ fallback(error, epoch, expected);+ return localCompareAndSet(expected, next, operation);+ }+ },+ reset(): void {+ generation += 1;+ localOnly = false;+ lastRemote = undefined;+ recoveredOnLoad = false;+ },+ };+}diff --git a/studio/frontend/src/features/chat/utils/settings-retry.ts b/studio/frontend/src/features/chat/utils/settings-retry.tsindex 828e2bfece5..afe601036db 100644--- a/studio/frontend/src/features/chat/utils/settings-retry.ts+++ b/studio/frontend/src/features/chat/utils/settings-retry.ts@@ -24,6 +24,14 @@ export function isTerminalSettingsRejection(error: unknown): boolean {return status >= 400 && status < 500;}+/** A 401 may be a transient token-refresh failure; sign-out discards the pin queue itself. */+export function isRetryablePinError(error: unknown): boolean {+ return (+ !isTerminalSettingsRejection(error) ||+ (error as ChatSettingsRequestError).status === 401+ );+}+/** Top-level fields from FastAPI detail[].loc[0]; empty means drop the whole patch. */export function rejectedSettingKeys(detail: unknown): string[] {if (!Array.isArray(detail)) return [];diff --git a/studio/frontend/tests/legacy-pinned-chats.test.ts b/studio/frontend/tests/legacy-pinned-chats.test.tsnew file mode 100644index 00000000000..96ce5e5978c--- /dev/null+++ b/studio/frontend/tests/legacy-pinned-chats.test.ts@@ -0,0 +1,95 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import {+ readLegacyPinnedChatIds,+ writeLocalPinnedChatIds,+} from "../src/features/chat/utils/legacy-pinned-chats.ts";++function storage(pins: unknown, order?: unknown) {+ const values = new Map<string, string>([+ ["unsloth_pinned_chats", JSON.stringify({ state: { pinnedIds: pins } })],+ [+ "unsloth_sidebar_organization",+ JSON.stringify({ state: { manualOrder: { pinned: order } } }),+ ],+ ]);+ return {+ getItem: (key: string) => values.get(key) ?? null,+ setItem: (key: string, value: string) => {+ values.set(key, value);+ },+ };+}++test("migration retains comparison IDs and the existing manual pin order", () => {+ const saved = storage(+ ["new", "pair-id", "chat-a", "chat-b"],+ ["chat-b", "chat-a", "pair-id"],+ );+ assert.deepEqual(readLegacyPinnedChatIds(saved), [+ "new",+ "chat-b",+ "chat-a",+ "pair-id",+ ]);+});++test("stale order entries do not resurrect unpinned chats", () => {+ assert.deepEqual(readLegacyPinnedChatIds(storage(["a"], ["deleted", "a"])), [+ "a",+ ]);+});++test("legacy migration accepts only unique bounded string IDs", () => {+ assert.deepEqual(+ readLegacyPinnedChatIds(+ storage(["a", "a", null, 12, "", "x".repeat(513), "b"]),+ ),+ ["a", "b"],+ );+ assert.equal(+ readLegacyPinnedChatIds(+ storage(Array.from({ length: 10_001 }, (_, i) => String(i))),+ ).length,+ 10_000,+ );+});++test("bad sidebar JSON does not discard valid pins", () => {+ const saved = storage(["a"]);+ saved.setItem("unsloth_sidebar_organization", "{");+ assert.deepEqual(readLegacyPinnedChatIds(saved), ["a"]);+});++test("missing, malformed, and inaccessible browser storage can be ignored", () => {+ assert.deepEqual(readLegacyPinnedChatIds({ getItem: () => null }), []);+ assert.deepEqual(readLegacyPinnedChatIds({ getItem: () => "{" }), []);+ assert.deepEqual(+ readLegacyPinnedChatIds({+ getItem: () => {+ throw new Error("blocked");+ },+ }),+ [],+ );+});++test("legacy migration filters malformed UTF-16 IDs without losing valid pins", () => {+ assert.deepEqual(+ readLegacyPinnedChatIds(+ storage(["a", "\ud800", "\udfff", "\ud83d\udcac", "b"]),+ ),+ ["a", "\ud83d\udcac", "b"],+ );+});++test("local compatibility writes retain new order without reapplying legacy order", () => {+ const saved = storage(["a", "b"], ["b", "a"]);+ writeLocalPinnedChatIds(saved, ["a", "b"]);+ assert.deepEqual(readLegacyPinnedChatIds(saved), ["a", "b"]);+ writeLocalPinnedChatIds(saved, []);+ assert.deepEqual(readLegacyPinnedChatIds(saved), []);+});diff --git a/studio/frontend/tests/pinned-chats-journal.test.ts b/studio/frontend/tests/pinned-chats-journal.test.tsnew file mode 100644index 00000000000..96f8a631f0e--- /dev/null+++ b/studio/frontend/tests/pinned-chats-journal.test.ts@@ -0,0 +1,503 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import {+ PIN_JOURNAL_PREFIX,+ createPinnedChatsJournal,+} from "../src/features/chat/utils/pinned-chats-journal.ts";+import {+ preserveFallbackPins,+ readLegacyPinnedChatIds,+} from "../src/features/chat/utils/legacy-pinned-chats.ts";+import {+ type PinOperation,+ applyPinOperation,+ createPinnedChatsSync,+} from "../src/features/chat/utils/pinned-chats-sync.ts";++class MemoryStorage implements Storage {+ readonly values = new Map<string, string>();+ fail?: (method: "get" | "set" | "remove" | "key", key: string) => boolean;+ get length() {+ return this.values.size;+ }+ clear() {+ this.values.clear();+ }+ key(index: number) {+ if (this.fail?.("key", String(index))) {+ throw new Error("storage unavailable");+ }+ return [...this.values.keys()][index] ?? null;+ }+ getItem(key: string) {+ if (this.fail?.("get", key)) {+ throw new Error("storage unavailable");+ }+ return this.values.get(key) ?? null;+ }+ setItem(key: string, value: string) {+ if (this.fail?.("set", key)) {+ throw new Error("storage unavailable");+ }+ this.values.set(key, value);+ }+ removeItem(key: string) {+ if (this.fail?.("remove", key)) {+ throw new Error("storage unavailable");+ }+ this.values.delete(key);+ }+}++function pin(operationId: string, id: string, pinned = true): PinOperation {+ return { kind: "pin", operationId, ids: [id], pinned };+}++function fallback(baseIds: string[], operations: PinOperation[] = []) {+ return {+ baseIds,+ operations,+ pinnedIds: operations.reduce(applyPinOperation, baseIds),+ };+}++const a = pin("01-a", "a");+const b = pin("02-b", "b");++test("tabs append independent durable entries without replacing an unseen intent", () => {+ const storage = new MemoryStorage();+ const first = createPinnedChatsJournal(storage, "session");+ const second = createPinnedChatsJournal(storage, "session");+ assert.deepEqual(first.readPending(), []);+ assert.deepEqual(second.readPending(), []);+ first.writePending([a]);+ second.writePending([b]);+ const reloaded = createPinnedChatsJournal(storage, "session");+ assert.deepEqual(reloaded.readPending(), [a, b]);+ // The first request can acknowledge only what it observed before awaiting I/O.+ first.writePending([]);+ assert.deepEqual(reloaded.readPending(), [b]);+});++test("acknowledging an observed queue cannot erase a later append in another tab", () => {+ const storage = new MemoryStorage();+ const first = createPinnedChatsJournal(storage, "session");+ first.writePending([a]);+ const second = createPinnedChatsJournal(storage, "session");+ assert.deepEqual(second.readPending(), [a]);+ first.writePending([a, b]);+ second.writePending([]);+ assert.deepEqual(createPinnedChatsJournal(storage, "session").readPending(), [+ b,+ ]);+});++test("repeated writes keep an operation immutable and preserve FIFO order", () => {+ const storage = new MemoryStorage();+ const journal = createPinnedChatsJournal(storage, "session");+ journal.writePending([a, b]);+ const saved = [...storage.values.entries()];+ journal.writePending([a, b]);+ assert.deepEqual([...storage.values.entries()], saved);+ assert.deepEqual(createPinnedChatsJournal(storage, "session").readPending(), [+ a,+ b,+ ]);+});++test("partial append remains recoverable after reload and can be retried", () => {+ const storage = new MemoryStorage();+ const journal = createPinnedChatsJournal(storage, "session");+ storage.fail = (method, key) =>+ method === "set" && key.endsWith(b.operationId);+ assert.throws(() => journal.writePending([a, b]), /storage unavailable/);+ const reloaded = createPinnedChatsJournal(storage, "session");+ assert.deepEqual(reloaded.readPending(), [a]);+ storage.fail = undefined;+ reloaded.writePending([a, b]);+ assert.deepEqual(createPinnedChatsJournal(storage, "session").readPending(), [+ a,+ b,+ ]);+});++test("partial acknowledgment retains every not-yet-removed entry for retry", () => {+ const storage = new MemoryStorage();+ const journal = createPinnedChatsJournal(storage, "session");+ journal.writePending([a, b]);+ storage.fail = (method, key) =>+ method === "remove" && key.endsWith(b.operationId);+ assert.throws(() => journal.writePending([]), /storage unavailable/);+ const reloaded = createPinnedChatsJournal(storage, "session");+ assert.deepEqual(reloaded.readPending(), [b]);+ storage.fail = undefined;+ reloaded.writePending([]);+ assert.deepEqual(journal.readPending(), []);+});++test("concurrent initial fallback snapshots retain both tabs' known pins", () => {+ const storage = new MemoryStorage();+ const first = createPinnedChatsJournal(storage, "session");+ const second = createPinnedChatsJournal(storage, "session");+ assert.equal(first.readFallback(), undefined);+ assert.equal(second.readFallback(), undefined);+ first.writeFallback(fallback(["from-first"]));+ second.writeFallback(fallback(["from-second"]));+ const reloaded = createPinnedChatsJournal(storage, "session");+ assert.deepEqual(+ new Set(reloaded.readFallback()?.pinnedIds),+ new Set(["from-first", "from-second"]),+ );+ assert.equal(storage.length, 2);+});++test("fallback combines separate baselines before replaying explicit unpin and pin", () => {+ const storage = new MemoryStorage();+ const first = createPinnedChatsJournal(storage, "session");+ const second = createPinnedChatsJournal(storage, "session");+ const unpin = pin("01-remove", "removed", false);+ const added = pin("02-add", "added");+ first.writeFallback(fallback(["a", "removed", "c"], [unpin]));+ second.readFallback();+ second.writeFallback(+ fallback(["a", "removed", "c", "remote"], [unpin, added]),+ );+ const saved = createPinnedChatsJournal(storage, "session").readFallback();+ assert.deepEqual(saved?.baseIds, ["a", "removed", "c", "remote"]);+ assert.deepEqual(saved?.operations, [unpin, added]);+ assert.deepEqual(saved?.pinnedIds, ["added", "a", "c", "remote"]);+});++test("completed fallback replay acknowledges only entries observed before another tab wrote", () => {+ const storage = new MemoryStorage();+ const first = createPinnedChatsJournal(storage, "session");+ const second = createPinnedChatsJournal(storage, "session");+ first.writeFallback(fallback(["base"], [a]));+ assert.deepEqual(first.readFallback()?.operations, [a]);+ second.writeFallback(fallback(["base"], [b]));+ first.writeFallback(undefined);+ const saved = createPinnedChatsJournal(storage, "session").readFallback();+ assert.deepEqual(saved?.operations, [b]);+ assert.deepEqual(saved?.pinnedIds, ["b", "base"]);+});++test("a fallback seed can be replaced with a durable explicit operation", () => {+ const storage = new MemoryStorage();+ const journal = createPinnedChatsJournal(storage, "session");+ journal.writeFallback(fallback(["base"]));+ journal.writeFallback(fallback(["base"], [a]));+ assert.equal(storage.length, 1);+ assert.deepEqual(+ createPinnedChatsJournal(storage, "session").readFallback(),+ fallback(["base"], [a]),+ );+});++test("fallback set failure leaves the previous durable snapshot intact", () => {+ const storage = new MemoryStorage();+ const journal = createPinnedChatsJournal(storage, "session");+ journal.writeFallback(fallback(["base"]));+ storage.fail = (method) => method === "set";+ assert.throws(+ () => journal.writeFallback(fallback(["base"], [a])),+ /storage unavailable/,+ );+ assert.deepEqual(+ createPinnedChatsJournal(storage, "session").readFallback(),+ fallback(["base"]),+ );+});++test("clear removes all entries for the auth scope but preserves other scopes and unrelated storage", () => {+ const storage = new MemoryStorage();+ const first = createPinnedChatsJournal(storage, "backend|auth:a");+ const same = createPinnedChatsJournal(storage, "backend|auth:a");+ const other = createPinnedChatsJournal(storage, "backend|auth:a:other");+ first.writePending([a]);+ same.writeFallback(fallback(["base"], [b]));+ other.writePending([b]);+ other.writeFallback(fallback(["other"]));+ storage.setItem("unrelated", "keep");+ first.clear();+ assert.deepEqual(same.readPending(), []);+ assert.equal(same.readFallback(), undefined);+ assert.deepEqual(other.readPending(), [b]);+ assert.deepEqual(other.readFallback()?.pinnedIds, ["other"]);+ assert.equal(storage.getItem("unrelated"), "keep");+});++test("journal storage read and key enumeration errors are reported without deleting entries", () => {+ for (const failure of ["get", "key"] as const) {+ const storage = new MemoryStorage();+ const journal = createPinnedChatsJournal(storage, "session");+ journal.writePending([a]);+ storage.fail = (method) => method === failure;+ assert.throws(() => journal.readPending(), /storage unavailable/);+ assert.equal(storage.length, 1);+ }+});++test("failed auth cleanup reports the error and can be retried", () => {+ const storage = new MemoryStorage();+ const journal = createPinnedChatsJournal(storage, "session");+ journal.writePending([a]);+ storage.fail = (method) => method === "remove";+ assert.throws(() => journal.clear(), /storage unavailable/);+ assert.equal(storage.length, 1);+ storage.fail = undefined;+ journal.clear();+ assert.equal(storage.length, 0);+});++test("corrupted pending and fallback entries are rejected rather than published", () => {+ for (const [kind, value] of [+ ["pending", { order: null, operation: a }],+ ["pending", { order: 1, operation: { ...a, ids: [null] } }],+ ["fallback", { order: 1, baseIds: ["duplicate", "duplicate"] }],+ ["fallback", { order: 1, operation: a }],+ ] as const) {+ const storage = new MemoryStorage();+ storage.setItem(+ `${PIN_JOURNAL_PREFIX}session:${kind}:corrupt`,+ JSON.stringify(value),+ );+ const journal = createPinnedChatsJournal(storage, "session");+ assert.throws(() =>+ kind === "pending" ? journal.readPending() : journal.readFallback(),+ );+ assert.equal(storage.length, 1);+ }+});++test("sign-out keeps an older backend's local saves for the next session's baseline", () => {+ const storage = new MemoryStorage();+ const before = createPinnedChatsJournal(storage, "server|session-1");+ before.writeFallback(fallback(["legacy"], [pin("01", "new"), pin("02", "legacy", false)]));+ preserveFallbackPins(storage, before.readFallback);+ before.clear();+ assert.equal(before.readFallback(), undefined);+ assert.deepEqual(readLegacyPinnedChatIds(storage), ["new"]);+ const after = createPinnedChatsJournal(storage, "server|session-2");+ assert.equal(after.readFallback(), undefined);+});++test("a tab holding a pin another tab's unpin cancelled does not replay it", async () => {+ const storage = new MemoryStorage();+ let server: string[] = [];+ const save = async (expected: string[] | undefined, next: string[]) => {+ if (JSON.stringify(expected ?? []) !== JSON.stringify(server)) return { applied: false, pinnedIds: server.slice() };+ server = next.slice();+ return { applied: true, pinnedIds: server.slice() };+ };+ function tab(online: () => boolean) {+ const disk = createPinnedChatsJournal(storage, "server|session");+ return createPinnedChatsSync({+ load: async () => server.slice(),+ compareAndSet: async (expected, next) => {+ if (!online()) throw new Error("offline");+ return save(expected, next);+ },+ readLegacy: () => [],+ readPending: disk.readPending,+ writePending: disk.writePending,+ publish: () => undefined,+ });+ }+ let aOnline = false;+ const a = tab(() => aOnline);+ await a.refresh();+ await assert.rejects(a.setPinned(["chat"], true));+ const b = tab(() => true);+ await b.refresh().catch(() => undefined);+ await b.setPinned(["chat"], false);+ assert.deepEqual(server, []);+ aOnline = true;+ await a.refresh();+ assert.deepEqual(server, []);+});++test("a tab finishing an earlier intent does not recreate one another tab cancelled meanwhile", async () => {+ const storage = new MemoryStorage();+ let server: string[] = [];+ let release!: () => void;+ let holding = false;+ const hold = new Promise<void>((resolve) => { release = resolve; });+ const save = async (expected: string[] | undefined, next: string[]) => {+ if (JSON.stringify(expected ?? []) !== JSON.stringify(server)) return { applied: false, pinnedIds: server.slice() };+ server = next.slice();+ return { applied: true, pinnedIds: server.slice() };+ };+ function tab(delayed: boolean) {+ const disk = createPinnedChatsJournal(storage, "server|session");+ return createPinnedChatsSync({+ load: async () => server.slice(),+ compareAndSet: async (expected, next) => {+ const result = await save(expected, next);+ if (delayed && holding) await hold;+ return result;+ },+ readLegacy: () => [],+ readPending: disk.readPending,+ writePending: disk.writePending,+ publish: () => undefined,+ });+ }+ const a = tab(true);+ await a.refresh();+ holding = true;+ const first = a.setPinned(["a"], true);+ const second = a.setPinned(["x"], true).catch(() => undefined);+ await new Promise((resolve) => setTimeout(resolve, 10));+ const b = tab(false);+ await b.setPinned(["x"], false).catch(() => undefined);+ await b.refresh().catch(() => undefined);+ release();+ await first;+ await second;+ await a.refresh().catch(() => undefined);+ assert.deepEqual(server, ["a"]);+});++test("a conflicting pin is not retried once another tab cancelled it", async () => {+ const storage = new MemoryStorage();+ let server: string[] = [];+ let release!: () => void;+ const held = new Promise<void>((resolve) => { release = resolve; });+ let firstA = true;+ const pins: string[][] = [];+ function tab(name: "a" | "b") {+ const disk = createPinnedChatsJournal(storage, "server|session");+ return createPinnedChatsSync({+ load: async () => server.slice(),+ compareAndSet: async (expected, next) => {+ if (name === "a" && firstA) {+ firstA = false;+ await held;+ }+ if (next.includes("x")) pins.push(next.slice());+ if (JSON.stringify(expected ?? []) !== JSON.stringify(server)) return { applied: false, pinnedIds: server.slice() };+ server = next.slice();+ return { applied: true, pinnedIds: server.slice() };+ },+ readLegacy: () => [],+ readPending: disk.readPending,+ writePending: disk.writePending,+ publish: () => undefined,+ });+ }+ const a = tab("a");+ await a.refresh();+ const pinning = a.setPinned(["x"], true).catch(() => undefined);+ await new Promise((resolve) => setTimeout(resolve, 10));+ server = ["other"];+ const b = tab("b");+ await b.setPinned(["x"], false).catch(() => undefined);+ await b.refresh().catch(() => undefined);+ release();+ await pinning;+ assert.deepEqual(server, ["other"]);+ assert.equal(pins.length, 1);+});++test("unpinning one chat of a queued bulk pin keeps the rest and unblocks the queue", async () => {+ const storage = new MemoryStorage();+ let server: string[] = [];+ const disk = createPinnedChatsJournal(storage, "server|session");+ const sync = createPinnedChatsSync({+ load: async () => server.slice(),+ compareAndSet: async (expected, next) => {+ // A legacy comparison still awaiting import: the server cannot place it yet.+ if (next.includes("unimported") || JSON.stringify(expected ?? []) !== JSON.stringify(server)) {+ return { applied: false, pinnedIds: server.slice() };+ }+ server = next.slice();+ return { applied: true, pinnedIds: server.slice() };+ },+ readLegacy: () => [],+ readPending: disk.readPending,+ writePending: disk.writePending,+ publish: () => undefined,+ });+ await sync.refresh();+ const bulk = sync.setPinned(["unimported", "existing"], true).catch(() => undefined);+ await sync.setPinned(["unimported"], false);+ await sync.setPinned(["later"], true);+ await bulk;+ await sync.refresh();+ assert.deepEqual(server, ["later", "existing"]);+ assert.deepEqual(disk.readPending(), []);+});++test("an older intent another tab journaled replays before this tab's newer one", async () => {+ const storage = new MemoryStorage();+ let server: string[] = [];+ const writes: string[][] = [];+ let online = false;+ const disk = createPinnedChatsJournal(storage, "server|session");+ const a = createPinnedChatsSync({+ load: async () => server.slice(),+ compareAndSet: async (expected, next) => {+ if (!online) throw new Error("offline");+ writes.push(next.slice());+ if (JSON.stringify(expected ?? []) !== JSON.stringify(server)) return { applied: false, pinnedIds: server.slice() };+ server = next.slice();+ return { applied: true, pinnedIds: server.slice() };+ },+ readLegacy: () => [],+ readPending: disk.readPending,+ writePending: disk.writePending,+ publish: () => undefined,+ });+ await a.refresh().catch(() => undefined);+ await assert.rejects(a.setPinned(["chat"], false));+ // Tab B's pin, written before A's unpin but not yet seen by A.+ storage.setItem(+ `${PIN_JOURNAL_PREFIX}${encodeURIComponent("server|session")}:pending:b-pin`,+ JSON.stringify({ operation: pin("b-pin", "chat"), order: 1 }),+ );+ online = true;+ await a.refresh().catch(() => undefined);+ await a.refresh().catch(() => undefined);+ assert.deepEqual(server, []);+});++test("a twice-trimmed offline bulk pin keeps its place ahead of the unpins that fence it", async () => {+ const storage = new MemoryStorage();+ let server: string[] = [];+ const acknowledged = new Set<string>();+ let online = false;+ function client() {+ const disk = createPinnedChatsJournal(storage, "server|session");+ return createPinnedChatsSync({+ load: async () => server.slice(),+ compareAndSet: async (expected, next, operation) => {+ if (!online) throw new Error("offline");+ const id = operation && (operation.serverId ?? operation.operationId);+ if (id && acknowledged.has(id)) return { applied: true, pinnedIds: server.slice() };+ if (JSON.stringify(expected ?? []) !== JSON.stringify(server)) return { applied: false, pinnedIds: server.slice() };+ server = next.slice();+ if (id) acknowledged.add(id);+ operation?.cancels?.forEach((cancelled) => acknowledged.add(cancelled));+ return { applied: true, pinnedIds: server.slice() };+ },+ readLegacy: () => [],+ readPending: disk.readPending,+ writePending: disk.writePending,+ publish: () => undefined,+ });+ }+ const offline = client();+ await offline.refresh().catch(() => undefined);+ await assert.rejects(offline.setPinned(["a", "b", "c"], true));+ await offline.setPinned(["a"], false).catch(() => undefined);+ await offline.setPinned(["b"], false).catch(() => undefined);+ online = true;+ // After a reload, a fresh client replays the journal in its stored order.+ const reloaded = client();+ await reloaded.refresh().catch(() => undefined);+ await reloaded.refresh().catch(() => undefined);+ assert.deepEqual(server, ["c"]);+});diff --git a/studio/frontend/tests/pinned-chats-store.test.ts b/studio/frontend/tests/pinned-chats-store.test.tsnew file mode 100644index 00000000000..bf785925b17--- /dev/null+++ b/studio/frontend/tests/pinned-chats-store.test.ts@@ -0,0 +1,54 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import {+ discardUnboundPinEdits,+ setPinnedChatsActions,+ usePinnedChatsStore,+} from "../src/features/chat/stores/pinned-chats-store.ts";++const STORE = "../src/features/chat/stores/pinned-chats-store.ts";++test("pins made before the sync runtime binds are replayed into it, and sign-out drops them", () => {+ const calls: Array<[string[], boolean]> = [];+ usePinnedChatsStore.getState().togglePin("early");+ usePinnedChatsStore.getState().unpin("other");+ assert.deepEqual(usePinnedChatsStore.getState().pinnedIds, ["early"]);+ setPinnedChatsActions({ setPinned: (ids, pinned) => calls.push([ids, pinned]) });+ assert.deepEqual(calls, [[["early"], true], [["other"], false]]);++ setPinnedChatsActions(null);+ usePinnedChatsStore.getState().togglePin("signed-out");+ discardUnboundPinEdits();+ assert.deepEqual(usePinnedChatsStore.getState().pinnedIds, []);+ setPinnedChatsActions({ setPinned: (ids, pinned) => calls.push([ids, pinned]) });+ assert.equal(calls.length, 2);+ setPinnedChatsActions(null);+});++test("a pin made before the runtime binds survives a reload", async () => {+ const values = new Map<string, string>();+ const storage = {+ getItem: (key: string) => values.get(key) ?? null,+ setItem: (key: string, value: string) => void values.set(key, value),+ removeItem: (key: string) => void values.delete(key),+ };+ const descriptor = Object.getOwnPropertyDescriptor(globalThis, "localStorage");+ Object.defineProperty(globalThis, "localStorage", { value: storage, configurable: true });+ try {+ const before = await import(`${STORE}?page=1`);+ before.usePinnedChatsStore.getState().togglePin("early");+ const after = await import(`${STORE}?page=2`);+ const calls: Array<[string[], boolean]> = [];+ after.setPinnedChatsActions({+ setPinned: (ids: string[], pinned: boolean) => calls.push([ids, pinned]),+ });+ assert.deepEqual(calls, [[["early"], true]]);+ assert.equal(values.size, 0);+ } finally {+ if (descriptor) Object.defineProperty(globalThis, "localStorage", descriptor);+ else delete (globalThis as { localStorage?: unknown }).localStorage;+ }+});diff --git a/studio/frontend/tests/pinned-chats-sync.test.ts b/studio/frontend/tests/pinned-chats-sync.test.tsnew file mode 100644index 00000000000..d584d3483ca--- /dev/null+++ b/studio/frontend/tests/pinned-chats-sync.test.ts@@ -0,0 +1,888 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import {+ type PinOperation,+ PinnedChatsValidationError,+ createPinnedChatsSync,+ validatePinOperation,+ validatePinnedIds,+} from "../src/features/chat/utils/pinned-chats-sync.ts";+import {+ ChatSettingsRequestError,+ isRetryablePinError,+} from "../src/features/chat/utils/settings-retry.ts";++function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (error: unknown) => void;+ const promise = new Promise<T>((yes, no) => {+ resolve = yes;+ reject = no;+ });+ return { promise, resolve, reject };+}++function server(initial?: string[]) {+ let value = initial?.slice();+ const calls: { expected: string[] | undefined; next: string[] }[] = [];+ return {+ calls,+ get value() {+ return value?.slice();+ },+ load: async () => value?.slice(),+ compareAndSet: async (expected: string[] | undefined, next: string[]) => {+ calls.push({ expected: expected?.slice(), next: next.slice() });+ const applied = JSON.stringify(value) === JSON.stringify(expected);+ if (applied) {+ value = next.slice();+ }+ return { applied, pinnedIds: value?.slice() };+ },+ };+}++function client(+ backend: ReturnType<typeof server>,+ legacy: string[] = [],+ isRetryable?: (error: unknown) => boolean,+) {+ let visible: string[] = [];+ const errors: unknown[] = [];+ const history: string[][] = [];+ const sync = createPinnedChatsSync({+ load: backend.load,+ compareAndSet: backend.compareAndSet,+ readLegacy: () => legacy,+ isRetryable,+ publish: (ids) => {+ visible = ids;+ history.push(ids.slice());+ },+ onError: (error) => errors.push(error),+ });+ return {+ sync,+ errors,+ history,+ get visible() {+ return visible;+ },+ };+}++test("a fresh browser reads without claiming an empty migration value", async () => {+ const backend = server();+ const fresh = client(backend);+ await fresh.sync.refresh();+ assert.deepEqual(fresh.visible, []);+ assert.equal(backend.value, undefined);+ assert.equal(backend.calls.length, 0);++ const old = client(backend, ["old-chat", "old-chat"]);+ await old.sync.refresh();+ await fresh.sync.refresh();+ assert.deepEqual(backend.value, ["old-chat"]);+ assert.deepEqual(fresh.visible, ["old-chat"]);+ assert.equal(backend.calls.length, 1);+});++test("an explicitly empty server list prevents stale local pins returning", async () => {+ const backend = server([]);+ const old = client(backend, ["old-chat"]);+ await old.sync.refresh();+ assert.deepEqual(old.visible, []);+ assert.equal(backend.calls.length, 0);+});++test("two legacy clients cannot overwrite the migration winner", async () => {+ const backend = server();+ const a = client(backend, ["A"]);+ const b = client(backend, ["B"]);+ await Promise.all([a.sync.refresh(), b.sync.refresh()]);+ assert.deepEqual(backend.value, ["A"]);+ assert.deepEqual(a.visible, ["A"]);+ assert.deepEqual(b.visible, ["A"]);+});++test("a fresh client and reload read pins saved by another browser", async () => {+ const backend = server();+ const a = client(backend);+ await a.sync.setPinned(["chat"], true);+ const b = client(backend);+ const reloadedA = client(backend);+ await Promise.all([b.sync.refresh(), reloadedA.sync.refresh()]);+ assert.deepEqual(b.visible, ["chat"]);+ assert.deepEqual(reloadedA.visible, ["chat"]);+});++test("concurrent additions rebase on the server without losing either pin", async () => {+ const backend = server(["old"]);+ const a = client(backend);+ const b = client(backend);+ await Promise.all([a.sync.refresh(), b.sync.refresh()]);+ await Promise.all([+ a.sync.setPinned(["A"], true),+ b.sync.setPinned(["B"], true),+ ]);+ assert.deepEqual(backend.value, ["B", "A", "old"]);+ assert.equal(backend.calls.length, 3);+ await a.sync.refresh();+ assert.deepEqual(a.visible, b.visible);+});++test("bulk operations deduplicate IDs and preserve existing pin positions", async () => {+ const backend = server(["old", "existing"]);+ const a = client(backend);+ await a.sync.refresh();+ await a.sync.setPinned(["new", "existing", "new", "another"], true);+ assert.deepEqual(backend.value, ["new", "another", "old", "existing"]);+ await a.sync.setPinned(["old", "new"], false);+ assert.deepEqual(backend.value, ["another", "existing"]);+});++test("pinning before initial hydration preserves legacy pins", async () => {+ const backend = server();+ const a = client(backend, ["old"]);+ const saved = a.sync.setPinned(["new"], true);+ assert.deepEqual(a.visible, ["new"]);+ await saved;+ assert.deepEqual(backend.value, ["new", "old"]);+});++test("late hydration cannot hide a newer optimistic pin", async () => {+ const backend = server(["old"]);+ const read = deferred<string[] | undefined>();+ backend.load = () => read.promise;+ const a = client(backend);+ const refreshing = a.sync.refresh();+ await Promise.resolve();+ const saved = a.sync.setPinned(["new"], true);+ const from = a.history.length - 1;+ read.resolve(["old"]);+ await Promise.all([refreshing, saved]);+ assert.deepEqual(a.visible, ["new", "old"]);+ assert.ok(a.history.slice(from).every((ids) => ids.includes("new")));+});++test("a terminal rejected write rolls back without discarding a newer pending action", async () => {+ const backend = server(["old"]);+ const cas = backend.compareAndSet;+ let first = true;+ backend.compareAndSet = async (expected, next) => {+ if (first) {+ first = false;+ throw new Error("unavailable");+ }+ return cas(expected, next);+ };+ const a = client(backend, [], () => false);+ await a.sync.refresh();+ const results = await Promise.allSettled([+ a.sync.setPinned(["failed"], true),+ a.sync.setPinned(["saved"], true),+ ]);+ assert.equal(results[0].status, "rejected");+ assert.equal(results[1].status, "fulfilled");+ assert.deepEqual(a.visible, ["saved", "old"]);+ assert.deepEqual(backend.value, ["saved", "old"]);+ assert.equal(a.errors.length, 1);+});++test("an ambiguous failed response reads back a committed write", async () => {+ const backend = server(["old"]);+ const cas = backend.compareAndSet;+ backend.compareAndSet = async (expected, next) => {+ await cas(expected, next);+ throw new Error("connection closed after commit");+ };+ const a = client(backend);+ await a.sync.refresh();+ await assert.rejects(a.sync.setPinned(["new"], true));+ assert.deepEqual(a.visible, ["new", "old"]);+ assert.deepEqual(backend.value, a.visible);+});++test("failed recovery keeps unsaved intent visible and retries it before a later mutation", async () => {+ const backend = server(["old"]);+ const load = backend.load;+ const cas = backend.compareAndSet;+ let offline = false;+ let visible: string[] = [];+ const b = createPinnedChatsSync({+ load: () => (offline ? Promise.reject(new Error("offline")) : load()),+ compareAndSet: (expected, next) =>+ offline ? Promise.reject(new Error("offline")) : cas(expected, next),+ readLegacy: () => [],+ publish: (ids) => {+ visible = ids;+ },+ });+ await b.refresh();+ offline = true;+ await assert.rejects(b.setPinned(["failed"], true));+ assert.deepEqual(visible, ["failed", "old"]);+ offline = false;+ await b.setPinned(["new"], true);+ assert.deepEqual(visible, ["new", "failed", "old"]);+});++test("reset ignores an old hydration and prevents its queued write", async () => {+ const backend = server(["new-session"]);+ const oldRead = deferred<string[] | undefined>();+ let calls = 0;+ backend.load = () =>+ ++calls === 1 ? oldRead.promise : Promise.resolve(backend.value);+ const a = client(backend);+ const old = a.sync.setPinned(["old-session-edit"], true);+ await Promise.resolve();+ a.sync.reset();+ await a.sync.refresh();+ oldRead.resolve(["old-session"]);+ await old;+ assert.deepEqual(a.visible, ["new-session"]);+ assert.equal(backend.calls.length, 0);+});++test("reset ignores an in-flight write response and drops the next queued write", async () => {+ const backend = server(["server"]);+ const response = deferred<{+ pinnedIds: string[] | undefined;+ applied: boolean;+ }>();+ let writes = 0;+ backend.compareAndSet = () => {+ writes += 1;+ return response.promise;+ };+ const a = client(backend);+ await a.sync.refresh();+ const first = a.sync.setPinned(["old-first"], true);+ const second = a.sync.setPinned(["old-second"], true);+ await Promise.resolve();+ await Promise.resolve();+ assert.equal(writes, 1);+ a.sync.reset();+ await a.sync.refresh();+ response.resolve({ applied: true, pinnedIds: ["old-first", "server"] });+ await Promise.all([first, second]);+ assert.deepEqual(a.visible, ["server"]);+ assert.equal(writes, 1);+});++test("refresh requests coalesce while the server read is pending", async () => {+ const backend = server();+ const read = deferred<string[] | undefined>();+ let reads = 0;+ backend.load = () => {+ reads += 1;+ return read.promise;+ };+ const a = client(backend);+ const first = a.sync.refresh();+ const second = a.sync.refresh();+ assert.equal(first, second);+ read.resolve([]);+ await Promise.all([first, second]);+ assert.equal(reads, 1);+});++test("repeated compare-and-set conflicts stop after a bounded number of attempts", async () => {+ const backend = server([]);+ let calls = 0;+ backend.compareAndSet = async () => {+ calls += 1;+ return { applied: false, pinnedIds: ["remote"] };+ };+ const a = client(backend);+ await a.sync.refresh();+ await assert.rejects(+ a.sync.setPinned(["local"], true),+ /changed in another browser/,+ );+ assert.equal(calls, 8);+ assert.deepEqual(a.visible, ["local"]);+ assert.equal(a.errors.length, 1);+});++test("an absent unpin reaches the server to record migration tombstones", async () => {+ const backend = server();+ const operations: PinOperation[] = [];+ const fresh = createPinnedChatsSync({+ load: backend.load,+ compareAndSet: async (expected, next, operation) => {+ if (operation) {+ operations.push(operation);+ }+ return backend.compareAndSet(expected, next);+ },+ readLegacy: () => [],+ publish: () => undefined,+ });+ await fresh.setPinned(["unrelated-chat"], false);+ assert.deepEqual(backend.value, []);+ assert.equal(backend.calls.length, 1);+ assert.equal(operations[0]?.kind, "pin");+ assert.deepEqual(+ operations[0] && "ids" in operations[0] ? operations[0].ids : [],+ ["unrelated-chat"],+ );+ assert.equal(+ operations[0] && "pinned" in operations[0]+ ? operations[0].pinned+ : undefined,+ false,+ );+});++test("unpinning the final migrated pin persists an authoritative empty list", async () => {+ const backend = server();+ const a = client(backend, ["old-chat"]);+ await a.sync.setPinned(["old-chat"], false);+ assert.deepEqual(backend.value, []);+ const stale = client(backend, ["old-chat"]);+ await stale.sync.refresh();+ assert.deepEqual(stale.visible, []);+ assert.equal(backend.calls.length, 2);+});++test("a recovered absent setting still migrates legacy pins before the next write", async () => {+ const backend = server();+ const load = backend.load;+ let first = true;+ backend.load = async () => {+ if (first) {+ first = false;+ throw new Error("temporary read failure");+ }+ return load();+ };+ const a = client(backend, ["legacy"]);+ const results = await Promise.allSettled([+ a.sync.setPinned(["failed"], true),+ a.sync.setPinned(["saved"], true),+ ]);+ assert.equal(results[0].status, "rejected");+ assert.equal(results[1].status, "rejected");+ await a.sync.refresh();+ assert.deepEqual(backend.value, ["saved", "failed", "legacy"]);+});++function journal() {+ let entries: PinOperation[] = [];+ return {+ read: () => structuredClone(entries),+ write: (next: PinOperation[]) => {+ entries = structuredClone(next);+ },+ };+}++function durableClient(+ backend: ReturnType<typeof server>,+ disk: ReturnType<typeof journal>,+ extra: Partial<Parameters<typeof createPinnedChatsSync>[0]> = {},+) {+ let visible: string[] = [];+ const sync = createPinnedChatsSync({+ load: backend.load,+ compareAndSet: backend.compareAndSet,+ readLegacy: () => [],+ readPending: disk.read,+ writePending: disk.write,+ publish: (ids) => {+ visible = ids;+ },+ ...extra,+ });+ return {+ sync,+ get visible() {+ return visible;+ },+ };+}++test("a pin queued behind hydration is durable before optimistic publish and survives reload", async () => {+ const backend = server(["old"]);+ const disk = journal();+ const stalled = deferred<string[] | undefined>();+ const a = durableClient(backend, disk, { load: () => stalled.promise });+ const hydration = a.sync.refresh();+ const saving = a.sync.setPinned(["new"], true);+ assert.deepEqual(a.visible, ["new"]);+ assert.equal(disk.read().length, 1);+ assert.equal(disk.read()[0].kind, "pin");+ await Promise.resolve();+ a.sync.reset();+ assert.equal(disk.read().length, 1);+ const reloaded = durableClient(backend, disk);+ await reloaded.sync.refresh();+ assert.deepEqual(backend.value, ["new", "old"]);+ assert.deepEqual(reloaded.visible, ["new", "old"]);+ assert.deepEqual(disk.read(), []);+ stalled.resolve(["old"]);+ await Promise.all([hydration, saving]);+ assert.deepEqual(reloaded.visible, ["new", "old"]);+});++test("journal write failure rejects before publishing the optimistic action", async () => {+ const backend = server(["old"]);+ const disk = journal();+ const a = durableClient(backend, disk, {+ writePending: () => {+ throw new Error("storage full");+ },+ });+ await a.sync.refresh();+ await assert.rejects(a.sync.setPinned(["new"], true), /storage full/);+ assert.deepEqual(a.visible, ["old"]);+ assert.deepEqual(backend.value, ["old"]);+ assert.equal(backend.calls.length, 0);+ assert.deepEqual(disk.read(), []);+});++test("retryable failure retains durable intent and later actions wait in FIFO order", async () => {+ const backend = server(["old"]);+ const disk = journal();+ let offline = true;+ const a = durableClient(backend, disk, {+ compareAndSet: (expected, next) =>+ offline+ ? Promise.reject(new Error("offline"))+ : backend.compareAndSet(expected, next),+ });+ await a.sync.refresh();+ await assert.rejects(a.sync.setPinned(["new"], true));+ assert.deepEqual(a.visible, ["new", "old"]);+ assert.equal(disk.read().length, 1);+ await assert.rejects(a.sync.setPinned(["old"], false));+ assert.equal(disk.read().length, 2);+ assert.deepEqual(a.visible, ["new"]);+ assert.deepEqual(backend.value, ["old"]);+ offline = false;+ await a.sync.refresh();+ assert.deepEqual(+ backend.calls.map((call) => call.next),+ [["new", "old"], ["new"]],+ );+ assert.deepEqual(backend.value, ["new"]);+ assert.deepEqual(disk.read(), []);+});++test("terminal rejection removes only the failed journal entry", async () => {+ const backend = server(["old"]);+ const disk = journal();+ let first = true;+ const a = durableClient(backend, disk, {+ isRetryable: () => false,+ compareAndSet: async (expected, next) => {+ if (first) {+ first = false;+ throw new Error("invalid operation");+ }+ return backend.compareAndSet(expected, next);+ },+ });+ const results = await Promise.allSettled([+ a.sync.setPinned(["rejected"], true),+ a.sync.setPinned(["accepted"], true),+ ]);+ assert.equal(results[0].status, "rejected");+ assert.equal(results[1].status, "fulfilled");+ assert.deepEqual(a.visible, ["accepted", "old"]);+ assert.deepEqual(disk.read(), []);+});++test("acknowledged operations are not replayed when the journal is read again", async () => {+ const backend = server([]);+ const disk = journal();+ disk.write([+ {+ kind: "pin",+ ids: ["restored"],+ pinned: true,+ operationId: "restored-operation",+ },+ ]);+ const a = durableClient(backend, disk);+ await a.sync.refresh();+ await a.sync.refresh();+ assert.deepEqual(backend.value, ["restored"]);+ assert.equal(backend.calls.length, 1);+ assert.deepEqual(disk.read(), []);+});++test("server operation IDs prevent acknowledged journal replay from restoring a later unpin", async () => {+ const backend = server([]);+ const disk = journal();+ const seen = new Set<string>();+ let rejectCleanup = true;+ const compareAndSet = async (+ expected: string[] | undefined,+ next: string[],+ operation?: PinOperation,+ ) => {+ if (operation && seen.has(operation.operationId)) {+ return { applied: true, pinnedIds: backend.value };+ }+ const result = await backend.compareAndSet(expected, next);+ if (result.applied && operation) {+ seen.add(operation.operationId);+ }+ return result;+ };+ const a = durableClient(backend, disk, {+ compareAndSet,+ writePending: (entries) => {+ if (entries.length === 0 && rejectCleanup) {+ throw new Error("cannot acknowledge locally");+ }+ disk.write(entries);+ },+ });+ await assert.rejects(a.sync.setPinned(["new"], true));+ assert.deepEqual(backend.value, ["new"]);+ assert.equal(disk.read().length, 1);+ await backend.compareAndSet(["new"], []);+ a.sync.reset();+ rejectCleanup = false;+ const reloaded = durableClient(backend, disk, { compareAndSet });+ await reloaded.sync.refresh();+ assert.deepEqual(backend.value, []);+ assert.deepEqual(reloaded.visible, []);+ assert.deepEqual(disk.read(), []);+});++test("cleanup failure retries journal removal without resending a known acknowledged operation", async () => {+ const backend = server([]);+ const disk = journal();+ let failing = true;+ const a = durableClient(backend, disk, {+ writePending: (entries) => {+ if (entries.length === 0 && failing) {+ throw new Error("storage unavailable");+ }+ disk.write(entries);+ },+ });+ await assert.rejects(a.sync.setPinned(["new"], true));+ assert.equal(backend.calls.length, 1);+ failing = false;+ await a.sync.refresh();+ assert.equal(backend.calls.length, 1);+ assert.deepEqual(disk.read(), []);+});++test("explicit session reset clears the old journal while normal reset retains it", async () => {+ const backend = server([]);+ const disk = journal();+ const a = durableClient(backend, disk, {+ compareAndSet: async () => {+ throw new Error("offline");+ },+ });+ await assert.rejects(a.sync.setPinned(["private-intent"], true));+ a.sync.reset();+ assert.equal(disk.read().length, 1);+ a.sync.reset({ clearPending: true });+ assert.deepEqual(disk.read(), []);+ assert.deepEqual(a.visible, []);+});++test("legacy merge runs even when server pins exist and preserves durable unpin tombstones", async () => {+ const backend = server(["server"]);+ const tombstones = new Set(["removed"]);+ let merges = 0;+ function mergingClient(initialLegacy: string[]) {+ let legacy = initialLegacy;+ return createPinnedChatsSync({+ load: backend.load,+ compareAndSet: backend.compareAndSet,+ readLegacy: () => legacy,+ migrateLegacy: async (ids) => {+ merges++;+ const current = backend.value ?? [];+ await backend.compareAndSet(current, [+ ...current,+ ...ids.filter((id) => !(current.includes(id) || tombstones.has(id))),+ ]);+ legacy = [];+ return backend.value;+ },+ publish: () => {},+ });+ }+ const a = mergingClient(["legacy-A", "removed"]);+ const b = mergingClient(["legacy-B", "removed"]);+ await a.refresh();+ await b.refresh();+ await a.refresh();+ assert.deepEqual(backend.value, ["server", "legacy-A", "legacy-B"]);+ assert.equal(merges, 2);+});++test("malformed loaded snapshots never replace the last valid published state", async () => {+ const malformed: unknown[] = [+ "string",+ null,+ {},+ [1],+ [""],+ ["duplicate", "duplicate"],+ ["x".repeat(513)],+ Array.from({ length: 10_001 }, (_, i) => String(i)),+ ];+ for (const bad of malformed) {+ const backend = server(["valid"]);+ let loadBad = false;+ const a = durableClient(backend, journal(), {+ load: async () => (loadBad ? (bad as string[]) : backend.value),+ });+ await a.sync.refresh();+ loadBad = true;+ await assert.rejects(a.sync.refresh(), PinnedChatsValidationError);+ assert.deepEqual(a.visible, ["valid"]);+ }+});++test("malformed CAS snapshots and applied flags are rejected without corrupting the UI", async () => {+ const responses: unknown[] = [+ { applied: true, pinnedIds: "string" },+ { applied: true, pinnedIds: undefined },+ { applied: true, pinnedIds: ["duplicate", "duplicate"] },+ { applied: "false", pinnedIds: [] },+ null,+ ];+ for (const response of responses) {+ const backend = server(["valid"]);+ const disk = journal();+ const a = durableClient(backend, disk, {+ compareAndSet: async () =>+ response as { applied: boolean; pinnedIds: string[] },+ });+ await a.sync.refresh();+ await assert.rejects(+ a.sync.setPinned(["new"], true),+ PinnedChatsValidationError,+ );+ assert.deepEqual(a.visible, ["valid"]);+ assert.deepEqual(disk.read(), []);+ }+});++test("malformed migration and pending journal data are rejected before writes", async () => {+ const backend = server(["valid"]);+ const badMigration = durableClient(backend, journal(), {+ readLegacy: () => ["old"],+ migrateLegacy: async () => "string" as unknown as string[],+ });+ await assert.rejects(badMigration.sync.refresh(), PinnedChatsValidationError);+ assert.deepEqual(badMigration.visible, []);+ const badJournal = durableClient(backend, journal(), {+ readPending: () =>+ [+ {+ kind: "move",+ operationId: "op",+ id: "a",+ targetId: "b",+ placement: "sideways",+ },+ ] as unknown as PinOperation[],+ });+ await assert.rejects(badJournal.sync.refresh(), PinnedChatsValidationError);+ assert.equal(backend.calls.length, 0);+});++test("orphaned legacy IDs may leave server state absent without blocking new pins", async () => {+ const backend = server();+ let migrations = 0;+ const a = durableClient(backend, journal(), {+ readLegacy: () => ["deleted-legacy-thread"],+ migrateLegacy: async () => {+ migrations += 1;+ return backend.value;+ },+ });+ await a.sync.refresh();+ assert.deepEqual(a.visible, []);+ assert.equal(backend.value, undefined);+ await a.sync.setPinned(["existing-thread"], true);+ assert.deepEqual(backend.value, ["existing-thread"]);+ assert.equal(migrations, 1);+});++test("IDs reject lone UTF-16 surrogates while preserving valid Unicode", () => {+ for (const value of [+ "\ud800",+ "\udfff",+ "a\ud800b",+ "\ud800\ud800",+ "\udfff\udc00",+ ]) {+ assert.throws(() => validatePinnedIds([value]), PinnedChatsValidationError);+ assert.throws(+ () =>+ validatePinOperation({+ kind: "pin",+ operationId: value,+ ids: [],+ pinned: true,+ }),+ PinnedChatsValidationError,+ );+ }+ assert.deepEqual(validatePinnedIds(["\ud83d\udcac", "chat-\u00e9"]), [+ "\ud83d\udcac",+ "chat-\u00e9",+ ]);+});++test("pins save on a plain-HTTP origin, where crypto.randomUUID does not exist", async () => {+ const original = Object.getOwnPropertyDescriptor(globalThis.crypto, "randomUUID");+ Object.defineProperty(globalThis.crypto, "randomUUID", { value: undefined, configurable: true });+ try {+ const backend = server(["old"]);+ const a = client(backend);+ await a.sync.refresh();+ await a.sync.setPinned(["new"], true);+ assert.deepEqual(backend.value, ["new", "old"]);+ } finally {+ if (original) Object.defineProperty(globalThis.crypto, "randomUUID", original);+ else delete (globalThis.crypto as { randomUUID?: unknown }).randomUUID;+ }+});++test("unpinning a chat the server cannot place yet cancels its queued pin instead of waiting behind it", async () => {+ let value: string[] = [];+ const operations: PinOperation[] = [];+ let visible: string[] = [];+ const sync = createPinnedChatsSync({+ load: async () => value.slice(),+ compareAndSet: async (expected, next, operation) => {+ if (operation) operations.push(operation);+ // A comparison deleted before its legacy import: the server never acknowledges its pin.+ if (next.includes("pair") || JSON.stringify(expected) !== JSON.stringify(value)) {+ return { applied: false, pinnedIds: value.slice() };+ }+ value = next.slice();+ return { applied: true, pinnedIds: value.slice() };+ },+ readLegacy: () => [],+ publish: (ids) => { visible = ids; },+ });+ await sync.refresh();+ const blocked = sync.setPinned(["pair"], true).catch(() => undefined);+ await sync.setPinned(["pair"], false);+ await sync.setPinned(["chat"], true);+ await blocked;+ assert.deepEqual(value, ["chat"]);+ assert.deepEqual(visible, ["chat"]);+ assert.ok(operations.some((op) => !op.pinned && op.ids.includes("pair")));+});++test("a 401 from a transient token-refresh failure keeps the queued pin for a later retry", async () => {+ const backend = server(["old"]);+ const disk = journal();+ let unauthorized = true;+ const a = durableClient(backend, disk, {+ isRetryable: isRetryablePinError,+ compareAndSet: (expected, next) =>+ unauthorized+ ? Promise.reject(new ChatSettingsRequestError("Unauthorized", 401, null))+ : backend.compareAndSet(expected, next),+ });+ await a.sync.refresh();+ await assert.rejects(a.sync.setPinned(["new"], true));+ assert.equal(disk.read().length, 1);+ unauthorized = false;+ await a.sync.refresh();+ assert.deepEqual(backend.value, ["new", "old"]);+ assert.equal(isRetryablePinError(new ChatSettingsRequestError("Bad request", 400, null)), false);+});++test("an unpin that cancels a queued pin sends that pin's ID so a delayed copy is fenced", async () => {+ let value: string[] = [];+ const sent: PinOperation[] = [];+ let offline = true;+ const sync = createPinnedChatsSync({+ load: async () => value.slice(),+ compareAndSet: async (expected, next, operation) => {+ if (offline) throw new Error("offline");+ if (operation) sent.push(operation);+ if (JSON.stringify(expected ?? []) !== JSON.stringify(value)) return { applied: false, pinnedIds: value.slice() };+ value = next.slice();+ return { applied: true, pinnedIds: value.slice() };+ },+ readLegacy: () => [],+ publish: () => undefined,+ });+ await sync.refresh();+ await assert.rejects(sync.setPinned(["chat"], true));+ offline = false;+ await sync.setPinned(["chat"], false);+ const unpin = sent.find((op) => !op.pinned);+ assert.ok(unpin?.cancels?.length === 1);+ assert.ok(!sent.some((op) => op.pinned));+ assert.deepEqual(validatePinOperation(unpin).cancels, unpin.cancels);+});++test("trimming an already-committed bulk pin does not repin what another client unpinned", async () => {+ let value: string[] = [];+ const seen = new Set<string>();+ let loseResponse = true;+ const sync = createPinnedChatsSync({+ load: async () => value.slice(),+ compareAndSet: async (expected, next, operation) => {+ const id = operation && (operation.serverId ?? operation.operationId);+ if (id && seen.has(id)) return { applied: true, pinnedIds: value.slice() };+ if (JSON.stringify(expected ?? []) !== JSON.stringify(value)) return { applied: false, pinnedIds: value.slice() };+ value = next.slice();+ if (id) seen.add(id);+ if (loseResponse) {+ loseResponse = false;+ throw new TypeError("connection reset");+ }+ return { applied: true, pinnedIds: value.slice() };+ },+ readLegacy: () => [],+ publish: () => undefined,+ });+ await sync.refresh();+ await assert.rejects(sync.setPinned(["a", "b"], true));+ assert.deepEqual(value, ["a", "b"]);+ value = ["a"]; // Another client unpins "b".+ await sync.setPinned(["a"], false);+ await sync.refresh();+ assert.deepEqual(value, []);+});++test("an unpin over an original and its trimmed copy fences their shared server ID once", async () => {+ const sent: PinOperation[] = [];+ const queued: PinOperation[] = [+ { kind: "pin", operationId: "orig", ids: ["a", "b", "c"], pinned: true },+ { kind: "pin", operationId: "copy", ids: ["b", "c"], pinned: true, serverId: "orig" },+ ];+ let journal = structuredClone(queued);+ const sync = createPinnedChatsSync({+ load: async () => [],+ compareAndSet: async (_expected, _next, operation) => {+ if (operation) sent.push(operation);+ return { applied: false, pinnedIds: [] };+ },+ readLegacy: () => [],+ readPending: () => structuredClone(journal),+ writePending: (operations) => { journal = structuredClone(operations); },+ publish: () => undefined,+ });+ const unpin = sync.setPinned(["b"], false).catch(() => undefined);+ const saved = journal.find((operation) => !operation.pinned);+ assert.deepEqual(saved?.cancels, ["orig"]);+ sync.reset();+ await unpin;+});+diff --git a/studio/frontend/tests/pinned-chats-transport.test.ts b/studio/frontend/tests/pinned-chats-transport.test.tsnew file mode 100644index 00000000000..542482c75cc--- /dev/null+++ b/studio/frontend/tests/pinned-chats-transport.test.ts@@ -0,0 +1,514 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import { createPinnedChatsSync, type PinOperation } from "../src/features/chat/utils/pinned-chats-sync.ts";+import { createPinnedChatsTransport, type PinnedChatsFallbackState } from "../src/features/chat/utils/pinned-chats-transport.ts";+import { ChatSettingsRequestError } from "../src/features/chat/utils/settings-retry.ts";++function unsupported(status = 400, loc = ["patch", "pinnedChatIds"]) {+ return new ChatSettingsRequestError("unsupported", status, [+ { type: "extra_forbidden", loc },+ ]);+}+function pin(operationId: string, ids: string[], pinned = true): PinOperation {+ return { operationId, kind: "pin", ids, pinned };+}+function fixture(error: unknown = unsupported()) {+ const legacy = ["legacy"];+ let remote: string[] | undefined;+ let failure = error;+ let loadFailure: unknown;+ let remoteCalls = 0;+ let loads = 0;+ let warnings = 0;+ let fallback: PinnedChatsFallbackState | undefined;+ let journalFailure = false;+ const acknowledged = new Set<string>();+ const tombstones = new Set<string>();+ const readLegacy = () => legacy.slice();+ const options = {+ load: async () => {+ loads += 1;+ if (loadFailure) throw loadFailure;+ return remote?.slice();+ },+ compareAndSet: async (expected: string[] | undefined, next: string[], operation?: PinOperation) => {+ remoteCalls += 1;+ if (failure) throw failure;+ if (operation && acknowledged.has(operation.operationId))+ return { pinnedIds: remote?.slice(), applied: true };+ const applied = JSON.stringify(expected) === JSON.stringify(remote);+ if (applied) {+ remote = next.slice();+ if (operation) acknowledged.add(operation.operationId);+ }+ return { pinnedIds: remote?.slice(), applied };+ },+ migrateLegacy: async (ids: string[]) => {+ if (failure) throw failure;+ remote = [...new Set([...(remote ?? []), ...ids.filter((id) => !tombstones.has(id))])];+ return remote.slice();+ },+ readLegacy,+ readFallback: () => fallback && structuredClone(fallback),+ writeFallback: (value: PinnedChatsFallbackState | undefined) => {+ if (journalFailure) throw new Error("journal full");+ fallback = value && structuredClone(value);+ },+ onUnsupported: () => { warnings += 1; },+ };+ const transport = createPinnedChatsTransport(options);+ let visible: string[] = [];+ const sync = createPinnedChatsSync({+ ...transport, readLegacy, publish: (ids) => { visible = ids; },+ });+ return {+ options, transport, sync, tombstones, acknowledged,+ upgrade: () => { failure = undefined; },+ set failure(value: unknown) { failure = value; },+ set loadFailure(value: unknown) { loadFailure = value; },+ set journalFailure(value: boolean) { journalFailure = value; },+ set remote(value: string[] | undefined) { remote = value; },+ get remote() { return remote; },+ get local() { return fallback?.pinnedIds ?? legacy; },+ get visible() { return visible; },+ get fallback() { return fallback; },+ get remoteCalls() { return remoteCalls; },+ get loads() { return loads; },+ get warnings() { return warnings; },+ };+}++test("an older backend journals local pin/unpin and probes again on refresh", async () => {+ const f = fixture();+ await f.sync.refresh();+ assert.deepEqual(f.visible, ["legacy"]);+ await f.sync.setPinned(["new", "another"], true);+ assert.deepEqual(f.local, ["new", "another", "legacy"]);+ await f.sync.setPinned(["legacy", "new", "another"], false);+ assert.deepEqual(f.local, []);+ assert.equal(f.fallback?.operations.length, 2);+ const before = f.loads;+ await f.sync.refresh();+ assert.equal(f.loads, before + 1);+ assert.deepEqual(f.visible, []);+ assert.equal(f.warnings, 1);+});++test("explicit missing routes and combined old-schema errors enable fallback", async () => {+ const errors = [unsupported(404), unsupported(405), new ChatSettingsRequestError("unsupported", 400, [+ { type: "extra_forbidden", loc: ["expected", "pinnedChatIds"] },+ { type: "extra_forbidden", loc: ["patch", "pinnedChatIds"] },+ ]), new ChatSettingsRequestError("unsupported", 400, [+ // Downgraded since operation IDs were probed: the old schema rejects them too.+ { type: "extra_forbidden", loc: ["patch", "pinnedChatIds"] },+ { type: "extra_forbidden", loc: ["operationId"] },+ ]), new ChatSettingsRequestError("unsupported", 400, [+ { type: "value_error", loc: ["expectedAbsent"], msg: "Value error, Unknown chat settings field(s): pinnedChatIds" },+ { type: "extra_forbidden", loc: ["patch", "pinnedChatIds"] },+ ])];+ for (const error of errors) {+ const f = fixture(error);+ await f.sync.setPinned(["new"], true);+ assert.deepEqual(f.local, ["new", "legacy"]);+ assert.equal(f.fallback?.operations.length, 1);+ assert.equal(f.warnings, 1);+ }+});++test("network, auth, server, and unrelated validation failures never switch to local writes", async () => {+ const errors = [+ new TypeError("network unavailable"),+ new ChatSettingsRequestError("unauthorized", 401, null),+ new ChatSettingsRequestError("forbidden", 403, null),+ new ChatSettingsRequestError("internal error", 500, null),+ new ChatSettingsRequestError("bad pins", 400, [+ { type: "too_long", loc: ["patch", "pinnedChatIds"] },+ ]),+ new ChatSettingsRequestError("other field", 400, [+ { type: "extra_forbidden", loc: ["patch", "other"] },+ ]),+ new ChatSettingsRequestError("mixed error", 400, [+ { type: "extra_forbidden", loc: ["patch", "pinnedChatIds"] },+ { type: "bool_type", loc: ["expected", "toolsEnabled"] },+ ]),+ new ChatSettingsRequestError("absent field alone", 400, [+ {+ type: "value_error",+ loc: ["expectedAbsent"],+ msg: "Value error, Unknown chat settings field(s): pinnedChatIds",+ },+ ]),+ new ChatSettingsRequestError("other absent field", 400, [+ { type: "extra_forbidden", loc: ["patch", "pinnedChatIds"] },+ {+ type: "value_error",+ loc: ["expectedAbsent"],+ msg: "Value error, Unknown chat settings field(s): other, pinnedChatIds",+ },+ ]),+ new ChatSettingsRequestError("other absent validation", 400, [+ { type: "extra_forbidden", loc: ["patch", "pinnedChatIds"] },+ {+ type: "list_type",+ loc: ["expectedAbsent"],+ msg: "Input should be a valid list",+ },+ ]),+ new ChatSettingsRequestError("other absent path", 400, [+ { type: "extra_forbidden", loc: ["patch", "pinnedChatIds"] },+ {+ type: "value_error",+ loc: ["expectedAbsentPaths"],+ msg: "Value error, Unknown chat settings field(s): pinnedChatIds",+ },+ ]),+ new ChatSettingsRequestError("malformed detail", 400, "pinnedChatIds"),+ new ChatSettingsRequestError("no details", 400, []),+ ];+ for (const error of errors) {+ const f = fixture(error);+ await assert.rejects(+ f.transport.compareAndSet(undefined, ["new"]),+ (caught) => caught === error,+ );+ await assert.rejects(+ f.transport.compareAndSet(undefined, ["new"]),+ (caught) => caught === error,+ );+ assert.deepEqual(f.local, ["legacy"]);+ assert.equal(f.warnings, 0);+ assert.equal(f.remoteCalls, 2);+ assert.equal(f.fallback, undefined);+ }+});+++test("upgrade automatically merges baseline and replays explicit changes in order", async () => {+ const f = fixture();+ await f.sync.setPinned(["new"], true);+ await f.sync.setPinned(["another"], true);+ await f.sync.setPinned(["legacy"], false);+ f.remote = ["other-browser"];+ f.upgrade();+ await f.sync.refresh();+ assert.deepEqual(f.remote, ["another", "new", "other-browser"]);+ assert.deepEqual(f.visible, f.remote);+ assert.equal(f.fallback, undefined);+ await f.sync.setPinned(["after-upgrade"], true);+ assert.deepEqual(f.remote, ["after-upgrade", "another", "new", "other-browser"]);+});++test("downgrade starts local state from last remote pins, preserving existing pins", async () => {+ const f = fixture();+ f.upgrade();+ f.remote = ["server-a", "server-b"];+ await f.transport.load();+ f.remote = undefined;+ await f.transport.load();+ f.failure = unsupported();+ const operation = pin("downgrade", ["new"]);+ const conflict = await f.transport.compareAndSet(undefined, ["new"], operation);+ assert.deepEqual(conflict, { applied: false, pinnedIds: ["server-a", "server-b"] });+ await f.transport.compareAndSet(conflict.pinnedIds, ["new", ...conflict.pinnedIds!], operation);+ assert.deepEqual(f.local, ["new", "server-a", "server-b"]);+ assert.deepEqual(f.fallback?.baseIds, ["server-a", "server-b"]);+});++test("fallback survives adapter recreation and skips tombstoned legacy pins on upgrade", async () => {+ const f = fixture();+ await f.sync.setPinned(["new"], true);+ const restored = createPinnedChatsTransport(f.options);+ assert.deepEqual(await restored.load(), ["new", "legacy"]);+ f.tombstones.add("legacy");+ f.upgrade();+ assert.deepEqual(await restored.load(), ["new"]);+ assert.deepEqual(f.remote, ["new"]);+ assert.equal(f.fallback, undefined);+});++test("a fallback baseline without operations still probes and migrates after upgrade", async () => {+ const f = fixture();+ await f.sync.refresh();+ assert.deepEqual(f.fallback?.operations, []);+ f.upgrade();+ await f.sync.refresh();+ assert.deepEqual(f.remote, ["legacy"]);+ assert.equal(f.fallback, undefined);+});++test("journal failure cannot claim a saved local write", async () => {+ const f = fixture();+ await f.sync.refresh();+ f.journalFailure = true;+ await assert.rejects(f.transport.compareAndSet(["legacy"], ["new", "legacy"], pin("write", ["new"])), /journal full/);+ assert.deepEqual(f.local, ["legacy"]);+ assert.deepEqual(f.fallback?.operations, []);+});++test("partial replay retains operation IDs and retries without repeating acknowledged edits", async () => {+ const f = fixture();+ await f.sync.setPinned(["first"], true);+ await f.sync.setPinned(["second"], true);+ f.upgrade();+ let calls = 0;+ const interrupted = createPinnedChatsTransport({ ...f.options,+ compareAndSet: async (...args) => {+ calls += 1;+ if (calls === 2) throw new TypeError("network disconnected");+ return f.options.compareAndSet(...args);+ },+ });+ assert.deepEqual(await interrupted.load(), ["second", "first", "legacy"]);+ assert.equal(f.fallback?.operations.length, 2);+ assert.deepEqual(f.remote, ["first", "legacy"]);+ // A different browser puts a new row above the first acknowledged pin.+ f.remote = ["other-browser", ...f.remote!];+ assert.deepEqual(await interrupted.load(), ["second", "other-browser", "first", "legacy"]);+ assert.equal(f.fallback, undefined);+});++test("replay conflict retries are bounded and leave the recovery journal intact", async () => {+ const f = fixture();+ await f.sync.setPinned(["new"], true);+ f.upgrade();+ let conflicts = 0;+ const transport = createPinnedChatsTransport({ ...f.options,+ compareAndSet: async () => { conflicts += 1; return { applied: false, pinnedIds: ["racer"] }; },+ });+ // The saved view stands in until the replay can land.+ assert.deepEqual(await transport.load(), ["new", "legacy"]);+ assert.equal(conflicts, 8);+ assert.equal(f.fallback?.operations.length, 1);+});++test("auth failure propagates during recovery while transient failures keep saved local pins", async () => {+ const f = fixture();+ await f.sync.setPinned(["new"], true);+ f.loadFailure = new TypeError("offline");+ assert.deepEqual(await f.transport.load(), ["new", "legacy"]);+ f.loadFailure = new ChatSettingsRequestError("unauthorized", 401, null);+ await assert.rejects(f.transport.load(), /unauthorized/);+ assert.equal(f.fallback?.operations.length, 1);+});++test("stale unsupported response after session reset cannot create a fallback journal", async () => {+ const f = fixture();+ let reject!: (error: unknown) => void;+ const transport = createPinnedChatsTransport({ ...f.options,+ compareAndSet: () => new Promise((_yes, no) => { reject = no; }),+ });+ const before = transport.compareAndSet(["legacy"], ["new"], pin("old", ["new"]));+ transport.reset();+ reject(unsupported());+ await assert.rejects(before, /session changed/);+ assert.equal(f.fallback, undefined);+});++test("stale recovery after reset cannot clear the durable fallback", async () => {+ const f = fixture();+ await f.sync.setPinned(["new"], true);+ let resolve!: (ids: string[]) => void;+ const transport = createPinnedChatsTransport({ ...f.options,+ migrateLegacy: () => new Promise((yes) => { resolve = yes; }),+ });+ const before = transport.load();+ await Promise.resolve();+ transport.reset();+ resolve(["legacy"]);+ await assert.rejects(before, /session changed/);+ assert.equal(f.fallback?.operations.length, 1);+});++test("malformed remote responses are rejected without entering fallback", async () => {+ const f = fixture();+ const transport = createPinnedChatsTransport({ ...f.options,+ load: async () => ["duplicate", "duplicate"],+ compareAndSet: async () => ({ applied: true, pinnedIds: undefined }),+ });+ await assert.rejects(transport.load(), /Invalid pinned chats response/);+ await assert.rejects(transport.compareAndSet([], ["new"], pin("bad", ["new"])), /Invalid pinned chats response/);+ assert.equal(f.fallback, undefined);+});++test("local compare and set preserves another tab's newer snapshot", async () => {+ const f = fixture();+ await f.sync.setPinned(["new"], true);+ assert.deepEqual(await f.transport.compareAndSet(["legacy"], [], pin("stale", ["legacy"], false)), {+ applied: false, pinnedIds: ["new", "legacy"],+ });+ assert.deepEqual(f.local, ["new", "legacy"]);+});+++test("orphan-only migration may leave pins absent before a valid operation is replayed", async () => {+ const f = fixture();+ await f.sync.setPinned(["new"], true);+ f.upgrade();+ const transport = createPinnedChatsTransport({ ...f.options,+ migrateLegacy: async () => undefined,+ });+ assert.deepEqual(await transport.load(), ["new"]);+ assert.equal(f.fallback, undefined);++ const fresh = fixture();+ const noValidLegacy = createPinnedChatsTransport({ ...fresh.options,+ migrateLegacy: async () => undefined,+ });+ assert.equal(await noValidLegacy.migrateLegacy(["orphan"]), undefined);+ assert.equal(fresh.fallback, undefined);+});++test("upgrade replay skips a pin whose chat was unpinned (deleted) later in the offline log", async () => {+ let remote: string[] = ["chat"];+ const sent: PinOperation[] = [];+ const tombstones = new Set<string>();+ let fallback: PinnedChatsFallbackState | undefined = {+ baseIds: [],+ pinnedIds: ["new"],+ operations: [pin("01", ["pair"]), pin("02", ["pair"], false), pin("03", ["new"])],+ };+ const transport = createPinnedChatsTransport({+ load: async () => remote.slice(),+ compareAndSet: async (expected, next, operation) => {+ if (operation) sent.push(operation);+ // The upgraded server never learned the deleted comparison's pair ID.+ if (next.includes("pair")) return { pinnedIds: remote.slice(), applied: false };+ if (JSON.stringify(expected) !== JSON.stringify(remote)) return { pinnedIds: remote.slice(), applied: false };+ if (operation && !operation.pinned) operation.ids.forEach((id) => tombstones.add(id));+ remote = next.slice();+ return { pinnedIds: remote.slice(), applied: true };+ },+ migrateLegacy: async () => remote.slice(),+ readLegacy: () => [],+ readFallback: () => fallback && structuredClone(fallback),+ writeFallback: (value) => { fallback = value && structuredClone(value); },+ });+ assert.deepEqual(await transport.load(), ["new", "chat"]);+ assert.equal(fallback, undefined);+ assert.ok(tombstones.has("pair"));+ // Another tab may already be replaying the dropped pin: the unpin fences its ID.+ assert.deepEqual(sent.find((op) => !op.pinned)?.cancels, ["01"]);+});++test("saved fallback pins hydrate when authFetch reports the network down", async () => {+ const f = fixture();+ await f.sync.setPinned(["new"], true);+ f.loadFailure = Object.assign(new Error("Failed to fetch"), { unslothTransportFailure: true });+ assert.deepEqual(await f.transport.load(), ["new", "legacy"]);+});++test("an upgrade replay retries a trimmed bulk pin under the same ID", async () => {+ let remote: string[] = [];+ const seen = new Set<string>();+ const ids: string[] = [];+ let loseResponse = true;+ let fallback: PinnedChatsFallbackState | undefined = {+ baseIds: [],+ pinnedIds: ["b"],+ operations: [pin("01", ["a", "b"]), pin("02", ["a"], false)],+ };+ const transport = createPinnedChatsTransport({+ load: async () => remote.slice(),+ compareAndSet: async (expected, next, operation) => {+ if (operation) ids.push(operation.operationId);+ if (operation && seen.has(operation.operationId)) return { pinnedIds: remote.slice(), applied: true };+ if (JSON.stringify(expected) !== JSON.stringify(remote)) return { pinnedIds: remote.slice(), applied: false };+ remote = next.slice();+ if (operation) seen.add(operation.operationId);+ if (operation?.pinned && loseResponse) {+ loseResponse = false;+ throw new TypeError("connection reset");+ }+ return { pinnedIds: remote.slice(), applied: true };+ },+ migrateLegacy: async () => remote.slice(),+ readLegacy: () => [],+ readFallback: () => fallback && structuredClone(fallback),+ writeFallback: (value) => { fallback = value && structuredClone(value); },+ });+ // The first replay commits ["b"] but its response is lost; the saved state stands in.+ assert.deepEqual(await transport.load(), ["b"]);+ assert.deepEqual(remote, ["b"]);+ // Another client explicitly unpins "b" before this one retries.+ remote = [];+ await transport.load();+ const replays = ids.filter((id) => id !== "02");+ assert.equal(new Set(replays).size, 1);+ assert.deepEqual(remote, []);+});++test("a replay the server keeps refusing still lets a later unpin cancel that pin", async () => {+ let remote: string[] = [];+ let fallback: PinnedChatsFallbackState | undefined = {+ baseIds: [],+ pinnedIds: ["pair"],+ operations: [pin("01", ["pair"])],+ };+ const options = {+ load: async () => remote.slice(),+ compareAndSet: async (expected: string[] | undefined, next: string[]) => {+ // A legacy comparison still awaiting import: the upgraded server cannot place it.+ if (next.includes("pair") || JSON.stringify(expected) !== JSON.stringify(remote)) {+ return { pinnedIds: remote.slice(), applied: false };+ }+ remote = next.slice();+ return { pinnedIds: remote.slice(), applied: true };+ },+ migrateLegacy: async () => remote.slice(),+ readLegacy: () => [],+ readFallback: () => fallback && structuredClone(fallback),+ writeFallback: (value: PinnedChatsFallbackState | undefined) => {+ fallback = value && structuredClone(value);+ },+ };+ const transport = createPinnedChatsTransport(options);+ let visible: string[] = [];+ const sync = createPinnedChatsSync({ ...transport, readLegacy: () => [], publish: (ids) => { visible = ids; } });+ await sync.refresh();+ assert.deepEqual(visible, ["pair"]);+ await sync.setPinned(["pair"], false);+ await sync.setPinned(["chat"], true);+ await sync.refresh();+ assert.deepEqual(remote, ["chat"]);+ assert.equal(fallback, undefined);+});++test("local fallback acknowledges a late pin an earlier unpin already fenced", async () => {+ const f = fixture();+ await f.sync.refresh();+ const unpin: PinOperation = { ...pin("u", ["chat"], false), cancels: ["late"] };+ await f.transport.compareAndSet(["legacy"], ["legacy"], unpin);+ const result = await f.transport.compareAndSet(["legacy"], ["chat", "legacy"], pin("late", ["chat"]));+ assert.deepEqual(result, { applied: true, pinnedIds: ["legacy"] });+ assert.equal(f.fallback?.operations.length, 1);+});++test("upgrade replay sends each fenced ID once", async () => {+ let remote: string[] = [];+ const sent: PinOperation[] = [];+ let fallback: PinnedChatsFallbackState | undefined = {+ baseIds: [],+ pinnedIds: [],+ operations: [pin("p", ["chat"]), { ...pin("u", ["chat"], false), cancels: ["p"] }],+ };+ const transport = createPinnedChatsTransport({+ load: async () => remote.slice(),+ compareAndSet: async (expected, next, operation) => {+ if (operation) sent.push(operation);+ if (JSON.stringify(expected) !== JSON.stringify(remote)) return { pinnedIds: remote.slice(), applied: false };+ remote = next.slice();+ return { pinnedIds: remote.slice(), applied: true };+ },+ migrateLegacy: async () => remote.slice(),+ readLegacy: () => [],+ readFallback: () => fallback && structuredClone(fallback),+ writeFallback: (value) => { fallback = value && structuredClone(value); },+ });+ await transport.load();+ assert.deepEqual(sent.find((op) => !op.pinned)?.cancels, ["p"]);+ assert.equal(fallback, undefined);+});+diff --git a/tests/studio/playwright_pinned_chat_persistence.py b/tests/studio/playwright_pinned_chat_persistence.pynew file mode 100644index 00000000000..d3558fc5077--- /dev/null+++ b/tests/studio/playwright_pinned_chat_persistence.py@@ -0,0 +1,507 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Chat pins survive browser lifecycle changes and synchronize between clients.++Loads the production store and lifecycle hook through Vite, with browser requests+served by the real chat-settings routes against temporary SQLite. No model or+running Unsloth installation is required, and no existing user data is touched.+The delayed-read cases put an optimistic edit behind an in-flight request; merely+adding keepalive to the eventual write cannot make those cases pass.++Prerequisites: frontend npm dependencies, Chromium installed by Playwright, and+Python packages playwright, fastapi, httpx, pyjwt, argon2-cffi, cryptography, huggingface_hub,+python-multipart, and structlog. Run from any directory:++ python tests/studio/playwright_pinned_chat_persistence.py++PLAYWRIGHT_CHROMIUM_EXECUTABLE optionally selects an already installed browser.+"""++from __future__ import annotations++import asyncio+import importlib.util+import json+import os+import subprocess+import sys+import tempfile+import time+from pathlib import Path+from urllib.parse import urlsplit++REPO = Path(__file__).resolve().parents[2]+FRONTEND = REPO / "studio" / "frontend"+BACKEND = REPO / "studio" / "backend"+++def write_browser_fixture(directory: Path) -> None:+ source = "/@fs/" + (FRONTEND / "src").as_posix().lstrip("/")+ (directory / "index.html").write_text(+ """<!doctype html><html><body><div id="sync"></div><script type="module">+import React, {useEffect} from "react";+import {createRoot} from "react-dom/client";+import * as store from "__SOURCE__/features/chat/stores/pinned-chats-store.ts";+import * as runtime from "__SOURCE__/features/chat/sync-pinned-chats.ts";+import {usePinnedChatsSync} from "__SOURCE__/features/chat/hooks/use-pinned-chats-sync.ts";+import * as auth from "__SOURCE__/features/auth/session.ts";+window.pins = {...store, ...runtime};+window.auth = auth;+let root;+function Sync() {+ usePinnedChatsSync();+ useEffect(() => {+ window.syncMounted = true;+ return () => {window.syncMounted = false;};+ }, []);+ return null;+}+window.mountSync = () => {+ root = createRoot(document.getElementById("sync"));+ root.render(React.createElement(Sync));+};+window.unmountSync = () => root.unmount();+window.ready = true;+</script></body></html>""".replace("__SOURCE__", source),+ encoding = "utf-8",+ )+ (directory / "vite.mjs").write_text(+ "import {createServer} from "+ + json.dumps((FRONTEND / "node_modules/vite/dist/node/index.js").as_uri())+ + ";\nimport {writeFileSync} from 'node:fs';\n"+ + "const server = await createServer("+ + json.dumps(+ {+ "configFile": str(FRONTEND / "vite.config.ts"),+ "root": str(directory),+ "server": {"host": "127.0.0.1", "port": 0, "fs": {"allow": [str(REPO)]}},+ }+ )+ + ");\nawait server.listen();\n"+ + "writeFileSync("+ + json.dumps(str(directory / "ready.json"))+ + ", JSON.stringify({url: `http://127.0.0.1:${server.httpServer.address().port}`}));\n",+ encoding = "utf-8",+ )+++def settings_client(home: Path):+ # Import the actual route file without importing routes/__init__.py, whose+ # application-wide registry eagerly loads unrelated training dependencies.+ os.environ["UNSLOTH_STUDIO_HOME"] = str(home)+ os.environ["UNSLOTH_STUDIO_DISABLE_DEVICE_PROBE"] = "1"+ sys.path.insert(0, str(BACKEND))+ from fastapi import FastAPI+ from fastapi.testclient import TestClient+ from auth.authentication import get_current_subject++ spec = importlib.util.spec_from_file_location(+ "pin_persistence_routes", BACKEND / "routes/chat_history.py"+ )+ module = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = module+ spec.loader.exec_module(module)+ app = FastAPI()+ app.include_router(module.router, prefix = "/api/chat")+ app.dependency_overrides[get_current_subject] = lambda: "pin-persistence-test"+ return TestClient(app)+++async def exercise_browser(url: str, client) -> list[str]:+ from playwright.async_api import async_playwright++ passed: list[str] = []+ errors: list[str] = []++ def server_pins():+ return client.get("/api/chat/settings").json()["settings"].get("pinnedChatIds")++ def save_server_pins(ids):+ response = client.put("/api/chat/settings", json = {"pinnedChatIds": ids})+ assert response.status_code == 200, response.text++ async with async_playwright() as playwright:+ executable = os.environ.get("PLAYWRIGHT_CHROMIUM_EXECUTABLE")+ browser = await playwright.chromium.launch(+ **({"executable_path": executable} if executable else {})+ )+ try:++ async def new_client(+ *,+ context = None,+ legacy = None,+ old_backend = False,+ missing_route_status = 404,+ ):+ context = context or await browser.new_context()+ page = await context.new_page()+ state = {+ "hold_next_get": False,+ "held": asyncio.Event(),+ "release": asyncio.Event(),+ "old_backend": old_backend,+ "old_pins": None,+ }++ async def serve(route):+ request = route.request+ if request.method == "GET" and state["hold_next_get"]:+ state["hold_next_get"] = False+ state["held"].set()+ await state["release"].wait()+ if state["old_backend"]:+ if urlsplit(request.url).path.startswith("/api/chat/pins"):+ # Reverse proxies and older servers may return plain text.+ await route.fulfill(+ status = missing_route_status,+ body = "Missing endpoint",+ content_type = "text/plain",+ )+ return+ response = (+ {+ "settings": {}+ if state["old_pins"] is None+ else {"pinnedChatIds": state["old_pins"]}+ }+ if request.method == "GET"+ else {+ "detail": [+ {+ "type": "value_error",+ "loc": ["expectedAbsent"],+ "msg": "Value error, Unknown chat settings field(s): pinnedChatIds",+ },+ {+ "type": "extra_forbidden",+ "loc": ["patch", "pinnedChatIds"],+ "msg": "Extra inputs are not permitted",+ },+ ]+ }+ )+ await route.fulfill(+ status = 200 if request.method == "GET" else 400, json = response+ )+ return+ response = client.request(+ request.method,+ urlsplit(request.url).path,+ content = request.post_data,+ headers = {"Content-Type": "application/json"},+ )+ # Reload/signout can abort the intentionally delayed read.+ try:+ await route.fulfill(+ status = response.status_code,+ body = response.content,+ headers = {"Content-Type": "application/json"},+ )+ except Exception:+ if not request.failure:+ raise++ await page.route("**/api/chat/settings**", serve)+ await page.route("**/api/chat/pins**", serve)+ page.on("pageerror", lambda error: errors.append(str(error)))+ # Supported older WebKit versions lack these static helpers.+ # Keep every lifecycle scenario on that API feature floor.+ await page.add_init_script("""+ Object.defineProperty(AbortSignal, 'any', {value: undefined, configurable: true});+ Object.defineProperty(AbortSignal, 'timeout', {value: undefined, configurable: true});+ """)+ await page.add_init_script("""if (!localStorage.getItem('unsloth_auth_token')) {+ localStorage.setItem('unsloth_auth_token', 'pin-test-access');+ localStorage.setItem('unsloth_auth_refresh_token', 'pin-test-refresh');+ localStorage.setItem('unsloth_auth_session_mark', 'pin-test-session');+ }""")+ if legacy is not None:+ await page.add_init_script(+ "localStorage.setItem('unsloth_pinned_chats', "+ + json.dumps(json.dumps({"state": {"pinnedIds": legacy}, "version": 0}))+ + ")"+ )+ await page.goto(url)+ await page.wait_for_function("window.ready === true")+ assert await page.evaluate(+ "AbortSignal.any === undefined && AbortSignal.timeout === undefined"+ )+ return context, page, state++ async def mount(page):+ await page.evaluate("window.mountSync()")+ await page.wait_for_function("window.syncMounted === true")+ await page.evaluate("window.pins.refreshPinnedChats()")++ async def pins(page):+ return await page.evaluate("window.pins.usePinnedChatsStore.getState().pinnedIds")++ async def delay_focus_read(page, state):+ state.update(hold_next_get = True, held = asyncio.Event(), release = asyncio.Event())+ await page.evaluate("window.dispatchEvent(new Event('focus'))")+ await asyncio.wait_for(state["held"].wait(), timeout = 5)++ for chat_id in (+ "survives-reload",+ "survives-remount",+ "server-before-signout",+ "old-session-only",+ "from-second-browser",+ "local-before-upgrade",+ "after-server-upgrade",+ "downgrade-a",+ "downgrade-b",+ "downgrade-offline",+ "downgrade-concurrent",+ "legacy-token-pending",+ ):+ response = client.post(+ "/api/chat/threads",+ json = {+ "id": chat_id,+ "title": chat_id,+ "modelType": "base",+ "createdAt": 1,+ },+ )+ assert response.status_code == 200, response.text+ save_server_pins([])+ context, page, state = await new_client()+ await mount(page)+ for pinned in (True, False):+ await delay_focus_read(page, state)+ await page.evaluate(+ "pinned => window.pins.usePinnedChatsStore.getState().setPinned(['survives-reload'], pinned)",+ pinned,+ )+ expected = ["survives-reload"] if pinned else []+ assert await pins(page) == expected+ await page.reload()+ await page.wait_for_function("window.ready === true")+ state["release"].set()+ await mount(page)+ assert await pins(page) == expected+ assert server_pins() == expected+ passed.append("queued pin and unpin survive reload")++ # A component cleanup is not itself a session change (StrictMode+ # and remounts also run it), so an unconfirmed edit must survive.+ await delay_focus_read(page, state)+ await page.evaluate(+ "window.pins.usePinnedChatsStore.getState().togglePin('survives-remount'); window.unmountSync()"+ )+ state["release"].set()+ await mount(page)+ assert await pins(page) == ["survives-remount"]+ assert server_pins() == ["survives-remount"]+ passed.append("same-session hook remount retains pending intent")++ save_server_pins(["server-before-signout"])+ await page.evaluate("window.pins.refreshPinnedChats()")+ await delay_focus_read(page, state)+ await page.evaluate(+ "window.pins.usePinnedChatsStore.getState().togglePin('old-session-only'); window.auth.clearAuthTokens()"+ )+ assert await pins(page) == []+ state["release"].set()+ await page.evaluate(+ "window.auth.storeAuthTokens('new-session-access', 'new-session-refresh')"+ )+ await page.evaluate("window.pins.refreshPinnedChats()")+ assert await pins(page) == ["server-before-signout"]+ assert server_pins() == ["server-before-signout"]+ passed.append("signout never replays old pending intent into a new session")++ _, other, _ = await new_client()+ await mount(other)+ await other.evaluate(+ "window.pins.usePinnedChatsStore.getState().togglePin('from-second-browser')"+ )+ await other.evaluate("window.pins.refreshPinnedChats()")+ await page.evaluate("window.dispatchEvent(new Event('focus'))")+ await page.wait_for_function(+ "window.pins.usePinnedChatsStore.getState().pinnedIds[0] === 'from-second-browser'"+ )+ passed.append("focus refresh synchronizes isolated browser clients")++ # Same-origin session changes use storage events instead of the+ # in-document auth events emitted by clearAuthTokens.+ sibling = await context.new_page()+ await sibling.goto(url)+ await sibling.wait_for_function("window.ready === true")+ await sibling.evaluate(+ "localStorage.removeItem('unsloth_auth_token'); localStorage.removeItem('unsloth_auth_session_mark')"+ )+ await page.wait_for_function(+ "window.pins.usePinnedChatsStore.getState().pinnedIds.length === 0"+ )+ await sibling.evaluate(+ "localStorage.setItem('unsloth_auth_token','cross-tab-access'); localStorage.setItem('unsloth_auth_session_mark','cross-tab-session')"+ )+ await page.wait_for_function(+ "window.pins.usePinnedChatsStore.getState().pinnedIds[0] === 'from-second-browser'"+ )+ passed.append("cross-tab session changes reset and rehydrate pins")++ # A supported old backend initially preserves local pins. Once it+ # is upgraded, the open page must resume shared persistence.+ _, compatible, compatibility = await new_client(+ legacy = ["local-before-upgrade"], old_backend = True, missing_route_status = 405+ )+ await mount(compatible)+ assert await pins(compatible) == ["local-before-upgrade"]+ compatibility["old_backend"] = False+ await compatible.evaluate("window.pins.refreshPinnedChats()")+ await compatible.evaluate(+ "window.pins.usePinnedChatsStore.getState().togglePin('after-server-upgrade')"+ )+ await compatible.evaluate("window.pins.refreshPinnedChats()")+ assert "after-server-upgrade" in server_pins()+ passed.append("old-server fallback resumes synchronization after upgrade")++ # Downgrading after reading server pins must preserve that baseline.+ # Keep explicit local changes across reload, then replay against the+ # upgraded server's newer list without replacing another client edit.+ save_server_pins(["downgrade-a", "downgrade-b"])+ _, downgraded, downgrade = await new_client()+ await mount(downgraded)+ downgrade.update(old_backend = True, old_pins = ["downgrade-a", "downgrade-b"])+ await downgraded.evaluate("window.pins.refreshPinnedChats()")+ await downgraded.evaluate(+ "window.pins.usePinnedChatsStore.getState().setPinned(['downgrade-offline'], true)"+ )+ await downgraded.evaluate("window.pins.refreshPinnedChats()")+ assert await pins(downgraded) == ["downgrade-offline", "downgrade-a", "downgrade-b"]+ await downgraded.evaluate(+ "window.pins.usePinnedChatsStore.getState().unpin('downgrade-a')"+ )+ await downgraded.evaluate("window.pins.refreshPinnedChats()")+ await downgraded.reload()+ await downgraded.wait_for_function("window.ready === true")+ await mount(downgraded)+ assert await pins(downgraded) == ["downgrade-offline", "downgrade-b"]+ save_server_pins(["downgrade-concurrent", "downgrade-a", "downgrade-b"])+ downgrade["old_backend"] = False+ await downgraded.evaluate("window.pins.refreshPinnedChats()")+ expected = ["downgrade-offline", "downgrade-concurrent", "downgrade-b"]+ assert await pins(downgraded) == expected+ assert server_pins() == expected+ passed.append(+ "downgrade preserves server pins and reload replays ordered offline changes after upgrade"+ )++ # Browser pin migration can beat the independent legacy thread+ # import. Retry the original IDs after import, while tombstones keep+ # an explicit unpin from being undone by later refreshes or reloads.+ save_server_pins([])+ _, delayed_import, _ = await new_client(legacy = ["legacy-imported-later"])+ await mount(delayed_import)+ assert await pins(delayed_import) == []+ response = client.post(+ "/api/chat/threads",+ json = {+ "id": "legacy-imported-later",+ "title": "Imported later",+ "modelType": "base",+ "createdAt": 1,+ },+ )+ assert response.status_code == 200, response.text+ await delayed_import.evaluate("window.dispatchEvent(new Event('focus'))")+ await delayed_import.wait_for_function(+ "window.pins.usePinnedChatsStore.getState().pinnedIds.includes('legacy-imported-later')"+ )+ assert server_pins() == ["legacy-imported-later"]+ await delayed_import.evaluate(+ "window.pins.usePinnedChatsStore.getState().unpin('legacy-imported-later')"+ )+ await delayed_import.evaluate("window.pins.refreshPinnedChats()")+ await delayed_import.evaluate("window.dispatchEvent(new Event('focus'))")+ await delayed_import.evaluate("window.pins.refreshPinnedChats()")+ assert await pins(delayed_import) == []+ await delayed_import.reload()+ await delayed_import.wait_for_function("window.ready === true")+ await mount(delayed_import)+ assert await pins(delayed_import) == []+ assert server_pins() == []+ passed.append(+ "legacy pins migrate after delayed thread import and explicit unpins do not resurrect"+ )++ # Pre-session-mark auth storage must gain a stable scope before a+ # durable intent is saved. Hourly token rotation preserves that+ # scope, including while navigation interrupts a pending request.+ _, old_auth, old_auth_state = await new_client()+ await old_auth.evaluate("localStorage.removeItem('unsloth_auth_session_mark')")+ await mount(old_auth)+ mark = await old_auth.evaluate("localStorage.getItem('unsloth_auth_session_mark')")+ assert mark+ await delay_focus_read(old_auth, old_auth_state)+ await old_auth.evaluate(+ "window.pins.usePinnedChatsStore.getState().setPinned(['legacy-token-pending'], true)"+ )+ await old_auth.evaluate(+ "window.auth.storeAuthTokens('rotated-access', 'rotated-refresh')"+ )+ assert (+ await old_auth.evaluate("localStorage.getItem('unsloth_auth_session_mark')") == mark+ )+ assert await pins(old_auth) == ["legacy-token-pending"]+ assert server_pins() == []+ await old_auth.reload()+ await old_auth.wait_for_function("window.ready === true")+ old_auth_state["release"].set()+ await mount(old_auth)+ assert (+ await old_auth.evaluate("localStorage.getItem('unsloth_auth_session_mark')") == mark+ )+ assert await pins(old_auth) == ["legacy-token-pending"]+ assert server_pins() == ["legacy-token-pending"]+ passed.append(+ "legacy auth gains a stable mark and token rotation preserves queued pins across reload"+ )+ assert not errors, errors+ finally:+ await browser.close()+ return passed+++def main() -> None:+ if not (FRONTEND / "node_modules").is_dir():+ raise RuntimeError(+ "Install frontend dependencies before running the pin persistence browser test"+ )+ with tempfile.TemporaryDirectory(prefix = ".pin-persistence-test-", dir = FRONTEND) as directory:+ directory = Path(directory)+ write_browser_fixture(directory)+ client = settings_client(directory / "home")+ with (directory / "vite.log").open("w", encoding = "utf-8") as log:+ server = subprocess.Popen(+ ["node", str(directory / "vite.mjs")],+ cwd = FRONTEND,+ stdout = log,+ stderr = subprocess.STDOUT,+ )+ try:+ deadline = time.monotonic() + 60+ while not (directory / "ready.json").exists():+ if server.poll() is not None or time.monotonic() >= deadline:+ raise RuntimeError((directory / "vite.log").read_text(encoding = "utf-8"))+ time.sleep(0.05)+ url = json.loads((directory / "ready.json").read_text(encoding = "utf-8"))["url"]+ passed = asyncio.run(exercise_browser(url, client))+ print(json.dumps({"passed": passed, "count": len(passed)}, indent = 2))+ finally:+ server.terminate()+ try:+ server.wait(timeout = 5)+ except subprocess.TimeoutExpired:+ server.kill()+ server.wait()+ client.close()+++if __name__ == "__main__":+ main()diff --git a/tests/studio/test_multi_chat_prompt_queue_contract.py b/tests/studio/test_multi_chat_prompt_queue_contract.pyindex 7f1c20ab0a2..0891a164ada 100644--- a/tests/studio/test_multi_chat_prompt_queue_contract.py+++ b/tests/studio/test_multi_chat_prompt_queue_contract.py@@ -949,7 +949,7 @@ def test_clear_all_invalidates_and_removes_late_fresh_thread_initialization():)# Matched on the call prefix; only the ordering is pinned.assert CLEAR_ALL_CHATS.index("requestPromptQueueStop();") < CLEAR_ALL_CHATS.index(- "return await clearStoredChats("+ "await clearStoredChats(")assert "const historyClearGeneration = chatHistoryClearBoundary.capture();" in RUNTIME_PROVIDERassert "await throwIfHistoryWasCleared(initialized.remoteId);" in RUNTIME_PROVIDER