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 a reply's details when you edit its text (#10161)
Nilay4900286907fc
diff --git a/studio/backend/tests/test_chat_generation_runs.py b/studio/backend/tests/test_chat_generation_runs.pyindex cfe7faf282b..99f4ebe143f 100644--- a/studio/backend/tests/test_chat_generation_runs.py+++ b/studio/backend/tests/test_chat_generation_runs.py@@ -299,6 +299,66 @@ def test_settled_generation_response_can_be_explicitly_edited(chat_home):_assert_protected(authoritative)+def test_explicit_edit_keeps_display_metadata_but_not_the_run_claim(chat_home):+ """The shape the edit pencil sends: the details the reply is shown with, minus the run's claim.++ Passing the whole stored metadata back through is refused, because the record still says the+ run owns the turn and detaching it is the whole point of an explicit edit.+ """+ _create()+ token = runs_db.get_worker_token("run-1")+ assert runs_db.mark_running("run-1", token)+ streamed = studio_db.get_chat_message("thread-1", "assistant-1")+ streamed["metadata"].update(+ {+ "generationStatus": "running",+ "timing": {"tokensPerSecond": 42.5, "durationMs": 1200},+ "contextUsage": {"promptTokens": 900, "contextLength": 4096},+ }+ )+ studio_db.upsert_chat_message(streamed)+ assert runs_db.finish_run(+ "run-1", worker_token = token, status = "completed", finish_reason = "length"+ )+ run = runs_db.get_run("run-1", "alice")+ settled = studio_db.get_chat_message("thread-1", "assistant-1")+ settled["metadata"].update(+ {+ "generationSeq": run["lastEventSeq"],+ "generationStatus": "completed",+ "generationSettled": True,+ }+ )+ studio_db.upsert_chat_message(settled)+ authoritative = studio_db.get_chat_message("thread-1", "assistant-1")+ assert authoritative["metadata"]["incomplete"] == {"reason": "length"}++ edited = {**authoritative, "content": [{"type": "text", "text": "edited"}]}+ with pytest.raises(studio_db.ChatMessageProtectedError):+ studio_db.upsert_chat_message(edited, allow_generation_edit = True)++ edited["metadata"] = {+ key: value+ for key, value in authoritative["metadata"].items()+ if key+ not in {+ "serverManaged",+ "generationRunId",+ "generationSeq",+ "generationStatus",+ "generationSettled",+ }+ }+ saved = studio_db.upsert_chat_message(edited, allow_generation_edit = True)+ assert saved["content"] == [{"type": "text", "text": "edited"}]+ assert saved["metadata"] == {+ "incomplete": {"reason": "length"},+ "timing": {"tokensPerSecond": 42.5, "durationMs": 1200},+ "contextUsage": {"promptTokens": 900, "contextLength": 4096},+ }+ assert runs_db.get_run("run-1", "alice") is None++def test_batched_events_have_gapless_cursor_and_terminal_flush(chat_home):run, _created = _create()worker_token = runs_db.get_worker_token("run-1")diff --git a/studio/frontend/src/features/chat/utils/delete-thread-message.ts b/studio/frontend/src/features/chat/utils/delete-thread-message.tsindex 126f511f715..312cf543e95 100644--- a/studio/frontend/src/features/chat/utils/delete-thread-message.ts+++ b/studio/frontend/src/features/chat/utils/delete-thread-message.ts@@ -44,6 +44,12 @@ function snapshotContent(: [];}+// Epoch millis pass through; `getTime?.()` alone re-dated them to now and reordered the thread.+function toEpochMillis(value: unknown): number {+ if (value instanceof Date) return value.getTime();+ return typeof value === "number" && Number.isFinite(value) ? value : Date.now();+}+function snapshotAttachments(attachments: readonly CompleteAttachment[] | undefined,): readonly CompleteAttachment[] {@@ -67,7 +73,7 @@ export function exportedItemToRecord(content: content as Extract<ThreadMessage, { role: "user" }>["content"],...(attachments.length > 0 && { attachments }),...(custom && Object.keys(custom).length > 0 && { metadata: custom }),- createdAt: message.createdAt?.getTime?.() ?? Date.now(),+ createdAt: toEpochMillis(message.createdAt),};}const custom = (message.metadata?.custom ?? {}) as Record<string, unknown>;@@ -81,7 +87,7 @@ export function exportedItemToRecord({ role: "assistant" }>["content"],...(Object.keys(custom).length > 0 && { metadata: custom }),- createdAt: message.createdAt?.getTime?.() ?? Date.now(),+ createdAt: toEpochMillis(message.createdAt),};}diff --git a/studio/frontend/src/features/chat/utils/research-message-sync.ts b/studio/frontend/src/features/chat/utils/research-message-sync.tsindex fd9ec0f6174..a9d15da1e01 100644--- a/studio/frontend/src/features/chat/utils/research-message-sync.ts+++ b/studio/frontend/src/features/chat/utils/research-message-sync.ts@@ -4,7 +4,7 @@import type { MessageRecord } from "../types";/** Mirrors studio_db._RESEARCH_LINK_KEYS: what marks a message as owned by a research run. */-const RESEARCH_METADATA_KEYS = [+export const RESEARCH_METADATA_KEYS = ["researchRunId","researchRun","researchStatus",diff --git a/studio/frontend/src/features/chat/utils/update-thread-message.ts b/studio/frontend/src/features/chat/utils/update-thread-message.tsindex 0b6e029b226..7425115a47d 100644--- a/studio/frontend/src/features/chat/utils/update-thread-message.ts+++ b/studio/frontend/src/features/chat/utils/update-thread-message.ts@@ -1,5 +1,30 @@import type { ExportedMessageRepository, ThreadMessage } from "@assistant-ui/react";import { saveChatMessage } from "../api/chat-api";+import type { MessageRecord } from "../types";+import { exportedItemToRecord } from "./delete-thread-message";+import { RESEARCH_METADATA_KEYS } from "./research-message-sync";++// Mirrors studio_db._SERVER_MANAGED_LINK_KEYS. The backend detaches a finished run only when+// the edit drops its ownership claim; display fields such as timing and incomplete stay.+const SERVER_OWNED_METADATA_KEYS: readonly string[] = [+ ...RESEARCH_METADATA_KEYS,+ "generationRunId",+ "generationSeq",+ "generationStatus",+ "generationSettled",+];++function withoutServerOwnership(record: MessageRecord): MessageRecord {+ const metadata = record.metadata as Record<string, unknown> | undefined;+ if (!metadata) return record;+ const kept = Object.fromEntries(+ Object.entries(metadata).filter(+ ([key]) => !SERVER_OWNED_METADATA_KEYS.includes(key),+ ),+ );+ const { metadata: _owned, ...rest } = record;+ return Object.keys(kept).length > 0 ? { ...rest, metadata: kept } : rest;+}type ThreadImportExport = {export: () => ExportedMessageRepository;@@ -137,7 +162,6 @@ export async function updateThreadMessage(args: {}const { parentId: originalParentId } = targetMessageEntry;- const { createdAt: originalCreatedAt } = targetMessageEntry.message;const updatedMessages = currentExport.messages.map((m) => {if (m.message.id !== messageId) return m;@@ -201,18 +225,15 @@ export async function updateThreadMessage(args: {const originalExport = currentExport;thread.import({ ...currentExport, messages: updatedMessages });+ const editedMessage = updatedMessages.find(m => m.message.id === messageId)?.message;+// If it's NOT incognito, we attempt to save to the DB regardless of the ID.- if (remoteId && !isIncognito) {+ if (remoteId && !isIncognito && editedMessage) {try {await saveChatMessage(- {- id: messageId,- threadId: remoteId,- parentId: originalParentId,- role: "assistant",- content: (updatedMessages.find(m => m.message.id === messageId)?.message.content) || [],- createdAt: originalCreatedAt ? Number(originalCreatedAt) : Date.now(),- },+ withoutServerOwnership(+ exportedItemToRecord(remoteId, originalParentId, editedMessage),+ ),{ allowGenerationEdit: true },);} catch (e) {diff --git a/studio/frontend/tests/edit-message-keeps-metadata.test.ts b/studio/frontend/tests/edit-message-keeps-metadata.test.tsnew file mode 100644index 00000000000..8b21b704e0b--- /dev/null+++ b/studio/frontend/tests/edit-message-keeps-metadata.test.ts@@ -0,0 +1,248 @@+// 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 { loadWithStubs } from "./helpers/module-stubs.ts";++type Exported = {+ headId: string | null;+ messages: { parentId: string | null; message: Record<string, unknown> }[];+};++type Module = {+ extractTaggedText: (content: unknown) => string;+ updateThreadMessage: (args: {+ thread: { export: () => Exported; import: (data: Exported) => void };+ messageId: string;+ remoteId: string | undefined;+ newText: string;+ isIncognito: boolean;+ }) => Promise<unknown>;+};++const RECORD_MODULE = loadWithStubs<{+ exportedItemToRecord: (+ threadId: string,+ parentId: string | null,+ message: unknown,+ ) => Record<string, unknown>;+}>(+ 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 () => {},+ syncStoredChatMessages: async (+ _threadId: string,+ records: Record<string, unknown>[],+ ) => records,+ },+ "./research-message-sync": researchSync,+ },+);++const CUSTOM = {+ incomplete: { reason: "length" },+ contextUsage: { promptTokens: 900, contextLength: 4096 },+ timing: { tokensPerSecond: 42.5, durationMs: 1200 },+ contextTruncation: { dropped: 4, fits: true },+};++function harness() {+ const saved: Record<string, unknown>[] = [];+ const module = loadWithStubs<Module>(+ new URL(+ "../src/features/chat/utils/update-thread-message.ts",+ import.meta.url,+ ),+ {+ "../api/chat-api": {+ saveChatMessage: async (record: Record<string, unknown>) => {+ saved.push(record);+ return record;+ },+ },+ "./delete-thread-message": RECORD_MODULE,+ "./research-message-sync": researchSync,+ },+ );+ return { module, saved };+}++function thread(content: unknown[]): Exported {+ return {+ headId: "a0",+ messages: [+ {+ parentId: null,+ message: {+ id: "u0",+ role: "user",+ content: [{ type: "text", text: "hello" }],+ createdAt: new Date(1000),+ },+ },+ {+ parentId: "u0",+ message: {+ id: "a0",+ role: "assistant",+ content,+ createdAt: new Date(2000),+ metadata: { custom: CUSTOM },+ },+ },+ ],+ };+}++async function save(+ newText: string,+ content: unknown[] = [{ type: "text", text: "the original reply" }],+) {+ const h = harness();+ const exported = thread(content);+ await h.module.updateThreadMessage({+ thread: { export: () => exported, import: () => {} },+ messageId: "a0",+ remoteId: "remote-1",+ newText,+ isIncognito: false,+ });+ assert.equal(h.saved.length, 1, "the edit was never written");+ return h.saved[0];+}++test("an edited reply keeps the metadata the turn was stored with", async () => {+ const record = await save("an edited reply");++ assert.deepEqual(record.metadata, CUSTOM);+});++test("the edit still rewrites the content and its identity", async () => {+ const record = await save("an edited reply");++ assert.equal(record.id, "a0");+ assert.equal(record.threadId, "remote-1");+ assert.equal(record.parentId, "u0");+ assert.equal(record.role, "assistant");+ assert.equal(record.createdAt, 2000);+ assert.deepEqual(record.content, [{ type: "text", text: "an edited reply" }]);+});++test("a reply with no metadata of its own writes none", async () => {+ const h = harness();+ const exported = thread([{ type: "text", text: "hi" }]);+ const target = exported.messages[1].message;+ target.metadata = { custom: {} };++ await h.module.updateThreadMessage({+ thread: { export: () => exported, import: () => {} },+ messageId: "a0",+ remoteId: "remote-1",+ newText: "edited",+ isIncognito: false,+ });++ assert.equal("metadata" in h.saved[0], false);+});++test("an incognito edit is never written at all", async () => {+ const h = harness();+ const exported = thread([{ type: "text", text: "hi" }]);++ await h.module.updateThreadMessage({+ thread: { export: () => exported, import: () => {} },+ messageId: "a0",+ remoteId: "remote-1",+ newText: "edited",+ isIncognito: true,+ });++ assert.equal(h.saved.length, 0);+});++test("the turn keeps its timestamp when the export carries epoch millis", async () => {+ // Re-dating the turn to now would reorder the thread.+ const h = harness();+ const exported = thread([{ type: "text", text: "hi" }]);+ (exported.messages[1].message as Record<string, unknown>).createdAt = 2000;++ await h.module.updateThreadMessage({+ thread: { export: () => exported, import: () => {} },+ messageId: "a0",+ remoteId: "remote-1",+ newText: "edited",+ isIncognito: false,+ });++ assert.equal(h.saved[0].createdAt, 2000);+});++// What a generated reply carries on `metadata.custom` after a reload. Sent back with an edit,+// the backend refuses to detach the run and answers 409.+const GENERATION_OWNERSHIP = {+ serverManaged: true,+ generationRunId: "run-1",+ generationSeq: 3,+ generationStatus: "completed",+ generationSettled: true,+};++async function saveOwnedReply(custom: Record<string, unknown>) {+ const h = harness();+ const exported = thread([{ type: "text", text: "the original reply" }]);+ exported.messages[1].message.metadata = { custom };++ await h.module.updateThreadMessage({+ thread: { export: () => exported, import: () => {} },+ messageId: "a0",+ remoteId: "remote-1",+ newText: "an edited reply",+ isIncognito: false,+ });++ assert.equal(h.saved.length, 1, "the edit was never written");+ return h.saved[0];+}++test("editing a generated reply drops the run's claim on the turn", async () => {+ const record = await saveOwnedReply({ ...CUSTOM, ...GENERATION_OWNERSHIP });++ assert.deepEqual(record.metadata, CUSTOM);+ assert.deepEqual(+ Object.keys(GENERATION_OWNERSHIP).filter(+ (key) => key in (record.metadata as Record<string, unknown>),+ ),+ [],+ );+ assert.deepEqual(record.content, [{ type: "text", text: "an edited reply" }]);+});++test("the strip covers the backend's whole server-managed key set", async () => {+ // Parity only: research reports have no pencil and the backend still refuses to edit them.+ const record = await saveOwnedReply({+ ...CUSTOM,+ serverManaged: true,+ researchRunId: "research-1",+ researchStatus: "completed",+ researchPlanRevision: 2,+ researchRun: { id: "research-1" },+ });++ assert.deepEqual(record.metadata, CUSTOM);+});++test("a reply whose only metadata was the run's claim writes none", async () => {+ const record = await saveOwnedReply({ ...GENERATION_OWNERSHIP });++ assert.equal("metadata" in record, false);+});