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: persist personalization (profile, avatar, theme) server-side (#6516)

Daniel Han53e8de601d6b
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index 516502c1e5e..d01009fc20c 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -1,12 +1,21 @@
# 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 typing import Literal, Optional
+from urllib.parse import unquote, urlsplit
+
from fastapi import APIRouter, Depends
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, ConfigDict, Field, field_validator
from auth.authentication import get_current_subject
from loggers import get_logger
from utils.utils import safe_error_detail, log_and_http_error
+from utils.personalization_settings import (
+ MAX_AVATAR_DATA_URL_BYTES,
+ PERSONALIZATION_VERSION,
+ get_personalization,
+ set_personalization,
+)
from utils.upload_limits import (
MAX_UPLOAD_LIMIT_MB,
MIN_UPLOAD_LIMIT_MB,
@@ -111,3 +120,80 @@ def update_helper_precache(
log = logger,
) from exc
return _helper_precache_response(enabled)
+
+
+def _is_bundled_avatar_url(value: str) -> bool:
+ parsed = urlsplit(value)
+ if parsed.scheme or parsed.netloc:
+ return False
+ path = unquote(parsed.path).lstrip("/")
+ if ".." in path.split("/"):
+ return False
+ marker = "Sloth emojis/"
+ if marker not in path:
+ return False
+ return path[path.index(marker) :].lower().endswith(".png")
+
+
+class PersonalizationProfile(BaseModel):
+ model_config = ConfigDict(extra = "ignore")
+
+ displayName: str = Field("", max_length = 200)
+ nickname: str = Field("", max_length = 200)
+ avatarDataUrl: Optional[str] = Field(None, max_length = MAX_AVATAR_DATA_URL_BYTES)
+ avatarShape: Literal["circle", "rounded"] = "circle"
+
+ @field_validator("avatarDataUrl")
+ @classmethod
+ def _validate_avatar(cls, value: Optional[str]) -> Optional[str]:
+ if not value:
+ return value
+ if not value.startswith("data:image/") and not _is_bundled_avatar_url(value):
+ raise ValueError("avatarDataUrl must be an image data URL or bundled avatar.")
+ return value
+
+
+class PersonalizationAppearance(BaseModel):
+ model_config = ConfigDict(extra = "ignore")
+
+ theme: Literal["light", "dark", "system"] = "system"
+ language: Optional[str] = Field(None, max_length = 20)
+
+
+class PersonalizationPayload(BaseModel):
+ model_config = ConfigDict(extra = "ignore")
+
+ version: int = PERSONALIZATION_VERSION
+ profile: PersonalizationProfile = Field(default_factory = PersonalizationProfile)
+ appearance: PersonalizationAppearance = Field(default_factory = PersonalizationAppearance)
+
+
+class PersonalizationResponse(PersonalizationPayload):
+ saved: bool = False
+
+
[email protected]("/personalization", response_model = PersonalizationResponse)
+def get_personalization_settings(
+ current_subject: str = Depends(get_current_subject),
+) -> PersonalizationResponse:
+ stored = get_personalization()
+ response = PersonalizationResponse.model_validate(stored or {})
+ response.saved = bool(stored)
+ return response
+
+
[email protected]("/personalization", response_model = PersonalizationPayload)
+def update_personalization_settings(
+ payload: PersonalizationPayload, current_subject: str = Depends(get_current_subject)
+) -> PersonalizationPayload:
+ try:
+ set_personalization(payload.model_dump())
+ except ValueError as exc:
+ raise log_and_http_error(
+ exc,
+ 400,
+ safe_error_detail(exc, fallback = "Invalid personalization settings."),
+ event = "settings.update_personalization_failed",
+ log = logger,
+ ) from exc
+ return payload
diff --git a/studio/backend/tests/test_personalization_settings.py b/studio/backend/tests/test_personalization_settings.py
new file mode 100644
index 00000000000..c80bfa196b0
--- /dev/null
+++ b/studio/backend/tests/test_personalization_settings.py
@@ -0,0 +1,146 @@
+# 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 sys
+from pathlib import Path
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from pydantic import ValidationError
+
+_BACKEND = Path(__file__).resolve().parents[1]
+if str(_BACKEND) not in sys.path:
+ sys.path.insert(0, str(_BACKEND))
+
+import utils.personalization_settings as pers # noqa: E402
+from auth.authentication import get_current_subject # noqa: E402
+from routes import settings as settings_routes # noqa: E402
+from routes.settings import PersonalizationPayload # noqa: E402
+
+
+def test_defaults_fill_missing_fields():
+ p = PersonalizationPayload.model_validate({})
+ assert p.version == pers.PERSONALIZATION_VERSION
+ assert p.appearance.theme == "system"
+ assert p.profile.avatarShape == "circle"
+ assert p.profile.displayName == ""
+
+
+def test_unknown_keys_are_ignored():
+ p = PersonalizationPayload.model_validate(
+ {"profile": {"displayName": "Mike", "bogus": 1}, "extra": True}
+ )
+ assert p.profile.displayName == "Mike"
+
+
+def test_invalid_theme_rejected():
+ with pytest.raises(ValidationError):
+ PersonalizationPayload.model_validate({"appearance": {"theme": "neon"}})
+
+
+def test_avatar_must_be_image_data_url():
+ with pytest.raises(ValidationError):
+ PersonalizationPayload.model_validate(
+ {"profile": {"avatarDataUrl": "http://example.com/a.png"}}
+ )
+
+
+def test_avatar_size_is_capped():
+ big = "data:image/png;base64," + "A" * (pers.MAX_AVATAR_DATA_URL_BYTES + 1)
+ with pytest.raises(ValidationError):
+ PersonalizationPayload.model_validate({"profile": {"avatarDataUrl": big}})
+
+
+def test_valid_avatar_and_shape():
+ p = PersonalizationPayload.model_validate(
+ {
+ "profile": {
+ "avatarDataUrl": "data:image/png;base64,AAAA",
+ "avatarShape": "rounded",
+ }
+ }
+ )
+ assert p.profile.avatarShape == "rounded"
+
+
+def test_bundled_avatar_url_allowed():
+ p = PersonalizationPayload.model_validate(
+ {"profile": {"avatarDataUrl": "/Sloth%20emojis/large%20sloth%20yay.png"}}
+ )
+ assert p.profile.avatarDataUrl == "/Sloth%20emojis/large%20sloth%20yay.png"
+
+
+def test_bundled_avatar_subpath_allowed():
+ p = PersonalizationPayload.model_validate(
+ {"profile": {"avatarDataUrl": "/studio/Sloth%20emojis/large%20sloth%20yay.png"}}
+ )
+ assert "Sloth%20emojis" in p.profile.avatarDataUrl
+
+
+def test_bundled_avatar_traversal_rejected():
+ with pytest.raises(ValidationError):
+ PersonalizationPayload.model_validate(
+ {"profile": {"avatarDataUrl": "/Sloth%20emojis/../secret.png"}}
+ )
+
+
+def test_get_read_errors_propagate(monkeypatch):
+ def fail(*args, **kwargs):
+ raise RuntimeError("read failed")
+
+ monkeypatch.setattr("storage.studio_db.get_app_setting", fail)
+
+ with pytest.raises(RuntimeError, match = "read failed"):
+ pers.get_personalization()
+
+
+def test_get_set_roundtrip(monkeypatch):
+ store: dict = {}
+ monkeypatch.setattr("storage.studio_db.get_app_setting", lambda k, d = None: store.get(k, d))
+ monkeypatch.setattr("storage.studio_db.upsert_app_settings", lambda d: store.update(d))
+
+ assert pers.get_personalization() == {}
+ data = {
+ "version": 1,
+ "profile": {"displayName": "Mike"},
+ "appearance": {"theme": "dark"},
+ }
+ pers.set_personalization(data)
+ assert store[pers.PERSONALIZATION_SETTING_KEY]["profile"]["displayName"] == "Mike"
+ assert pers.get_personalization()["appearance"]["theme"] == "dark"
+
+
+def test_personalization_route_roundtrip_real_shape(monkeypatch):
+ store: dict = {}
+ monkeypatch.setattr("storage.studio_db.get_app_setting", lambda k, d = None: store.get(k, d))
+ monkeypatch.setattr("storage.studio_db.upsert_app_settings", lambda d: store.update(d))
+
+ app = FastAPI()
+ app.dependency_overrides[get_current_subject] = lambda: "unsloth"
+ app.include_router(settings_routes.router, prefix = "/api/settings")
+ client = TestClient(app)
+
+ initial = client.get("/api/settings/personalization")
+ assert initial.status_code == 200
+ assert initial.json()["saved"] is False
+
+ payload = {
+ "version": 1,
+ "profile": {
+ "displayName": "Mike",
+ "nickname": "M",
+ "avatarDataUrl": "/Sloth%20emojis/large%20sloth%20yay.png",
+ "avatarShape": "rounded",
+ },
+ "appearance": {"theme": "dark", "language": "en"},
+ }
+ put = client.put("/api/settings/personalization", json = payload)
+ assert put.status_code == 200
+
+ saved = client.get("/api/settings/personalization")
+ assert saved.status_code == 200
+ body = saved.json()
+ assert body["saved"] is True
+ assert body["profile"] == payload["profile"]
+ assert body["appearance"] == payload["appearance"]
diff --git a/studio/backend/utils/personalization_settings.py b/studio/backend/utils/personalization_settings.py
new file mode 100644
index 00000000000..3efbf16623b
--- /dev/null
+++ b/studio/backend/utils/personalization_settings.py
@@ -0,0 +1,20 @@
+# 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
+
+PERSONALIZATION_SETTING_KEY = "personalization"
+PERSONALIZATION_VERSION = 1
+MAX_AVATAR_DATA_URL_BYTES = 512 * 1024
+
+
+def get_personalization() -> dict:
+ from storage.studio_db import get_app_setting
+ stored = get_app_setting(PERSONALIZATION_SETTING_KEY, None)
+ return stored if isinstance(stored, dict) else {}
+
+
+def set_personalization(data: dict) -> dict:
+ from storage.studio_db import upsert_app_settings
+ upsert_app_settings({PERSONALIZATION_SETTING_KEY: data})
+ return data
diff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsx
index f4f40e73f69..b7e7bc01d2f 100644
--- a/studio/frontend/src/app/routes/__root.tsx
+++ b/studio/frontend/src/app/routes/__root.tsx
@@ -5,7 +5,10 @@ import { AppSidebar } from "@/components/app-sidebar";
import { Navbar } from "@/components/navbar";
import { fetchDeviceType, usePlatformStore } from "@/config/env";
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
-import { SettingsDialog, useSettingsDialogStore } from "@/features/settings";
+import {
+ SettingsDialog,
+ useSettingsDialogStore,
+} from "@/features/settings";
import {
ChatPage,
clearNewChatDraft,
@@ -15,6 +18,8 @@ import {
import { RemoteCodeConsentDialog } from "@/features/security";
import { useTrainingUnloadGuard } from "@/features/training";
import { useExportRuntimeLifecycle } from "@/features/export";
+import { hasAuthToken } from "@/features/auth";
+import { usePersonalizationSync } from "@/features/profile";
import { useSidebarPin } from "@/hooks/use-sidebar-pin";
import { useT, type TranslationKey } from "@/i18n";
import {
@@ -52,6 +57,11 @@ function RouteFallback() {
);
}
+function PersonalizationSyncMount() {
+ usePersonalizationSync(hasAuthToken());
+ return null;
+}
+
const CHAT_ONLY_ALLOWED = new Set([
"/",
"/chat",
@@ -200,6 +210,7 @@ function RootLayout() {
return (
<AppProvider>
+ <PersonalizationSyncMount />
<SettingsDialog />
<RemoteCodeConsentDialog />
{hideNavbar ? (
diff --git a/studio/frontend/src/features/profile/components/profile-personalization-panel.tsx b/studio/frontend/src/features/profile/components/profile-personalization-panel.tsx
index 4ec8395bcfa..7c81411a3c3 100644
--- a/studio/frontend/src/features/profile/components/profile-personalization-panel.tsx
+++ b/studio/frontend/src/features/profile/components/profile-personalization-panel.tsx
@@ -11,11 +11,14 @@ import { useT } from "@/i18n";
import { toastError, toastSuccess } from "@/shared/toast";
import { Camera01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
-import { useMemo, useRef, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { SLOTH_AVATARS } from "../sloth-avatars";
import { decodeJwtSubject } from "../utils/jwt-subject";
import { resizeImageFileToDataUrl } from "../utils/resize-image-file";
-import { useUserProfileStore } from "../stores/user-profile-store";
+import {
+ PROFILE_TEXT_MAX_LENGTH,
+ useUserProfileStore,
+} from "../stores/user-profile-store";
import { UserAvatar } from "./user-avatar";
const PROFILE_STORAGE_KEY = "unsloth_user_profile";
@@ -65,6 +68,8 @@ export function ProfilePersonalizationPanel() {
const [draftName, setDraftName] = useState(displayName);
const [draftNickname, setDraftNickname] = useState(nickname);
const fileInputRef = useRef<HTMLInputElement>(null);
+ const lastDisplayNameRef = useRef(displayName);
+ const lastNicknameRef = useRef(nickname);
const sessionSub = decodeJwtSubject(getAuthToken()) ?? "";
const previewName = draftName.trim() || sessionSub || "Unsloth";
@@ -77,6 +82,18 @@ export function ProfilePersonalizationPanel() {
[draftNickname, nickname],
);
+ useEffect(() => {
+ const previous = lastDisplayNameRef.current;
+ lastDisplayNameRef.current = displayName;
+ setDraftName((draft) => (draft === previous ? displayName : draft));
+ }, [displayName]);
+
+ useEffect(() => {
+ const previous = lastNicknameRef.current;
+ lastNicknameRef.current = nickname;
+ setDraftNickname((draft) => (draft === previous ? nickname : draft));
+ }, [nickname]);
+
const saveName = () => {
const trimmed = draftName.trim();
if (trimmed !== draftName) setDraftName(trimmed);
@@ -111,7 +128,6 @@ export function ProfilePersonalizationPanel() {
}
};
- // Persist an avatar value (data URL or asset URL) and toast the result.
const applyAvatar = (value: string) => {
setAvatarDataUrl(value);
const persisted = readPersistedProfile();
@@ -138,7 +154,6 @@ export function ProfilePersonalizationPanel() {
}
};
- // Use a bundled sloth sticker as the avatar.
const pickSloth = (path: string) => {
setImageError(null);
applyAvatar(publicAssetUrl(path));
@@ -182,6 +197,7 @@ export function ProfilePersonalizationPanel() {
id="profile-display-name"
type="text"
value={draftName}
+ maxLength={PROFILE_TEXT_MAX_LENGTH}
onChange={(e) => setDraftName(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
@@ -208,6 +224,7 @@ export function ProfilePersonalizationPanel() {
id="profile-nickname"
type="text"
value={draftNickname}
+ maxLength={PROFILE_TEXT_MAX_LENGTH}
onChange={(e) => setDraftNickname(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") {
@@ -259,7 +276,6 @@ export function ProfilePersonalizationPanel() {
{SLOTH_AVATARS.map((path) => {
const url = publicAssetUrl(path);
const selected = avatarDataUrl === url;
- // Readable accessible name from the filename, e.g. "sloth yay".
const label =
path.split("/").pop()?.replace(/\.png$/i, "").replace(/^large\s+/i, "").trim() ??
"sloth";
diff --git a/studio/frontend/src/features/profile/hooks/use-personalization-sync.ts b/studio/frontend/src/features/profile/hooks/use-personalization-sync.ts
new file mode 100644
index 00000000000..eac1a64d7a3
--- /dev/null
+++ b/studio/frontend/src/features/profile/hooks/use-personalization-sync.ts
@@ -0,0 +1,267 @@
+// 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 {
+ loadPersonalization,
+ savePersonalization,
+ setTheme,
+ useTheme,
+ type Theme,
+} from "@/features/settings";
+import {
+ DEFAULT_LOCALE,
+ getLocale,
+ isSupportedLocale,
+ setLocale,
+ useLocale,
+ type Locale,
+} from "@/i18n";
+import { useCallback, useEffect, useRef, useState } from "react";
+import {
+ PROFILE_TEXT_MAX_LENGTH,
+ useUserProfileStore,
+} from "../stores/user-profile-store";
+import type { AvatarShape } from "../stores/user-profile-store";
+
+const PUSH_DEBOUNCE_MS = 800;
+
+type ProfileSnapshot = {
+ displayName: string;
+ nickname: string;
+ avatarDataUrl: string | null;
+ avatarShape: AvatarShape;
+};
+
+type PersonalizationWrite = Parameters<typeof savePersonalization>[0];
+type QueuedSave = {
+ data: PersonalizationWrite;
+ generation: number;
+ serialized: string;
+};
+type RefValue<T> = { current: T };
+
+function profileText(value: string): string {
+ return value.slice(0, PROFILE_TEXT_MAX_LENGTH);
+}
+
+function normalizeProfile(profile: ProfileSnapshot): ProfileSnapshot {
+ return {
+ ...profile,
+ displayName: profileText(profile.displayName),
+ nickname: profileText(profile.nickname),
+ };
+}
+
+function sameProfile(a: ProfileSnapshot, b: ProfileSnapshot): boolean {
+ return (
+ a.displayName === b.displayName &&
+ a.nickname === b.nickname &&
+ a.avatarDataUrl === b.avatarDataUrl &&
+ a.avatarShape === b.avatarShape
+ );
+}
+
+function drainQueuedSave(
+ saveInFlightRef: RefValue<boolean>,
+ queuedSaveRef: RefValue<QueuedSave | null>,
+ authGenerationRef: RefValue<number>,
+ lastSavedRef: RefValue<string>,
+): void {
+ if (saveInFlightRef.current) return;
+ const next = queuedSaveRef.current;
+ if (!next) return;
+ queuedSaveRef.current = null;
+ saveInFlightRef.current = true;
+ void savePersonalization(next.data)
+ .then(() => {
+ if (authGenerationRef.current === next.generation) {
+ lastSavedRef.current = next.serialized;
+ }
+ })
+ .catch(() => {
+ if (authGenerationRef.current === next.generation) {
+ lastSavedRef.current = "";
+ }
+ })
+ .finally(() => {
+ saveInFlightRef.current = false;
+ const queued = queuedSaveRef.current;
+ if (queued && authGenerationRef.current === queued.generation) {
+ drainQueuedSave(
+ saveInFlightRef,
+ queuedSaveRef,
+ authGenerationRef,
+ lastSavedRef,
+ );
+ }
+ });
+}
+
+function profileSnapshot(): ProfileSnapshot {
+ const s = useUserProfileStore.getState();
+ return {
+ displayName: s.displayName,
+ nickname: s.nickname,
+ avatarDataUrl: s.avatarDataUrl,
+ avatarShape: s.avatarShape,
+ };
+}
+
+function payload(
+ profile: ProfileSnapshot,
+ theme: Theme,
+ language: Locale | null,
+): PersonalizationWrite {
+ return {
+ version: 1,
+ profile: normalizeProfile(profile),
+ appearance: { theme, language },
+ };
+}
+
+function serialized(data: PersonalizationWrite): string {
+ return JSON.stringify(data);
+}
+
+function hasLocalSettings(
+ profile: ProfileSnapshot,
+ theme: Theme,
+ language: Locale,
+): boolean {
+ return Boolean(
+ profile.displayName ||
+ profile.nickname ||
+ profile.avatarDataUrl ||
+ profile.avatarShape !== "circle" ||
+ theme !== "system" ||
+ language !== DEFAULT_LOCALE,
+ );
+}
+
+export function usePersonalizationSync(enabled: boolean): void {
+ const displayName = useUserProfileStore((s) => s.displayName);
+ const nickname = useUserProfileStore((s) => s.nickname);
+ const avatarDataUrl = useUserProfileStore((s) => s.avatarDataUrl);
+ const avatarShape = useUserProfileStore((s) => s.avatarShape);
+ const { theme } = useTheme();
+ const language = useLocale();
+ const [hydratedGeneration, setHydratedGeneration] = useState(0);
+ const authGenerationRef = useRef(0);
+ const latestThemeRef = useRef(theme);
+ const latestLanguageRef = useRef(language);
+ const lastSavedRef = useRef("");
+ const saveInFlightRef = useRef(false);
+ const queuedSaveRef = useRef<QueuedSave | null>(null);
+
+ const drainSaveQueue = useCallback(() => {
+ drainQueuedSave(
+ saveInFlightRef,
+ queuedSaveRef,
+ authGenerationRef,
+ lastSavedRef,
+ );
+ }, []);
+
+ useEffect(() => {
+ latestThemeRef.current = theme;
+ }, [theme]);
+
+ useEffect(() => {
+ latestLanguageRef.current = language;
+ }, [language]);
+
+ useEffect(() => {
+ authGenerationRef.current += 1;
+ const generation = authGenerationRef.current;
+ lastSavedRef.current = "";
+ queuedSaveRef.current = null;
+ if (!enabled) {
+ return;
+ }
+ let cancelled = false;
+ void (async () => {
+ try {
+ const remote = await loadPersonalization();
+ if (cancelled) return;
+ if (remote.saved) {
+ const nextProfile: ProfileSnapshot = {
+ displayName: remote.profile.displayName ?? "",
+ nickname: remote.profile.nickname ?? "",
+ avatarDataUrl: remote.profile.avatarDataUrl ?? null,
+ avatarShape: remote.profile.avatarShape === "rounded" ? "rounded" : "circle",
+ };
+ const nextTheme = remote.appearance.theme;
+ const nextLanguage = isSupportedLocale(remote.appearance.language)
+ ? remote.appearance.language
+ : latestLanguageRef.current;
+ useUserProfileStore.setState(nextProfile);
+ if (nextTheme !== latestThemeRef.current) setTheme(nextTheme);
+ if (nextLanguage !== latestLanguageRef.current) setLocale(nextLanguage);
+ lastSavedRef.current = serialized(
+ payload(nextProfile, nextTheme, nextLanguage),
+ );
+ } else {
+ const rawProfile = profileSnapshot();
+ const nextProfile = normalizeProfile(rawProfile);
+ if (!sameProfile(rawProfile, nextProfile)) {
+ useUserProfileStore.setState(nextProfile);
+ }
+ const nextTheme = latestThemeRef.current;
+ const nextLanguage = getLocale();
+ const nextPayload = payload(nextProfile, nextTheme, nextLanguage);
+ const nextSerialized = serialized(nextPayload);
+ if (hasLocalSettings(nextProfile, nextTheme, nextLanguage)) {
+ try {
+ await savePersonalization(nextPayload);
+ lastSavedRef.current = nextSerialized;
+ } catch {
+ lastSavedRef.current = "";
+ }
+ } else {
+ lastSavedRef.current = nextSerialized;
+ }
+ }
+ if (!cancelled && authGenerationRef.current === generation) {
+ setHydratedGeneration(generation);
+ }
+ } catch {
+ if (!cancelled && authGenerationRef.current === generation) {
+ lastSavedRef.current = "";
+ }
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, [enabled]);
+
+ useEffect(() => {
+ if (!enabled || hydratedGeneration !== authGenerationRef.current) return;
+ const current = payload(
+ { displayName, nickname, avatarDataUrl, avatarShape },
+ theme,
+ language,
+ );
+ const currentSerialized = serialized(current);
+ if (currentSerialized === lastSavedRef.current) return;
+ const id = window.setTimeout(() => {
+ queuedSaveRef.current = {
+ data: current,
+ generation: authGenerationRef.current,
+ serialized: currentSerialized,
+ };
+ drainSaveQueue();
+ }, PUSH_DEBOUNCE_MS);
+ return () => window.clearTimeout(id);
+ }, [
+ enabled,
+ hydratedGeneration,
+ displayName,
+ nickname,
+ avatarDataUrl,
+ avatarShape,
+ theme,
+ language,
+ drainSaveQueue,
+ ]);
+}
diff --git a/studio/frontend/src/features/profile/index.ts b/studio/frontend/src/features/profile/index.ts
index feec20607ef..33bc4e3ef66 100644
--- a/studio/frontend/src/features/profile/index.ts
+++ b/studio/frontend/src/features/profile/index.ts
@@ -4,3 +4,4 @@
export { ProfilePersonalizationPanel } from "./components/profile-personalization-panel";
export { UserAvatar } from "./components/user-avatar";
export { useEffectiveProfile } from "./hooks/use-effective-profile";
+export { usePersonalizationSync } from "./hooks/use-personalization-sync";
diff --git a/studio/frontend/src/features/profile/stores/user-profile-store.ts b/studio/frontend/src/features/profile/stores/user-profile-store.ts
index 709f4b5c1c1..0055a58f5da 100644
--- a/studio/frontend/src/features/profile/stores/user-profile-store.ts
+++ b/studio/frontend/src/features/profile/stores/user-profile-store.ts
@@ -5,13 +5,12 @@ import { create } from "zustand";
import { persist } from "zustand/middleware";
export type AvatarShape = "circle" | "rounded";
+export const PROFILE_TEXT_MAX_LENGTH = 200;
export interface UserProfileState {
displayName: string;
- // Preferred name used to address the user (greetings, etc.).
nickname: string;
avatarDataUrl: string | null;
- // Avatar outline: full circle or rounded rectangle.
avatarShape: AvatarShape;
setDisplayName: (displayName: string) => void;
setNickname: (nickname: string) => void;
diff --git a/studio/frontend/src/features/settings/api/personalization.ts b/studio/frontend/src/features/settings/api/personalization.ts
new file mode 100644
index 00000000000..829e8249bb8
--- /dev/null
+++ b/studio/frontend/src/features/settings/api/personalization.ts
@@ -0,0 +1,46 @@
+// 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 PersonalizationProfile = {
+ displayName: string;
+ nickname: string;
+ avatarDataUrl: string | null;
+ avatarShape: "circle" | "rounded";
+};
+
+export type PersonalizationAppearance = {
+ theme: "light" | "dark" | "system";
+ language: string | null;
+};
+
+export type Personalization = {
+ version: number;
+ profile: PersonalizationProfile;
+ appearance: PersonalizationAppearance;
+ // Distinguishes server hydrate from first local migration.
+ saved: boolean;
+};
+
+export async function loadPersonalization(): Promise<Personalization> {
+ const res = await authFetch("/api/settings/personalization");
+ if (!res.ok) {
+ throw new Error(await readFastApiError(res, "Failed to load personalization"));
+ }
+ return (await res.json()) as Personalization;
+}
+
+export async function savePersonalization(
+ data: Omit<Personalization, "saved">,
+): Promise<void> {
+ const res = await authFetch("/api/settings/personalization", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(data),
+ });
+ if (!res.ok) {
+ throw new Error(await readFastApiError(res, "Failed to save personalization"));
+ }
+}
diff --git a/studio/frontend/src/features/settings/index.ts b/studio/frontend/src/features/settings/index.ts
index bf9e8fe21ab..364ca1611f3 100644
--- a/studio/frontend/src/features/settings/index.ts
+++ b/studio/frontend/src/features/settings/index.ts
@@ -2,5 +2,16 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
export { SettingsDialog } from "./settings-dialog";
+export {
+ loadPersonalization,
+ savePersonalization,
+} from "./api/personalization";
+export { setTheme, useTheme } from "./stores/theme-store";
+export type {
+ Personalization,
+ PersonalizationAppearance,
+ PersonalizationProfile,
+} from "./api/personalization";
export { useSettingsDialogStore } from "./stores/settings-dialog-store";
export type { SettingsTab } from "./stores/settings-dialog-store";
+export type { ResolvedTheme, Theme } from "./stores/theme-store";