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: stop New chat from requesting a thread row that does not exist yet (#12539)
oobabooga8c344a6e74e2
diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex d281e1206d8..173054db75a 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -37,6 +37,7 @@ import {useCallback,useContext,useEffect,+ useLayoutEffect,useMemo,useRef,} from "react";@@ -197,6 +198,7 @@ import {readStoredChatMessages,listStoredChatThreads,markThreadIncognito,+ registerNewThreadIdSource,saveStoredChatMessage,saveStoredChatThread,syncStoredChatMessages,@@ -3313,6 +3315,17 @@ function ThreadNewChatSwitch({return null;}+function NewThreadIdRegistrar(): null {+ const aui = useAui();+ // Register before passive effects read storage.+ useLayoutEffect(+ () =>+ registerNewThreadIdSource(() => aui.threads().getState().newThreadId),+ [aui],+ );+ return null;+}+function ActiveThreadSync({enabled,}: { enabled: boolean }): ReactElement | null {@@ -3977,6 +3990,7 @@ export function ChatRuntimeProvider({<ChatProjectScopeContext.Provider value={projectId ?? null}><ToolPaneScopeContext.Provider value={toolPaneScope(modelType, pairId)}><ComparePaneContext.Provider value={Boolean(pairId)}>+ <NewThreadIdRegistrar /><ActiveThreadSyncenabled={modelType === "base" &&diff --git a/studio/frontend/src/features/chat/utils/chat-history-storage.ts b/studio/frontend/src/features/chat/utils/chat-history-storage.tsindex 9c139f1b5d4..dcbe7c06adb 100644--- a/studio/frontend/src/features/chat/utils/chat-history-storage.ts+++ b/studio/frontend/src/features/chat/utils/chat-history-storage.ts@@ -63,6 +63,29 @@ export function isThreadIncognito(threadId: string): boolean {return incognitoThreadIds.has(threadId);}+// Read live: initialize() clears newThreadId before persisting the thread.+const newThreadIdSources = new Set<() => string | null | undefined>();+// Settings can start a row write while the runtime still considers the thread new.+const writtenThreadIds = new Set<string>();++/** Returns the unregister function. */+export function registerNewThreadIdSource(+ source: () => string | null | undefined,+): () => void {+ newThreadIdSources.add(source);+ return () => {+ newThreadIdSources.delete(source);+ };+}++function isPendingNewThread(threadId: string): boolean {+ if (writtenThreadIds.has(threadId)) return false;+ for (const source of newThreadIdSources) {+ if (source() === threadId) return true;+ }+ return false;+}+type ThreadListArgs = {modelType?: ModelType;pairId?: string;@@ -404,6 +427,7 @@ async function saveLegacyChatThread(}function writeChatThreadRecord(thread: ThreadRecord): Promise<ThreadRecord> {+ writtenThreadIds.add(thread.id);return threadRecordWrites.write(thread.id, () => saveChatThread(thread));}@@ -632,6 +656,9 @@ export async function getStoredChatThreadReadResult(if (isChatThreadDeleted(threadId)) {return { thread: undefined, cacheable: true };}+ if (isPendingNewThread(threadId)) {+ return { thread: undefined, cacheable: true };+ }const legacyThread = await readLegacyStore(() => db.threads.get(threadId),undefined,@@ -817,6 +844,7 @@ export async function readStoredChatMessages(): Promise<{ messages: MessageRecord[]; fromBackend: boolean }> {if (isThreadIncognito(threadId)) return { messages: [], fromBackend: false };if (isChatThreadDeleted(threadId)) return { messages: [], fromBackend: false };+ if (isPendingNewThread(threadId)) return { messages: [], fromBackend: false };const legacyMessages = await readLegacyStore(() => db.messages.where("threadId").equals(threadId).toArray(),[] as MessageRecord[],diff --git a/studio/frontend/tests/new-thread-storage-reads.test.ts b/studio/frontend/tests/new-thread-storage-reads.test.tsnew file mode 100644index 00000000000..7e033da6454--- /dev/null+++ b/studio/frontend/tests/new-thread-storage-reads.test.ts@@ -0,0 +1,140 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";++import type { ThreadRecord } from "../src/features/chat/types";+import { loadWithStubs } from "./helpers/module-stubs.ts";++type Storage = {+ registerNewThreadIdSource: (+ source: () => string | null | undefined,+ ) => () => void;+ getStoredChatThreadReadResult: (+ threadId: string,+ ) => Promise<{ thread: ThreadRecord | undefined; cacheable: boolean }>;+ listStoredChatMessages: (threadId: string) => Promise<unknown[]>;+ saveStoredChatThread: (thread: ThreadRecord) => Promise<ThreadRecord>;+};++const NEW_ID = "__LOCALID_unsent";++const thread = (id: string): ThreadRecord => ({+ id,+ title: "New Chat",+ modelType: "base",+ archived: false,+ createdAt: 1,+});++function loadStorage() {+ const rows = new Map<string, ThreadRecord>();+ const requests: string[] = [];+ const storage = loadWithStubs<Storage>(+ new URL(+ "../src/features/chat/utils/chat-history-storage.ts",+ import.meta.url,+ ),+ {+ "../api/chat-api": {+ ChatThreadDeletedError: class extends Error {},+ // getChatThread returns null on 404.+ getChatThread: (threadId: string) => {+ requests.push(`GET thread ${threadId}`);+ return Promise.resolve(rows.get(threadId) ?? null);+ },+ // listChatMessages returns [] on 404.+ listChatMessages: (threadId: string) => {+ requests.push(`GET messages ${threadId}`);+ return Promise.resolve([]);+ },+ saveChatThread: (record: ThreadRecord) => {+ rows.set(record.id, record);+ return Promise.resolve(record);+ },+ notifyChatHistoryUpdated: () => {},+ },+ "../db": {+ DEXIE_DB_NAME: "unsloth-chat",+ db: {+ threads: { get: () => Promise.resolve(undefined) },+ messages: {+ where: () => ({+ equals: () => ({ toArray: () => Promise.resolve([]) }),+ }),+ },+ },+ },+ "./chat-thread-tombstones": {+ isChatThreadDeleted: () => false,+ markChatThreadDeleted: () => {},+ markChatThreadsDeleted: () => {},+ },+ "./thread-record-write-coordinator": {+ ThreadRecordWriteCoordinator: class {+ write<T>(_threadId: string, run: () => Promise<T>): Promise<T> {+ return run();+ }+ },+ },+ "../stores/fork-boundary-store": { setForkBoundary: () => {} },+ },+ );+ return { storage, requests };+}++Object.assign(globalThis, {+ indexedDB: { databases: () => Promise.resolve([{ name: "unsloth-chat" }]) },+});++test("a runtime's unsaved new thread is answered as missing without a request", async () => {+ const { storage, requests } = loadStorage();+ storage.registerNewThreadIdSource(() => NEW_ID);+ assert.deepEqual(await storage.getStoredChatThreadReadResult(NEW_ID), {+ thread: undefined,+ cacheable: true,+ });+ assert.deepEqual(await storage.listStoredChatMessages(NEW_ID), []);+ assert.deepEqual(requests, []);+});++test("other threads, and a thread once it stops being new, still ask the backend", async () => {+ const { storage, requests } = loadStorage();+ let newThreadId: string | undefined = NEW_ID;+ storage.registerNewThreadIdSource(() => newThreadId);+ await storage.getStoredChatThreadReadResult("saved");+ // initialize() clears newThreadId before saving.+ newThreadId = undefined;+ await storage.getStoredChatThreadReadResult(NEW_ID);+ assert.deepEqual(requests, ["GET thread saved", `GET thread ${NEW_ID}`]);+});++test("a row written while the runtime still calls the thread new is read back", async () => {+ const { storage, requests } = loadStorage();+ storage.registerNewThreadIdSource(() => NEW_ID);+ // Code-exec settings can create the row before first send.+ await storage.saveStoredChatThread(thread(NEW_ID));+ const { thread: read } = await storage.getStoredChatThreadReadResult(NEW_ID);+ assert.equal(read?.id, NEW_ID);+ assert.deepEqual(await storage.listStoredChatMessages(NEW_ID), []);+ assert.deepEqual(requests, [+ `GET thread ${NEW_ID}`,+ `GET thread ${NEW_ID}`,+ `GET messages ${NEW_ID}`,+ ]);+});++test("each registered runtime answers for its own id until it is unregistered", async () => {+ const { storage, requests } = loadStorage();+ // Each compare pane has its own runtime.+ const unregister = storage.registerNewThreadIdSource(() => NEW_ID);+ storage.registerNewThreadIdSource(() => "__LOCALID_other_pane");+ await storage.getStoredChatThreadReadResult(NEW_ID);+ await storage.getStoredChatThreadReadResult("__LOCALID_other_pane");+ assert.deepEqual(requests, []);+ unregister();+ await storage.getStoredChatThreadReadResult(NEW_ID);+ await storage.getStoredChatThreadReadResult("__LOCALID_other_pane");+ assert.deepEqual(requests, [`GET thread ${NEW_ID}`]);+});