Skip to content

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

Studio: keep the chat background, interface scale and Browser preferences with the account (#16454)

Michael Hanbae35f64c164
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index 1d2b6fabc36..9b3dc2f28a1 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -14,7 +14,7 @@ from typing import Annotated, Any, Literal, Optional, Union, get_args
from urllib.parse import unquote, urlsplit
from fastapi import APIRouter, BackgroundTasks, Depends, Header, HTTPException, Request
-from fastapi.responses import StreamingResponse
+from fastapi.responses import Response, StreamingResponse
from starlette.background import BackgroundTask
from pydantic import (
BaseModel,
@@ -61,6 +61,17 @@ from core.rag.config import (
)
from loggers import get_logger
from utils.utils import safe_curated_detail, safe_error_detail, log_and_http_error
+from utils.device_sync_settings import (
+ MAX_BACKGROUND_IMAGE_BYTES,
+ background_image_path,
+ background_lock,
+ clear_background,
+ get_chat_background,
+ get_client_preferences,
+ save_background_adjustments,
+ save_background_image,
+ update_client_preferences,
+)
from utils.personalization_settings import (
MAX_AVATAR_DATA_URL_BYTES,
PERSONALIZATION_VERSION,
@@ -5001,6 +5012,145 @@ def update_personalization_settings(
return PersonalizationPayload.model_validate(drop_unknown_palette(merged, _PALETTE_IDS))
+class BrowserPrefsPayload(BaseModel):
+ model_config = ConfigDict(extra = "ignore")
+
+ openLinksInBrowser: Optional[bool] = None
+ openFilesInBrowser: Optional[bool] = None
+ searchEngine: Optional[Literal["duckduckgo", "google", "bing", "brave"]] = None
+ showFullUrl: Optional[bool] = None
+ bookmarksToolbar: Optional[Literal["always", "newtab", "never"]] = None
+ showBookmarkEditor: Optional[bool] = None
+ hiddenSuggestions: Optional[list[Annotated[str, Field(max_length = 253)]]] = Field(
+ None, max_length = 500
+ )
+ switchToNewTabs: Optional[bool] = None
+ defaultZoom: Optional[float] = Field(None, ge = 0.25, le = 5)
+ showSuggestedSites: Optional[bool] = None
+ showRecentPages: Optional[bool] = None
+ saveHistory: Optional[bool] = None
+ historyRetentionDays: Optional[int] = Field(None, ge = 0, le = 3650)
+ saveDownloadHistory: Optional[bool] = None
+ askWhereToSave: Optional[bool] = None
+ askBeforeDownloading: Optional[bool] = None
+ annotationScreenshots: Optional[Literal["always", "never"]] = None
+
+
+class ClientPreferencesPayload(BaseModel):
+ interfaceScale: Optional[int] = Field(None, ge = 50, le = 200)
+ browser: Optional[BrowserPrefsPayload] = None
+
+
+class ClientPreferencesResponse(ClientPreferencesPayload):
+ saved: bool = False
+ updatedAt: Optional[int] = None
+
+
+def _client_preferences_response(stored: dict) -> ClientPreferencesResponse:
+ response = ClientPreferencesResponse.model_validate(
+ {k: stored.get(k) for k in ("interfaceScale", "browser", "updatedAt")}
+ )
+ response.saved = bool(stored)
+ return response
+
+
+@_account_settings_router.get("/client-preferences", response_model = ClientPreferencesResponse)
+def get_client_preferences_settings(
+ current_subject: str = Depends(get_current_subject),
+) -> ClientPreferencesResponse:
+ return _client_preferences_response(get_client_preferences())
+
+
+@_account_settings_router.put("/client-preferences", response_model = ClientPreferencesResponse)
+def update_client_preferences_settings(
+ payload: ClientPreferencesPayload, current_subject: str = Depends(get_current_subject)
+) -> ClientPreferencesResponse:
+ changes = payload.model_dump(exclude_none = True)
+ return _client_preferences_response(update_client_preferences(changes))
+
+
+class ChatBackgroundImageMeta(BaseModel):
+ sha256: str
+ type: str
+ size: int
+
+
+class ChatBackgroundAdjustmentsPayload(BaseModel):
+ adjustments: dict[str, Union[str, int, float, bool, None]] = Field(max_length = 32)
+
+
+class ChatBackgroundResponse(BaseModel):
+ saved: bool = False
+ adjustments: Optional[dict[str, Union[str, int, float, bool, None]]] = None
+ image: Optional[ChatBackgroundImageMeta] = None
+ updatedAt: Optional[int] = None
+
+
+def _chat_background_response(stored: dict) -> ChatBackgroundResponse:
+ response = ChatBackgroundResponse.model_validate(
+ {k: stored.get(k) for k in ("adjustments", "image", "updatedAt")}
+ )
+ response.saved = bool(stored)
+ return response
+
+
+@_account_settings_router.get("/chat-background", response_model = ChatBackgroundResponse)
+def get_chat_background_settings(
+ current_subject: str = Depends(get_current_subject),
+) -> ChatBackgroundResponse:
+ return _chat_background_response(get_chat_background())
+
+
+@_account_settings_router.get("/chat-background/image")
+def get_chat_background_image(current_subject: str = Depends(get_current_subject)) -> Response:
+ with background_lock():
+ image = get_chat_background().get("image")
+ path = background_image_path()
+ if not isinstance(image, dict) or not path.is_file():
+ raise HTTPException(status_code = 404, detail = "No background image is saved.")
+ return Response(
+ content = path.read_bytes(),
+ media_type = image.get("type", "application/octet-stream"),
+ headers = {"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff"},
+ )
+
+
+@_account_settings_router.put("/chat-background/image", response_model = ChatBackgroundResponse)
+async def update_chat_background_image(
+ request: Request, current_subject: str = Depends(get_current_subject)
+) -> ChatBackgroundResponse:
+ declared = request.headers.get("content-length")
+ if declared and declared.isdigit() and int(declared) > MAX_BACKGROUND_IMAGE_BYTES:
+ raise HTTPException(status_code = 413, detail = "Background image is too large.")
+ data = bytearray()
+ async for chunk in request.stream():
+ data.extend(chunk)
+ if len(data) > MAX_BACKGROUND_IMAGE_BYTES:
+ raise HTTPException(status_code = 413, detail = "Background image is too large.")
+ try:
+ stored = await asyncio.to_thread(save_background_image, bytes(data))
+ except ValueError as exc:
+ raise HTTPException(status_code = 400, detail = str(exc)) from exc
+ return _chat_background_response(stored)
+
+
+@_account_settings_router.put("/chat-background", response_model = ChatBackgroundResponse)
+def update_chat_background_settings(
+ payload: ChatBackgroundAdjustmentsPayload, current_subject: str = Depends(get_current_subject)
+) -> ChatBackgroundResponse:
+ try:
+ return _chat_background_response(save_background_adjustments(payload.adjustments))
+ except LookupError as exc:
+ raise HTTPException(status_code = 409, detail = str(exc)) from exc
+
+
+@_account_settings_router.delete("/chat-background", response_model = ChatBackgroundResponse)
+def delete_chat_background_settings(
+ current_subject: str = Depends(get_current_subject),
+) -> ChatBackgroundResponse:
+ return _chat_background_response(clear_background())
+
+
# Backs Settings > Logs: the session log existed, but its path went only to an unseen console.
class DebugLogSourceModel(BaseModel):
id: str
diff --git a/studio/backend/tests/test_device_sync_settings.py b/studio/backend/tests/test_device_sync_settings.py
new file mode 100644
index 00000000000..49c352b1c6d
--- /dev/null
+++ b/studio/backend/tests/test_device_sync_settings.py
@@ -0,0 +1,192 @@
+# 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 hashlib
+import sqlite3
+import sys
+import threading
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+_BACKEND = Path(__file__).resolve().parents[1]
+if str(_BACKEND) not in sys.path:
+ sys.path.insert(0, str(_BACKEND))
+
+import utils.device_sync_settings as sync # noqa: E402
+from auth.authentication import get_current_subject # noqa: E402
+from routes import settings as settings_routes # noqa: E402
+
+PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 64
+
+
+def settings_db(monkeypatch, tmp_path):
+ database = tmp_path / "studio.db"
+
+ def connect():
+ connection = sqlite3.connect(database, timeout = 5)
+ connection.row_factory = sqlite3.Row
+ return connection
+
+ with connect() as connection:
+ connection.execute(
+ "CREATE TABLE app_settings (key TEXT PRIMARY KEY, value_json TEXT, updated_at TEXT)"
+ )
+ monkeypatch.setattr("storage.studio_db.get_connection", connect)
+ return database
+
+
+def client(monkeypatch, tmp_path, settings_db):
+ monkeypatch.setattr(
+ sync, "background_image_path", lambda: tmp_path / "appearance" / "chat-background"
+ )
+ monkeypatch.setattr(settings_routes, "background_image_path", sync.background_image_path)
+ app = FastAPI()
+ app.dependency_overrides[get_current_subject] = lambda: "unsloth"
+ app.include_router(settings_routes.router, prefix = "/api/settings")
+ return TestClient(app)
+
+
+def test_client_preferences_start_unsaved_and_merge_by_section(client):
+ assert client.get("/api/settings/client-preferences").json()["saved"] is False
+ client.put("/api/settings/client-preferences", json = {"browser": {"searchEngine": "brave"}})
+ body = client.put("/api/settings/client-preferences", json = {"interfaceScale": 125}).json()
+ assert body["saved"] is True
+ assert body["interfaceScale"] == 125
+ assert body["browser"]["searchEngine"] == "brave"
+ assert isinstance(body["updatedAt"], int)
+
+
+def test_client_preferences_reject_out_of_range_values(client):
+ assert (
+ client.put("/api/settings/client-preferences", json = {"interfaceScale": 400}).status_code
+ == 422
+ )
+ bad = {"browser": {"searchEngine": "javascript:alert(1)"}}
+ assert client.put("/api/settings/client-preferences", json = bad).status_code == 422
+
+
+def test_background_image_round_trips_and_follows_its_own_bytes(client):
+ assert client.get("/api/settings/chat-background").json()["saved"] is False
+ put = client.put(
+ "/api/settings/chat-background/image", content = PNG, headers = {"content-type": "text/html"}
+ )
+ assert put.status_code == 200
+ meta = put.json()["image"]
+ assert meta["type"] == "image/png" and meta["size"] == len(PNG)
+ image = client.get("/api/settings/chat-background/image")
+ assert image.content == PNG
+ assert image.headers["content-type"] == "image/png"
+ assert image.headers["x-content-type-options"] == "nosniff"
+
+
+def test_background_rejects_non_images(client):
+ svg = b'<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>'
+ assert client.put("/api/settings/chat-background/image", content = svg).status_code == 400
+ assert client.put("/api/settings/chat-background/image", content = b"").status_code == 400
+
+
+def test_adjustments_need_an_image_and_keep_it(client):
+ adjustments = {"adjustments": {"effect": "Blur", "visibility": 60}}
+ assert client.put("/api/settings/chat-background", json = adjustments).status_code == 409
+ client.put("/api/settings/chat-background/image", content = PNG)
+ body = client.put("/api/settings/chat-background", json = adjustments).json()
+ assert body["adjustments"] == {"effect": "Blur", "visibility": 60}
+ assert body["image"]["size"] == len(PNG)
+
+
+def test_removing_the_background_leaves_a_dated_empty_record(client, tmp_path):
+ client.put("/api/settings/chat-background/image", content = PNG)
+ body = client.delete("/api/settings/chat-background").json()
+ assert body["saved"] is True and body["image"] is None and isinstance(body["updatedAt"], int)
+ assert not (tmp_path / "appearance" / "chat-background").exists()
+ assert client.get("/api/settings/chat-background/image").status_code == 404
+
+
+def test_concurrent_preference_sections_are_both_saved(monkeypatch, settings_db):
+ import storage.studio_db as db
+
+ sync.update_client_preferences({"interfaceScale": 100, "browser": {"searchEngine": "google"}})
+ original = db.get_app_setting
+ readers = threading.Barrier(2)
+ calls = threading.local()
+
+ def simultaneous_read(key, fallback = None):
+ value = original(key, fallback)
+ if not getattr(calls, "read", False):
+ calls.read = True
+ readers.wait(timeout = 5)
+ return value
+
+ monkeypatch.setattr(db, "get_app_setting", simultaneous_read)
+ with ThreadPoolExecutor(max_workers = 2) as executor:
+ scale = executor.submit(sync.update_client_preferences, {"interfaceScale": 125})
+ browser = executor.submit(
+ sync.update_client_preferences, {"browser": {"searchEngine": "brave"}}
+ )
+ scale.result(timeout = 5)
+ browser.result(timeout = 5)
+ stored = original(sync.CLIENT_PREFERENCES_KEY)
+ assert stored["interfaceScale"] == 125
+ assert stored["browser"]["searchEngine"] == "brave"
+
+
[email protected]("operation", ["upload", "clear", "adjust", "read"])
+def test_background_mutations_serialize_file_and_metadata(
+ monkeypatch, tmp_path, settings_db, operation
+):
+ monkeypatch.setattr(sync, "background_image_path", lambda: tmp_path / "chat-background")
+ monkeypatch.setattr(settings_routes, "background_image_path", sync.background_image_path)
+ first_writing = threading.Event()
+ release_first = threading.Event()
+ second_writing = threading.Event()
+ second_started = threading.Event()
+ original = sync._write
+
+ def delayed_write(key, value):
+ if threading.current_thread().name.endswith("_0"):
+ first_writing.set()
+ assert release_first.wait(timeout = 5)
+ else:
+ second_writing.set()
+ return original(key, value)
+
+ monkeypatch.setattr(sync, "_write", delayed_write)
+
+ def second_operation():
+ second_started.set()
+ if operation == "upload":
+ return sync.save_background_image(PNG + b"second")
+ if operation == "clear":
+ return sync.clear_background()
+ if operation == "read":
+ return settings_routes.get_chat_background_image("unsloth")
+ return sync.save_background_adjustments({"visibility": 70})
+
+ with ThreadPoolExecutor(max_workers = 2, thread_name_prefix = "background") as executor:
+ first = executor.submit(sync.save_background_image, PNG)
+ try:
+ assert first_writing.wait(timeout = 5)
+ second = executor.submit(second_operation)
+ assert second_started.wait(timeout = 5)
+ assert not second_writing.wait(timeout = 0.2)
+ finally:
+ release_first.set()
+ first.result(timeout = 5)
+ result = second.result(timeout = 5)
+ if operation == "read":
+ assert result.body == PNG
+ stored = sync.get_chat_background()
+ path = sync.background_image_path()
+ if operation == "clear":
+ assert stored["image"] is None
+ assert not path.exists()
+ else:
+ assert stored["image"]["sha256"] == hashlib.sha256(path.read_bytes()).hexdigest()
+ if operation == "adjust":
+ assert stored["adjustments"] == {"visibility": 70}
diff --git a/studio/backend/utils/device_sync_settings.py b/studio/backend/utils/device_sync_settings.py
new file mode 100644
index 00000000000..4d292729a50
--- /dev/null
+++ b/studio/backend/utils/device_sync_settings.py
@@ -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
+from __future__ import annotations
+
+import hashlib
+import os
+import tempfile
+import time
+from pathlib import Path
+from typing import Optional
+
+from filelock import FileLock
+
+CLIENT_PREFERENCES_KEY = "client_preferences"
+CHAT_BACKGROUND_KEY = "chat_background"
+MAX_BACKGROUND_IMAGE_BYTES = 20 * 1024 * 1024
+BACKGROUND_IMAGE_TYPES = ("image/png", "image/jpeg", "image/webp")
+
+
+def _now_ms() -> int:
+ return int(time.time() * 1000)
+
+
+def _read(key: str) -> dict:
+ from storage.studio_db import get_app_setting
+ stored = get_app_setting(key, None)
+ return stored if isinstance(stored, dict) else {}
+
+
+def _write(key: str, value: dict) -> dict:
+ from storage.studio_db import upsert_app_settings
+ upsert_app_settings({key: value}, read_back = False)
+ return value
+
+
+def get_client_preferences() -> dict:
+ return _read(CLIENT_PREFERENCES_KEY)
+
+
+def update_client_preferences(changes: dict) -> dict:
+ from storage.studio_db import compare_and_set_app_setting, get_app_setting
+ while True:
+ previous = get_app_setting(CLIENT_PREFERENCES_KEY, None)
+ stored = previous if isinstance(previous, dict) else {}
+ merged = {
+ **stored,
+ **{k: v for k, v in changes.items() if v is not None},
+ "updatedAt": _now_ms(),
+ }
+ if compare_and_set_app_setting(CLIENT_PREFERENCES_KEY, previous, merged):
+ return merged
+
+
+def get_chat_background() -> dict:
+ return _read(CHAT_BACKGROUND_KEY)
+
+
+def background_image_path() -> Path:
+ from utils.paths.storage_roots import account_path
+ return account_path("appearance/chat-background")
+
+
+def background_lock() -> FileLock:
+ path = background_image_path()
+ path.parent.mkdir(parents = True, exist_ok = True)
+ return FileLock(str(path.with_name(".chat-background.lock")))
+
+
+def sniff_image_type(data: bytes) -> Optional[str]:
+ if data.startswith(b"\x89PNG\r\n\x1a\n"):
+ return "image/png"
+ if data.startswith(b"\xff\xd8\xff"):
+ return "image/jpeg"
+ if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WEBP":
+ return "image/webp"
+ return None
+
+
+def save_background_image(data: bytes) -> dict:
+ if not data or len(data) > MAX_BACKGROUND_IMAGE_BYTES:
+ raise ValueError("Background image is empty or too large.")
+ media_type = sniff_image_type(data)
+ if media_type is None:
+ raise ValueError("Background image must be PNG, JPEG or WebP.")
+ with background_lock():
+ path = background_image_path()
+ fd, tmp = tempfile.mkstemp(dir = path.parent, prefix = ".chat-background-")
+ try:
+ with os.fdopen(fd, "wb") as handle:
+ handle.write(data)
+ os.replace(tmp, path)
+ except BaseException:
+ Path(tmp).unlink(missing_ok = True)
+ raise
+ image = {"sha256": hashlib.sha256(data).hexdigest(), "type": media_type, "size": len(data)}
+ stored = get_chat_background()
+ return _write(
+ CHAT_BACKGROUND_KEY,
+ {"adjustments": stored.get("adjustments"), "image": image, "updatedAt": _now_ms()},
+ )
+
+
+def save_background_adjustments(adjustments: dict) -> dict:
+ with background_lock():
+ stored = get_chat_background()
+ if not stored.get("image"):
+ raise LookupError("No background image is saved.")
+ return _write(
+ CHAT_BACKGROUND_KEY, {**stored, "adjustments": adjustments, "updatedAt": _now_ms()}
+ )
+
+
+def clear_background() -> dict:
+ with background_lock():
+ background_image_path().unlink(missing_ok = True)
+ return _write(
+ CHAT_BACKGROUND_KEY, {"adjustments": None, "image": None, "updatedAt": _now_ms()}
+ )
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsx
index ed7f015896a..3150609db95 100644
--- a/studio/frontend/src/app/routes/__root.tsx
+++ b/studio/frontend/src/app/routes/__root.tsx
@@ -47,6 +47,7 @@ import {
import { backfillModelOverrides } from "@/features/model-picker/api/migrate-model-overrides";
import { hydratePins } from "@/lib/pins-mirror";
import { usePersonalizationSync } from "@/features/profile";
+import { useDeviceSettingsSync } from "@/features/settings/hooks/use-device-settings-sync";
import { ScheduledTaskRunNotifier } from "@/features/scheduled-tasks/run-notifier";
import { RemoteCodeConsentDialog } from "@/features/security";
import {
@@ -243,7 +244,9 @@ const AudioPage = lazy(() =>
// Enabled once the session settles: a read refused mid password change would never retry until reload.
function PersonalizationSyncMount() {
useRouterState({ select: (s) => s.location.pathname });
- usePersonalizationSync(hasSettledAuthSession());
+ const settled = hasSettledAuthSession();
+ usePersonalizationSync(settled);
+ useDeviceSettingsSync(settled);
return null;
}
diff --git a/studio/frontend/src/features/chat-background/storage.ts b/studio/frontend/src/features/chat-background/storage.ts
index e9b5ee74f3f..48283873f2b 100644
--- a/studio/frontend/src/features/chat-background/storage.ts
+++ b/studio/frontend/src/features/chat-background/storage.ts
@@ -20,8 +20,57 @@ let database: Dexie | undefined;
let account = "";
let revision = 0;
let committed: ChatBackgroundValue | null = null;
+// Kept with the image it describes: another tab can replace the stored one while this one still shows its own.
+let committedSha: string | null = null;
let writes: Promise<unknown> = Promise.resolve();
let hydration: Promise<void> | undefined;
+export type BackgroundSyncState = {
+ updatedAt: number | null;
+ sha256: string | null;
+ dirty: boolean;
+};
+const CLEAN_SYNC: BackgroundSyncState = {
+ updatedAt: null,
+ sha256: null,
+ dirty: false,
+};
+let onLocalChange: (() => void) | null = null;
+export function setBackgroundChangeListener(listener: (() => void) | null) {
+ onLocalChange = listener;
+}
+export function backgroundRevision(): number {
+ return revision;
+}
+export async function readBackgroundSync(): Promise<BackgroundSyncState> {
+ const table = currentDatabase().table("backgrounds");
+ const row = await table.get("sync");
+ return {
+ ...CLEAN_SYNC,
+ ...(row?.state ?? {}),
+ sha256: committedSha,
+ };
+}
+export async function writeBackgroundSync(
+ patch: Partial<Omit<BackgroundSyncState, "sha256">>,
+): Promise<void> {
+ const table = currentDatabase().table("backgrounds");
+ const row = await table.get("sync");
+ const { sha256: _sha, ...state } = { ...CLEAN_SYNC, ...(row?.state ?? {}), ...patch };
+ await table.put({ id: "sync", state });
+}
+export async function recordUploadedImage(
+ blob: Blob,
+ sha256: string | null,
+): Promise<void> {
+ const db = currentDatabase();
+ const write = writes.then(async () => {
+ if (committed?.blob !== blob) return;
+ await db.table("backgrounds").put({ id: "current", value: committed, sha256 });
+ if (db === database) committedSha = sha256;
+ });
+ writes = write.catch(() => undefined);
+ await write;
+}
function currentDatabase() {
const name = accountDatabaseName("unsloth-chat-background");
if (!database || account !== name) {
@@ -32,6 +81,7 @@ function currentDatabase() {
database.version(1).stores({ backgrounds: "id" });
hydration = undefined;
committed = null;
+ committedSha = null;
writes = Promise.resolve();
useBackgroundStore.setState({
value: null,
@@ -55,6 +105,8 @@ export function hydrateBackground(): Promise<void> {
row?.value?.blob instanceof Blob
? { ...sanitizeAdjustments(row.value), blob: row.value.blob }
: null;
+ committedSha =
+ committed && typeof row?.sha256 === "string" ? row.sha256 : null;
useBackgroundStore.setState({ value: committed, ready: true });
})
.catch(() => {
@@ -76,20 +128,33 @@ export function setBackgroundError(error: BackgroundError) {
async function persist(
value: ChatBackgroundValue | null,
optimistic: boolean,
+ fromServer?: Partial<BackgroundSyncState>,
): Promise<boolean> {
const db = currentDatabase();
const ticket = ++revision;
if (optimistic) useBackgroundStore.setState({ value, error: null });
const write = writes.then(async () => {
- if (value) await db.table("backgrounds").put({ id: "current", value });
+ if (fromServer && ticket !== revision) return;
+ const sameImage = Boolean(value && committed && value.blob === committed.blob);
+ const sha256 = fromServer ? (fromServer.sha256 ?? null) : sameImage ? committedSha : null;
+ if (value) await db.table("backgrounds").put({ id: "current", value, sha256 });
else await db.table("backgrounds").delete("current");
- if (db === database) committed = value;
+ if (db === database) {
+ committed = value;
+ committedSha = value ? sha256 : null;
+ }
+ await writeBackgroundSync(
+ fromServer
+ ? { updatedAt: fromServer.updatedAt ?? null, dirty: false }
+ : { dirty: true },
+ );
});
writes = write.catch(() => undefined);
try {
await write;
if (ticket === revision)
useBackgroundStore.setState({ value, error: null, ready: true });
+ if (!fromServer) onLocalChange?.();
return true;
} catch {
if (ticket === revision)
@@ -101,6 +166,14 @@ async function persist(
return false;
}
}
+export function applyServerBackground(
+ value: ChatBackgroundValue | null,
+ sync: Pick<BackgroundSyncState, "updatedAt" | "sha256">,
+ expectedRevision: number,
+): Promise<boolean> {
+ if (expectedRevision !== revision) return Promise.resolve(false);
+ return persist(value, false, sync);
+}
export function patchBackground(patch: Partial<BackgroundAdjustments>) {
const value = useBackgroundStore.getState().value;
if (value)
diff --git a/studio/frontend/src/features/chat-background/sync-plan.ts b/studio/frontend/src/features/chat-background/sync-plan.ts
new file mode 100644
index 00000000000..a35d0836a6d
--- /dev/null
+++ b/studio/frontend/src/features/chat-background/sync-plan.ts
@@ -0,0 +1,17 @@
+// 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 { ChatBackgroundRecord } from "@/features/settings/api/device-sync";
+
+export type PullPlan = "push" | "keep" | "clear" | "adjust" | "download";
+
+export function planBackgroundPull(
+ remote: Pick<ChatBackgroundRecord, "saved" | "updatedAt" | "image">,
+ sync: { updatedAt: number | null; sha256: string | null; dirty: boolean },
+ hasLocal: boolean,
+): PullPlan {
+ if (sync.dirty || (!remote.saved && hasLocal)) return "push";
+ if (!remote.saved || remote.updatedAt === sync.updatedAt) return "keep";
+ if (!remote.image) return hasLocal ? "clear" : "keep";
+ return hasLocal && remote.image.sha256 === sync.sha256 ? "adjust" : "download";
+}
diff --git a/studio/frontend/src/features/chat-background/sync.ts b/studio/frontend/src/features/chat-background/sync.ts
new file mode 100644
index 00000000000..8a889d90403
--- /dev/null
+++ b/studio/frontend/src/features/chat-background/sync.ts
@@ -0,0 +1,103 @@
+// 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 {
+ clearChatBackground,
+ loadChatBackground,
+ loadChatBackgroundImage,
+ saveChatBackgroundAdjustments,
+ saveChatBackgroundImage,
+} from "@/features/settings/api/device-sync";
+import { sanitizeAdjustments } from "./model";
+import { planBackgroundPull } from "./sync-plan";
+import {
+ applyServerBackground,
+ backgroundRevision,
+ hydrateBackground,
+ readBackgroundSync,
+ recordUploadedImage,
+ setBackgroundChangeListener,
+ useBackgroundStore,
+ writeBackgroundSync,
+} from "./storage";
+
+const PUSH_DEBOUNCE_MS = 800;
+
+let queue: Promise<void> = Promise.resolve();
+let timer: ReturnType<typeof setTimeout> | undefined;
+let changes = 0;
+
+function enqueue(task: () => Promise<void>) {
+ queue = queue.then(task).catch(() => undefined);
+ return queue;
+}
+
+async function push() {
+ const started = changes;
+ const value = useBackgroundStore.getState().value;
+ if (!value) {
+ const record = await clearChatBackground();
+ if (changes === started)
+ await writeBackgroundSync({ dirty: false, updatedAt: record.updatedAt });
+ return;
+ }
+ let { sha256 } = await readBackgroundSync();
+ if (!sha256) {
+ sha256 = (await saveChatBackgroundImage(value.blob)).image?.sha256 ?? null;
+ await recordUploadedImage(value.blob, sha256);
+ }
+ const { blob: _blob, ...adjustments } = value;
+ const save = () =>
+ saveChatBackgroundAdjustments(adjustments).catch(async (error: unknown) => {
+ await recordUploadedImage(value.blob, null);
+ throw error;
+ });
+ let record = await save();
+ if (record.image?.sha256 !== sha256) {
+ sha256 = (await saveChatBackgroundImage(value.blob)).image?.sha256 ?? null;
+ record = await save();
+ }
+ await recordUploadedImage(value.blob, sha256);
+ if (changes === started)
+ await writeBackgroundSync({ dirty: false, updatedAt: record.updatedAt });
+}
+
+async function pull() {
+ const started = changes;
+ await hydrateBackground();
+ const revision = backgroundRevision();
+ const [remote, sync] = await Promise.all([
+ loadChatBackground(),
+ readBackgroundSync(),
+ ]);
+ const local = useBackgroundStore.getState().value;
+ const plan = planBackgroundPull(remote, sync, Boolean(local));
+ if (plan === "push") return push();
+ if (plan === "keep") return;
+ const stamp = { updatedAt: remote.updatedAt, sha256: remote.image?.sha256 ?? null };
+ if (plan === "clear" || !remote.image) {
+ if (changes === started) await applyServerBackground(null, stamp, revision);
+ return;
+ }
+ const blob =
+ plan === "adjust" && local ? local.blob : await loadChatBackgroundImage();
+ if (changes !== started) return;
+ await applyServerBackground(
+ { ...sanitizeAdjustments(remote.adjustments ?? {}), blob },
+ stamp,
+ revision,
+ );
+}
+
+export function startChatBackgroundSync(): () => void {
+ setBackgroundChangeListener(() => {
+ changes++;
+ clearTimeout(timer);
+ timer = setTimeout(() => void enqueue(push), PUSH_DEBOUNCE_MS);
+ });
+ void enqueue(pull);
+ return () => {
+ setBackgroundChangeListener(null);
+ clearTimeout(timer);
+ };
+}
diff --git a/studio/frontend/src/features/settings/api/device-sync.ts b/studio/frontend/src/features/settings/api/device-sync.ts
new file mode 100644
index 00000000000..aa60c0f61ee
--- /dev/null
+++ b/studio/frontend/src/features/settings/api/device-sync.ts
@@ -0,0 +1,92 @@
+// 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 { readFastApiError } from "@/lib/format-fastapi-error";
+
+export type ClientPreferences = {
+ saved: boolean;
+ updatedAt: number | null;
+ interfaceScale: number | null;
+ browser: Record<string, unknown> | null;
+};
+
+export type ChatBackgroundRecord = {
+ saved: boolean;
+ updatedAt: number | null;
+ adjustments: Record<string, unknown> | null;
+ image: { sha256: string; type: string; size: number } | null;
+};
+
+async function json<T>(res: Response, fallback: string): Promise<T> {
+ if (!res.ok) throw new Error(await readFastApiError(res, fallback));
+ return (await res.json()) as T;
+}
+
+export async function loadClientPreferences(): Promise<ClientPreferences> {
+ return json(
+ await authFetch("/api/settings/client-preferences"),
+ "Failed to load preferences",
+ );
+}
+
+export async function saveClientPreferences(
+ data: Partial<Pick<ClientPreferences, "interfaceScale" | "browser">>,
+): Promise<ClientPreferences> {
+ return json(
+ await authFetch("/api/settings/client-preferences", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(data),
+ }),
+ "Failed to save preferences",
+ );
+}
+
+export async function loadChatBackground(): Promise<ChatBackgroundRecord> {
+ return json(
+ await authFetch("/api/settings/chat-background"),
+ "Failed to load the background",
+ );
+}
+
+export async function loadChatBackgroundImage(): Promise<Blob> {
+ const res = await authFetch("/api/settings/chat-background/image");
+ if (!res.ok) {
+ throw new Error(await readFastApiError(res, "Failed to load the background"));
+ }
+ return res.blob();
+}
+
+export async function saveChatBackgroundImage(
+ blob: Blob,
+): Promise<ChatBackgroundRecord> {
+ return json(
+ await authFetch("/api/settings/chat-background/image", {
+ method: "PUT",
+ headers: { "Content-Type": blob.type || "application/octet-stream" },
+ body: blob,
+ }),
+ "Failed to save the background",
+ );
+}
+
+export async function saveChatBackgroundAdjustments(
+ adjustments: Record<string, unknown>,
+): Promise<ChatBackgroundRecord> {
+ return json(
+ await authFetch("/api/settings/chat-background", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ adjustments }),
+ }),
+ "Failed to save the background",
+ );
+}
+
+export async function clearChatBackground(): Promise<ChatBackgroundRecord> {
+ return json(
+ await authFetch("/api/settings/chat-background", { method: "DELETE" }),
+ "Failed to remove the background",
+ );
+}
diff --git a/studio/frontend/src/features/settings/hooks/use-device-settings-sync.ts b/studio/frontend/src/features/settings/hooks/use-device-settings-sync.ts
new file mode 100644
index 00000000000..91e50a9de0b
--- /dev/null
+++ b/studio/frontend/src/features/settings/hooks/use-device-settings-sync.ts
@@ -0,0 +1,132 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { useBrowserPrefsStore } from "@/features/browser/prefs-store";
+import { startChatBackgroundSync } from "@/features/chat-background/sync";
+import { useEffect } from "react";
+import { loadClientPreferences, saveClientPreferences } from "../api/device-sync";
+import {
+ INTERFACE_SCALE_RANGE,
+ useInterfaceScaleStore,
+} from "../stores/interface-scale-store";
+import { type Pending, readPending, writePending } from "../lib/client-prefs-pending";
+
+const PUSH_DEBOUNCE_MS = 800;
+
+type BrowserPrefs = Record<string, unknown>;
+
+function prefsOf(state: object): BrowserPrefs {
+ return Object.fromEntries(
+ Object.entries(state).filter(([, value]) => typeof value !== "function"),
+ );
+}
+
+const browserPrefs = () => prefsOf(useBrowserPrefsStore.getState());
+const DEFAULT_BROWSER_PREFS = prefsOf(useBrowserPrefsStore.getInitialState());
+
+export function browserPrefsFromRemote(remote: BrowserPrefs): BrowserPrefs {
+ return Object.fromEntries(
+ Object.entries(remote).filter(([key, value]) => {
+ const fallback = DEFAULT_BROWSER_PREFS[key];
+ return (
+ key in DEFAULT_BROWSER_PREFS &&
+ value !== null &&
+ Array.isArray(value) === Array.isArray(fallback) &&
+ typeof value === typeof fallback
+ );
+ }),
+ );
+}
+
+function sameBrowserPrefs(a: BrowserPrefs, b: BrowserPrefs): boolean {
+ return JSON.stringify(a) === JSON.stringify(b);
+}
+
+export function useDeviceSettingsSync(enabled: boolean): void {
+ useEffect(() => {
+ if (!enabled) return;
+ const stopBackground = startChatBackgroundSync();
+ let loaded = false;
+ let applying = false;
+ let cancelled = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const touched = readPending();
+ let edits = 0;
+ const touch = (section: keyof Pending) => {
+ touched[section] = true;
+ edits++;
+ writePending(touched);
+ };
+
+ let saving: Promise<void> = Promise.resolve();
+ const pushAll = () => {
+ clearTimeout(timer);
+ timer = setTimeout(() => {
+ saving = saving
+ .then(async () => {
+ const sent = edits;
+ if (!touched.scale && !touched.browser) return;
+ await saveClientPreferences({
+ interfaceScale: touched.scale
+ ? useInterfaceScaleStore.getState().scale
+ : undefined,
+ browser: touched.browser ? browserPrefs() : undefined,
+ });
+ if (edits === sent) {
+ touched.scale = false;
+ touched.browser = false;
+ writePending(touched);
+ }
+ })
+ .catch(() => undefined);
+ }, PUSH_DEBOUNCE_MS);
+ };
+
+ const stopScale = useInterfaceScaleStore.subscribe((state, prev) => {
+ if (applying || state.scale === prev.scale) return;
+ touch("scale");
+ if (loaded) pushAll();
+ });
+ let lastBrowser = browserPrefs();
+ const stopBrowser = useBrowserPrefsStore.subscribe(() => {
+ const next = browserPrefs();
+ if (applying || sameBrowserPrefs(next, lastBrowser)) return;
+ lastBrowser = next;
+ touch("browser");
+ if (loaded) pushAll();
+ });
+
+ void loadClientPreferences()
+ .then((remote) => {
+ if (cancelled) return;
+ loaded = true;
+ applying = true;
+ if (remote.interfaceScale !== null && !touched.scale)
+ useInterfaceScaleStore.getState().setScale(remote.interfaceScale);
+ if (remote.browser && !touched.browser)
+ useBrowserPrefsStore.setState(browserPrefsFromRemote(remote.browser));
+ lastBrowser = browserPrefs();
+ applying = false;
+ const scale = useInterfaceScaleStore.getState().scale;
+ const missingScale =
+ remote.interfaceScale === null &&
+ scale !== INTERFACE_SCALE_RANGE.default;
+ const missingBrowser =
+ !remote.browser && !sameBrowserPrefs(lastBrowser, DEFAULT_BROWSER_PREFS);
+ if (missingScale) touch("scale");
+ if (missingBrowser) touch("browser");
+ if (touched.scale || touched.browser) pushAll();
+ })
+ .catch(() => {
+ loaded = true;
+ });
+
+ return () => {
+ cancelled = true;
+ clearTimeout(timer);
+ stopScale();
+ stopBrowser();
+ stopBackground();
+ };
+ }, [enabled]);
+}
diff --git a/studio/frontend/src/features/settings/lib/client-prefs-pending.ts b/studio/frontend/src/features/settings/lib/client-prefs-pending.ts
new file mode 100644
index 00000000000..f29b273c27f
--- /dev/null
+++ b/studio/frontend/src/features/settings/lib/client-prefs-pending.ts
@@ -0,0 +1,29 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Relative with .ts: the node tests import this file and cannot resolve @/.
+import { accountDatabaseName } from "../../../lib/account-transition.ts";
+
+export type Pending = { scale: boolean; browser: boolean };
+
+const pendingKey = () => accountDatabaseName("unsloth_client_prefs_pending");
+
+export function readPending(): Pending {
+ try {
+ const saved = JSON.parse(localStorage.getItem(pendingKey()) ?? "{}");
+ return { scale: saved?.scale === true, browser: saved?.browser === true };
+ } catch {
+ return { scale: false, browser: false };
+ }
+}
+
+export function writePending(pending: Pending): void {
+ try {
+ if (pending.scale || pending.browser) {
+ localStorage.setItem(pendingKey(), JSON.stringify(pending));
+ } else {
+ localStorage.removeItem(pendingKey());
+ }
+ } catch {
+ }
+}
diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsx
index 9e15c38e026..7448b8468e7 100644
--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx
@@ -84,6 +84,7 @@ import {
LIBRARY_SETTINGS_STORAGE_KEY,
LIBRARY_VIEW_STORAGE_KEY,
} from "@/features/library";
+import { readPending, writePending } from "../lib/client-prefs-pending";
import { DesktopInstallTypeControl } from "../components/full-install-dialog";
import { ChangePasswordDialog } from "../components/change-password-dialog";
import { DesktopRepairControl } from "../components/desktop-repair-control";
@@ -225,6 +226,8 @@ async function resetAllPrefs() {
// ignore
}
}
+ // The account keeps its own scale: mark the reset default as an unsent edit so it wins after the reload.
+ writePending({ ...readPending(), scale: true });
window.location.reload();
}
diff --git a/studio/frontend/tests/chat-background-sync-race.test.ts b/studio/frontend/tests/chat-background-sync-race.test.ts
new file mode 100644
index 00000000000..e9bcf8848f0
--- /dev/null
+++ b/studio/frontend/tests/chat-background-sync-race.test.ts
@@ -0,0 +1,102 @@
+// 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 { stripTypeScriptTypes } from "node:module";
+import test from "node:test";
+import { readSrc } from "./helpers/kit.ts";
+
+const tick = () => new Promise<void>((resolve) => setImmediate(resolve));
+function deferred() {
+ let resolve!: () => void;
+ const promise = new Promise<void>((done) => { resolve = done; });
+ return { promise, resolve };
+}
+
+test("a background selected during download survives a pending IndexedDB write", async () => {
+ const localWrite = deferred();
+ const imageDownload = deferred();
+ const downloading = deferred();
+ const old = new Blob(["old"]);
+ const chosen = new Blob(["chosen"]);
+ const server = new Blob(["server"]);
+ const rows = new Map<string, any>([
+ ["current", { value: { blob: old }, sha256: "old" }],
+ ["sync", { state: { updatedAt: 1, dirty: false } }],
+ ]);
+ const dependencies: Record<string, any> = {
+ Dexie: class {
+ version() { return { stores() {} }; }
+ close() {}
+ table() {
+ return {
+ get: async (key: string) => rows.get(key),
+ put: async (row: any) => {
+ if (row.id === "current" && row.value.blob === chosen)
+ await localWrite.promise;
+ rows.set(row.id, row);
+ },
+ delete: async (key: string) => rows.delete(key),
+ };
+ }
+ },
+ create: (initial: () => any) => {
+ let state = initial();
+ const store = () => state;
+ store.getState = () => state;
+ store.setState = (patch: any) => { state = { ...state, ...patch }; };
+ return store;
+ },
+ useEffect() {},
+ accountDatabaseName: () => "test-background",
+ loadChatBackground: async () => ({
+ saved: true, updatedAt: 2, image: { sha256: "server" }, adjustments: {},
+ }),
+ loadChatBackgroundImage: async () => {
+ downloading.resolve();
+ await imageDownload.promise;
+ return server;
+ },
+ clearChatBackground: async () => { throw new Error("Unexpected clear"); },
+ saveChatBackgroundImage: async () => { throw new Error("Unexpected upload"); },
+ saveChatBackgroundAdjustments: async () => { throw new Error("Unexpected save"); },
+ };
+ (globalThis as any).__backgroundSyncRace = dependencies;
+ async function load(relative: string) {
+ const source = stripTypeScriptTypes(readSrc(`features/${relative}`))
+ .replace(/^import[\s\S]*?;\n/gm, "");
+ const bindings = `const {${Object.keys(dependencies).join(",")}} = globalThis.__backgroundSyncRace;\n`;
+ const module = await import(`data:text/javascript;base64,${Buffer.from(bindings + source).toString("base64")}`);
+ Object.assign(dependencies, module);
+ return module;
+ }
+ await load("chat-background/model.ts");
+ const storage = await load("chat-background/storage.ts");
+ await load("chat-background/sync-plan.ts");
+ const sync = await load("chat-background/sync.ts");
+ const stop = sync.startChatBackgroundSync();
+ try {
+ await downloading.promise;
+ const save = storage.finishBackgroundUpload(
+ storage.beginBackgroundUpload(), { blob: chosen },
+ );
+ await tick();
+ imageDownload.resolve();
+ await tick();
+ await tick();
+ localWrite.resolve();
+ await save;
+ await tick();
+ await tick();
+ assert.equal(await storage.useBackgroundStore.getState().value.blob.text(), "chosen");
+ assert.equal(await rows.get("current").value.blob.text(), "chosen");
+ assert.equal(rows.get("sync").state.dirty, true);
+ rows.set("current", { value: { blob: server }, sha256: "server" });
+ assert.equal((await storage.readBackgroundSync()).sha256, null);
+ } finally {
+ stop();
+ localWrite.resolve();
+ imageDownload.resolve();
+ delete (globalThis as any).__backgroundSyncRace;
+ }
+});
diff --git a/studio/frontend/tests/chat-background-sync.test.ts b/studio/frontend/tests/chat-background-sync.test.ts
new file mode 100644
index 00000000000..b8a6f5c3986
--- /dev/null
+++ b/studio/frontend/tests/chat-background-sync.test.ts
@@ -0,0 +1,60 @@
+// 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 { planBackgroundPull } from "../src/features/chat-background/sync-plan.ts";
+import { readSrc } from "./helpers/kit.ts";
+
+const image = { sha256: "abc", type: "image/png", size: 10 };
+const clean = { updatedAt: 1, sha256: "abc", dirty: false };
+
+test("a new browser or origin takes the account's background", () => {
+ const remote = { saved: true, updatedAt: 5, image };
+ assert.equal(planBackgroundPull(remote, { updatedAt: null, sha256: null, dirty: false }, false), "download");
+});
+
+test("the first browser after the update uploads its existing background", () => {
+ assert.equal(planBackgroundPull({ saved: false, updatedAt: null, image: null }, clean, true), "push");
+});
+
+test("unsent local edits are sent instead of being overwritten", () => {
+ const remote = { saved: true, updatedAt: 9, image };
+ assert.equal(planBackgroundPull(remote, { ...clean, dirty: true }, true), "push");
+});
+
+test("an unchanged account copy leaves this browser alone", () => {
+ assert.equal(planBackgroundPull({ saved: true, updatedAt: 1, image }, clean, true), "keep");
+});
+
+test("adjustments from another browser reuse the image already here", () => {
+ assert.equal(planBackgroundPull({ saved: true, updatedAt: 7, image }, clean, true), "adjust");
+ const other = { ...image, sha256: "def" };
+ assert.equal(planBackgroundPull({ saved: true, updatedAt: 7, image: other }, clean, true), "download");
+});
+
+test("a background removed elsewhere is removed here instead of uploaded back", () => {
+ assert.equal(planBackgroundPull({ saved: true, updatedAt: 8, image: null }, clean, true), "clear");
+});
+
+test("an edit made while the account's copy downloads is not overwritten by it", () => {
+ const sync = readSrc("features/chat-background/sync.ts");
+ const pull = sync.slice(sync.indexOf("async function pull()"));
+ assert.match(pull, /const started = changes;/);
+ assert.match(pull, /await loadChatBackgroundImage\(\);\n\s*if \(changes !== started\) return;\n\s*await applyServerBackground\(/);
+ assert.match(pull, /if \(changes === started\) await applyServerBackground\(null, stamp, revision\);/);
+});
+
+test("adjustments saved against another browser's newer image re-upload this browser's image", () => {
+ const sync = readSrc("features/chat-background/sync.ts");
+ assert.match(sync, /if \(record\.image\?\.sha256 !== sha256\) \{\n[^}]*saveChatBackgroundImage\(value\.blob\)[^}]*record = await save\(\);/);
+});
+
+test("the uploaded hash is stored with its image, so a stale tab cannot keep another tab's", () => {
+ const storage = readSrc("features/chat-background/storage.ts");
+ assert.match(storage, /const sha256 = fromServer \? \(fromServer\.sha256 \?\? null\) : sameImage \? committedSha : null;/);
+ assert.match(storage, /put\(\{ id: "current", value, sha256 \}\)/);
+ assert.match(storage, /if \(committed\?\.blob !== blob\) return;/);
+ assert.doesNotMatch(readSrc("features/chat-background/sync.ts"), /writeBackgroundSync\(\{[^}]*sha256/);
+});
diff --git a/studio/frontend/tests/client-prefs-pending.test.ts b/studio/frontend/tests/client-prefs-pending.test.ts
new file mode 100644
index 00000000000..19a5102def1
--- /dev/null
+++ b/studio/frontend/tests/client-prefs-pending.test.ts
@@ -0,0 +1,44 @@
+// 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";
+
+const store = new Map<string, string>();
+const localStorage = {
+ getItem: (key: string) => store.get(key) ?? null,
+ setItem: (key: string, value: string) => void store.set(key, value),
+ removeItem: (key: string) => void store.delete(key),
+};
+Object.assign(globalThis, {
+ localStorage,
+ window: { localStorage, location: { protocol: "http:", host: "127.0.0.1", hostname: "127.0.0.1", pathname: "/", href: "" } },
+});
+
+const { readPending, writePending } = await import(
+ "../src/features/settings/lib/client-prefs-pending.ts"
+);
+
+test("an unconfirmed preference edit survives a reload until the server takes it", () => {
+ assert.deepEqual(readPending(), { scale: false, browser: false });
+ writePending({ scale: true, browser: false });
+ assert.deepEqual(readPending(), { scale: true, browser: false });
+ writePending({ scale: false, browser: false });
+ assert.equal(store.size, 0);
+ assert.deepEqual(readPending(), { scale: false, browser: false });
+});
+
+test("a corrupt marker reads as nothing pending", () => {
+ writePending({ scale: true, browser: true });
+ const [key] = [...store.keys()];
+ store.set(key, "{");
+ assert.deepEqual(readPending(), { scale: false, browser: false });
+});
+
+test("preference saves run one at a time and send only the sections edited here", async () => {
+ const { readSrc } = await import("./helpers/kit.ts");
+ const hook = readSrc("features/settings/hooks/use-device-settings-sync.ts");
+ assert.match(hook, /saving = saving\n\s*\.then\(async \(\) => \{\n\s*const sent = edits;/);
+ assert.match(hook, /interfaceScale: touched\.scale\n\s*\? useInterfaceScaleStore\.getState\(\)\.scale\n\s*: undefined,/);
+ assert.match(hook, /browser: touched\.browser \? browserPrefs\(\) : undefined,/);
+});
diff --git a/studio/frontend/tests/general-settings-token-sync.test.ts b/studio/frontend/tests/general-settings-token-sync.test.ts
index f51aa5b9ae2..86637c5a331 100644
--- a/studio/frontend/tests/general-settings-token-sync.test.ts
+++ b/studio/frontend/tests/general-settings-token-sync.test.ts
@@ -199,6 +199,10 @@ function generalTab(initialToken: string) {
LIBRARY_SETTINGS_STORAGE_KEY: "library-settings",
LIBRARY_VIEW_STORAGE_KEY: "library-view",
},
+ "../lib/client-prefs-pending": {
+ readPending: () => ({ scale: false, browser: false }),
+ writePending: () => undefined,
+ },
"../components/full-install-dialog": componentStub,
"../components/change-password-dialog": componentStub,
"../components/desktop-repair-control": componentStub,