Skip to content

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.

Studio: keep tagged edit text lossless on a no-op save (#17157)

DimitriChrysafis8f9987624567
diff --git a/studio/frontend/src/features/chat/utils/update-thread-message.ts b/studio/frontend/src/features/chat/utils/update-thread-message.ts
index 624cdc3d07c..1f1a4c7f974 100644
--- a/studio/frontend/src/features/chat/utils/update-thread-message.ts
+++ b/studio/frontend/src/features/chat/utils/update-thread-message.ts
@@ -51,23 +51,31 @@ type ThreadImportExport = {
type ContentPart = { type: "text" | "reasoning" | "tool"; text: string; slot?: number };
// Raw strings are prose without a marker; they must count as editable or slots misalign.
+// A typed part whose text is not a string cannot be edited: it joins the placeholders.
function isEditablePart(part: any): boolean {
- return typeof part === 'string' || part?.type === 'text' || part?.type === 'reasoning';
+ if (typeof part === 'string') return true;
+ if (part?.type !== 'text' && part?.type !== 'reasoning') return false;
+ const raw = part.text || part.content;
+ return raw == null || typeof raw === 'string';
}
function toolLabel(part: any): string {
const name = typeof part?.toolName === 'string' && part.toolName ? part.toolName : part?.type;
- const label = typeof name === 'string' ? name.replace(/[<>\n]+/g, ' ').trim() : "";
+ const label = typeof name === 'string' ? name.replace(/[<>\r\n]+/g, ' ').trim() : "";
return label || "tool";
}
// Escape marker-like prose so the parser does not read it as a placeholder.
function escapeMarkers(text: string): string {
- return text.replace(/<(\\*)TOOL (\d+: )/g, "<\\$1TOOL $2");
+ return text
+ .replace(/<(\/?)(\\*)THINK>/g, "<$1\\$2THINK>")
+ .replace(/<(\\*)TOOL (\d+: )/g, "<\\$1TOOL $2");
}
function unescapeMarkers(text: string): string {
- return text.replace(/<\\(\\*)TOOL (\d+: )/g, "<$1TOOL $2");
+ return text
+ .replace(/<(\/?)\\(\\*)THINK>/g, "<$1$2THINK>")
+ .replace(/<\\(\\*)TOOL (\d+: )/g, "<$1TOOL $2");
}
/**
@@ -116,7 +124,7 @@ function stripSeparators(text: string, afterTag: boolean, beforeTag: boolean): s
function parseTaggedTextToContent(text: string): ContentPart[] {
const parts: ContentPart[] = [];
// Requiring the slot number keeps prose and half-deleted markers from matching.
- const tagRegex = /<\/?THINK>|<TOOL (\d+): ([^<>\n]*)>/g;
+ const tagRegex = /<\/?THINK>|<TOOL (\d+): ([^<>\r\n]*)>/g;
let lastIndex = 0;
let match;
let sawTag = false;
@@ -174,19 +182,22 @@ export async function updateThreadMessage(args: {
const originalContent = m.message.content;
const finalContent: any[] = [];
- // Append to the previous text part so a save never multiplies parts.
+ // Merge into the previous text part this save made, so parts never multiply; restored cards keep their payload.
+ const ownTextParts = new Set<object>();
const pushText = (text: string) => {
const last = finalContent[finalContent.length - 1];
- if (last && last.type === 'text') {
+ if (last && ownTextParts.has(last)) {
last.text = `${last.text}\n\n${text}`;
return;
}
- finalContent.push({ type: 'text', text });
+ const part = { type: 'text', text };
+ ownTextParts.add(part);
+ finalContent.push(part);
};
if (Array.isArray(originalContent)) {
const nonEditableParts = originalContent.filter(
- (part: any) => !isEditablePart(part)
+ (part: any) => part && !isEditablePart(part)
);
const restored = new Set<number>();
@@ -218,16 +229,19 @@ export async function updateThreadMessage(args: {
const previousContent = m.message.content;
const previousTools = Array.isArray(previousContent)
- ? previousContent.filter((part) => !isEditablePart(part))
+ ? previousContent.filter((part) => part && !isEditablePart(part))
: [];
- const unchanged = extractTaggedText(finalContent) === extractTaggedText(previousContent)
- && JSON.stringify(finalContent.filter((part) => !isEditablePart(part))) === JSON.stringify(previousTools);
+ const previousText = extractTaggedText(previousContent);
+ const unchanged = extractTaggedText(finalContent) === previousText
+ && JSON.stringify(finalContent.filter((part) => part && !isEditablePart(part))) === JSON.stringify(previousTools);
+ // Not `unchanged`: tagged text trims reasoning, which would drop a whitespace-only reasoning edit.
+ const untouched = newText === previousText && Array.isArray(previousContent);
return {
...m,
message: {
...m.message,
- content: finalContent,
+ content: untouched ? previousContent : finalContent,
metadata:
unchanged
? withoutGeminiContinuationReplay(m.message.metadata)
diff --git a/studio/frontend/tests/edit-message-keeps-metadata.test.ts b/studio/frontend/tests/edit-message-keeps-metadata.test.ts
index 8c971450040..d843b773e07 100644
--- a/studio/frontend/tests/edit-message-keeps-metadata.test.ts
+++ b/studio/frontend/tests/edit-message-keeps-metadata.test.ts
@@ -182,6 +182,8 @@ test("saving a reply unchanged does not mark it revised, however the parts were
[{ type: "reasoning", text: "\nlet me think\n" }, { type: "text", text: "the reply" }],
[{ type: "text", text: "one" }, { type: "text", text: "two" }],
[{ type: "text", text: "the reply", status: { type: "complete" } }],
+ [{ type: "text", text: "the reply </THINK> verbatim" }],
+ [{ type: "reasoning", text: "a </THINK> inside" }, { type: "text", text: "the reply" }],
]) {
const h = harness();
const exported = thread(content);
diff --git a/studio/frontend/tests/edit-reply-keeps-tool-order.test.ts b/studio/frontend/tests/edit-reply-keeps-tool-order.test.ts
index fe030daacdb..7b75836097b 100644
--- a/studio/frontend/tests/edit-reply-keeps-tool-order.test.ts
+++ b/studio/frontend/tests/edit-reply-keeps-tool-order.test.ts
@@ -314,6 +314,7 @@ const shapes: any[][] = [
{ type: "text", text: "B" }],
[{ type: "text", text: "A" }, tool("1"), tool("2"), { type: "text", text: "B" }],
[{ type: "reasoning", text: "R" }],
+ [{ type: "reasoning", text: "R </THINK> tail" }, { type: "text", text: "A" }],
[tool("1")],
];
@@ -366,6 +367,193 @@ test("text that already contains an escaped marker round-trips too", async () =>
assert.deepEqual(await roundTrip(content), content);
});
+test("prose that spells the reasoning marker is not mistaken for one", async () => {
+ const content = [
+ { type: "text", text: "The tag is <THINK> on this surface." },
+ SEARCH,
+ { type: "text", text: "Done." },
+ ];
+
+ assert.deepEqual(await roundTrip(content), content);
+});
+
+test("a literal closing reasoning tag is not swallowed mid-sentence", async () => {
+ const content = [
+ { type: "text", text: "Write </THINK> to close the block." },
+ ];
+
+ assert.deepEqual(await roundTrip(content), content);
+});
+
+test("a closing tag inside reasoning keeps the rest of the thought", async () => {
+ const content = [
+ { type: "reasoning", text: "First half </THINK> second half." },
+ { type: "text", text: "The answer." },
+ ];
+
+ assert.deepEqual(await roundTrip(content), content);
+});
+
+test("an opening tag inside reasoning stays reasoning text", async () => {
+ const content = [
+ { type: "reasoning", text: "It emitted <THINK> literally." },
+ { type: "text", text: "The answer." },
+ ];
+
+ assert.deepEqual(await roundTrip(content), content);
+});
+
+test("text that already contains an escaped reasoning marker round-trips too", async () => {
+ const content = [
+ { type: "text", text: "Escape reads <\\THINK> in the box." },
+ ];
+
+ assert.deepEqual(await roundTrip(content), content);
+});
+
+test("a backslash before the slash is not an escape and stays put", async () => {
+ const content = [
+ { type: "text", text: "The form <\\/THINK> does nothing." },
+ ];
+
+ assert.deepEqual(await roundTrip(content), content);
+});
+
+test("a card marker spelled inside reasoning stays reasoning text", async () => {
+ const content = [
+ { type: "reasoning", text: "Ran <TOOL 1: web_search> for this." },
+ SEARCH,
+ { type: "text", text: "Done." },
+ ];
+
+ assert.deepEqual(await roundTrip(content), content);
+});
+
+test("a closing literal at the end of reasoning keeps the real close", async () => {
+ const content = [{ type: "reasoning", text: "It ended </THINK>" }];
+
+ assert.deepEqual(await roundTrip(content), content);
+});
+
+test("a literal open beside a real reasoning block stays separate", async () => {
+ const content = [
+ { type: "text", text: "Tags read <THINK> here." },
+ { type: "reasoning", text: "Actual thought." },
+ ];
+
+ assert.deepEqual(await roundTrip(content), content);
+});
+
+test("adjacent literal markers round-trip as one run of prose", async () => {
+ const content = [
+ { type: "text", text: "A pair </THINK><THINK> together." },
+ ];
+
+ assert.deepEqual(await roundTrip(content), content);
+});
+
+test("a raw string part that spells a marker is prose, not a tag", async () => {
+ const content = ["it says </THINK> plainly", SEARCH] as unknown as Part[];
+
+ const { result } = await save(content);
+
+ assert.equal(result, content);
+});
+
+test("a run of backslashes in front of a marker loses none", async () => {
+ const content = [
+ { type: "text", text: "Two backslashes <\\\\THINK> stay two." },
+ ];
+
+ assert.deepEqual(await roundTrip(content), content);
+});
+
+test("a part without text becomes a card instead of crashing the box", async () => {
+ const content = [
+ { type: "text", text: 5 },
+ SEARCH,
+ { type: "text", text: "Done." },
+ ];
+
+ assert.deepEqual(await roundTrip(content), content);
+});
+
+test("prose after a text card starts a new part instead of rewriting the card", async () => {
+ const content = [{ type: "text", text: 5 }];
+
+ const { result } = await save(content, "<TOOL 1: text>\n\nhello");
+
+ assert.deepEqual(result, [
+ { type: "text", text: 5 },
+ { type: "text", text: "hello" },
+ ]);
+ assert.equal(content[0].text, 5, "the stored part was mutated");
+});
+
+test("a card whose text field is an empty string still cannot absorb prose", async () => {
+ const content = [
+ { type: "text", text: "", content: { custom: 1 } },
+ { type: "text", text: "B" },
+ ];
+
+ const { result } = await save(content);
+
+ assert.deepEqual(result, content);
+ assert.equal(content[0].text, "", "the stored part was mutated");
+});
+
+test("a no-op save writes back the stored parts, fields and all", async () => {
+ const content = [
+ { type: "text", text: "the reply", status: { type: "complete" } },
+ SEARCH,
+ ];
+
+ const { result } = await save(content);
+
+ assert.deepEqual(result, content);
+ assert.equal(result[0], content[0], "the stored part was rebuilt");
+});
+
+test("indenting a reasoning line is saved, not mistaken for a no-op", async () => {
+ const content = [{ type: "reasoning", text: "print(1)" }, { type: "text", text: "A" }];
+
+ const { result } = await save(content, "<THINK>\n print(1)\n</THINK>\n\nA");
+
+ assert.deepEqual(result, [
+ { type: "reasoning", text: " print(1)" },
+ { type: "text", text: "A" },
+ ]);
+});
+
+test("a hole in the parts list does not shift a card's slot", async () => {
+ const content = [
+ { type: "text", text: "A" },
+ null,
+ SEARCH,
+ { type: "text", text: "B" },
+ ] as unknown as Part[];
+
+ const { result } = await save(content);
+
+ assert.equal(result, content);
+ assert.equal(result[2], SEARCH);
+});
+
+test("a tool name carrying a carriage return cannot kill its marker", async () => {
+ const odd = {
+ type: "tool-call",
+ toolCallId: "call-cr",
+ toolName: "read\rfile",
+ args: {},
+ result: {},
+ };
+ const content = [{ type: "text", text: "A" }, odd];
+ const { text, result } = await save(content);
+
+ assert.ok(!text.includes("\r"));
+ assert.deepEqual(result, content);
+});
+
test("an indented code block after a card keeps its indentation", async () => {
// Four leading spaces are a Markdown code block; trimming them would change rendering.
const content = [
@@ -381,11 +569,8 @@ test("a raw string part is prose, and does not consume a card's slot", async ()
const legacy = ["intro", SEARCH, { type: "text", text: "answer" }] as unknown as Part[];
const { result } = await save(legacy);
- assert.deepEqual(result, [
- { type: "text", text: "intro" },
- SEARCH,
- { type: "text", text: "answer" },
- ]);
+ assert.equal(result, legacy);
+ assert.equal(result[1], SEARCH);
});
test("a reply stored as one plain string round-trips, markers and all", async () => {