Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: keep chat, time format and spell check settings per account (#16958)
Nilay669036c7bc12
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.pyindex 184a5504bfd..8034c651ff9 100644--- a/studio/backend/routes/settings.py+++ b/studio/backend/routes/settings.py@@ -5123,9 +5123,54 @@ class BrowserPrefsPayload(BaseModel):annotationScreenshots: Optional[Literal["always", "never"]] = None+_DisplayVisibility = Literal["collapsed", "auto", "expanded"]+++class ChatPrefsPayload(BaseModel):+ model_config = ConfigDict(extra = "ignore")++ plainTextComposer: Optional[bool] = None+ showContextWindowUsage: Optional[bool] = None+ sendShortcut: Optional[Literal["enter", "mod-enter-multiline", "mod-enter"]] = None+ followUpBehavior: Optional[Literal["queue", "steer"]] = None+ confirmDeleteChats: Optional[bool] = None+ alwaysDeleteChatFiles: Optional[bool] = None+ showResponseModel: Optional[bool] = None+ showLinkPreviews: Optional[bool] = None+ showReplyTimes: Optional[bool] = None+ showGenerationDetails: Optional[bool] = None+ showInlineEditResponse: Optional[bool] = None+ thinkingVisibility: Optional[_DisplayVisibility] = None+ toolVisibility: Optional[_DisplayVisibility] = None+ foldToolActivityIntoThinking: Optional[bool] = None+ pastedTextMinChars: Optional[Literal[0, 2000, 4000, 8000, 16000]] = None+ autoScrollWhileGenerating: Optional[bool] = None+ newChatComposerPosition: Optional[int] = Field(None, ge = 0, le = 100)+ showTurnNavigation: Optional[bool] = None+ richTextPaste: Optional[bool] = None+ generationStatsUpdates: Optional[Literal["settled", "realtime"]] = None+++_PlusMenuId = Annotated[str, Field(max_length = 64)]+_PinnedId = Annotated[str, Field(max_length = 256)]+++class PlusMenuPrefsPayload(BaseModel):+ model_config = ConfigDict(extra = "ignore")++ pins: Optional[dict[_PlusMenuId, bool]] = Field(None, max_length = 64)+ order: Optional[list[_PlusMenuId]] = Field(None, max_length = 64)+ pinnedPromptIds: Optional[list[_PinnedId]] = Field(None, max_length = 500)+ pinnedListIds: Optional[list[_PinnedId]] = Field(None, max_length = 500)++class ClientPreferencesPayload(BaseModel):interfaceScale: Optional[int] = Field(None, ge = 50, le = 200)browser: Optional[BrowserPrefsPayload] = None+ chat: Optional[ChatPrefsPayload] = None+ plusMenu: Optional[PlusMenuPrefsPayload] = None+ timeFormat: Optional[Literal["system", "12h", "24h"]] = None+ spellcheck: Optional[bool] = Noneclass ClientPreferencesResponse(ClientPreferencesPayload):@@ -5135,7 +5180,7 @@ class ClientPreferencesResponse(ClientPreferencesPayload):def _client_preferences_response(stored: dict) -> ClientPreferencesResponse:response = ClientPreferencesResponse.model_validate(- {k: stored.get(k) for k in ("interfaceScale", "browser", "updatedAt")}+ {k: stored.get(k) for k in (*ClientPreferencesPayload.model_fields, "updatedAt")})response.saved = bool(stored)return responsediff --git a/studio/backend/tests/test_device_sync_settings.py b/studio/backend/tests/test_device_sync_settings.pyindex 49c352b1c6d..9aaf91a13b5 100644--- a/studio/backend/tests/test_device_sync_settings.py+++ b/studio/backend/tests/test_device_sync_settings.py@@ -71,6 +71,39 @@ def test_client_preferences_reject_out_of_range_values(client):assert client.put("/api/settings/client-preferences", json = bad).status_code == 422+def test_chat_menu_time_and_spellcheck_preferences_follow_the_account(client):+ chat = {+ "sendShortcut": "mod-enter",+ "showReplyTimes": True,+ "pastedTextMinChars": 8000,+ "generationStatsUpdates": "realtime",+ }+ plus_menu = {"pins": {"mcp": True}, "order": ["mcp", "skills"], "pinnedPromptIds": ["p1"]}+ client.put("/api/settings/client-preferences", json = {"chat": chat, "plusMenu": plus_menu})+ client.put("/api/settings/client-preferences", json = {"timeFormat": "24h", "spellcheck": False})+ body = client.get("/api/settings/client-preferences").json()+ assert {k: body["chat"][k] for k in chat} == chat+ assert body["plusMenu"]["pins"] == {"mcp": True}+ assert body["plusMenu"]["order"] == ["mcp", "skills"]+ assert body["plusMenu"]["pinnedPromptIds"] == ["p1"]+ assert body["timeFormat"] == "24h"+ assert body["spellcheck"] is False+++ "bad",+ [+ {"chat": {"sendShortcut": "alt-enter"}},+ {"chat": {"newChatComposerPosition": 101}},+ {"plusMenu": {"order": "mcp"}},+ {"timeFormat": "36h"},+ {"chat": {"generationStatsUpdates": "live"}},+ ],+)+def test_synced_preferences_reject_invalid_values(client, bad):+ 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 Falseput = client.put(diff --git a/studio/frontend/src/features/chat/stores/plus-menu-prefs-store.ts b/studio/frontend/src/features/chat/stores/plus-menu-prefs-store.tsindex dc5dcf11b7a..d3d835acecb 100644--- a/studio/frontend/src/features/chat/stores/plus-menu-prefs-store.ts+++ b/studio/frontend/src/features/chat/stores/plus-menu-prefs-store.ts@@ -3,6 +3,7 @@import { create } from "zustand";import { persist } from "zustand/middleware";+import { syncAcrossWindows } from "../../../lib/sync-across-windows.ts";// Core items and the "More" overflow are always shown and intentionally not listed here.export type PlusMenuItemId =@@ -167,3 +168,5 @@ export const usePlusMenuPrefsStore = create<PlusMenuPrefsState>()(},),);++syncAcrossWindows(usePlusMenuPrefsStore);diff --git a/studio/frontend/src/features/settings/api/device-sync.ts b/studio/frontend/src/features/settings/api/device-sync.tsindex aa60c0f61ee..24733ba0839 100644--- a/studio/frontend/src/features/settings/api/device-sync.ts+++ b/studio/frontend/src/features/settings/api/device-sync.ts@@ -9,8 +9,16 @@ export type ClientPreferences = {updatedAt: number | null;interfaceScale: number | null;browser: Record<string, unknown> | null;+ chat: Record<string, unknown> | null;+ plusMenu: Record<string, unknown> | null;+ timeFormat: string | null;+ spellcheck: boolean | null;};+export type ClientPreferencesChanges = Partial<+ Omit<ClientPreferences, "saved" | "updatedAt">+>;+export type ChatBackgroundRecord = {saved: boolean;updatedAt: number | null;@@ -31,7 +39,7 @@ export async function loadClientPreferences(): Promise<ClientPreferences> {}export async function saveClientPreferences(- data: Partial<Pick<ClientPreferences, "interfaceScale" | "browser">>,+ data: ClientPreferencesChanges,): Promise<ClientPreferences> {return json(await authFetch("/api/settings/client-preferences", {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.tsindex 91e50a9de0b..9279f69bc58 100644--- a/studio/frontend/src/features/settings/hooks/use-device-settings-sync.ts+++ b/studio/frontend/src/features/settings/hooks/use-device-settings-sync.ts@@ -1,35 +1,61 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0+// eslint-disable-next-line no-restricted-importsimport { useBrowserPrefsStore } from "@/features/browser/prefs-store";+// eslint-disable-next-line no-restricted-importsimport { startChatBackgroundSync } from "@/features/chat-background/sync";+// eslint-disable-next-line no-restricted-imports+import { useChatPreferencesStore } from "@/features/chat/stores/chat-preferences-store";+// eslint-disable-next-line no-restricted-imports+import { usePlusMenuPrefsStore } from "@/features/chat/stores/plus-menu-prefs-store";+import {+ accountTransitionPending,+ BROWSER_ACCOUNT_KEY,+ sameBrowserAccount,+} from "@/lib/account-transition";+import { getSpellCheck, setSpellCheck, subscribeSpellCheck } from "@/lib/spellcheck";+import {+ getTimeFormat,+ setTimeFormat,+ subscribeTimeFormat,+ type TimeFormat,+} from "@/lib/time-format";import { useEffect } from "react";-import { loadClientPreferences, saveClientPreferences } from "../api/device-sync";+import {+ type ClientPreferencesChanges,+ 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";+import {+ markPending,+ type Pending,+ PENDING_SECTIONS,+ readPending,+} from "../lib/client-prefs-pending";const PUSH_DEBOUNCE_MS = 800;-type BrowserPrefs = Record<string, unknown>;+type Prefs = Record<string, unknown>;-function prefsOf(state: object): BrowserPrefs {+function prefsOf(state: object, skip?: ReadonlySet<string>): Prefs {return Object.fromEntries(- Object.entries(state).filter(([, value]) => typeof value !== "function"),+ Object.entries(state).filter(+ ([key, value]) => typeof value !== "function" && !skip?.has(key),+ ),);}-const browserPrefs = () => prefsOf(useBrowserPrefsStore.getState());-const DEFAULT_BROWSER_PREFS = prefsOf(useBrowserPrefsStore.getInitialState());--export function browserPrefsFromRemote(remote: BrowserPrefs): BrowserPrefs {+export function prefsFromRemote(remote: Prefs, defaults: Prefs): Prefs {return Object.fromEntries(Object.entries(remote).filter(([key, value]) => {- const fallback = DEFAULT_BROWSER_PREFS[key];+ const fallback = defaults[key];return (- key in DEFAULT_BROWSER_PREFS &&+ key in defaults &&value !== null &&Array.isArray(value) === Array.isArray(fallback) &&typeof value === typeof fallback@@ -38,94 +64,175 @@ export function browserPrefsFromRemote(remote: BrowserPrefs): BrowserPrefs {);}-function sameBrowserPrefs(a: BrowserPrefs, b: BrowserPrefs): boolean {- return JSON.stringify(a) === JSON.stringify(b);+// The notification needs this browser's permission; the files panel is layout state.+const LOCAL_CHAT_PREFS = new Set(["notifyWhenReplyFinishes", "filesPanelCollapsed"]);++type Section = {+ field: keyof ClientPreferencesChanges;+ fallback: unknown;+ read: () => unknown;+ apply: (remote: unknown) => void;+ subscribe: (listener: () => void) => () => void;+};++type PersistedStore<S> = {+ getState: () => S;+ getInitialState: () => S;+ setState: (state: Partial<S>) => void;+ subscribe: (listener: () => void) => () => void;+ persist: {+ getOptions: () => { merge?: (persisted: unknown, current: S) => S };+ };+};++function storeSection<S extends object>(+ field: Section["field"],+ store: PersistedStore<S>,+ skip?: ReadonlySet<string>,+): Section {+ const fallback = prefsOf(store.getInitialState(), skip);+ return {+ field,+ fallback,+ read: () => prefsOf(store.getState(), skip),+ apply: (remote) => {+ // merge() resets absent fields to defaults; a field the record lacks keeps this browser's value.+ const saved = {+ ...prefsOf(store.getState(), skip),+ ...prefsFromRemote(remote as Prefs, fallback),+ };+ const next =+ store.persist.getOptions().merge?.(saved, store.getState()) ?? saved;+ store.setState(prefsOf(next, skip) as Partial<S>);+ },+ subscribe: store.subscribe,+ };}-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);- };+function sections(): Record<keyof Pending, Section> {+ return {+ scale: {+ field: "interfaceScale",+ fallback: INTERFACE_SCALE_RANGE.default,+ read: () => useInterfaceScaleStore.getState().scale,+ apply: (remote) =>+ useInterfaceScaleStore.getState().setScale(remote as number),+ subscribe: useInterfaceScaleStore.subscribe,+ },+ browser: storeSection("browser", useBrowserPrefsStore),+ chat: storeSection("chat", useChatPreferencesStore, LOCAL_CHAT_PREFS),+ plusMenu: storeSection("plusMenu", usePlusMenuPrefsStore),+ timeFormat: {+ field: "timeFormat",+ fallback: "system",+ read: getTimeFormat,+ apply: (remote) => setTimeFormat(remote as TimeFormat),+ subscribe: subscribeTimeFormat,+ },+ spellcheck: {+ field: "spellcheck",+ fallback: true,+ read: getSpellCheck,+ apply: (remote) => setSpellCheck(remote as boolean),+ subscribe: subscribeSpellCheck,+ },+ };+}- 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 same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);++export function startClientPreferencesSync(): () => void {+ const all = sections();+ 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++;+ markPending([section], true);+ };- const stopScale = useInterfaceScaleStore.subscribe((state, prev) => {- if (applying || state.scale === prev.scale) return;- touch("scale");+ const account = localStorage.getItem(BROWSER_ACCOUNT_KEY);+ // Another tab's switch clears these keys and a queued request outlives this one's: neither is this account's.+ const switched = () => accountTransitionPending() || !sameBrowserAccount(account);++ let saving: Promise<void> = Promise.resolve();+ const pushAll = () => {+ clearTimeout(timer);+ timer = setTimeout(() => {+ saving = saving+ .then(async () => {+ const sent = edits;+ const edited = PENDING_SECTIONS.filter((section) => touched[section]);+ if (edited.length === 0 || switched()) return;+ await saveClientPreferences(+ Object.fromEntries(+ edited.map((section) => [all[section].field, all[section].read()]),+ ),+ );+ if (edits === sent && !switched()) {+ for (const section of edited) touched[section] = false;+ markPending(edited, false);+ }+ })+ .catch(() => undefined);+ }, PUSH_DEBOUNCE_MS);+ };++ const last = {} as Record<keyof Pending, unknown>;+ const stops = PENDING_SECTIONS.map((section) => {+ last[section] = all[section].read();+ return all[section].subscribe(() => {+ const next = all[section].read();+ if (applying || same(next, last[section])) return;+ if (switched()) return;+ last[section] = next;+ touch(section);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 || switched()) return;+ loaded = true;+ applying = true;+ for (const section of PENDING_SECTIONS) {+ const value = remote[all[section].field];+ if (value != null && !touched[section]) all[section].apply(value);+ last[section] = all[section].read();+ }+ applying = false;+ for (const section of PENDING_SECTIONS) {+ if (+ remote[all[section].field] == null &&+ !same(last[section], all[section].fallback)+ )+ touch(section);+ }+ if (PENDING_SECTIONS.some((section) => touched[section])) pushAll();+ })+ .catch(() => {+ loaded = true;});- 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);+ for (const stop of stops) stop();+ };+}+export function useDeviceSettingsSync(enabled: boolean): void {+ useEffect(() => {+ if (!enabled) return;+ const stopBackground = startChatBackgroundSync();+ const stopPreferences = startClientPreferencesSync();return () => {- cancelled = true;- clearTimeout(timer);- stopScale();- stopBrowser();+ stopPreferences();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.tsindex f29b273c27f..3c5f0bacd11 100644--- a/studio/frontend/src/features/settings/lib/client-prefs-pending.ts+++ b/studio/frontend/src/features/settings/lib/client-prefs-pending.ts@@ -4,26 +4,47 @@// 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 };+export const PENDING_SECTIONS = [+ "scale",+ "browser",+ "chat",+ "plusMenu",+ "timeFormat",+ "spellcheck",+] as const;++export type PendingSection = (typeof PENDING_SECTIONS)[number];+export type Pending = Record<PendingSection, boolean>;const pendingKey = () => accountDatabaseName("unsloth_client_prefs_pending");export function readPending(): Pending {+ let saved: Record<string, unknown> | null = null;try {- const saved = JSON.parse(localStorage.getItem(pendingKey()) ?? "{}");- return { scale: saved?.scale === true, browser: saved?.browser === true };+ saved = JSON.parse(localStorage.getItem(pendingKey()) ?? "{}");} catch {- return { scale: false, browser: false };+ // nothing pending}+ return Object.fromEntries(+ PENDING_SECTIONS.map((section) => [section, saved?.[section] === true]),+ ) as Pending;}export function writePending(pending: Pending): void {try {- if (pending.scale || pending.browser) {+ if (Object.values(pending).some(Boolean)) {localStorage.setItem(pendingKey(), JSON.stringify(pending));} else {localStorage.removeItem(pendingKey());}} catch {+ // storage unavailable}}++// Re-read first: other tabs of this account share the marker.+export function markPending(sections: readonly PendingSection[], value: boolean): void {+ const pending = readPending();+ for (const section of sections) pending[section] = value;+ writePending(pending);+}diff --git a/studio/frontend/src/features/settings/tabs/general-tab.tsx b/studio/frontend/src/features/settings/tabs/general-tab.tsxindex 2362e09e55c..130b6443053 100644--- a/studio/frontend/src/features/settings/tabs/general-tab.tsx+++ b/studio/frontend/src/features/settings/tabs/general-tab.tsx@@ -228,8 +228,14 @@ 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 });+ // Unsent, so the defaults beat the account's saved copy after the reload.+ writePending({+ ...readPending(),+ scale: true,+ chat: true,+ timeFormat: true,+ spellcheck: true,+ });window.location.reload();}diff --git a/studio/frontend/src/lib/account-transition.ts b/studio/frontend/src/lib/account-transition.tsindex f410ee98190..179a651e54a 100644--- a/studio/frontend/src/lib/account-transition.ts+++ b/studio/frontend/src/lib/account-transition.ts@@ -58,7 +58,6 @@ export const ACCOUNT_CHROME_KEYS = new Set(["palette",APPEARANCE_KEY,"unsloth_locale",- "unsloth_spellcheck","sidebar_pinned","sidebar_width","chat_settings_width",@@ -161,6 +160,17 @@ function isSameAccount(previous: MarkedAccount, next: MarkedAccount): boolean {return previous.username === next.username;}+/** Whether `storage` still names the account `since` was taken from, across marker upgrades. */+export function sameBrowserAccount(+ since: string | null,+ storage: Pick<Storage, "getItem"> = window.localStorage,+): boolean {+ return isSameAccount(+ parseAccountMarker(since ?? OWNER_BROWSER_ACCOUNT),+ parseAccountMarker(storage.getItem(BROWSER_ACCOUNT_KEY) ?? OWNER_BROWSER_ACCOUNT),+ );+}+export function resetFullAccessForMultiUser(storage: Storage): void {if (storage.getItem("unsloth_chat_permission_mode") === "full") {storage.setItem("unsloth_chat_permission_mode", "auto");diff --git a/studio/frontend/src/lib/spellcheck.ts b/studio/frontend/src/lib/spellcheck.tsindex c43c3ae39ab..0678fe1d02b 100644--- a/studio/frontend/src/lib/spellcheck.ts+++ b/studio/frontend/src/lib/spellcheck.ts@@ -42,13 +42,13 @@ export function setSpellCheck(enabled: boolean): void {}}-function subscribe(listener: () => void): () => void {+export function subscribeSpellCheck(listener: () => void): () => void {listeners.add(listener);return () => listeners.delete(listener);}export function useSpellCheck(): boolean {- return useSyncExternalStore(subscribe, getSpellCheck);+ return useSyncExternalStore(subscribeSpellCheck, getSpellCheck);}/** Apply the stored choice now and follow toggles made in another tab. */diff --git a/studio/frontend/src/lib/time-format.ts b/studio/frontend/src/lib/time-format.tsindex 3eca0a09e1d..55097f4b718 100644--- a/studio/frontend/src/lib/time-format.ts+++ b/studio/frontend/src/lib/time-format.ts@@ -41,13 +41,13 @@ function notify(): void {}}-function subscribe(listener: () => void): () => void {+export function subscribeTimeFormat(listener: () => void): () => void {listeners.add(listener);return () => listeners.delete(listener);}export function useTimeFormat(): TimeFormat {- return useSyncExternalStore(subscribe, getTimeFormat, getTimeFormat);+ return useSyncExternalStore(subscribeTimeFormat, getTimeFormat, getTimeFormat);}export function watchTimeFormat(win: Window): void {diff --git a/studio/frontend/tests/chat-menu-order.test.ts b/studio/frontend/tests/chat-menu-order.test.tsindex ac1b4591121..dde37f78842 100644--- a/studio/frontend/tests/chat-menu-order.test.ts+++ b/studio/frontend/tests/chat-menu-order.test.ts@@ -7,7 +7,7 @@ import test from "node:test";import { installLocalStorageFake, readSrc, registerBundlerResolver } from "./helpers/kit.ts";registerBundlerResolver();-const { store } = installLocalStorageFake();+const { store, fireWindowEvent } = installLocalStorageFake();const {PLUS_MENU_ORDER,PLUS_MENU_PINS_STORAGE_KEY,@@ -124,6 +124,17 @@ test("moving another row keeps Deep research where it was in More, not at the toassert.deepEqual(keepSavedSlot(["mcp"], ["mcp"], "deepResearch"), ["deepResearch", "mcp"]);});+test("a menu change in another tab applies here, so this tab never sends a stale copy", () => {+ store.set(+ PLUS_MENU_PINS_STORAGE_KEY,+ JSON.stringify({ state: { pins: { mcp: true }, pinnedPromptIds: ["p9"] }, version: 1 }),+ );+ fireWindowEvent("storage", { key: PLUS_MENU_PINS_STORAGE_KEY });+ const menu = usePlusMenuPrefsStore.getState();+ assert.equal(menu.pins.mcp, true);+ assert.deepEqual(menu.pinnedPromptIds, ["p9"]);+});+test("Reset to default greys out only while the menu is at its defaults", () => {const initial = usePlusMenuPrefsStore.getInitialState();assert.equal(plusMenuAtDefaults(initial.pins, initial.order), true);diff --git a/studio/frontend/tests/client-prefs-pending.test.ts b/studio/frontend/tests/client-prefs-pending.test.tsindex 19a5102def1..4ecf5118553 100644--- a/studio/frontend/tests/client-prefs-pending.test.ts+++ b/studio/frontend/tests/client-prefs-pending.test.ts@@ -15,30 +15,42 @@ Object.assign(globalThis, {window: { localStorage, location: { protocol: "http:", host: "127.0.0.1", hostname: "127.0.0.1", pathname: "/", href: "" } },});-const { readPending, writePending } = await import(+const { markPending, readPending, writePending } = await import("../src/features/settings/lib/client-prefs-pending.ts");+const none = {+ scale: false,+ browser: false,+ chat: false,+ plusMenu: false,+ timeFormat: false,+ spellcheck: false,+};+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.deepEqual(readPending(), none);+ writePending({ ...none, chat: true });+ assert.deepEqual(readPending(), { ...none, chat: true });+ writePending(none);assert.equal(store.size, 0);- assert.deepEqual(readPending(), { scale: false, browser: false });+ assert.deepEqual(readPending(), none);});test("a corrupt marker reads as nothing pending", () => {- writePending({ scale: true, browser: true });+ writePending({ ...none, scale: true, browser: true });const [key] = [...store.keys()];store.set(key, "{");- assert.deepEqual(readPending(), { scale: false, browser: false });+ assert.deepEqual(readPending(), none);});-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,/);+test("one tab's pending flags survive another tab marking or clearing its own", () => {+ writePending(none);+ markPending(["chat"], true);+ markPending(["scale"], true);+ assert.deepEqual(readPending(), { ...none, chat: true, scale: true });+ markPending(["scale"], false);+ assert.deepEqual(readPending(), { ...none, chat: true });+ markPending(["chat"], false);+ assert.equal(store.size, 0);});diff --git a/studio/frontend/tests/device-settings-sync.test.ts b/studio/frontend/tests/device-settings-sync.test.tsnew file mode 100644index 00000000000..8eddd44ff78--- /dev/null+++ b/studio/frontend/tests/device-settings-sync.test.ts@@ -0,0 +1,226 @@+// 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 { register } from "node:module";+import test from "node:test";++import { installLocalStorageFake } from "./helpers/kit.ts";++register("./helpers/tauri-webview-resolver.mjs", import.meta.url);+register("./helpers/settings-api-resolver.mjs", import.meta.url);+const { store, fireWindowEvent } = installLocalStorageFake();+const attrs = new Map<string, string>();+Object.assign(globalThis.document, {+ documentElement: {+ style: {},+ getAttribute: (name: string) => attrs.get(name) ?? null,+ setAttribute: (name: string, value: string) => attrs.set(name, value),+ removeAttribute: (name: string) => attrs.delete(name),+ },+});++const empty = {+ saved: false,+ updatedAt: null,+ interfaceScale: null,+ browser: null,+ chat: null,+ plusMenu: null,+ timeFormat: null,+ spellcheck: null,+};+let account: Record<string, unknown> = empty;+const puts: Record<string, unknown>[] = [];+globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => {+ if (init?.method === "PUT") puts.push(JSON.parse(String(init.body)));+ return new Response(JSON.stringify(account), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ });+}) as typeof fetch;++const { startClientPreferencesSync } = await import(+ "../src/features/settings/hooks/use-device-settings-sync.ts"+);+const { useChatPreferencesStore } = await import(+ "../src/features/chat/stores/chat-preferences-store.ts"+);+const { PLUS_MENU_ORDER, usePlusMenuPrefsStore } = await import(+ "../src/features/chat/stores/plus-menu-prefs-store.ts"+);+const { getTimeFormat, setTimeFormat, TIME_FORMAT_STORAGE_KEY, watchTimeFormat } =+ await import("../src/lib/time-format.ts");+const { getSpellCheck, setSpellCheck, SPELLCHECK_STORAGE_KEY, watchSpellCheck } =+ await import("../src/lib/spellcheck.ts");+const { BROWSER_ACCOUNT_KEY } = await import("../src/lib/account-transition.ts");+const { markPending, readPending } = await import(+ "../src/features/settings/lib/client-prefs-pending.ts"+);++const settle = () => new Promise((resolve) => setTimeout(resolve, 1600));++function freshBrowser() {+ store.clear();+ puts.length = 0;+ useChatPreferencesStore.setState(useChatPreferencesStore.getInitialState());+ usePlusMenuPrefsStore.setState(usePlusMenuPrefsStore.getInitialState());+ setTimeFormat("system");+ store.clear();+}++test("a fresh browser takes the account's preferences and sends no defaults back", async () => {+ freshBrowser();+ account = {+ ...empty,+ saved: true,+ chat: { sendShortcut: "mod-enter", showReplyTimes: true, toolVisibility: "expanded" },+ plusMenu: {+ pins: { mcp: true },+ order: [...PLUS_MENU_ORDER].reverse(),+ pinnedPromptIds: ["p1"],+ },+ timeFormat: "24h",+ spellcheck: false,+ };+ const stop = startClientPreferencesSync();+ await settle();+ stop();+ const chat = useChatPreferencesStore.getState();+ assert.equal(chat.sendShortcut, "mod-enter");+ assert.equal(chat.showReplyTimes, true);+ assert.equal(chat.toolVisibility, "expanded");+ assert.equal(chat.confirmDeleteChats, true);+ const menu = usePlusMenuPrefsStore.getState();+ assert.equal(menu.pins.mcp, true);+ assert.equal(menu.pins.deepResearch, true);+ assert.deepEqual(menu.order, [...PLUS_MENU_ORDER].reverse());+ assert.deepEqual(menu.pinnedPromptIds, ["p1"]);+ assert.equal(getTimeFormat(), "24h");+ assert.equal(getSpellCheck(), false);+ assert.deepEqual(puts, []);+});++test("an edit sends only its own section, without this browser's local-only fields", async () => {+ freshBrowser();+ account = { ...empty, saved: true, timeFormat: "24h" };+ const stop = startClientPreferencesSync();+ await settle();+ useChatPreferencesStore.getState().setShowReplyTimes(true);+ useChatPreferencesStore.getState().setNotifyWhenReplyFinishes(true);+ await settle();+ stop();+ assert.equal(puts.length, 1);+ assert.deepEqual(Object.keys(puts[0]), ["chat"]);+ const chat = puts[0].chat as Record<string, unknown>;+ assert.equal(chat.showReplyTimes, true);+ assert.equal("notifyWhenReplyFinishes" in chat, false);+ assert.equal("filesPanelCollapsed" in chat, false);+});++test("choices made here before the account had any are uploaded once", async () => {+ freshBrowser();+ setTimeFormat("12h");+ account = empty;+ const stop = startClientPreferencesSync();+ await settle();+ stop();+ assert.deepEqual(puts, [{ timeFormat: "12h" }]);+});++test("an edit not yet sent wins over the account's copy and is sent after load", async () => {+ freshBrowser();+ useChatPreferencesStore.getState().setShowReplyTimes(true);+ markPending(["chat"], true);+ account = { ...empty, saved: true, chat: { showReplyTimes: false }, timeFormat: "24h" };+ const stop = startClientPreferencesSync();+ await settle();+ stop();+ assert.equal(useChatPreferencesStore.getState().showReplyTimes, true);+ assert.equal(getTimeFormat(), "24h");+ assert.equal(puts.length, 1);+ assert.deepEqual(Object.keys(puts[0]), ["chat"]);+ assert.equal((puts[0].chat as Record<string, unknown>).showReplyTimes, true);+ assert.equal(readPending().chat, false);+});++test("another tab switching accounts does not mark its cleanup as edits", async () => {+ freshBrowser();+ setTimeFormat("24h");+ setSpellCheck(false);+ account = { ...empty, saved: true, timeFormat: "24h", spellcheck: false };+ watchTimeFormat(window);+ watchSpellCheck(window);+ const stop = startClientPreferencesSync();+ await settle();+ store.delete(TIME_FORMAT_STORAGE_KEY);+ store.delete(SPELLCHECK_STORAGE_KEY);+ store.set(BROWSER_ACCOUNT_KEY, "account:u2:alice");+ fireWindowEvent("storage", { key: TIME_FORMAT_STORAGE_KEY, newValue: null });+ fireWindowEvent("storage", { key: SPELLCHECK_STORAGE_KEY, newValue: null });+ await settle();+ stop();+ assert.equal(readPending().timeFormat, false);+ assert.equal(readPending().spellcheck, false);+ assert.deepEqual(puts, []);+});++test("a same-account marker upgrade keeps syncing edits", async () => {+ freshBrowser();+ store.set(BROWSER_ACCOUNT_KEY, "alice");+ account = { ...empty, saved: true, timeFormat: "12h" };+ const stop = startClientPreferencesSync();+ await settle();+ store.set(BROWSER_ACCOUNT_KEY, "account:a1:alice");+ setTimeFormat("24h");+ await settle();+ stop();+ assert.deepEqual(puts, [{ timeFormat: "24h" }]);+});++test("a field the account record lacks keeps this browser's value", async () => {+ freshBrowser();+ useChatPreferencesStore.setState({ generationStatsUpdates: "realtime" });+ account = { ...empty, saved: true, chat: { sendShortcut: "mod-enter" } };+ const stop = startClientPreferencesSync();+ await settle();+ stop();+ const chat = useChatPreferencesStore.getState();+ assert.equal(chat.sendShortcut, "mod-enter");+ assert.equal(chat.generationStatsUpdates, "realtime");+});++test("a load that lands after this tab switched accounts applies nothing", async () => {+ freshBrowser();+ store.set(BROWSER_ACCOUNT_KEY, "account:u1:alice");+ account = { ...empty, saved: true, chat: { sendShortcut: "mod-enter" }, timeFormat: "24h" };+ const realFetch = globalThis.fetch;+ let release!: () => void;+ const gate = new Promise<void>((resolve) => (release = resolve));+ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ await gate;+ return realFetch(input, init);+ }) as typeof fetch;+ const stop = startClientPreferencesSync();+ store.set(BROWSER_ACCOUNT_KEY, "account:u2:bob");+ release();+ await settle();+ stop();+ globalThis.fetch = realFetch;+ assert.equal(useChatPreferencesStore.getState().sendShortcut, "enter");+ assert.equal(getTimeFormat(), "system");+ assert.deepEqual(puts, []);+});++test("an edit still queued when this tab switches accounts is not sent as the next one", async () => {+ freshBrowser();+ store.set(BROWSER_ACCOUNT_KEY, "account:u1:alice");+ account = { ...empty, saved: true, timeFormat: "12h" };+ const stop = startClientPreferencesSync();+ await settle();+ setTimeFormat("24h");+ store.set(BROWSER_ACCOUNT_KEY, "account:u2:bob");+ await settle();+ stop();+ assert.deepEqual(puts, []);+});diff --git a/studio/frontend/tests/spellcheck-preference.test.ts b/studio/frontend/tests/spellcheck-preference.test.tsindex efa6bbc013f..e4d357fa506 100644--- a/studio/frontend/tests/spellcheck-preference.test.ts+++ b/studio/frontend/tests/spellcheck-preference.test.ts@@ -78,11 +78,11 @@ test("the app applies it before the first render", () => {assert.match(readSrc("main.tsx"), /watchSpellCheck\(window\);/);});-test("an account switch keeps the choice, like the display language", async () => {+test("an account switch leaves the choice to the next account's own saved copy", async () => {const { ACCOUNT_CHROME_KEYS } = await import("../src/lib/account-transition.ts");- assert.ok(ACCOUNT_CHROME_KEYS.has(SPELLCHECK_STORAGE_KEY));+ assert.equal(ACCOUNT_CHROME_KEYS.has(SPELLCHECK_STORAGE_KEY), false);});test("Reset all preferences turns spell check back on", () => {