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: skip superseded wallpaper writes and no-op history / bookmark persists (#17298)
Daniel Han406c48561f43
diff --git a/studio/frontend/src/features/browser/bookmarks-store.ts b/studio/frontend/src/features/browser/bookmarks-store.tsindex 4a2f58c97a2..0f4c524beba 100644--- a/studio/frontend/src/features/browser/bookmarks-store.ts+++ b/studio/frontend/src/features/browser/bookmarks-store.ts@@ -72,13 +72,14 @@ export const useBrowserBookmarksStore = create<BrowserBookmarksState>()(),lastFolder: patch.folder ?? state.lastFolder,})),- setBookmarkIcon: (id, icon) =>- set((state) => {- if (!icon.startsWith("data:image/") || icon.length > MAX_ICON_CHARS) return state;- const current = state.bookmarks.find((bookmark) => bookmark.id === id);- if (!current || current.icon === icon) return state;- return { bookmarks: state.bookmarks.map((bookmark) => (bookmark.id === id ? { ...bookmark, icon } : bookmark)) };- }),+ // No-op calls skip set(): persist rewrites storage on every set().+ setBookmarkIcon: (id, icon) => {+ if (!icon.startsWith("data:image/") || icon.length > MAX_ICON_CHARS) return;+ const { bookmarks } = get();+ const current = bookmarks.find((bookmark) => bookmark.id === id);+ if (!current || current.icon === icon) return;+ set({ bookmarks: bookmarks.map((bookmark) => (bookmark.id === id ? { ...bookmark, icon } : bookmark)) });+ },removeBookmark: (id) => set((state) => ({ bookmarks: state.bookmarks.filter((bookmark) => bookmark.id !== id) })),importBookmarks: (items) => {const saved = new Set(get().bookmarks.map((bookmark) => bookmark.url));@@ -103,13 +104,12 @@ export const useBrowserBookmarksStore = create<BrowserBookmarksState>()(if (added.length > 0) set((state) => ({ bookmarks: [...state.bookmarks, ...added] }));return { added: added.length, leftOut };},- restoreBookmark: (bookmark, index) =>- set((state) => {- if (state.bookmarks.some((other) => other.id === bookmark.id || other.url === bookmark.url)) return state;- const bookmarks = [...state.bookmarks];- bookmarks.splice(Math.min(index, bookmarks.length), 0, bookmark);- return { bookmarks };- }),+ restoreBookmark: (bookmark, index) => {+ const bookmarks = [...get().bookmarks];+ if (bookmarks.some((other) => other.id === bookmark.id || other.url === bookmark.url)) return;+ bookmarks.splice(Math.min(index, bookmarks.length), 0, bookmark);+ set({ bookmarks });+ },}),{name: accountDatabaseName("unsloth_browser_bookmarks"),diff --git a/studio/frontend/src/features/browser/history-store.ts b/studio/frontend/src/features/browser/history-store.tsindex 8c079f983f3..6d9daf47d59 100644--- a/studio/frontend/src/features/browser/history-store.ts+++ b/studio/frontend/src/features/browser/history-store.ts@@ -117,23 +117,24 @@ interface BrowserHistoryState {export const useBrowserHistoryStore = create<BrowserHistoryState>()(persist(- (set) => ({+ (set, get) => ({history: [],downloads: [],icons: {},- recordIcon: (host, icon, temporary = false) =>- set((state) => {- if (!host || icon.length > MAX_URL_CHARS || state.icons[host] === icon) return state;- // Icons name the hosts visited, so they follow the history setting.- if (!savesHistory(temporary)) return state;- const { [host]: _replaced, ...rest } = state.icons;- const hosts = Object.keys(rest);- for (const old of hosts.slice(0, Math.max(0, hosts.length + 1 - MAX_ICONS))) delete rest[old];- return { icons: { ...rest, [host]: icon } };- }),- recordVisit: (url, fullTitle, temporary = false) =>+ // No-op calls skip set(): persist rewrites storage on every set().+ recordIcon: (host, icon, temporary = false) => {+ const { icons } = get();+ if (!host || icon.length > MAX_URL_CHARS || icons[host] === icon) return;+ // Icons name the hosts visited, so they follow the history setting.+ if (!savesHistory(temporary)) return;+ const { [host]: _replaced, ...rest } = icons;+ const hosts = Object.keys(rest);+ for (const old of hosts.slice(0, Math.max(0, hosts.length + 1 - MAX_ICONS))) delete rest[old];+ set({ icons: { ...rest, [host]: icon } });+ },+ recordVisit: (url, fullTitle, temporary = false) => {+ if (url.length > MAX_URL_CHARS || !savesHistory(temporary)) return;set((state) => {- if (url.length > MAX_URL_CHARS || !savesHistory(temporary)) return state;const title = fullTitle.slice(0, MAX_TITLE_CHARS);const cutoff = retentionCutoff();const kept = cutoff ? state.history.filter((visit) => visit.visitedAt >= cutoff) : state.history;@@ -146,7 +147,8 @@ export const useBrowserHistoryStore = create<BrowserHistoryState>()(// Pruned against the new visit too: its icon was recorded just before it.const icons = kept.length < state.history.length ? iconsFor(history, state.icons) : state.icons;return { history, icons };- }),+ });+ },recordDownload: (item, temporary) => {// Callers that took the state when the download began pass it; the rest go by the chat shown now.if (!useBrowserPrefsStore.getState().saveDownloadHistory || (temporary ?? useChatRuntimeStore.getState().incognito)) {@@ -200,13 +202,13 @@ export const useBrowserHistoryStore = create<BrowserHistoryState>()(});historyStorage.flush();},- pruneHistory: () =>- set((state) => {- const cutoff = retentionCutoff();- if (!cutoff || state.history.every((visit) => visit.visitedAt >= cutoff)) return state;- const history = state.history.filter((visit) => visit.visitedAt >= cutoff);- return { history, icons: iconsFor(history, state.icons) };- }),+ pruneHistory: () => {+ const state = get();+ const cutoff = retentionCutoff();+ if (!cutoff || state.history.every((visit) => visit.visitedAt >= cutoff)) return;+ const history = state.history.filter((visit) => visit.visitedAt >= cutoff);+ set({ history, icons: iconsFor(history, state.icons) });+ },}),{// Per account: a write still deferred at a switch lands under the account that made it.diff --git a/studio/frontend/src/features/chat-background/storage.ts b/studio/frontend/src/features/chat-background/storage.tsindex 48283873f2b..28166688dbb 100644--- a/studio/frontend/src/features/chat-background/storage.ts+++ b/studio/frontend/src/features/chat-background/storage.ts@@ -19,6 +19,7 @@ export const useBackgroundStore = create<{let database: Dexie | undefined;let account = "";let revision = 0;+let patchRevision = 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;@@ -132,9 +133,13 @@ async function persist(): Promise<boolean> {const db = currentDatabase();const ticket = ++revision;- if (optimistic) useBackgroundStore.setState({ value, error: null });+ if (optimistic) {+ patchRevision = ticket;+ useBackgroundStore.setState({ value, error: null });+ }const write = writes.then(async () => {- if (fromServer && ticket !== revision) return;+ // A patch is skipped only for a newer patch: both keep the image and its sha256.+ if (ticket !== revision && (fromServer || (optimistic && patchRevision === revision && db === database))) 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 });diff --git a/studio/frontend/tests/browser-store-noop-writes.test.ts b/studio/frontend/tests/browser-store-noop-writes.test.tsnew file mode 100644index 00000000000..155c2b4a906--- /dev/null+++ b/studio/frontend/tests/browser-store-noop-writes.test.ts@@ -0,0 +1,65 @@+// 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";++const data = new Map<string, string>([["unsloth.browser-account.v1", "account:b1:bob"]]);+const flushes: (() => void)[] = [];+const writes: string[] = [];+const localStorage = {+ getItem: (key: string) => data.get(key) ?? null,+ setItem: (key: string, value: string) => {+ writes.push(key);+ data.set(key, value);+ },+ removeItem: (key: string) => void data.delete(key),+};+Object.assign(globalThis, {+ localStorage,+ window: {+ localStorage,+ location: { protocol: "http:" },+ addEventListener: (type: string, flush: () => void) => type === "pagehide" && flushes.push(flush),+ },+});++register("./helpers/browser-store-resolver.mjs", import.meta.url);+const { useBrowserHistoryStore } = await import("../src/features/browser/history-store.ts");+const { useBrowserBookmarksStore } = await import("../src/features/browser/bookmarks-store.ts");+const flush = () => {+ for (const run of flushes) run();+};++test("history actions that change nothing do not rewrite stored history", () => {+ const history = useBrowserHistoryStore.getState();+ history.recordVisit("https://example.com/", "Example");+ history.recordIcon("example.com", "https://example.com/icon.png");+ flush();+ const stored = data.get("unsloth_browser_history:b1");+ assert.match(stored ?? "", /icon\.png/);+ writes.length = 0;+ history.recordIcon("example.com", "https://example.com/icon.png");+ history.recordIcon("", "https://example.com/icon.png");+ history.pruneHistory();+ flush();+ assert.deepEqual(writes, []);+ assert.equal(data.get("unsloth_browser_history:b1"), stored);+});++test("bookmark actions that change nothing do not rewrite stored bookmarks", () => {+ const bookmarks = useBrowserBookmarksStore.getState();+ const bookmark = bookmarks.addBookmark("https://example.com/", "Example");+ assert.ok(bookmark);+ bookmarks.setBookmarkIcon(bookmark.id, "data:image/png;base64,AAAA");+ const stored = data.get("unsloth_browser_bookmarks:b1");+ assert.match(stored ?? "", /AAAA/);+ writes.length = 0;+ bookmarks.setBookmarkIcon(bookmark.id, "data:image/png;base64,AAAA");+ bookmarks.setBookmarkIcon(bookmark.id, "https://example.com/favicon.ico");+ bookmarks.setBookmarkIcon("missing", "data:image/png;base64,BBBB");+ bookmarks.restoreBookmark(bookmark, 0);+ assert.deepEqual(writes, []);+ assert.equal(data.get("unsloth_browser_bookmarks:b1"), stored);+});diff --git a/studio/frontend/tests/chat-background-drag-writes.test.ts b/studio/frontend/tests/chat-background-drag-writes.test.tsnew file mode 100644index 00000000000..344c2be019f--- /dev/null+++ b/studio/frontend/tests/chat-background-drag-writes.test.ts@@ -0,0 +1,122 @@+// 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";++let loads = 0;+const tick = () => new Promise<void>((resolve) => setImmediate(resolve));++async function loadStorage(+ rows: Map<string, any>,+ puts: any[],+ gate?: Promise<void>,+ fails: (row: any) => boolean = () => 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) => {+ puts.push(row);+ if (gate) await gate;+ if (fails(row)) throw new Error("QuotaExceededError");+ 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-drag",+ };+ (globalThis as any).__backgroundDrag = dependencies;+ async function load(relative: string) {+ const source = stripTypeScriptTypes(readSrc(`features/${relative}`))+ .replace(/^import[\s\S]*?;\n/gm, "");+ const bindings = `// ${++loads}\nconst {${Object.keys(dependencies).join(",")}} = globalThis.__backgroundDrag;\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");+ return load("chat-background/storage.ts");+}++test("a slider drag stores the image once per idle write, not once per tick, and keeps the last value", async () => {+ const image = new Blob(["image"]);+ const rows = new Map<string, any>([+ ["current", { id: "current", value: { blob: image, visibility: 50 }, sha256: "abc" }],+ ["sync", { id: "sync", state: { updatedAt: 1, dirty: false } }],+ ]);+ const puts: any[] = [];+ let release!: () => void;+ const gate = new Promise<void>((resolve) => { release = resolve; });+ try {+ const storage = await loadStorage(rows, puts, gate);+ let changes = 0;+ storage.setBackgroundChangeListener(() => { changes++; });+ await storage.hydrateBackground();+ // The first tick's write starts and is held; the rest queue behind it.+ storage.patchBackground({ visibility: 1 });+ await tick();+ for (let visibility = 2; visibility <= 40; visibility++) {+ storage.patchBackground({ visibility });+ assert.equal(storage.useBackgroundStore.getState().value.visibility, visibility);+ }+ release();+ for (let i = 0; i < 20; i++) await tick();+ const imagePuts = puts.filter((row) => row.id === "current");+ assert.deepEqual(imagePuts.map((row) => row.value.visibility), [1, 40]);+ assert.equal(rows.get("current").value.visibility, 40);+ assert.equal(rows.get("current").value.blob, image);+ assert.equal(rows.get("current").sha256, "abc");+ assert.deepEqual(rows.get("sync").state, { updatedAt: 1, dirty: true });+ assert.equal(changes, 40);+ assert.equal(storage.useBackgroundStore.getState().error, null);+ assert.equal(storage.useBackgroundStore.getState().value.visibility, 40);+ } finally {+ release();+ delete (globalThis as any).__backgroundDrag;+ }+});++test("patches before an upload are still stored when the upload write fails", async () => {+ const image = new Blob(["image"]);+ const upload = new Blob(["upload"]);+ const rows = new Map<string, any>([+ ["current", { id: "current", value: { blob: image, visibility: 50 }, sha256: "abc" }],+ ["sync", { id: "sync", state: { updatedAt: 1, dirty: false } }],+ ]);+ let release!: () => void;+ const gate = new Promise<void>((resolve) => { release = resolve; });+ try {+ const storage = await loadStorage(rows, [], gate, (row) => row.value?.blob === upload);+ await storage.hydrateBackground();+ storage.patchBackground({ visibility: 1 });+ await tick();+ for (let visibility = 2; visibility <= 5; visibility++) storage.patchBackground({ visibility });+ const ticket = storage.beginBackgroundUpload();+ release();+ await storage.finishBackgroundUpload(ticket, { blob: upload, visibility: 70 });+ assert.equal(rows.get("current").value.visibility, 5);+ assert.equal(rows.get("current").value.blob, image);+ assert.equal(storage.useBackgroundStore.getState().value.visibility, 5);+ assert.equal(storage.useBackgroundStore.getState().error, "storage");+ } finally {+ release();+ delete (globalThis as any).__backgroundDrag;+ }+});