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 re-uploading the whole chat while a reply streams (#15818)
Nilay30555d452b8e
diff --git a/studio/frontend/src/features/chat/api/chat-api.ts b/studio/frontend/src/features/chat/api/chat-api.tsindex c6770d74e09..9575103651e 100644--- a/studio/frontend/src/features/chat/api/chat-api.ts+++ b/studio/frontend/src/features/chat/api/chat-api.ts@@ -1428,19 +1428,15 @@ export async function saveChatMessage(const editQuery = options.allowGenerationEdit? "?allowGenerationEdit=true": "";- let response: Response;- try {- response = await authFetch(- `/api/chat/threads/${encodeURIComponent(message.threadId)}/messages/${encodeURIComponent(message.id)}${editQuery}`,- {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(message),- },- );- } finally {- forgetThreadReads([message.threadId]);- }+ const response = await threadWriteFetch(+ `/api/chat/threads/${encodeURIComponent(message.threadId)}/messages/${encodeURIComponent(message.id)}${editQuery}`,+ {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(message),+ },+ [message.threadId],+ );// Two failures share this status: a protected message, where the autosave must stop, and a// thread-id collision, which the caller must see. Only the header separates them.if (diff --git a/studio/frontend/src/features/chat/runtime-provider.tsx b/studio/frontend/src/features/chat/runtime-provider.tsxindex b6729c4e146..6b2daba46f5 100644--- a/studio/frontend/src/features/chat/runtime-provider.tsx+++ b/studio/frontend/src/features/chat/runtime-provider.tsx@@ -4111,6 +4111,8 @@ function ThreadBackendAutosave({const aui = useAui();const saveChainRef = useRef(Promise.resolve());const pendingFirstSavesRef = useRef(new Map<string, Promise<void>>());+ // Threads whose last whole-chat save failed: a reply-only checkpoint would leave its parent unsaved.+ const fullSaveDueRef = useRef(new Set<string>());// A ref: the save may resolve after the pane is hidden, so read at publish time.const backgroundedRef = useRef(backgrounded);backgroundedRef.current = backgrounded;@@ -4122,7 +4124,7 @@ function ThreadBackendAutosave({}, []);const saveThread = useCallback(- async (threadId: string): Promise<void> => {+ async (threadId: string, replyOnly = false): Promise<void> => {const runtime = aui.threads().__internal_getAssistantRuntime?.();if (!runtime) {return;@@ -4140,7 +4142,12 @@ function ThreadBackendAutosave({return;}await ensureStoredChatThread(remoteId);- await syncExportedRepositoryToBackend(remoteId, exported);+ const partial = replyOnly && !fullSaveDueRef.current.has(threadId);+ if (!partial) fullSaveDueRef.current.add(threadId);+ await syncExportedRepositoryToBackend(remoteId, exported, {+ replyOnly: partial,+ });+ if (!partial) fullSaveDueRef.current.delete(threadId);if (isChatThreadDeleted(remoteId)) {await deleteStoredChatThreads([remoteId]);return;@@ -4168,12 +4175,12 @@ function ThreadBackendAutosave({);const queueSave = useCallback(- (threadId: string): Promise<void> => {+ (threadId: string, replyOnly = false): Promise<void> => {const queued = saveChainRef.current.catch(() => {}).then(async () => {await pendingFirstSavesRef.current.get(threadId);- await saveThread(threadId);+ await saveThread(threadId, replyOnly);}).catch(reportAutosaveError);saveChainRef.current = queued;@@ -4230,7 +4237,7 @@ function ThreadBackendAutosave({(threadId) =>threadHasLiveGenerationRun(threadId)? Promise.resolve()- : queueSaveRef.current(threadId),+ : queueSaveRef.current(threadId, true),{isActive: (threadId) => isRunActiveRef.current(threadId),isBounded: (threadId) => threadHasDurableGenerationRun(threadId),diff --git a/studio/frontend/src/features/chat/utils/delete-thread-message.ts b/studio/frontend/src/features/chat/utils/delete-thread-message.tsindex cb09f979fe4..81b3cde3fde 100644--- a/studio/frontend/src/features/chat/utils/delete-thread-message.ts+++ b/studio/frontend/src/features/chat/utils/delete-thread-message.ts@@ -12,6 +12,7 @@ import { listChatMessages } from "../api/chat-api";import type { MessageRecord } from "../types";import {ensureStoredChatThread,+ saveStoredChatMessage,syncStoredChatMessages,} from "./chat-history-storage";import {@@ -99,8 +100,23 @@ async function withStoredResearchMessages(export async function syncExportedRepositoryToBackend(remoteId: string,exp: ExportedMessageRepository,- options: { pruneMissing?: boolean; deletedMessageIds?: string[] } = {},+ options: {+ pruneMissing?: boolean;+ deletedMessageIds?: string[];+ replyOnly?: boolean;+ } = {},): Promise<void> {+ const reply = options.replyOnly+ ? exp.messages.find(+ ({ message }) => message.id === exp.headId && message.role === "assistant",+ )+ : undefined;+ if (reply) {+ await saveStoredChatMessage(+ exportedItemToRecord(remoteId, reply.parentId, reply.message),+ );+ return;+ }// syncStoredChatMessages ensures the row itself.const records = exp.messages.map(({ message, parentId }) =>exportedItemToRecord(remoteId, parentId, message),diff --git a/studio/frontend/tests/autosave-checkpoint-reply.test.ts b/studio/frontend/tests/autosave-checkpoint-reply.test.tsnew file mode 100644index 00000000000..364dc3d6a0d--- /dev/null+++ b/studio/frontend/tests/autosave-checkpoint-reply.test.ts@@ -0,0 +1,128 @@+// 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 { MessageRepository } from "@assistant-ui/core/internal";+import * as researchSync from "../src/features/chat/utils/research-message-sync.ts";+import * as savedUsage from "../src/features/chat/utils/saved-context-usage.ts";+import { readSrc } from "./helpers/kit.ts";+import { loadWithStubs } from "./helpers/module-stubs.ts";++type Exported = {+ headId: string | null;+ messages: { parentId: string | null; message: Record<string, unknown> }[];+};++type Sync = (+ remoteId: string,+ exp: Exported,+ options?: { replyOnly?: boolean },+) => Promise<void>;++function harness() {+ const saved: Record<string, unknown>[] = [];+ const synced: Record<string, unknown>[][] = [];+ const module = loadWithStubs<{ syncExportedRepositoryToBackend: Sync }>(+ new URL("../src/features/chat/utils/delete-thread-message.ts", import.meta.url),+ {+ "@assistant-ui/core/internal": { MessageRepository },+ "../api/chat-api": { listChatMessages: async () => [] },+ "./chat-history-storage": {+ ensureStoredChatThread: async () => {},+ saveStoredChatMessage: async (record: Record<string, unknown>) => {+ saved.push(record);+ return record;+ },+ syncStoredChatMessages: async (_id: string, records: Record<string, unknown>[]) => {+ synced.push(records);+ return records;+ },+ },+ "./research-message-sync": researchSync,+ "./saved-context-usage": savedUsage,+ },+ );+ return { sync: module.syncExportedRepositoryToBackend, saved, synced };+}++const image = { type: "image", image: `data:image/png;base64,${"A".repeat(400_000)}` };++function chat(headRole: "user" | "assistant"): Exported {+ const messages: Exported["messages"] = [+ {+ parentId: null,+ message: {+ id: "u0",+ role: "user",+ content: [image, { type: "text", text: "what is this" }],+ createdAt: new Date(1000),+ },+ },+ {+ parentId: "u0",+ message: {+ id: "a0",+ role: "assistant",+ content: [{ type: "text", text: "a cat" }],+ createdAt: new Date(2000),+ },+ },+ {+ parentId: "a0",+ message: {+ id: "u1",+ role: "user",+ content: [{ type: "text", text: "and now?" }],+ createdAt: new Date(3000),+ },+ },+ ];+ if (headRole === "assistant") {+ messages.push({+ parentId: "u1",+ message: {+ id: "a1",+ role: "assistant",+ content: [{ type: "text", text: "still stream" }],+ createdAt: new Date(4000),+ },+ });+ }+ return { headId: headRole === "assistant" ? "a1" : "u1", messages };+}++test("a mid-run checkpoint saves only the reply being written, not the earlier image", async () => {+ const h = harness();+ await h.sync("remote-1", chat("assistant"), { replyOnly: true });+ assert.deepEqual(h.synced, []);+ assert.equal(h.saved.length, 1);+ assert.equal(h.saved[0].id, "a1");+ assert.equal(h.saved[0].parentId, "u1");+ assert.equal(h.saved[0].threadId, "remote-1");+ assert.deepEqual(h.saved[0].content, [{ type: "text", text: "still stream" }]);+ assert.ok(JSON.stringify(h.saved).length < 1_000);+});++test("a checkpoint with no reply yet still saves the whole thread", async () => {+ const h = harness();+ await h.sync("remote-1", chat("user"), { replyOnly: true });+ assert.deepEqual(h.saved, []);+ assert.deepEqual(h.synced[0].map((r) => r.id), ["u0", "a0", "u1"]);+});++test("a run's start and end saves still send the whole thread", async () => {+ const h = harness();+ await h.sync("remote-1", chat("assistant"));+ assert.deepEqual(h.saved, []);+ assert.deepEqual(h.synced[0].map((r) => r.id), ["u0", "a0", "u1", "a1"]);+});++test("a failed whole-chat save keeps later checkpoints whole until one lands", () => {+ const provider = readSrc("features/chat/runtime-provider.tsx");+ assert.match(+ provider,+ /const partial = replyOnly && !fullSaveDueRef\.current\.has\(threadId\);\s*if \(!partial\) fullSaveDueRef\.current\.add\(threadId\);\s*await syncExportedRepositoryToBackend\(remoteId, exported, \{\s*replyOnly: partial,\s*\}\);\s*if \(!partial\) fullSaveDueRef\.current\.delete\(threadId\);/,+ );+});diff --git a/studio/frontend/tests/chat-save-conflict-detail.test.ts b/studio/frontend/tests/chat-save-conflict-detail.test.tsindex c3490c65f92..4885b2d4363 100644--- a/studio/frontend/tests/chat-save-conflict-detail.test.ts+++ b/studio/frontend/tests/chat-save-conflict-detail.test.ts@@ -76,7 +76,9 @@ function harness(response: ReturnType<typeof jsonResponse>) {dismissCarveoutAdviceForModel: () => {},showCarveoutAdvice: () => {},},- "@/features/hub/lib/abort-signals": {},+ "@/features/hub/lib/abort-signals": {+ disposableTimeoutSignal: () => ({ signal: new AbortController().signal, dispose: () => {} }),+ },"@/features/hub/lib/hub-token-header": { hubTokenHeader: () => ({}) },"@/features/hub/lib/network": { isHuggingFaceOffline: () => false },"@/features/native-intents/api": { consumeNativePathToken: () => undefined },@@ -181,3 +183,9 @@ test("the manual-edit query parameter is still sent", async () => {await module.saveChatMessage(message, { allowGenerationEdit: true });assert.match(requests[0].url, /allowGenerationEdit=true/);});++test("the save is bounded, so a wedged request cannot stall the autosave chain", async () => {+ const { module, requests } = harness(jsonResponse(200, message));+ await module.saveChatMessage(message);+ assert.ok(requests[0].init?.signal instanceof AbortSignal);+});diff --git a/studio/frontend/tests/helpers/delete-thread-message-stub.mjs b/studio/frontend/tests/helpers/delete-thread-message-stub.mjsindex 9168a3d4d17..5b2720a9c09 100644--- a/studio/frontend/tests/helpers/delete-thread-message-stub.mjs+++ b/studio/frontend/tests/helpers/delete-thread-message-stub.mjs@@ -10,3 +10,4 @@ const unexpected = (name) => () => {export const listChatMessages = unexpected("listChatMessages");export const ensureStoredChatThread = unexpected("ensureStoredChatThread");export const syncStoredChatMessages = unexpected("syncStoredChatMessages");+export const saveStoredChatMessage = unexpected("saveStoredChatMessage");diff --git a/studio/frontend/tests/run-checkpoint-live-run.test.ts b/studio/frontend/tests/run-checkpoint-live-run.test.tsindex 3dde42348d9..1755aeb6da5 100644--- a/studio/frontend/tests/run-checkpoint-live-run.test.ts+++ b/studio/frontend/tests/run-checkpoint-live-run.test.ts@@ -43,7 +43,7 @@ test("checkpoints are skipped only while this tab streams the thread's durable rconst provider = readSrc("features/chat/runtime-provider.tsx");assert.match(provider,- /\(threadId\) =>\s*threadHasLiveGenerationRun\(threadId\)\s*\?\s*Promise\.resolve\(\)\s*:\s*queueSaveRef\.current\(threadId\),/,+ /\(threadId\) =>\s*threadHasLiveGenerationRun\(threadId\)\s*\?\s*Promise\.resolve\(\)\s*:\s*queueSaveRef\.current\(threadId, true\),/,);assert.match(provider,diff --git a/studio/frontend/tests/thread-read-sharing-source.test.ts b/studio/frontend/tests/thread-read-sharing-source.test.tsindex 873de9d4dd0..db708445c7b 100644--- a/studio/frontend/tests/thread-read-sharing-source.test.ts+++ b/studio/frontend/tests/thread-read-sharing-source.test.ts@@ -43,7 +43,7 @@ test("every thread write through chat-api drops the thread's in-flight read whenassert.match(slice(API, "export async function deleteChatThreads", "\n}"), /threadIds,\s*\);/);assert.match(slice(API, "export async function syncChatMessages", "\n}"), /\[threadId\],\s*\);/);assert.match(slice(API, "export async function clearBackendChats", "\n}"), /null,\s*\);/);- assert.match(slice(API, "export async function saveChatMessage", "\n}"), /forgetThreadReads\(\[message\.threadId\]\)/);+ assert.match(slice(API, "export async function saveChatMessage", "\n}"), /\[message\.threadId\],\s*\);/);assert.match(slice(API, "export async function forkChatThread", "\n}"), /forgetThreadReads\(\[threadId, args\.newThreadId\]\)/);assert.match(slice(API, "export async function deleteChatProject", "\n}"), /forgetThreadReads\(null\)/);});diff --git a/tests/studio/test_multi_chat_prompt_queue_contract.py b/tests/studio/test_multi_chat_prompt_queue_contract.pyindex 0891a164ada..bfb9d905990 100644--- a/tests/studio/test_multi_chat_prompt_queue_contract.py+++ b/tests/studio/test_multi_chat_prompt_queue_contract.py@@ -1067,7 +1067,7 @@ def test_a_backgrounded_pane_autosaves_without_naming_itself_active():# The save itself is ungated so a run outliving its view still lands on disk.for call in ("await ensureStoredChatThread(remoteId)",- "await syncExportedRepositoryToBackend(remoteId, exported)",+ "await syncExportedRepositoryToBackend(remoteId, exported, {",):assert call in autosave, f"{call} must still run while backgrounded"assert autosave.index(call) < guard_at, f"{call} must not sit behind the visibility guard"