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 long replies with escaped math streaming smoothly (#16490)
Nilayb87e219fbc23
diff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsxindex 40f67989b42..4661ce973ca 100644--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx@@ -35,7 +35,10 @@ import {} from "@/components/assistant-ui/message-derived";import { useMessagePartTextSafe } from "@/components/assistant-ui/stale-safe-scopes";import { copyToClipboard } from "@/lib/copy-to-clipboard";-import { normalizeEscapedInlineMath } from "@/lib/escaped-inline-math";+import {+ type SettledEscapedMath,+ normalizeEscapedInlineMath,+} from "@/lib/escaped-inline-math";import { preprocessLaTeX } from "@/lib/latex";import { withDataImageSupport } from "@/lib/markdown-data-images";import { downloadFile, isDownloadCancelled, urlToBlob } from "@/lib/native-files";@@ -1419,6 +1422,10 @@ function MarkdownTextRenderer({[messageTextKey],);const displayText = useCoalescedStreamingText(text, isStreaming, messageId);+ const [settledEscapedMath] = useState<SettledEscapedMath>(() => ({+ prefix: "",+ ranges: [],+ }));const processedText = useMemo(() =>stabilizeStreamingMarkdown(@@ -1437,12 +1444,20 @@ function MarkdownTextRenderer({),searchImages,),+ isStreaming ? settledEscapedMath : undefined,),isStreaming,),isStreaming,),- [displayText, isStreaming, messageTexts, precedingText, searchImages],+ [+ displayText,+ isStreaming,+ messageTexts,+ precedingText,+ searchImages,+ settledEscapedMath,+ ],);const incrementalCacheRef = useRef({messageId,diff --git a/studio/frontend/src/lib/escaped-inline-math.ts b/studio/frontend/src/lib/escaped-inline-math.tsindex 556cf8c01f9..cfc5a676bc8 100644--- a/studio/frontend/src/lib/escaped-inline-math.ts+++ b/studio/frontend/src/lib/escaped-inline-math.ts@@ -401,8 +401,12 @@ const escapedMathFromMarkdown: FromMarkdownExtension = {type MarkdownNode = {readonly type: string;readonly position?: {- readonly start: { readonly offset?: number };- readonly end: { readonly offset?: number };+ readonly start: {+ readonly line: number;+ readonly column: number;+ readonly offset?: number;+ };+ readonly end: { readonly line: number; readonly offset?: number };};readonly children?: readonly MarkdownNode[];};@@ -413,6 +417,11 @@ type EscapedMathRange = {readonly value: string;};+export type SettledEscapedMath = {+ prefix: string;+ ranges: readonly EscapedMathRange[];+};+function hasLikelyMathCloser(markdown: string, offset: number): boolean {const limit = Math.min(markdown.length, offset + MAX_BODY_LENGTH + 1);for (let index = offset + 1; index < limit; index += 1) {@@ -435,7 +444,32 @@ function hasLikelyMathCloser(markdown: string, offset: number): boolean {return false;}-function escapedMathRanges(markdown: string): EscapedMathRange[] {+function settledLength(children: readonly MarkdownNode[]): number {+ for (let index = children.length - 2; index > 0; index -= 1) {+ const start = children[index].position?.start;+ const previousEnd = children[index - 1].position?.end;+ if (+ start?.offset !== undefined &&+ previousEnd &&+ start.line - previousEnd.line > 1+ ) {+ return start.offset - start.column + 1;+ }+ }+ return 0;+}++function escapedMathRanges(+ fullMarkdown: string,+ settled?: SettledEscapedMath,+): readonly EscapedMathRange[] {+ const resumed = settled && fullMarkdown.startsWith(settled.prefix);+ const base = resumed ? settled.prefix.length : 0;+ const settledRanges = resumed ? settled.ranges : [];+ const markdown = fullMarkdown.slice(base);+ if (resumed && !mayHoldEscapedInlineMath(markdown)) {+ return settledRanges;+ }const masked = markdown.replace(CURRENCY_OPENER_RE, (opener, offset) =>hasLikelyMathCloser(markdown, offset) ? opener : MASKED_DOLLAR,);@@ -469,8 +503,8 @@ function escapedMathRanges(markdown: string): EscapedMathRange[] {!(openCodeTail && start >= openCodeTail.start && start < openCodeTail.end)) {ranges.push({- start,- end,+ start: base + start,+ end: base + end,value: markdown.slice(start + 2, end - 2).trim(),});}@@ -478,7 +512,14 @@ function escapedMathRanges(markdown: string): EscapedMathRange[] {pending.push(...node.children);}}- return ranges.sort((left, right) => left.start - right.start);+ ranges.sort((left, right) => left.start - right.start);+ const found = [...settledRanges, ...ranges];+ if (settled) {+ const length = base + settledLength(tree.children ?? []);+ settled.prefix = fullMarkdown.slice(0, length);+ settled.ranges = found.filter((range) => range.end <= length);+ }+ return found;}/** False only when no `\$` pair can tokenize as math; past PAIR_BUDGET pairs it defers to the parse. */@@ -525,12 +566,15 @@ function mayCloseEscapedMath(return false;}-/** Runs before currency and streaming repair. */-export function normalizeEscapedInlineMath(markdown: string): string {+/** Runs before currency and streaming repair. Pass `settled` only mid-stream: link definitions reach across blocks. */+export function normalizeEscapedInlineMath(+ markdown: string,+ settled?: SettledEscapedMath,+): string {if (!mayHoldEscapedInlineMath(markdown)) {return markdown;}- const ranges = escapedMathRanges(markdown);+ const ranges = escapedMathRanges(markdown, settled);if (ranges.length === 0) {return markdown;}diff --git a/studio/frontend/tests/escaped-inline-math.test.ts b/studio/frontend/tests/escaped-inline-math.test.tsindex be95c42a052..d6c4f0f1619 100644--- a/studio/frontend/tests/escaped-inline-math.test.ts+++ b/studio/frontend/tests/escaped-inline-math.test.ts@@ -9,6 +9,7 @@ import { renderToStaticMarkup } from "react-dom/server";import { Streamdown } from "streamdown";import { parseMarkdownIntoRenderableBlocks } from "../src/components/assistant-ui/streaming-render-schedule.ts";import {+ type SettledEscapedMath,looksLikeEscapedInlineMath,mayHoldEscapedInlineMath,normalizeEscapedInlineMath,@@ -317,3 +318,74 @@ test("escaped currency in a long streamed reply stays within the streaming budgeconst elapsed = performance.now() - started;assert.ok(elapsed < 500, `streaming took ${elapsed.toFixed(1)}ms`);});++test("real escaped math in a long streamed reply stays within the streaming budget", () => {+ const section =+ "## Derivation\n\nThe energy \\$E_k = \\frac{1}{2}mv^2\\$ grows, a [docs](https://example.com) link and `code`.\n\n- first \\$a + b\\$\n- second item\n\n```python\nprint(1)\n```\n\n";+ const reply = section.repeat(300);+ const settled: SettledEscapedMath = { prefix: "", ranges: [] };+ const started = performance.now();+ for (let end = 500; end <= reply.length; end += 500) {+ normalizeEscapedInlineMath(reply.slice(0, end), settled);+ }+ const elapsed = performance.now() - started;+ assert.ok(elapsed < 1500, `streaming took ${elapsed.toFixed(1)}ms`);+ assert.ok(settled.prefix.length > 0);+});++test("a streamed reply normalizes the same as the finished text at every length", () => {+ const reply = [+ String.raw`Intro \$x\$ costs $5 and \$20.`,+ "",+ "```python",+ String.raw`keep \$y\$ literal`,+ "",+ String.raw`and \$z\$ too`,+ "```",+ "",+ String.raw` indented \$a_1\$ paragraph`,+ "",+ String.raw`- list \$b\$`,+ "",+ String.raw` continued \$c\$`,+ "",+ String.raw`- next \$d\$`,+ "",+ "<pre>",+ "",+ String.raw`\$e\$ in html`,+ "",+ "</pre>",+ "",+ String.raw`Setext \$f\$`,+ "---",+ "",+ String.raw`> quote \$g\$`,+ "",+ String.raw`> second \$h\$`,+ "",+ " indented code \\$i\\$",+ "",+ " more code \\$j\\$",+ "",+ "| a | b |",+ "| - | - |",+ String.raw`| \$k\$ | 1 |`,+ "",+ String.raw`Open \(p \$l\$ \) then \`tick \$m\$`,+ "",+ String.raw`Last \$n\$ line`,+ ].join("\n");+ for (const source of [reply, reply.replaceAll("\n", "\r\n")]) {+ const settled: SettledEscapedMath = { prefix: "", ranges: [] };+ for (let end = 0; end <= source.length; end += 1) {+ const chunk = source.slice(0, end);+ assert.equal(+ normalizeEscapedInlineMath(chunk, settled),+ normalizeEscapedInlineMath(chunk),+ JSON.stringify(chunk.slice(-40)),+ );+ }+ assert.ok(settled.prefix.length > 0);+ }+});