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 lone asterisks and backticks in finished chat replies (#14391)

Nilayacb31d909b21
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.ts
index 0b12a9a9c2a..8438eb91f34 100644
--- a/studio/frontend/scripts/check-bundle-budget.ts
+++ b/studio/frontend/scripts/check-bundle-budget.ts
@@ -328,8 +328,10 @@ export const BUDGET = {
// Browser store sync across windows (#14277) adds 545 B raw / 288 B transfer on top (6,872,325 B raw, 2,069,596 B
// transfer merged with main at 4962983b0, Node 24, 97 chunks). Raised to that plus the same margin.
// The runtime update card's skip and Undo (#14436) add 1,706 B raw / 424 B transfer against 444f63275c.
- transferBytes: 2_070_209,
- rawBytes: 6_874_191,
+ // Finished chat replies render lone markdown markers as written, cut ones keep the repair (#14391): +179 B raw /
+ // +52 B transfer measured against main (6,870,298 -> 6,870,477 B raw, one machine and build). Raised by that.
+ transferBytes: 2_070_261,
+ rawBytes: 6_874_370,
};
// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering the
diff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsx
index b1836ba2543..e35c0a8bf63 100644
--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx
+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx
@@ -8,6 +8,7 @@ import { filesOpenInBrowser, openFileInBrowser } from "@/features/browser";
import { useT } from "@/i18n";
import {
ArtifactCard,
+ readIncompleteInfo,
useChatProjectScope,
useChatRuntimeStore,
} from "@/features/chat";
@@ -128,6 +129,7 @@ import {
type DiscreteInputTracker,
} from "./discrete-input";
import {
+ FINISHED_TEXT_REMEND,
IncrementalMarkdownCache,
LITERAL_LINK_REMEND,
hasIncompleteLinkRepair,
@@ -1489,6 +1491,7 @@ type MarkdownTextRendererProps = {
messageId: string;
messageTextKey: string;
precedingText: string;
+ cut?: boolean;
searchImagesKey: string;
statusType: string;
text: string;
@@ -1500,6 +1503,7 @@ function MarkdownTextRenderer({
messageId,
messageTextKey,
precedingText,
+ cut = !isStreaming,
searchImagesKey,
statusType,
text,
@@ -1568,10 +1572,6 @@ function MarkdownTextRenderer({
const incrementalRender = isStreaming
? incrementalCache.update(processedText)
: null;
- const pendingLinkRepair = useMemo(
- () => !isStreaming && hasIncompleteLinkRepair(processedText),
- [isStreaming, processedText],
- );
const renderKey = markdownRenderKey(processedText);
const audioMatch = displayText.match(AUDIO_PLAYER_RE);
@@ -1586,10 +1586,16 @@ function MarkdownTextRenderer({
<SearchImagesContext.Provider value={searchImages}>
<div data-status={statusType} className="min-w-0 max-w-full">
<Streamdown
- key={`${messageId}:${incrementalCache.renderGeneration}:${renderKey}:${sandboxScopeKey}`}
+ key={`${messageId}:${incrementalCache.renderGeneration}:${renderKey}:${sandboxScopeKey}:${cut}`}
mode="streaming"
parseIncompleteMarkdown={!incrementalRender}
- remend={pendingLinkRepair ? LITERAL_LINK_REMEND : undefined}
+ remend={
+ !cut
+ ? FINISHED_TEXT_REMEND
+ : hasIncompleteLinkRepair(processedText)
+ ? LITERAL_LINK_REMEND
+ : undefined
+ }
parseMarkdownIntoBlocksFn={
incrementalRender?.parseMarkdownIntoBlocks ??
parseMarkdownIntoRenderableBlocks
@@ -1646,6 +1652,13 @@ const MarkdownTextImpl = () => {
? partsTextKey(message.parts)
: "[]",
);
+ // Every streamed yield carries the incomplete stamp and only a normal finish clears it.
+ const cut = useAuiState(
+ ({ message }) =>
+ message.status?.type !== "running" &&
+ !!readIncompleteInfo(message.metadata) &&
+ !message.parts.slice(partIndex + 1).some((part) => part.type === "text"),
+ );
return (
<MarkdownTextRenderer
@@ -1654,6 +1667,7 @@ const MarkdownTextImpl = () => {
messageId={messageId}
messageTextKey={messageTextKey}
precedingText={precedingText}
+ cut={cut}
searchImagesKey={searchImagesKey}
statusType={status.type}
text={text}
diff --git a/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts b/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts
index 18b28e8773c..15d137bf8ff 100644
--- a/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts
+++ b/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts
@@ -1030,6 +1030,16 @@ export function hasIncompleteLinkRepair(
// Skips only remend's link pass, whose placeholder renders as "[blocked]"; every other repair still runs.
export const LITERAL_LINK_REMEND = { links: false, images: false } as const;
+// A finished reply keeps remend's literal escapes (`- > 25`, `20~25`) but not its marker completions.
+export const FINISHED_TEXT_REMEND = {
+ ...LITERAL_LINK_REMEND,
+ bold: false,
+ boldItalic: false,
+ inlineCode: false,
+ italic: false,
+ strikethrough: false,
+} as const;
+
export function repairStreamingMarkdown(source: string): string {
const repaired = remend(source);
return hasIncompleteLinkRepair(source, repaired)
diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.ts
index dc91fdba2f2..20e9a911125 100644
--- a/studio/frontend/src/features/chat/index.ts
+++ b/studio/frontend/src/features/chat/index.ts
@@ -411,6 +411,7 @@ export { useForkInFlight } from "./utils/fork-in-flight";
export { showForkCreatedToast } from "./utils/fork-toast";
export { clearAllChats, countAllChats } from "./utils/clear-all-chats";
export { stopRecoveredRun } from "./utils/chat-generation-recovery";
+export { readIncompleteInfo } from "./utils/continuation";
export { offerToDeleteKeptSandboxes } from "./utils/offer-kept-sandbox-files";
export { pasteClipboardFiles } from "./utils/clipboard-files";
export {
diff --git a/studio/frontend/tests/markdown-cut-reply-repair.test.ts b/studio/frontend/tests/markdown-cut-reply-repair.test.ts
new file mode 100644
index 00000000000..553e660f10f
--- /dev/null
+++ b/studio/frontend/tests/markdown-cut-reply-repair.test.ts
@@ -0,0 +1,157 @@
+// 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 { execFile } from "node:child_process";
+import test from "node:test";
+import { promisify } from "node:util";
+
+const execFileAsync = promisify(execFile);
+
+const RENDER_TIMEOUT_MS = 120_000;
+
+const RENDER_MESSAGES = String.raw`
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import {
+ AssistantRuntimeProvider,
+ MessagePrimitive,
+ ThreadPrimitive,
+ useExternalStoreRuntime,
+} from "@assistant-ui/react";
+import { createServer } from "vite";
+
+const vite = await createServer({
+ appType: "custom",
+ logLevel: "silent",
+ optimizeDeps: { noDiscovery: true },
+ server: { middlewareMode: true, watch: null },
+});
+const { MarkdownText } = await vite.ssrLoadModule(
+ "/src/components/assistant-ui/markdown-text.tsx",
+);
+const Assistant = () =>
+ createElement(MessagePrimitive.Parts, {
+ components: { Text: MarkdownText, Reasoning: MarkdownText },
+ });
+function Harness({ message }) {
+ const runtime = useExternalStoreRuntime({
+ messages: [message],
+ convertMessage: (m) => m,
+ isRunning: false,
+ onNew: async () => {},
+ });
+ return createElement(
+ AssistantRuntimeProvider,
+ { runtime },
+ createElement(ThreadPrimitive.Messages, {
+ components: { AssistantMessage: Assistant },
+ }),
+ );
+}
+const messages = JSON.parse(process.env.MESSAGES);
+const html = messages.map((message) =>
+ renderToStaticMarkup(createElement(Harness, { message })),
+);
+process.stdout.write(JSON.stringify(html), () => process.exit(0));
+`;
+
+type Part = { type: string; [key: string]: unknown };
+
+const COMPLETE = { type: "complete", reason: "stop" };
+const SOURCE: Part = {
+ type: "source",
+ sourceType: "url",
+ id: "s1",
+ url: "https://example.com",
+ title: "Example",
+};
+
+function message(content: Part[], status: object, incomplete?: string): object {
+ return {
+ id: "m1",
+ role: "assistant",
+ content,
+ status,
+ metadata: incomplete
+ ? { custom: { incomplete: { reason: incomplete } } }
+ : {},
+ };
+}
+
+async function render(messages: object[]): Promise<string[]> {
+ const { stdout } = await execFileAsync(
+ process.execPath,
+ ["--input-type=module", "--eval", RENDER_MESSAGES],
+ {
+ cwd: process.cwd(),
+ env: { ...process.env, MESSAGES: JSON.stringify(messages) },
+ maxBuffer: 10_000_000,
+ timeout: RENDER_TIMEOUT_MS,
+ },
+ );
+ return JSON.parse(stdout) as string[];
+}
+
+test("finished replies render as written; cut replies are still repaired", async () => {
+ const text = (value: string): Part => ({ type: "text", text: value });
+ const reasoning = (value: string): Part => ({
+ type: "reasoning",
+ text: value,
+ });
+ const [
+ finished,
+ finishedBackTick,
+ finishedThinking,
+ lengthLive,
+ lengthReloaded,
+ lengthWithSource,
+ stopped,
+ stoppedThinking,
+ finishedComparison,
+ finishedRanges,
+ ] = await render([
+ message(
+ [text("Fields marked with an asterisk (*) are required.")],
+ COMPLETE,
+ ),
+ message([text("Press the ` key to open the console.")], COMPLETE),
+ message([reasoning("Match *.pyc files."), text("Done.")], COMPLETE),
+ message([text("Then **bol")], COMPLETE, "length"),
+ message(
+ [text("Then **bol")],
+ { type: "incomplete", reason: "length" },
+ "length",
+ ),
+ message([text("Then **bol"), SOURCE], COMPLETE, "length"),
+ message(
+ [text("call `foo(")],
+ { type: "incomplete", reason: "cancelled" },
+ "cancelled",
+ ),
+ message(
+ [reasoning("so **maybe")],
+ { type: "incomplete", reason: "cancelled" },
+ "cancelled",
+ ),
+ message([text("- >= 16 GB of RAM")], COMPLETE),
+ message([text("It takes 5~10 minutes and uses 20~30 GB.")], COMPLETE),
+ ]);
+
+ assert.match(finished, /asterisk \(\*\) are required\./);
+ assert.doesNotMatch(finished, /<em/);
+ assert.match(finishedBackTick, /Press the ` key to open the console\./);
+ assert.doesNotMatch(finishedBackTick, /inline-code/);
+ assert.match(finishedThinking, /Match \*\.pyc files\./);
+ assert.doesNotMatch(finishedThinking, /<em/);
+
+ for (const cut of [lengthLive, lengthReloaded, lengthWithSource]) {
+ assert.match(cut, /data-streamdown="strong"[^>]*>bol</);
+ }
+ assert.match(stopped, /data-streamdown="inline-code"/);
+ assert.match(stoppedThinking, /data-streamdown="strong"[^>]*>maybe</);
+ assert.match(finishedComparison, /&gt;= 16 GB of RAM/);
+ assert.doesNotMatch(finishedComparison, /blockquote/);
+ assert.match(finishedRanges, /5~10 minutes and uses 20~30 GB\./);
+ assert.doesNotMatch(finishedRanges, /<del|strikethrough/);
+});
diff --git a/studio/frontend/tests/markdown-streaming-scheduling.test.ts b/studio/frontend/tests/markdown-streaming-scheduling.test.ts
index ad7e0d26f5c..c4458551de9 100644
--- a/studio/frontend/tests/markdown-streaming-scheduling.test.ts
+++ b/studio/frontend/tests/markdown-streaming-scheduling.test.ts
@@ -180,7 +180,13 @@ test("streaming reparses only the active Markdown tail", () => {
);
assert.equal(
jsxAttribute(streamdown, "remend")?.initializer?.getText(source),
- "{pendingLinkRepair ? LITERAL_LINK_REMEND : undefined}",
+ "{\n" +
+ " !cut\n" +
+ " ? FINISHED_TEXT_REMEND\n" +
+ " : hasIncompleteLinkRepair(processedText)\n" +
+ " ? LITERAL_LINK_REMEND\n" +
+ " : undefined\n" +
+ " }",
);
assert.equal(
jsxAttribute(streamdown, "parseMarkdownIntoBlocksFn")?.initializer?.getText(
@@ -194,12 +200,12 @@ test("streaming reparses only the active Markdown tail", () => {
});
test("retained block and sandbox changes move Streamdown's render identity", () => {
- // Streamdown also ignores rehypePlugins changes when memoizing.
+ // Streamdown's memo also ignores rehypePlugins and remend.
const streamdown = findChatStreamdown();
assert.ok(streamdown, "chat <Streamdown> is missing");
assert.equal(
jsxAttribute(streamdown, "key")?.initializer?.getText(source),
- "{`${messageId}:${incrementalCache.renderGeneration}:${renderKey}:${sandboxScopeKey}`}",
+ "{`${messageId}:${incrementalCache.renderGeneration}:${renderKey}:${sandboxScopeKey}:${cut}`}",
);
assert.match(
source.getText(),
diff --git a/studio/frontend/tests/reasoning-source-render.test.ts b/studio/frontend/tests/reasoning-source-render.test.ts
index 59a6b986e15..7ee507d7c13 100644
--- a/studio/frontend/tests/reasoning-source-render.test.ts
+++ b/studio/frontend/tests/reasoning-source-render.test.ts
@@ -147,3 +147,61 @@ test("source Markdown suppresses a duplicate HTML card when render_html is prese
assert.match(stdout, /reasoning HTML fence/);
assert.doesNotMatch(stdout, /Open HTML preview preview/);
});
+
+const RENDER_BOUNDED_BOLD_TRACE = String.raw`
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import {
+ AssistantRuntimeProvider,
+ useLocalRuntime,
+} from "@assistant-ui/react";
+import { createServer } from "vite";
+
+const vite = await createServer({
+ appType: "custom",
+ logLevel: "silent",
+ optimizeDeps: { noDiscovery: true },
+ server: { middlewareMode: true, watch: null },
+});
+const { MarkdownTextSource } = await vite.ssrLoadModule(
+ "/src/components/assistant-ui/markdown-text.tsx",
+);
+const { ReasoningTranscriptIndex } = await vite.ssrLoadModule(
+ "/src/components/assistant-ui/reasoning-transcript-index.ts",
+);
+const text = "**" + "long thought ".repeat(3000).trimEnd() + "**";
+const rows = new ReasoningTranscriptIndex().update([text]);
+const adapter = { async *run() {} };
+function Harness({ row }) {
+ const runtime = useLocalRuntime(adapter);
+ return createElement(
+ AssistantRuntimeProvider,
+ { runtime },
+ createElement(MarkdownTextSource, {
+ messageId: "bounded-trace",
+ sourceText: row.renderText ?? row.text,
+ streaming: false,
+ }),
+ );
+}
+const html = rows.map((row) => renderToStaticMarkup(createElement(Harness, { row })));
+process.stdout.write(JSON.stringify(html), () => process.exit(0));
+`;
+
+test("a finished long trace keeps bold across its bounded fragments", async () => {
+ const { stdout } = await execFileAsync(
+ process.execPath,
+ ["--input-type=module", "--eval", RENDER_BOUNDED_BOLD_TRACE],
+ {
+ cwd: process.cwd(),
+ maxBuffer: 10_000_000,
+ timeout: RENDER_TIMEOUT_MS,
+ },
+ );
+ const fragments = JSON.parse(stdout) as string[];
+ assert.ok(fragments.length > 1);
+ for (const html of fragments) {
+ assert.match(html, /data-streamdown="strong"/);
+ assert.doesNotMatch(html, /\*\*/);
+ }
+});
diff --git a/studio/frontend/tests/remend-complete-markdown.test.ts b/studio/frontend/tests/remend-complete-markdown.test.ts
index d941a72424c..f933e5bcb89 100644
--- a/studio/frontend/tests/remend-complete-markdown.test.ts
+++ b/studio/frontend/tests/remend-complete-markdown.test.ts
@@ -12,22 +12,21 @@ import { renderToStaticMarkup } from "react-dom/server";
import remend from "remend";
import { Streamdown } from "streamdown";
import {
+ FINISHED_TEXT_REMEND,
LITERAL_LINK_REMEND,
hasIncompleteLinkRepair,
} from "../src/components/assistant-ui/streaming-render-schedule.ts";
/**
* WHY THIS FILE EXISTS. `remend` is the incomplete-markdown repair Streamdown runs over a message
- * before parsing it, and Unsloth runs it on every SETTLED body: `markdown-text.tsx` passes
- * `parseIncompleteMarkdown={!incrementalRender}` and `incrementalRender` is null exactly when the
- * message is not streaming. So this dependency decides what a finished message LOOKS like, not
- * only what a half-written one looks like, and a version bump is a rendering change.
+ * before parsing it, and Unsloth runs it on every settled body (marker completions only on a cut
+ * one), so a version bump is a rendering change.
*
* These are RUN, not scraped. Every assertion below is either a call into the resolved package or
* a render through Streamdown, so the file fails if the dependency is downgraded, if the override
* that forces one copy of it is dropped, or if the settled branch stops asking for the repair.
* That last one is checked by EVALUATING the `parseIncompleteMarkdown` expression that
- * `markdown-text.tsx` writes, at `incrementalRender === null`, and handing the result to a real
+ * `markdown-text.tsx` writes and handing the result to a real
* `<Streamdown>` -- not by asserting on the package in isolation and hoping the wiring agrees.
*
* WHAT THIS FILE DOES NOT COVER, so that the paragraph above is not read as wider than it is: the
@@ -110,13 +109,8 @@ const MARKDOWN_TEXT = new URL(
import.meta.url,
);
-/**
- * The `parseIncompleteMarkdown` a SETTLED body is rendered with, taken from the source and
- * evaluated rather than restated. `incrementalRender` is null exactly when the message is not
- * streaming, so evaluating the real expression in that state is the same question the component
- * answers on the settled path.
- */
-function settledParseIncompleteMarkdown(): boolean {
+/** The settled `parseIncompleteMarkdown`, evaluated from the source rather than restated. */
+function settledParseIncompleteMarkdown(cut: boolean): boolean {
const source = readFileSync(MARKDOWN_TEXT, "utf8");
const opened = source.indexOf("<Streamdown");
assert.notEqual(
@@ -135,26 +129,29 @@ function settledParseIncompleteMarkdown(): boolean {
);
const value: unknown = new Function(
"incrementalRender",
+ "cut",
`return (${expression});`,
- )(null);
+ )(null, cut);
assert.equal(
typeof value,
"boolean",
- `parseIncompleteMarkdown={${expression}} did not evaluate to a boolean at incrementalRender === null`,
+ `parseIncompleteMarkdown={${expression}} did not evaluate to a boolean for a settled part`,
);
return value as boolean;
}
-function renderSettled(markdown: string): string {
+function renderSettled(markdown: string, cut = true): string {
return renderToStaticMarkup(
createElement(
Streamdown,
{
mode: "streaming",
- parseIncompleteMarkdown: settledParseIncompleteMarkdown(),
- remend: hasIncompleteLinkRepair(markdown)
- ? LITERAL_LINK_REMEND
- : undefined,
+ parseIncompleteMarkdown: settledParseIncompleteMarkdown(cut),
+ remend: !cut
+ ? FINISHED_TEXT_REMEND
+ : hasIncompleteLinkRepair(markdown)
+ ? LITERAL_LINK_REMEND
+ : undefined,
},
markdown,
),
@@ -174,14 +171,7 @@ test("a settled unfinished link remains text without a blocked placeholder", ()
});
test("the settled render path runs the repair, not just the package", () => {
- // THE TESTS ABOVE CALL `remend` THEMSELVES, so all of them pass while the UI has the repair
- // switched off: mutating `parseIncompleteMarkdown={!incrementalRender}` to `{false}` in
- // `markdown-text.tsx` left this file green until this test existed. The only way to see the
- // difference is to render, and the only documents where the repair is VISIBLE are truncated
- // ones -- a complete document is by construction unchanged either way.
- //
- // A truncated body does reach the settled path: a cancelled or errored response settles
- // mid-construct and is then rendered with `incrementalRender === null` forever.
+ // The tests above call `remend` directly, so only a render shows the UI still repairs cut bodies.
for (const [truncated, repaired] of [
["this is **bol", 'data-streamdown="strong"'],
["call `foo(", 'data-streamdown="inline-code"'],
@@ -226,7 +216,7 @@ test("a complete document survives the settled render path unchanged", () => {
// the `\(` escapes.
const underscores = (text: string): number => (text.match(/_/g) ?? []).length;
for (const complete of COMPLETE_LATEX_DOCUMENTS) {
- const text = renderedText(renderSettled(complete));
+ const text = renderedText(renderSettled(complete, false));
assert.equal(
underscores(text),
underscores(complete),
@@ -236,6 +226,61 @@ test("a complete document survives the settled render path unchanged", () => {
}
});
+test("a finished reply keeps its lone markers as written", () => {
+ for (const reply of [
+ "Fields marked with an asterisk (*) are required.",
+ "Add *.pyc to your .gitignore file.",
+ "Pass options with **kwargs to forward them.",
+ "Press the ` key to open the console.",
+ "Delete files matching *.tmp first.\n\nThen restart the server.",
+ "Unpack it with ***args in Python 2 style.",
+ "Use ***args to unpack them.\n",
+ "It costs ~~ 5 dollars.",
+ "Load it as ~~fast mode in the config.",
+ ]) {
+ const html = renderSettled(reply, false);
+ assert.doesNotMatch(
+ html,
+ /data-streamdown="(emphasis|strong|inline-code|strikethrough)"|<em>|<strong>|<code|<del/,
+ `a finished ${JSON.stringify(reply)} was restyled: ${html}`,
+ );
+ assert.equal(
+ renderedText(html).replace(/\s+/g, ""),
+ reply.replace(/\s+/g, ""),
+ `a finished ${JSON.stringify(reply)} did not reach the reader as written`,
+ );
+ }
+});
+
+test("a cut reply still hides a dangling image", () => {
+ for (const cut of [
+ "see ![alt](https://example.com/very/long/partial",
+ "see ![alt](data:image/png;base64,iVBORw0KGgo",
+ ]) {
+ const text = renderedText(renderSettled(cut));
+ assert.doesNotMatch(
+ text,
+ /!\[|example\.com|base64/,
+ `a cut ${JSON.stringify(cut)} showed its partial image: ${text}`,
+ );
+ }
+});
+
+test("a finished reply keeps remend's literal escapes", () => {
+ const list = renderSettled("- >= 16 GB of RAM", false);
+ assert.match(list, /<li[^>]*>&gt;= 16 GB of RAM<\/li>/);
+ assert.doesNotMatch(list, /blockquote/);
+ const ranges = renderSettled(
+ "It takes 5~10 minutes and uses 20~30 GB.",
+ false,
+ );
+ assert.doesNotMatch(ranges, /<del|data-streamdown="strikethrough"/);
+ assert.equal(
+ renderedText(ranges),
+ "It takes 5~10 minutes and uses 20~30 GB.",
+ );
+});
+
const FRONTEND_ROOT = fileURLToPath(new URL("..", import.meta.url));
// Every `node_modules/**/remend` in the tree, in npm's own layout: a package's private copy lives