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: optimize chat sends by reusing thread metadata (#8382)
oobabooga9e6dc61f66b4
diff --git a/studio/frontend/src/features/chat/api/chat-adapter.ts b/studio/frontend/src/features/chat/api/chat-adapter.tsindex 8d5b811e7ba..36f8bea2218 100644--- a/studio/frontend/src/features/chat/api/chat-adapter.ts+++ b/studio/frontend/src/features/chat/api/chat-adapter.ts@@ -102,7 +102,7 @@ import {toolPaneScope,toolThreadScope,} from "../tool-output-scope";-import type { ModelType } from "../types";+import type { ModelType, ThreadRecord } from "../types";import { isMultimodalResponse } from "../types/api";import type {CpuFallbackReason,@@ -115,6 +115,7 @@ import type {import type { ChatModelSummary } from "../types/runtime";import {getStoredChatThread,+ getStoredChatThreadReadResult,getStoredChatProject,listStoredChatThreads,listStoredChatMessages,@@ -126,6 +127,7 @@ import {recordLastLocalModelLoad,type LastLocalModelKind,} from "../utils/last-local-model-load";+import { createRetryableSharedRead } from "../utils/retryable-shared-read";import { getImageInputUnavailableReason } from "../utils/image-input-support";import {extractDeltaText,@@ -183,6 +185,8 @@ import { cancelResearchRun, createResearchRun } from "./research-api";// forces retrieval for them and leaves it to larger ones.const AUTOINJECT_AUTO_MAX_SIZE_B = 9;+type ThreadRecordReader = () => Promise<ThreadRecord | undefined>;+function resolveAutoInject(mode: RagAutoInject, checkpoint: string): boolean {if (mode === "on") return true;if (mode === "off") return false;@@ -1638,6 +1642,7 @@ export async function buildLocalTokenCountExtras(async function resolveUseAdapter(threadId: string | undefined,options: OpenAIStreamAdapterOptions = {},+ readThreadRecord?: ThreadRecordReader,): Promise<boolean | undefined> {if (options.modelType === "model1" || options.modelType === "model2") {return undefined;@@ -1652,7 +1657,7 @@ async function resolveUseAdapter(return undefined;}try {- const thread = await getStoredChatThread(threadId);+ const thread = await (readThreadRecord?.() ?? getStoredChatThread(threadId));if (!thread?.pairId) {return undefined;}@@ -1669,8 +1674,9 @@ async function resolveUseAdapter(async function resolveProjectInstructions(threadId: string | undefined,+ readThreadRecord?: ThreadRecordReader,): Promise<string> {- const projectId = await resolveProjectId(threadId);+ const projectId = await resolveProjectId(threadId, readThreadRecord);if (!projectId) {return "";}@@ -1686,6 +1692,7 @@ async function resolveChatInstructions(threadId: string | undefined,systemPrompt: unknown,systemVariables: unknown,+ readThreadRecord?: ThreadRecordReader,): Promise<string> {const safeSystemPrompt =typeof systemPrompt === "string"@@ -1694,7 +1701,10 @@ async function resolveChatInstructions(typeof systemVariables === "string" ? systemVariables : "",): "";- const projectInstructions = await resolveProjectInstructions(threadId);+ const projectInstructions = await resolveProjectInstructions(+ threadId,+ readThreadRecord,+ );return [projectInstructions? `<project_instructions>\n${projectInstructions}\n</project_instructions>`@@ -1707,9 +1717,12 @@ async function resolveChatInstructions(async function resolveProjectId(threadId: string | undefined,+ readThreadRecord?: ThreadRecordReader,): Promise<string | null> {if (threadId) {- const thread = await getStoredChatThread(threadId).catch(() => null);+ const thread = await (+ readThreadRecord?.() ?? getStoredChatThread(threadId)+ ).catch(() => null);return thread?.projectId ?? null;}const projectId = useChatRuntimeStore.getState().activeProjectId;@@ -1721,8 +1734,9 @@ async function resolveProjectId(async function resolveSandboxSessionId(threadId: string | undefined,+ readThreadRecord?: ThreadRecordReader,): Promise<string | undefined> {- const projectId = await resolveProjectId(threadId);+ const projectId = await resolveProjectId(threadId, readThreadRecord);return projectId ? `project-${projectId}` : threadId;}@@ -3386,6 +3400,15 @@ export function createOpenAIStreamAdapter(// switches chats while waiting for model load / auto-load.const resolvedThreadId =(unstable_threadId ?? runtime.activeThreadId) || undefined;+ const sharedThreadRecordRead = resolvedThreadId+ ? createRetryableSharedRead(+ () => getStoredChatThreadReadResult(resolvedThreadId),+ (result) => result.cacheable,+ )+ : undefined;+ const readThreadRecord = sharedThreadRecordRead+ ? async () => (await sharedThreadRecordRead()).thread+ : undefined;const releaseCurrentPreStreamRun = () =>releasePreStreamRunForThreadIds([unstable_threadId,@@ -3569,7 +3592,10 @@ export function createOpenAIStreamAdapter(runtime.reasoningEffortLevels,);}- const researchProjectId = await resolveProjectId(resolvedThreadId);+ const researchProjectId = await resolveProjectId(+ resolvedThreadId,+ readThreadRecord,+ );const projectRagEnabled = researchProjectId? await projectHasSources(researchProjectId): false;@@ -3577,6 +3603,7 @@ export function createOpenAIStreamAdapter(resolvedThreadId,params.systemPrompt,params.systemVariables,+ readThreadRecord,);const ragScope =runtime.ragEnabled || projectRagEnabled@@ -3726,10 +3753,6 @@ export function createOpenAIStreamAdapter(}return;}- const sandboxSessionId = await resolveSandboxSessionId(resolvedThreadId);- const toolConfirmationScopeId = resolvedThreadId- ? `${sandboxSessionId || "_default"}:${resolvedThreadId}`- : sandboxSessionId || "_default";const toolConfirmationIdsByBackendId = new Map<string, string>();// Local tool ids ("call_0") repeat across turns, panes and conversations, so scope by pane// AND thread. unstable_threadId alone, no activeThreadId fallback: the reader has only@@ -3861,6 +3884,13 @@ export function createOpenAIStreamAdapter(: liveRuntime;const { params } = runtime;await persistResolvedQueuedModel(params.checkpoint);+ const sandboxSessionId = await resolveSandboxSessionId(+ resolvedThreadId,+ readThreadRecord,+ );+ const toolConfirmationScopeId = resolvedThreadId+ ? `${sandboxSessionId || "_default"}:${resolvedThreadId}`+ : sandboxSessionId || "_default";const {supportsTools,toolsEnabled,@@ -3882,7 +3912,10 @@ export function createOpenAIStreamAdapter(// Project sources auto-scope: a chat inside a project retrieves from the// project's indexed sources even when the Docs pill is off. The probe is// cached, so this is one round trip per project every ~30s at most.- const ragProjectId = await resolveProjectId(resolvedThreadId);+ const ragProjectId = await resolveProjectId(+ resolvedThreadId,+ readThreadRecord,+ );const projectRagEnabled = ragProjectId? await projectHasSources(ragProjectId): false;@@ -4083,6 +4116,7 @@ export function createOpenAIStreamAdapter(resolvedThreadId,params.systemPrompt,params.systemVariables,+ readThreadRecord,);if (combinedSystemPrompt) {outboundMessages.unshift({@@ -4254,7 +4288,11 @@ export function createOpenAIStreamAdapter(}runtime.clearPendingAudio();}- const useAdapter = await resolveUseAdapter(resolvedThreadId, options);+ const useAdapter = await resolveUseAdapter(+ resolvedThreadId,+ options,+ readThreadRecord,+ );const threadKey = resolvedThreadId || "__default";// A first turn files its handles under "__default"; autosave then assigns a real id and@@ -4756,6 +4794,8 @@ export function createOpenAIStreamAdapter(let anthropicCodeExecContainerId: string | null = null;if (codeExecEnabledForThisTurn && resolvedThreadId) {try {+ // Container selection can change while this run waits for model loading,+ // so read it at payload construction instead of reusing run-start metadata.const thread = await getStoredChatThread(resolvedThreadId);openaiCodeExecContainerId =thread?.openaiCodeExecContainerId ?? null;diff --git a/studio/frontend/src/features/chat/utils/chat-history-storage.ts b/studio/frontend/src/features/chat/utils/chat-history-storage.tsindex 31e8c848f80..ddf66f88f6b 100644--- a/studio/frontend/src/features/chat/utils/chat-history-storage.ts+++ b/studio/frontend/src/features/chat/utils/chat-history-storage.ts@@ -567,28 +567,52 @@ async function importLegacyChatsIfNeeded(): Promise<void> {}}-export async function getStoredChatThread(+export type StoredChatThreadReadResult = {+ thread: ThreadRecord | undefined;+ cacheable: boolean;+};++export async function getStoredChatThreadReadResult(threadId: string,-): Promise<ThreadRecord | undefined> {+): Promise<StoredChatThreadReadResult> {// Incognito threads are never stored, so the lookup can only come back// empty -- short-circuit it instead of doing a Dexie read + backend GET.- if (isThreadIncognito(threadId)) return undefined;- if (isChatThreadDeleted(threadId)) return undefined;+ if (isThreadIncognito(threadId)) {+ return { thread: undefined, cacheable: true };+ }+ if (isChatThreadDeleted(threadId)) {+ return { thread: undefined, cacheable: true };+ }const legacyThread = await db.threads.get(threadId);let backendThread: ThreadRecord | null;try {backendThread = await getChatThread(threadId);} catch (error) {if (legacyThread && !isChatThreadDeleted(legacyThread.id)) {- return legacyThread;+ return { thread: legacyThread, cacheable: false };}throw error;}if (backendThread && !isChatThreadDeleted(backendThread.id)) {- return backfillLegacyThreadFields(backendThread, legacyThread);+ return {+ thread: await backfillLegacyThreadFields(backendThread, legacyThread),+ cacheable: true,+ };}- if (!legacyThread || isChatThreadDeleted(legacyThread.id)) return undefined;- return importLegacyThread(legacyThread).catch(() => legacyThread);+ if (!legacyThread || isChatThreadDeleted(legacyThread.id)) {+ return { thread: undefined, cacheable: true };+ }+ try {+ return { thread: await importLegacyThread(legacyThread), cacheable: true };+ } catch {+ return { thread: legacyThread, cacheable: false };+ }+}++export async function getStoredChatThread(+ threadId: string,+): Promise<ThreadRecord | undefined> {+ return (await getStoredChatThreadReadResult(threadId)).thread;}export async function ensureStoredChatThread(diff --git a/studio/frontend/src/features/chat/utils/retryable-shared-read.ts b/studio/frontend/src/features/chat/utils/retryable-shared-read.tsnew file mode 100644index 00000000000..b60e3628038--- /dev/null+++ b/studio/frontend/src/features/chat/utils/retryable-shared-read.ts@@ -0,0 +1,30 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export function createRetryableSharedRead<T>(+ read: () => Promise<T>,+ shouldCache: (value: T) => boolean = () => true,+): () => Promise<T> {+ let shared: Promise<T> | null = null;+ return () => {+ if (shared) {+ return shared;+ }+ const current = Promise.resolve()+ .then(read)+ .then((value) => {+ if (!shouldCache(value) && shared === current) {+ shared = null;+ }+ return value;+ })+ .catch((error) => {+ if (shared === current) {+ shared = null;+ }+ throw error;+ });+ shared = current;+ return current;+ };+}diff --git a/studio/frontend/tests/retryable-shared-read.test.ts b/studio/frontend/tests/retryable-shared-read.test.tsnew file mode 100644index 00000000000..990cb0b22f1--- /dev/null+++ b/studio/frontend/tests/retryable-shared-read.test.ts@@ -0,0 +1,96 @@+// 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 { createRetryableSharedRead } from "../src/features/chat/utils/retryable-shared-read.ts";++test("shares an in-flight read and its successful result", async () => {+ let calls = 0;+ const read = createRetryableSharedRead(async () => {+ calls += 1;+ await Promise.resolve();+ return "thread";+ });++ const first = read();+ const second = read();+ assert.equal(first, second);+ assert.deepEqual(await Promise.all([first, second]), ["thread", "thread"]);+ assert.equal(await read(), "thread");+ assert.equal(calls, 1);+});++test("retries after a failed read", async () => {+ let calls = 0;+ const read = createRetryableSharedRead(async () => {+ calls += 1;+ if (calls === 1) {+ throw new Error("temporary failure");+ }+ return "thread";+ });++ await assert.rejects(read(), /temporary failure/);+ assert.equal(await read(), "thread");+ assert.equal(calls, 2);+});++test("retries after a successful value marked as non-cacheable", async () => {+ let attempts = 0;+ const read = createRetryableSharedRead(+ async () => ++attempts,+ (value) => value > 1,+ );++ assert.equal(await read(), 1);+ assert.equal(await read(), 2);+ assert.equal(await read(), 2);+ assert.equal(attempts, 2);+});++test("every concurrent caller sees a rejection, from one underlying read", async () => {+ let calls = 0;+ const read = createRetryableSharedRead(async () => {+ calls += 1;+ await Promise.resolve();+ throw new Error("backend down");+ });++ const settled = await Promise.allSettled([read(), read(), read()]);+ assert.deepEqual(+ settled.map((r) => r.status),+ ["rejected", "rejected", "rejected"],+ );+ assert.equal(calls, 1);+});++test("a read that throws synchronously rejects rather than escaping", async () => {+ let calls = 0;+ const read = createRetryableSharedRead(() => {+ calls += 1;+ throw new Error("synchronous failure");+ });++ await assert.rejects(read(), /synchronous failure/);+ await assert.rejects(read(), /synchronous failure/);+ assert.equal(calls, 2);+});++test("an undefined record still counts as a cached value", async () => {+ // Incognito and deleted threads resolve to undefined; that is an answer, not+ // a miss, so it must not be re-read on every consumer.+ let calls = 0;+ const read = createRetryableSharedRead(+ async () => {+ calls += 1;+ return { thread: undefined, cacheable: true };+ },+ (result) => result.cacheable,+ );++ assert.equal((await read()).thread, undefined);+ assert.equal((await read()).thread, undefined);+ assert.equal(calls, 1);+});diff --git a/tests/studio/test_chat_thread_read_consolidation.py b/tests/studio/test_chat_thread_read_consolidation.pynew file mode 100644index 00000000000..afee83e527c--- /dev/null+++ b/tests/studio/test_chat_thread_read_consolidation.py@@ -0,0 +1,41 @@+# 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 pathlib import Path+++REPO = Path(__file__).resolve().parents[2]+ADAPTER = REPO / "studio/frontend/src/features/chat/api/chat-adapter.ts"+++def squash(text: str) -> str:+ """Drop whitespace so reformatting chat-adapter.ts cannot break these checks."""+ return "".join(text.split())+++def test_chat_run_reuses_one_thread_metadata_read() -> None:+ source = ADAPTER.read_text(encoding = "utf-8")+ run = squash(source[source.index("export function createOpenAIStreamAdapter(") :])++ assert run.count("getStoredChatThread(resolvedThreadId)") == 1+ assert run.count("getStoredChatThreadReadResult(resolvedThreadId)") == 1+ assert squash("const sharedThreadRecordRead = resolvedThreadId") in run+ assert squash("(result) => result.cacheable") in run+ assert "createRetryableSharedRead" in run+ assert squash("const thread = await getStoredChatThread(resolvedThreadId);") in run+ assert squash("getStoredChatThread(resolvedThreadId).catch(() => undefined)") not in run++ # The first shared read must sit after the model-ready wait, so a chat moved+ # to another project mid-load is still seen by the reads that follow.+ model_ready_boundary = run.index(squash("// Re-read store after auto-load / model-ready wait."))+ first_shared_read = run.index(squash("const sandboxSessionId = await resolveSandboxSessionId("))+ assert first_shared_read > model_ready_boundary++ # Prefixes, so a trailing comma or a one-line call both match.+ for call in (+ "resolveProjectId(resolvedThreadId,readThreadRecord",+ "resolveSandboxSessionId(resolvedThreadId,readThreadRecord",+ "resolveChatInstructions(resolvedThreadId,params.systemPrompt,params.systemVariables,readThreadRecord",+ "resolveUseAdapter(resolvedThreadId,options,readThreadRecord",+ ):+ assert call in run