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: render escaped inline math in lists (#9796)

Lee Jacksone584ffc49f9e
diff --git a/studio/frontend/package-lock.json b/studio/frontend/package-lock.json
index 83441d45c16..e03b2e6ce76 100644
--- a/studio/frontend/package-lock.json
+++ b/studio/frontend/package-lock.json
@@ -58,6 +58,7 @@
"mdast-util-math": "3.0.0",
"micromark-extension-gfm": "3.0.0",
"micromark-extension-math": "3.1.0",
+ "micromark-util-types": "2.0.2",
"motion": "^12.34.0",
"node-forge": "^1.4.0",
"radix-ui": "^1.4.3",
@@ -76,6 +77,7 @@
"tailwindcss": "^4.1.18",
"tw-animate-css": "^1.4.0",
"tw-shimmer": "^0.4.6",
+ "unified": "11.0.5",
"unpdf": "^1.4.0",
"zustand": "^5.0.11"
},
diff --git a/studio/frontend/package.json b/studio/frontend/package.json
index c4093b8707e..973dac10db5 100644
--- a/studio/frontend/package.json
+++ b/studio/frontend/package.json
@@ -72,6 +72,7 @@
"mdast-util-math": "3.0.0",
"micromark-extension-gfm": "3.0.0",
"micromark-extension-math": "3.1.0",
+ "micromark-util-types": "2.0.2",
"motion": "^12.34.0",
"node-forge": "^1.4.0",
"radix-ui": "^1.4.3",
@@ -90,6 +91,7 @@
"tailwindcss": "^4.1.18",
"tw-animate-css": "^1.4.0",
"tw-shimmer": "^0.4.6",
+ "unified": "11.0.5",
"unpdf": "^1.4.0",
"zustand": "^5.0.11"
},
diff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsx
index 40ff39f1f74..fe94afbe58b 100644
--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx
+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx
@@ -24,6 +24,7 @@ import {
searchImagesSignature,
} from "@/features/chat/search-images/search-images";
import { copyToClipboard } from "@/lib/copy-to-clipboard";
+import { normalizeEscapedInlineMath } from "@/lib/escaped-inline-math";
import { preprocessLaTeX } from "@/lib/latex";
import { downloadFile, isDownloadCancelled } from "@/lib/native-files";
import { openLink } from "@/lib/open-link";
@@ -78,6 +79,8 @@ import { unslothDarkTheme, unslothLightTheme } from "./code-themes";
import { stabilizeStreamingMarkdown } from "./streaming-markdown";
import {
IncrementalMarkdownCache,
+ markdownRenderKey,
+ parseMarkdownIntoRenderableBlocks,
withoutStreamdownAnimationPlugin,
} from "./streaming-render-schedule";
@@ -746,19 +749,21 @@ const MarkdownTextImpl = () => {
() =>
stabilizeStreamingMarkdown(
preprocessLaTeX(
- rewriteSearchImageTokens(
- placeSubjectImages(
- // No images means nothing to hold back, not even a trailing `[`.
- holdBackPartialSearchImageToken(
- displayText,
- isStreaming && searchImages.size > 0,
+ normalizeEscapedInlineMath(
+ rewriteSearchImageTokens(
+ placeSubjectImages(
+ // no images means nothing to hold back, including a trailing bracket.
+ holdBackPartialSearchImageToken(
+ displayText,
+ isStreaming && searchImages.size > 0,
+ ),
+ searchImages,
+ isStreaming,
+ precedingText,
+ messageTexts,
),
searchImages,
- isStreaming,
- precedingText,
- messageTexts,
),
- searchImages,
),
),
isStreaming,
@@ -779,6 +784,7 @@ const MarkdownTextImpl = () => {
const incrementalRender = isStreaming
? incrementalCache.update(processedText)
: null;
+ const renderKey = markdownRenderKey(processedText);
const audioMatch = displayText.match(AUDIO_PLAYER_RE);
if (audioMatch) {
@@ -792,10 +798,13 @@ const MarkdownTextImpl = () => {
<SearchImagesContext.Provider value={searchImages}>
<div data-status={status.type} className="min-w-0 max-w-full">
<Streamdown
- key={`${messageId}:${incrementalCache.renderGeneration}`}
+ key={`${messageId}:${incrementalCache.renderGeneration}:${renderKey}`}
mode="streaming"
parseIncompleteMarkdown={!incrementalRender}
- parseMarkdownIntoBlocksFn={incrementalRender?.parseMarkdownIntoBlocks}
+ parseMarkdownIntoBlocksFn={
+ incrementalRender?.parseMarkdownIntoBlocks ??
+ parseMarkdownIntoRenderableBlocks
+ }
isAnimating={isStreaming}
animated={STREAMDOWN_IMMEDIATE_UPDATES}
plugins={STREAMDOWN_PLUGINS}
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 315397d21bc..9da1a4c33eb 100644
--- a/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts
+++ b/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts
@@ -69,10 +69,36 @@ const INLINE_LATEX_CONTEXT = "\\(\n\n";
const FOOTNOTE_REFERENCE_RE = /\[\^[\w-]{1,200}\](?!:)/;
const FOOTNOTE_DEFINITION_RE = /\[\^[\w-]{1,200}\]:/;
const LINK_DEFINITION_RE = /\[(?:\\.|[^\]\n\\]){1,200}\]:/;
+const LINK_REFERENCE_RE =
+ /!?\[(?:\\.|[^\]\n\\]){1,200}\]\[(?:\\.|[^\]\n\\]){0,200}\]/;
const FENCED_CODE_BLOCK_RE = /^ {0,3}(?:```|~~~)/;
const WORD_CHARACTER_RE = /[\p{L}\p{N}_]/u;
const HTML_TAG_START_RE = /[a-zA-Z/]/;
+function hasGlobalLinkReference(markdown: string): boolean {
+ return LINK_REFERENCE_RE.test(markdown) && LINK_DEFINITION_RE.test(markdown);
+}
+
+export function markdownRenderScope(markdown: string): "blocks" | "document" {
+ return hasGlobalLinkReference(markdown) ? "document" : "blocks";
+}
+
+export function markdownRenderKey(markdown: string): string {
+ if (markdownRenderScope(markdown) === "blocks") {
+ return "blocks";
+ }
+ return `document:${markdown
+ .split("\n")
+ .filter((line) => LINK_DEFINITION_RE.test(line))
+ .join("\n")}`;
+}
+
+export function parseMarkdownIntoRenderableBlocks(markdown: string): string[] {
+ return markdownRenderScope(markdown) === "document"
+ ? [markdown]
+ : parseMarkdownIntoBlocks(markdown);
+}
+
// Where remend believes the emphasis scan sits with respect to math.
//
// remend 1.3.0 kept two booleans here, one for `$...$` and one for `$$...$$`,
@@ -1155,7 +1181,7 @@ export class IncrementalMarkdownCache {
readonly parseMarkdownIntoBlocks = (markdown: string): string[] => [
...this.committedBlocks,
- ...parseMarkdownIntoBlocks(markdown),
+ ...parseMarkdownIntoRenderableBlocks(markdown),
];
// Streamdown memoises the whole component on the Markdown string and ignores
@@ -1303,6 +1329,7 @@ export class IncrementalMarkdownCache {
// `"para\r"`, nothing is ever committed, and the whole reply re-repairs and
// re-lexes on every frame. Normalise first so both sides speak LF.
const markdown = normalizeLineEndings(rawMarkdown);
+ const globalLinkReference = markdownRenderScope(markdown) === "document";
// Tokens arrive faster than frames, so the coalescer hands the same text to
// several renders. Nothing about the result can differ, and repeating the
@@ -1324,10 +1351,10 @@ export class IncrementalMarkdownCache {
const repaired =
this.repairOpenFence() ?? repairTail(this.tail, this.context);
- // Streamdown deliberately turns a repaired document containing footnotes
- // into one block so definitions can resolve references anywhere in the
- // document. Such a construct is globally scoped and cannot retain a prefix.
+ // globally scoped definitions must stay in the same rendered document as
+ // their uses, so neither construct can retain an independently parsed prefix.
if (
+ globalLinkReference ||
FOOTNOTE_REFERENCE_RE.test(repaired) ||
FOOTNOTE_DEFINITION_RE.test(repaired)
) {
diff --git a/studio/frontend/src/lib/escaped-inline-math.ts b/studio/frontend/src/lib/escaped-inline-math.ts
new file mode 100644
index 00000000000..7186e33b87c
--- /dev/null
+++ b/studio/frontend/src/lib/escaped-inline-math.ts
@@ -0,0 +1,511 @@
+// 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 {
+ type CompileContext,
+ type Extension as FromMarkdownExtension,
+ fromMarkdown,
+} from "mdast-util-from-markdown";
+import { gfmFromMarkdown } from "mdast-util-gfm";
+import { type InlineMath, mathFromMarkdown } from "mdast-util-math";
+import { gfm } from "micromark-extension-gfm";
+import { math } from "micromark-extension-math";
+import type {
+ Construct,
+ Extension as MicromarkExtension,
+ State,
+ Token,
+ TokenizeContext,
+ Tokenizer,
+} from "micromark-util-types";
+import { openCodeSpanTail } from "./markdown-code-spans.ts";
+
+declare module "micromark-util-types" {
+ interface TokenTypeMap {
+ escapedMathText: "escapedMathText";
+ escapedMathTextData: "escapedMathTextData";
+ escapedMathTextSequence: "escapedMathTextSequence";
+ }
+}
+
+const BACKSLASH = 92;
+const DOLLAR = 36;
+const MAX_BODY_LENGTH = 200;
+const LINE_ENDINGS = new Set([-5, -4, -3]);
+
+const TOKEN = "escapedMathText";
+const SEQUENCE_TOKEN = "escapedMathTextSequence";
+const DATA_TOKEN = "escapedMathTextData";
+
+const STRONG_MATH_RE = /[\\^_{}]/;
+const SINGLE_VARIABLE_RE = /^[a-zA-Z]$/;
+const SIMPLE_OPERAND = String.raw`(?:\d+(?:,\d{3})*(?:\.\d+)?|[a-zA-Z])`;
+const SIMPLE_EXPRESSION_RE = new RegExp(
+ String.raw`^${SIMPLE_OPERAND}(?:\s*[=+\-<>/*]\s*${SIMPLE_OPERAND})+$`,
+);
+const SIMPLE_FUNCTION_RE = /^[a-zA-Z]\([a-zA-Z0-9]\)$/;
+const COMMAND_RE = /^[a-zA-Z]+/;
+const MARKDOWN_INLINE_BOUNDARY_RE =
+ /`|!?\[[^\]\n]*\](?:\(|\[[^\]\n]*\])|<\/?[a-zA-Z][^>\n]*>/;
+const HTML_LITERAL_TAG_START_RE = /^<\/?(code|pre|textarea)(?=[\s/>])/i;
+const CURRENCY_OPENER_RE =
+ /(?<![\\$])\$(?!\$)(?=\d+(?:,\d{3})*(?:\.\d+)?[KMBkmb]?(?:\s|$|[^a-zA-Z\d]))/g;
+const DIGIT_RE = /\d/;
+const MASKED_DOLLAR = "$";
+const TEXT_COMMANDS = new Set([
+ "emph",
+ "hbox",
+ "mbox",
+ "operatorname",
+ "text",
+ "textbf",
+ "textit",
+ "textmd",
+ "textnormal",
+ "textrm",
+ "textsc",
+ "textsf",
+ "textsl",
+ "texttt",
+ "textup",
+]);
+const htmlLiteralStates = new WeakMap<
+ TokenizeContext,
+ { eventIndex: number; openTags: string[] }
+>();
+type LatexBracketState = { eventIndex: number; openDelimiters: string[] };
+const latexBracketStates = new WeakMap<TokenizeContext, LatexBracketState>();
+const escapedMathNodes = new WeakSet<object>();
+
+function isInHtmlLiteral(context: TokenizeContext): boolean {
+ let state = htmlLiteralStates.get(context);
+ if (!state || state.eventIndex > context.events.length) {
+ state = { eventIndex: 0, openTags: [] };
+ }
+ for (; state.eventIndex < context.events.length; state.eventIndex += 1) {
+ const [phase, token] = context.events[state.eventIndex];
+ if (phase !== "exit" || token.type !== "htmlText") {
+ continue;
+ }
+ const source = context.sliceSerialize(token);
+ const match = HTML_LITERAL_TAG_START_RE.exec(source);
+ if (!match) {
+ continue;
+ }
+ const name = match[1].toLowerCase();
+ if (source.startsWith("</")) {
+ const opening = state.openTags.lastIndexOf(name);
+ if (opening >= 0) {
+ state.openTags.length = opening;
+ }
+ } else if (!source.endsWith("/>")) {
+ state.openTags.push(name);
+ }
+ }
+ htmlLiteralStates.set(context, state);
+ return state.openTags.length > 0;
+}
+
+function updateLatexBracketState(
+ state: LatexBracketState,
+ source: string,
+): void {
+ if (source === "\\(" || source === "\\[") {
+ state.openDelimiters.push(source[1]);
+ return;
+ }
+ if (source === "\\)" || source === "\\]") {
+ const opening = state.openDelimiters.lastIndexOf(
+ source === "\\)" ? "(" : "[",
+ );
+ if (opening >= 0) {
+ state.openDelimiters.length = opening;
+ }
+ }
+}
+
+function isInLatexBracketMath(context: TokenizeContext): boolean {
+ let state = latexBracketStates.get(context);
+ if (!state || state.eventIndex > context.events.length) {
+ state = { eventIndex: 0, openDelimiters: [] };
+ }
+ for (; state.eventIndex < context.events.length; state.eventIndex += 1) {
+ const [phase, token] = context.events[state.eventIndex];
+ if (phase === "exit" && token.type === "characterEscape") {
+ updateLatexBracketState(state, context.sliceSerialize(token));
+ }
+ }
+ latexBracketStates.set(context, state);
+ return state.openDelimiters.length > 0;
+}
+
+/** deliberately conservative: ambiguous prose remains literal. */
+export function looksLikeEscapedInlineMath(body: string): boolean {
+ const value = body.trim();
+ if (!value || value.length > MAX_BODY_LENGTH) {
+ return false;
+ }
+ return (
+ STRONG_MATH_RE.test(value) ||
+ SINGLE_VARIABLE_RE.test(value) ||
+ SIMPLE_EXPRESSION_RE.test(value) ||
+ SIMPLE_FUNCTION_RE.test(value)
+ );
+}
+
+function appendCode(value: string, code: number): string {
+ if (code === -2) {
+ return `${value}\t`;
+ }
+ if (code === -1) {
+ return value;
+ }
+ return `${value}${String.fromCodePoint(code)}`;
+}
+
+function braceBalance(value: string): number {
+ let depth = 0;
+ let escaped = false;
+ for (const character of value) {
+ if (escaped) {
+ escaped = false;
+ continue;
+ }
+ if (character === "\\") {
+ escaped = true;
+ } else if (character === "{") {
+ depth += 1;
+ } else if (character === "}") {
+ if (depth === 0) {
+ return -1;
+ }
+ depth -= 1;
+ }
+ }
+ return depth;
+}
+
+type MathBodyProtection = {
+ readonly parts: string[];
+ readonly textGroups: boolean[];
+ textCommandPending: boolean;
+};
+
+function consumeMathCommand(
+ value: string,
+ index: number,
+ state: MathBodyProtection,
+): number {
+ if (value[index + 1] === "$") {
+ state.parts.push(String.raw`{\char"24}`);
+ state.textCommandPending = false;
+ return index + 1;
+ }
+ const command = COMMAND_RE.exec(value.slice(index + 1))?.[0];
+ if (command) {
+ state.parts.push(`\\${command}`);
+ state.textCommandPending = TEXT_COMMANDS.has(command);
+ return index + command.length;
+ }
+ state.parts.push(value.slice(index, index + 2));
+ state.textCommandPending = false;
+ return index + 1;
+}
+
+function consumeMathCharacter(
+ value: string,
+ index: number,
+ state: MathBodyProtection,
+): number {
+ const character = value[index];
+ if (character === "\\") {
+ return consumeMathCommand(value, index, state);
+ }
+ if (character === "{") {
+ state.textGroups.push(
+ state.textCommandPending || state.textGroups.at(-1) === true,
+ );
+ state.textCommandPending = false;
+ } else if (character === "}") {
+ state.textGroups.pop();
+ state.textCommandPending = false;
+ } else if (character === "<") {
+ state.parts.push(
+ state.textGroups.at(-1) === true
+ ? String.raw`{\char"3C}`
+ : String.raw`\lt `,
+ );
+ state.textCommandPending = false;
+ return index;
+ } else if (character.trim() !== "") {
+ state.textCommandPending = false;
+ }
+ state.parts.push(character);
+ return index;
+}
+
+function protectMathBody(value: string): string {
+ const state: MathBodyProtection = {
+ parts: [],
+ textGroups: [],
+ textCommandPending: false,
+ };
+ for (let index = 0; index < value.length; index += 1) {
+ index = consumeMathCharacter(value, index, state);
+ }
+ return state.parts.join("");
+}
+
+const tokenizeEscapedMath: Tokenizer = function (effects, ok, nok) {
+ let body = "";
+ let pending: Token;
+
+ const start: State = (code) => {
+ const previousToken = this.events.at(-1)?.[1];
+ if (
+ code !== BACKSLASH ||
+ isInHtmlLiteral(this) ||
+ isInLatexBracketMath(this) ||
+ (this.previous === DOLLAR && previousToken?.type !== TOKEN)
+ ) {
+ return nok(code);
+ }
+ effects.enter(TOKEN);
+ effects.enter(SEQUENCE_TOKEN);
+ effects.consume(code);
+ return openingDollar;
+ };
+
+ const openingDollar: State = (code) => {
+ if (code !== DOLLAR) {
+ return nok(code);
+ }
+ effects.consume(code);
+ return afterOpening;
+ };
+
+ const afterOpening: State = (code) => {
+ effects.exit(SEQUENCE_TOKEN);
+ effects.enter(DATA_TOKEN);
+ return data(code);
+ };
+
+ const data: State = (code) => {
+ if (code === null || LINE_ENDINGS.has(code)) {
+ return nok(code);
+ }
+ if (code === BACKSLASH) {
+ effects.exit(DATA_TOKEN);
+ pending = effects.enter(SEQUENCE_TOKEN);
+ effects.consume(code);
+ return closingDollar;
+ }
+ body = appendCode(body, code);
+ if (body.length > MAX_BODY_LENGTH) {
+ return nok(code);
+ }
+ effects.consume(code);
+ return data;
+ };
+
+ const closingDollar: State = (code) => {
+ if (code === DOLLAR) {
+ effects.consume(code);
+ if (braceBalance(body) > 0) {
+ pending.type = DATA_TOKEN;
+ body += "\\$";
+ if (body.length > MAX_BODY_LENGTH) {
+ return nok(code);
+ }
+ return data;
+ }
+ return finish;
+ }
+ pending.type = DATA_TOKEN;
+ body += "\\";
+ if (body.length > MAX_BODY_LENGTH) {
+ return nok(code);
+ }
+ return data(code);
+ };
+
+ const finish: State = (code) => {
+ if (
+ braceBalance(body) !== 0 ||
+ MARKDOWN_INLINE_BOUNDARY_RE.test(body) ||
+ !looksLikeEscapedInlineMath(body)
+ ) {
+ return nok(code);
+ }
+ effects.exit(SEQUENCE_TOKEN);
+ effects.exit(TOKEN);
+ return ok(code);
+ };
+
+ return start;
+};
+
+const escapedMathConstruct: Construct = {
+ name: TOKEN,
+ tokenize: tokenizeEscapedMath,
+};
+
+const escapedMathSyntax: MicromarkExtension = {
+ text: { [BACKSLASH]: escapedMathConstruct },
+};
+
+const escapedMathFromMarkdown: FromMarkdownExtension = {
+ enter: {
+ [TOKEN](this: CompileContext, token: Token): void {
+ const node = {
+ type: "inlineMath",
+ value: "",
+ data: {
+ hName: "code",
+ hProperties: { className: ["language-math", "math-inline"] },
+ hChildren: [],
+ },
+ } satisfies InlineMath;
+ escapedMathNodes.add(node);
+ this.enter(node, token);
+ this.buffer();
+ },
+ },
+ exit: {
+ [TOKEN](this: CompileContext, token: Token): void {
+ const value = this.resume().trim();
+ const node = this.stack.at(-1);
+ if (node?.type !== "inlineMath") {
+ throw new Error(
+ "escaped inline math did not produce an inlineMath node",
+ );
+ }
+ this.exit(token);
+ node.value = value;
+ node.data = {
+ ...node.data,
+ hName: "code",
+ hProperties: { className: ["language-math", "math-inline"] },
+ hChildren: [{ type: "text", value }],
+ };
+ },
+ [DATA_TOKEN](this: CompileContext, token: Token): void {
+ this.config.enter.data.call(this, token);
+ this.config.exit.data.call(this, token);
+ },
+ },
+};
+
+type MarkdownNode = {
+ readonly type: string;
+ readonly position?: {
+ readonly start: { readonly offset?: number };
+ readonly end: { readonly offset?: number };
+ };
+ readonly children?: readonly MarkdownNode[];
+};
+
+type EscapedMathRange = {
+ readonly start: number;
+ readonly end: number;
+ readonly value: string;
+};
+
+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) {
+ const character = markdown[index];
+ if (character === "\n" || character === "\r") {
+ return false;
+ }
+ if (character !== "$" || markdown[index - 1] === "\\") {
+ continue;
+ }
+ if (markdown[index + 1] === "$") {
+ index += 1;
+ continue;
+ }
+ if (DIGIT_RE.test(markdown[index + 1] ?? "")) {
+ continue;
+ }
+ return looksLikeEscapedInlineMath(markdown.slice(offset + 1, index));
+ }
+ return false;
+}
+
+function escapedMathRanges(markdown: string): EscapedMathRange[] {
+ const masked = markdown.replace(CURRENCY_OPENER_RE, (opener, offset) =>
+ hasLikelyMathCloser(markdown, offset) ? opener : MASKED_DOLLAR,
+ );
+ const openCodeTail = openCodeSpanTail(masked);
+ const tree = fromMarkdown(masked, {
+ extensions: [
+ gfm(),
+ math({ singleDollarTextMath: true }),
+ escapedMathSyntax,
+ ],
+ mdastExtensions: [
+ gfmFromMarkdown(),
+ mathFromMarkdown(),
+ escapedMathFromMarkdown,
+ ],
+ }) as MarkdownNode;
+ const ranges: EscapedMathRange[] = [];
+ const pending = [tree];
+ while (pending.length > 0) {
+ const node = pending.pop();
+ if (!node) {
+ continue;
+ }
+ const start = node.position?.start.offset;
+ const end = node.position?.end.offset;
+ if (
+ node.type === "inlineMath" &&
+ escapedMathNodes.has(node) &&
+ start !== undefined &&
+ end !== undefined &&
+ !(openCodeTail && start >= openCodeTail.start && start < openCodeTail.end)
+ ) {
+ ranges.push({
+ start,
+ end,
+ value: markdown.slice(start + 2, end - 2).trim(),
+ });
+ }
+ if (node.children) {
+ pending.push(...node.children);
+ }
+ }
+ return ranges.sort((left, right) => left.start - right.start);
+}
+
+/** normalize model-emitted `\$…\$` before currency and streaming repair. */
+export function normalizeEscapedInlineMath(markdown: string): string {
+ if (!markdown.includes("\\$")) {
+ return markdown;
+ }
+ const ranges = escapedMathRanges(markdown);
+ if (ranges.length === 0) {
+ return markdown;
+ }
+
+ const parts: string[] = [];
+ let offset = 0;
+ let previousCharacter = "";
+ const append = (value: string): void => {
+ if (previousCharacter === "$" && value.startsWith("$")) {
+ parts.push(" ");
+ }
+ parts.push(value);
+ if (value.length > 0) {
+ previousCharacter = value.at(-1) ?? "";
+ }
+ };
+ for (const range of ranges) {
+ append(markdown.slice(offset, range.start));
+ append(`$${protectMathBody(range.value)}$`);
+ offset = range.end;
+ }
+ append(markdown.slice(offset));
+ return parts.join("");
+}
diff --git a/studio/frontend/src/lib/latex.ts b/studio/frontend/src/lib/latex.ts
index 831c446f14d..6b4fd7e3838 100644
--- a/studio/frontend/src/lib/latex.ts
+++ b/studio/frontend/src/lib/latex.ts
@@ -9,6 +9,22 @@
// 2. Escape currency dollar signs so they are not misinterpreted as LaTeX
// math delimiters when singleDollarTextMath is enabled.
+import { parseMarkdownIntoBlocks } from "streamdown";
+import {
+ codeSpans,
+ crossesCodeSpanBlockBoundary,
+} from "./markdown-code-spans.ts";
+import {
+ EMPTY_LIST_STATE,
+ NO_QUOTE,
+ containerContent,
+ indentWidth,
+ itemContent,
+ openLists,
+ quoteDepth,
+ quoteState,
+} from "./markdown-list-columns.ts";
+
/**
* Matches a single $ followed by a number pattern (currency), e.g.:
* $5, $1,000, $5.99, $100K, $3.5M
@@ -48,40 +64,283 @@ function mergeRegions(
return merged;
}
+const FENCE_LINE_RE = /^ {0,3}(`{3,}|~{3,})([^\r\n]*)$/;
+const FENCE_CANDIDATE_RE =
+ /(^|\r\n|\n|\r)((?:(?: {0,3}>[ \t]?)|(?:[ \t]*(?:[-+*]|\d{1,9}[.)])[ \t]+))*[ \t]*)(`{3,}|~{3,})([^\r\n]*)/g;
+const INDENTED_CODE_CANDIDATE_RE =
+ /(^|\r\n|\n|\r)(?: {0,3}>[ \t]?)*(?:(?: {4}| {0,3}\t)| {0,3}(?:[-+*]|\d{1,9}[.)])(?: {5,}|[ \t]*\t[ \t]*))/g;
+const BLOCK_LINE_RE =
+ /^ {0,3}(?:#{1,6}([ \t]|$)|(?:\*[ \t]*){3,}$|(?:-[ \t]*){3,}$|(?:_[ \t]*){3,}$|>|=+[ \t]*$)/;
+const LINK_DEFINITION_RE = /^ {0,3}\[(?:[^\[\]\\]|\\.)+\]:/;
+const NON_LINE_ENDING_RE = /[^\r\n]/g;
+
+/** `line` with up to `columns` columns of leading whitespace removed. */
+function stripIndent(line: string, columns: number): string {
+ let width = 0;
+ let index = 0;
+ while (index < line.length && width < columns) {
+ const char = line[index];
+ if (char !== " " && char !== "\t") break;
+ width += char === " " ? 1 : 4 - (width % 4);
+ index += 1;
+ }
+ return line.slice(index);
+}
+
+/** Display columns occupied by a Markdown container prefix. */
+function columnWidth(prefix: string): number {
+ let width = 0;
+ for (const char of prefix) {
+ width += char === "\t" ? 4 - (width % 4) : 1;
+ }
+ return width;
+}
+
/**
- * Find code-block regions (``` ... ```, ~~~ ... ~~~, and ` ... `) to skip.
+ * Find code regions (fenced, indented, and inline) to skip.
* Returns a sorted, non-overlapping array of [start, end] index pairs.
*/
+function normalizedMarkdownOffsets(content: string): {
+ text: string;
+ offsets: number[];
+} {
+ let text = "";
+ const offsets = [0];
+ for (let index = 0; index < content.length; index += 1) {
+ if (content[index] === "\r") {
+ if (content[index + 1] === "\n") {
+ index += 1;
+ }
+ text += "\n";
+ } else {
+ text += content[index];
+ }
+ offsets.push(index + 1);
+ }
+ return { text, offsets };
+}
+
+function findInlineCodeRegions(
+ content: string,
+ blockRegions: Array<[number, number]>,
+): Array<[number, number]> {
+ let masked = content;
+ if (blockRegions.length > 0) {
+ const parts: string[] = [];
+ let cursor = 0;
+ for (const [start, end] of blockRegions) {
+ parts.push(content.slice(cursor, start));
+ parts.push(content.slice(start, end).replace(NON_LINE_ENDING_RE, " "));
+ cursor = end;
+ }
+ parts.push(content.slice(cursor));
+ masked = parts.join("");
+ }
+
+ const spans = codeSpans(masked);
+ const crossesBlock = spans.some(({ start, end }) =>
+ crossesCodeSpanBlockBoundary(masked.slice(start, end)),
+ );
+ if (!crossesBlock) {
+ return spans.map(({ start, end }) => [start, end]);
+ }
+
+ const normalized = normalizedMarkdownOffsets(masked);
+ const blocks = parseMarkdownIntoBlocks(normalized.text);
+ const regions: Array<[number, number]> = [];
+ let blockStart = 0;
+ for (const block of blocks) {
+ for (const span of codeSpans(block)) {
+ regions.push([
+ normalized.offsets[blockStart + span.start] ?? content.length,
+ normalized.offsets[blockStart + span.end] ?? content.length,
+ ]);
+ }
+ blockStart += block.length;
+ }
+ return regions;
+}
+
export function findCodeBlockRegions(content: string): Array<[number, number]> {
- // Fenced code blocks: ```...``` and ~~~...~~~ (both are code in GFM)
const fenced: Array<[number, number]> = [];
- const fencedRe = /```[\s\S]*?```|~~~[\s\S]*?~~~/g;
let match: RegExpExecArray | null;
- while ((match = fencedRe.exec(content)) !== null) {
- fenced.push([match.index, match.index + match[0].length]);
- }
+ const indented: Array<[number, number]> = [];
- // Inline code: `...`, skipped when inside a fenced block. Both loops yield
- // ascending matches, so walk the fenced list with a cursor rather than
- // rescanning it per match (was quadratic on code-heavy text).
- const inline: Array<[number, number]> = [];
- const inlineRe = /`[^`\n]+`/g;
- let fencedIndex = 0;
- while ((match = inlineRe.exec(content)) !== null) {
- const start = match.index;
- const end = start + match[0].length;
- while (fencedIndex < fenced.length && fenced[fencedIndex][1] <= start) {
- fencedIndex += 1;
+ FENCE_CANDIDATE_RE.lastIndex = 0;
+ INDENTED_CODE_CANDIDATE_RE.lastIndex = 0;
+ let simpleFenceStart = -1;
+ let simpleFenceMarker = "";
+ let needsBlockScan = false;
+ while ((match = FENCE_CANDIDATE_RE.exec(content)) !== null) {
+ const prefix = match[2] ?? "";
+ if (prefix.trim() || indentWidth(prefix) > 3) {
+ needsBlockScan = true;
+ break;
+ }
+ const marker = match[3] ?? "";
+ const tail = match[4] ?? "";
+ const lineStart = match.index + (match[1]?.length ?? 0);
+ if (simpleFenceStart < 0) {
+ if (marker[0] !== "`" || !tail.includes("`")) {
+ simpleFenceStart = lineStart;
+ simpleFenceMarker = marker;
+ }
+ } else if (
+ marker[0] === simpleFenceMarker[0] &&
+ marker.length >= simpleFenceMarker.length &&
+ !tail.trim()
+ ) {
+ fenced.push([
+ simpleFenceStart,
+ lineStart + prefix.length + marker.length,
+ ]);
+ simpleFenceStart = -1;
+ simpleFenceMarker = "";
+ }
+ }
+ if (!needsBlockScan && simpleFenceStart >= 0) {
+ fenced.push([simpleFenceStart, content.length]);
+ }
+ if (!needsBlockScan) {
+ while ((match = INDENTED_CODE_CANDIDATE_RE.exec(content)) !== null) {
+ if (!isInRegion(match.index + match[0].length - 1, fenced)) {
+ needsBlockScan = true;
+ break;
+ }
}
- const block = fencedIndex < fenced.length ? fenced[fencedIndex] : null;
- if (!(block && start >= block[0] && end <= block[1])) {
- inline.push([start, end]);
+ }
+ if (needsBlockScan) {
+ fenced.length = 0;
+ const lines = content.matchAll(/[^\r\n]*(?:\r\n|\n|\r|$)/g);
+ let openFence: {
+ start: number;
+ marker: string;
+ column: number;
+ quotes: number;
+ } | null = null;
+ let indentedStart = -1;
+ let indentedEnd = -1;
+ let afterParagraph = false;
+ let lists = EMPTY_LIST_STATE;
+ let quote = NO_QUOTE;
+
+ for (const lineMatch of lines) {
+ const line = lineMatch[0];
+ if (!line) break;
+ const start = lineMatch.index;
+ const text = line.replace(/(?:\r\n|\n|\r)$/, "");
+ const above = quote;
+ quote = NO_QUOTE;
+ const quotes = quoteDepth(text);
+
+ if (openFence !== null) {
+ const quoted = containerContent(
+ text,
+ EMPTY_LIST_STATE,
+ openFence.quotes,
+ );
+ const leftContainer =
+ quotes < openFence.quotes ||
+ (quoted.trim() !== "" &&
+ openFence.column > 0 &&
+ indentWidth(quoted) < openFence.column);
+ if (leftContainer) {
+ fenced.push([openFence.start, start]);
+ openFence = null;
+ }
+ }
+
+ const activeFence = openFence;
+ const container = containerContent(
+ text,
+ lists,
+ activeFence?.quotes ?? quotes,
+ );
+ let fenceSource: string;
+ if (activeFence) {
+ fenceSource = stripIndent(container, activeFence.column);
+ } else {
+ fenceSource = container;
+ let previous: string;
+ let itemAfterParagraph = afterParagraph;
+ do {
+ previous = fenceSource;
+ fenceSource = itemContent(fenceSource, itemAfterParagraph);
+ itemAfterParagraph = false;
+ } while (fenceSource !== previous);
+ }
+ const fence = FENCE_LINE_RE.exec(fenceSource);
+ if (fence !== null) {
+ lists = openLists(text, lists, afterParagraph, above.quoted);
+ const marker = fence[1] ?? "";
+ const tail = fence[2] ?? "";
+ if (openFence === null) {
+ if (marker[0] !== "`" || !tail.includes("`")) {
+ const quoted = containerContent(text, EMPTY_LIST_STATE, quotes);
+ openFence = {
+ start,
+ marker,
+ column: columnWidth(
+ quoted.slice(0, quoted.length - fenceSource.length),
+ ),
+ quotes,
+ };
+ }
+ } else if (
+ marker[0] === openFence.marker[0] &&
+ marker.length >= openFence.marker.length &&
+ !tail.trim()
+ ) {
+ fenced.push([openFence.start, start + line.length]);
+ openFence = null;
+ }
+ afterParagraph = false;
+ continue;
+ }
+
+ if (openFence !== null) {
+ lists = openLists("", lists, afterParagraph, above.quoted);
+ afterParagraph = false;
+ continue;
+ }
+
+ lists = openLists(text, lists, afterParagraph, above.quoted);
+ const inner = itemContent(
+ containerContent(text, lists, quoteDepth(text)),
+ afterParagraph,
+ );
+ const blank = /^\s*$/.test(inner);
+ const code = indentWidth(inner) >= 4;
+ if (indentedStart >= 0) {
+ if (code || blank) {
+ indentedEnd = start + line.length;
+ continue;
+ }
+ indented.push([indentedStart, indentedEnd]);
+ indentedStart = -1;
+ }
+ if (code && !afterParagraph && !blank) {
+ indentedStart = start;
+ indentedEnd = start + line.length;
+ afterParagraph = false;
+ continue;
+ }
+ afterParagraph =
+ !blank &&
+ !BLOCK_LINE_RE.test(text) &&
+ (afterParagraph || !LINK_DEFINITION_RE.test(text));
+ quote = quoteState(text, above.inQuote);
}
+ if (openFence !== null) fenced.push([openFence.start, content.length]);
+ if (indentedStart >= 0) indented.push([indentedStart, indentedEnd]);
}
+ const blocks = mergeRegions(fenced, indented);
+ const inline = findInlineCodeRegions(content, blocks);
+
// An inline span can CONTAIN a fence (`` `~~~a~~~ $5` ``); that overlap made
// the binary search land on the inner span and miss the outer one.
- return mergeRegions(fenced, inline);
+ return mergeRegions(blocks, inline);
}
/**
@@ -92,7 +351,7 @@ export function findCodeBlockRegions(content: string): Array<[number, number]> {
* of balanced parens.
*/
const LINK_DEST_RE =
- /!?\[(?:\\.|[^\]\\])*?\]\(((?:\\.|[^()\\]|\([^()]*\))*)\)/gd;
+ /!?\[(?:\\.|[^\]\\])*?\]\(((?:\\.|[^()\\]|\([^()]*\))*)\)/dg;
/**
* Find the destination spans of inline links/images, so a `\(...\)` written with
@@ -244,15 +503,10 @@ function hasInlineMathCloser(
}
/**
- * Matches a `\[...\]` (display) or `\(...\)` (inline) LaTeX span. Non-greedy so
- * the first closer wins; dotall so display spans can wrap lines. `(?<!\\)` on
- * each opener leaves an escaped literal `\\[` (a real backslash then bracket)
- * alone. The body is length-capped so an unclosed opener can't scan to
- * end-of-input: without the cap, many unclosed `\(`/`\[` make matching O(n^2),
- * and this runs per animation frame while streaming. Real spans are far shorter
- * than the cap; a longer one just stays literal.
+ * Matches a `\[...\]` (display) or `\(...\)` (inline) LaTeX span. The body
+ * is capped so repeated incomplete openers stay linear during streaming.
*/
-const LATEX_DELIM_RE =
+const CONVERT_LATEX_DELIM_RE =
/(?<!\\)\\\[([\s\S]{0,4096}?)\\\]|(?<!\\)\\\(([\s\S]{0,4096}?)\\\)/g;
/**
@@ -310,8 +564,8 @@ function convertLatexDelimiters(content: string): {
return start;
};
let match: RegExpExecArray | null;
- LATEX_DELIM_RE.lastIndex = 0;
- while ((match = LATEX_DELIM_RE.exec(content)) !== null) {
+ CONVERT_LATEX_DELIM_RE.lastIndex = 0;
+ while ((match = CONVERT_LATEX_DELIM_RE.exec(content)) !== null) {
const matchEnd = match.index + match[0].length;
// Skip if either delimiter is inside code or a link destination: an opener
// outside such a zone must not consume a closer inside one and rewrite
@@ -319,7 +573,7 @@ function convertLatexDelimiters(content: string): {
// match) so a valid span that this match spanned across (a stray code `\(`
// paired with a real closer) is still found on the next pass, not swallowed.
if (inSkipZone(match.index) || inSkipZone(matchEnd - 1)) {
- LATEX_DELIM_RE.lastIndex = match.index + 1;
+ CONVERT_LATEX_DELIM_RE.lastIndex = match.index + 1;
continue;
}
const isDisplay = match[1] !== undefined;
diff --git a/studio/frontend/src/lib/markdown-code-spans.ts b/studio/frontend/src/lib/markdown-code-spans.ts
index 537aabb1ab3..ad1484c7749 100644
--- a/studio/frontend/src/lib/markdown-code-spans.ts
+++ b/studio/frontend/src/lib/markdown-code-spans.ts
@@ -14,6 +14,9 @@ export interface CodeSpan {
content: string;
}
+const BLOCK_BOUNDARY_RE =
+ /(?:\r?\n[ \t]*\r?\n|(?:^|[\r\n]) {0,3}(?:#{1,6}(?:[ \t]|$)|>|[-+*](?:[ \t]|$)|\d{1,9}[.)](?:[ \t]|$)|`{3,}|~{3,}|(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,}|=+[ \t]*)(?=$|[\r\n])))/;
+
function runLength(text: string, index: number): number {
let end = index;
while (text[end] === "`") {
@@ -44,8 +47,7 @@ function stripPadding(content: string): string {
return content;
}
-/** Every code span in `text`, in order. Unclosed runs are ordinary text. */
-export function codeSpans(text: string): CodeSpan[] {
+function scanCodeSpans(text: string, includeOpenTail: boolean): CodeSpan[] {
const spans: CodeSpan[] = [];
let index = 0;
@@ -79,6 +81,14 @@ export function codeSpans(text: string): CodeSpan[] {
cursor += candidate;
}
if (!closed) {
+ if (includeOpenTail && ticks < 3) {
+ spans.push({
+ start: index,
+ end: text.length,
+ content: stripPadding(text.slice(contentStart)),
+ });
+ break;
+ }
// Nothing closes this run: it is literal text, carry on after it.
index = contentStart;
}
@@ -86,6 +96,35 @@ export function codeSpans(text: string): CodeSpan[] {
return spans;
}
+/** Every code span in `text`, in order. Unclosed runs are ordinary text. */
+export function codeSpans(text: string): CodeSpan[] {
+ return scanCodeSpans(text, false);
+}
+
+/** closed spans plus the unmatched tail that incomplete-Markdown repair makes code. */
+export function codeSpansWithOpenTail(text: string): CodeSpan[] {
+ return scanCodeSpans(text, true);
+}
+
+/** the unmatched tail that streaming repair treats as code, if it stays in one block. */
+export function openCodeSpanTail(text: string): CodeSpan | undefined {
+ const closed = codeSpans(text);
+ const withOpenTail = codeSpansWithOpenTail(text);
+ const tail = withOpenTail.at(-1);
+ if (
+ !tail ||
+ closed.some((span) => span.start === tail.start && span.end === tail.end) ||
+ crossesCodeSpanBlockBoundary(text.slice(tail.start, tail.end))
+ ) {
+ return undefined;
+ }
+ return tail;
+}
+
+export function crossesCodeSpanBlockBoundary(text: string): boolean {
+ return BLOCK_BOUNDARY_RE.test(text);
+}
+
/** Replaces every code span with `park(content)`, leaving the rest as is. */
export function parkCodeSpans(
text: string,
diff --git a/studio/frontend/src/lib/markdown-list-columns.ts b/studio/frontend/src/lib/markdown-list-columns.ts
index ced82a7b30a..0c75aadd74a 100644
--- a/studio/frontend/src/lib/markdown-list-columns.ts
+++ b/studio/frontend/src/lib/markdown-list-columns.ts
@@ -309,6 +309,43 @@ function closeDedented(
return open === columns.length ? columns : columns.slice(0, open);
}
+function sameLineListColumns(
+ line: string,
+ firstItem: RegExpExecArray,
+ firstIndent: number,
+ outerColumns: number[],
+): number[] {
+ let item = firstItem;
+ let itemIndent = firstIndent;
+ let rest = line;
+ const columns = [...outerColumns];
+
+ while (true) {
+ const marker = item[1] ?? "";
+ const rawPadding = indentWidth(item[2] ?? "");
+ const padding =
+ rawPadding === 0 || rawPadding > MAX_ITEM_PADDING ? 1 : rawPadding;
+ const contentColumn = itemIndent + marker.length + padding;
+ columns.push(contentColumn);
+ if (rawPadding === 0 || rawPadding > MAX_ITEM_PADDING) {
+ break;
+ }
+
+ rest = rest.slice(item[0].length);
+ const relativeIndent = indentWidth(rest);
+ if (relativeIndent >= INDENTED_CODE || THEMATIC_BREAK.test(rest)) {
+ break;
+ }
+ const nested = LIST_ITEM.exec(rest);
+ if (nested === null) {
+ break;
+ }
+ item = nested;
+ itemIndent = contentColumn + relativeIndent;
+ }
+ return columns;
+}
+
/**
* The list items still open after `line`. A dedented line closes an item unless
* it is a lazy paragraph continuation. A new marker nests under a deeper column
@@ -343,15 +380,14 @@ export function openLists(
if (item === null || indent - (columns.at(-1) ?? 0) >= INDENTED_CODE) {
return { columns, emptyItem: false };
}
- const marker = item[1] ?? "";
- let padding = indentWidth(item[2] ?? "");
- if (padding === 0 || padding > MAX_ITEM_PADDING) {
- // An empty or over-indented item still holds one column of content.
- padding = 1;
- }
// A sibling marker replaces the item it lines up with.
return {
- columns: [...dropDeeper(columns, indent), indent + marker.length + padding],
+ columns: sameLineListColumns(
+ line,
+ item,
+ indent,
+ dropDeeper(columns, indent),
+ ),
emptyItem: empty,
};
}
diff --git a/studio/frontend/tests/escaped-inline-math.test.ts b/studio/frontend/tests/escaped-inline-math.test.ts
new file mode 100644
index 00000000000..8b38a9d45c0
--- /dev/null
+++ b/studio/frontend/tests/escaped-inline-math.test.ts
@@ -0,0 +1,285 @@
+// 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 { createMathPlugin } from "@streamdown/math";
+import React from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { Streamdown } from "streamdown";
+import { parseMarkdownIntoRenderableBlocks } from "../src/components/assistant-ui/streaming-render-schedule.ts";
+import {
+ looksLikeEscapedInlineMath,
+ normalizeEscapedInlineMath,
+} from "../src/lib/escaped-inline-math.ts";
+import { preprocessLaTeX } from "../src/lib/latex.ts";
+
+const math = createMathPlugin({ singleDollarTextMath: true });
+
+function render(
+ markdown: string,
+ mode: "static" | "streaming" = "static",
+ normalizeEscapedMath = true,
+): string {
+ return renderToStaticMarkup(
+ React.createElement(
+ Streamdown,
+ {
+ mode,
+ plugins: { math },
+ parseMarkdownIntoBlocksFn: parseMarkdownIntoRenderableBlocks,
+ },
+ preprocessLaTeX(
+ normalizeEscapedMath ? normalizeEscapedInlineMath(markdown) : markdown,
+ ),
+ ),
+ );
+}
+
+function annotations(html: string): string[] {
+ return Array.from(
+ html.matchAll(
+ /<annotation encoding="application\/x-tex">(.*?)<\/annotation>/g,
+ ),
+ (match) => match[1],
+ );
+}
+
+test("the escaped-math classifier stays conservative", () => {
+ for (const body of ["x", "v_s", String.raw`f \to 0`, "x + y", "f(x)"]) {
+ assert.equal(looksLikeEscapedInlineMath(body), true, body);
+ }
+ for (const body of ["5", "5 to 10", "read-only", "USD/EUR", "not math"]) {
+ assert.equal(looksLikeEscapedInlineMath(body), false, body);
+ }
+});
+
+test("escaped math is parsed in ordinary and list text", () => {
+ const html = render(
+ [
+ String.raw`- \$v_s\$ and \$f(r_s)\$`,
+ String.raw`- \$f \to 0\$ and \$x + y\$`,
+ String.raw`after \$f(x)\$`,
+ ].join("\n"),
+ );
+ assert.deepEqual(annotations(html), [
+ "v_s",
+ "f(r_s)",
+ "f \\to 0",
+ "x + y",
+ "f(x)",
+ ]);
+});
+
+test("Markdown syntax decides where escaped math is allowed", () => {
+ const literalCases = [
+ "`\\$v_s\\$`",
+ "``a ` \\$v_s\\$ b``",
+ " \\$v_s\\$",
+ "# heading\n \\$v_s\\$",
+ " \t\\$v_s\\$",
+ "```tex\n\\$v_s\\$\n```",
+ "```tex\n\\$v_s\\$",
+ "```\n ```\n\\$v_s\\$\n```",
+ "- ```\n \\$v_s\\$\n ```",
+ "> ```\n> \\$v_s\\$\n> ```",
+ "```\n- ```\n\\$v_s\\$\n```",
+ "> \\$v_s\\$",
+ "- \\$v_s\\$",
+ "- item\n\n \\$v_s\\$",
+ String.raw`<https://example.com/\$v_s\$>`,
+ ];
+ for (const markdown of literalCases) {
+ assert.deepEqual(annotations(render(markdown)), [], markdown);
+ }
+
+ const linked = render(String.raw`[\$v_s\$](https://example.com/\$literal\$)`);
+ assert.deepEqual(annotations(linked), ["v_s"]);
+
+ const rawCode = render(String.raw`<code>\$x_1\$</code> after \$y_2\$`);
+ assert.deepEqual(annotations(rawCode), ["y_2"]);
+ assert.match(rawCode, /data-streamdown="inline-code">\$x_1\$<\/code>/);
+
+ const quotedAttribute = render(
+ String.raw`<code title="x > y">\$v_s\$</code>`,
+ );
+ assert.deepEqual(annotations(quotedAttribute), []);
+ assert.ok(quotedAttribute.includes("$v_s$"));
+});
+
+test("escaped candidates cannot consume nested Markdown", () => {
+ for (const markdown of [
+ `${String.raw`Before \$x + `}\`y\`${String.raw`\$ then \$z\$`}`,
+ String.raw`Before \$x + [y](https://e.test)\$ then \$z\$`,
+ String.raw`Before \$x_ + [y][ref]\$ then \$z\$
+
+[ref]: https://example.com/reference`,
+ String.raw`Before \$x_ + [y][]\$ then \$z\$
+
+[y]: https://example.com/reference`,
+ String.raw`Before \$x + <code>y</code>\$ then \$z\$`,
+ ]) {
+ assert.deepEqual(annotations(render(markdown)), ["z"], markdown);
+ }
+
+ const referenceLink = render(String.raw`Before \$x_ + [y][ref]\$ then \$z\$
+
+[ref]: https://example.com/reference`);
+ assert.ok(referenceLink.includes('data-streamdown="link"'));
+ assert.ok(referenceLink.includes(">y</button>"));
+});
+
+test("rejected candidates do not consume later math openers", () => {
+ const cases: [string, string][] = [
+ [String.raw`literal \$ then \$v_s\$`, "v_s"],
+ [String.raw`literal \$ not math \$v_s\$`, "v_s"],
+ [String.raw`\$5\$ + \$10\$ and \$v_s\$`, "v_s"],
+ [String.raw`\$\$ then \$v_s\$`, "v_s"],
+ [`${String.raw`\$`}${"a".repeat(201)}${String.raw`\$ + \$x\$`}`, "x"],
+ ];
+ for (const [markdown, expected] of cases) {
+ assert.deepEqual(annotations(render(markdown)), [expected]);
+ }
+});
+
+test("the maximum body length is inclusive", () => {
+ const body = `v_${"a".repeat(198)}`;
+ assert.equal(body.length, 200);
+ assert.deepEqual(annotations(render(`\\$${body}\\$ and \\$x\\$`)), [
+ body,
+ "x",
+ ]);
+});
+
+test("escaped prose and currency remain literal", () => {
+ for (const markdown of [
+ String.raw`the label \$read-only\$`,
+ String.raw`the pair \$USD/EUR\$`,
+ String.raw`\$5\$ is intentionally literal currency`,
+ String.raw`\$5 to 10\$ is prose`,
+ ]) {
+ assert.deepEqual(annotations(render(markdown)), [], markdown);
+ }
+});
+
+test("non-interrupting list markers cannot hide later escaped math", () => {
+ const html = render("paragraph\n2. ```\n\\$v_s\\$");
+ assert.deepEqual(annotations(html), ["v_s"]);
+});
+
+test("adjacent escaped spans remain separate math nodes", () => {
+ assert.deepEqual(annotations(render(String.raw`\$a\$\$b\$`)), ["a", "b"]);
+});
+
+test("escaped display delimiters remain literal", () => {
+ const markdown = String.raw`\$\$x^2\$\$`;
+ assert.equal(normalizeEscapedInlineMath(markdown), markdown);
+ assert.deepEqual(annotations(render(markdown)), []);
+});
+
+test("escaped currency inside a braced math command is not a closer", () => {
+ const markdown = String.raw`\$\text{Revenue: \$5}\$`;
+ assert.equal(
+ normalizeEscapedInlineMath(markdown),
+ String.raw`$\text{Revenue: {\char"24}5}$`,
+ );
+ const html = render(markdown);
+ assert.deepEqual(annotations(html), [
+ String.raw`\text{Revenue: {\char&quot;24}5}`,
+ ]);
+ assert.ok(html.includes("<mtext>Revenue:\u00a0$5</mtext>"));
+ assert.ok(!html.includes("katex-error"));
+});
+
+test("currency markers do not hide escaped math between them", () => {
+ const markdown = String.raw`Cost $5; variable \$x\$; cap $10`;
+ assert.equal(
+ normalizeEscapedInlineMath(markdown),
+ "Cost $5; variable $x$; cap $10",
+ );
+ const html = render(markdown);
+ assert.deepEqual(annotations(html), ["x"]);
+ assert.ok(html.includes("Cost $5; variable"));
+ assert.ok(html.includes("; cap $10"));
+});
+
+test("less-than signs remain valid inside TeX text", () => {
+ const html = render(String.raw`\$\text{x<y}\$`);
+ assert.deepEqual(annotations(html), [
+ String.raw`\text{x{\char&quot;3C}y}`,
+ ]);
+ assert.match(html, /<mtext>x&lt;y<\/mtext>/);
+ assert.ok(!html.includes("katex-error"));
+});
+
+test("escaped dollars inside existing math stay inside that math", () => {
+ const exactBoundary = String.raw`\text{Revenue: \$USD\$}`.padEnd(200, "x");
+ const cases = [
+ String.raw`$\text{Revenue: \$USD\$}$`,
+ String.raw`$30^\circ + \text{\$x\$}$`,
+ `$${exactBoundary}$`,
+ String.raw`\(\text{Revenue: \$x\$}\)`,
+ String.raw`$$
+\text{Revenue: \$USD\$}
+$$`,
+ String.raw`\[a + \$x\$\]`,
+ ];
+ for (const markdown of cases) {
+ assert.equal(normalizeEscapedInlineMath(markdown), markdown);
+ assert.equal(render(markdown), render(markdown, "static", false), markdown);
+ }
+});
+
+test("unmatched bracket math does not escape its Markdown block", () => {
+ const markdown = String.raw`unfinished \(
+
+- \$v_s\$`;
+ assert.equal(
+ normalizeEscapedInlineMath(markdown),
+ String.raw`unfinished \(
+
+- $v_s$`,
+ );
+ assert.deepEqual(annotations(render(markdown)), ["v_s"]);
+});
+
+test("streaming waits for the escaped closer", () => {
+ const incomplete = String.raw`- \$v_s`;
+ assert.deepEqual(annotations(render(incomplete, "streaming")), []);
+ assert.deepEqual(annotations(render(`${incomplete}\\$`, "streaming")), [
+ "v_s",
+ ]);
+});
+
+test("block boundaries and nested list continuations keep escaped math active", () => {
+ for (const mode of ["static", "streaming"] as const) {
+ assert.deepEqual(
+ annotations(render("- - item\n\n \\$nested_s\\$", mode)),
+ ["nested_s"],
+ );
+ assert.deepEqual(
+ annotations(render("`open\n***\n\\$boundary_s\\$`", mode)),
+ ["boundary_s"],
+ );
+ }
+});
+
+test("incomplete code spans preserve escaped dollars while streaming", () => {
+ for (const opener of ["`", "``"]) {
+ const incomplete = `${opener}formula \\$x\\$`;
+ assert.equal(normalizeEscapedInlineMath(incomplete), incomplete);
+ const streamingHtml = render(incomplete, "streaming");
+ assert.deepEqual(annotations(streamingHtml), []);
+ if (opener === "`") {
+ assert.ok(streamingHtml.includes(String.raw`formula \$x\$`));
+ }
+ assert.deepEqual(annotations(render(incomplete)), []);
+
+ const completed = `${incomplete}${opener} after \\$y\\$`;
+ for (const mode of ["streaming", "static"] as const) {
+ const completedHtml = render(completed, mode);
+ assert.deepEqual(annotations(completedHtml), ["y"]);
+ assert.ok(completedHtml.includes(String.raw`formula \$x\$`));
+ }
+ }
+});
diff --git a/studio/frontend/tests/latex-code-regions.test.ts b/studio/frontend/tests/latex-code-regions.test.ts
index e4987e35f09..048429b017e 100644
--- a/studio/frontend/tests/latex-code-regions.test.ts
+++ b/studio/frontend/tests/latex-code-regions.test.ts
@@ -56,10 +56,21 @@ test("LaTeX inside inline code stays literal whatever follows it", () => {
assert.equal(preprocessLaTeX(`${span}\n\n\`x\``), `${span}\n\n\`x\``);
});
+test("thematic and setext breaks stop cross-block code spans", () => {
+ for (const boundary of ["***", "---", "==="]) {
+ assert.equal(
+ preprocessLaTeX(`\`open\n${boundary}\n\\(x\\)\``),
+ `\`open\n${boundary}\n$x$\``,
+ boundary,
+ );
+ }
+});
+
test("ordinary code spans and fences are unchanged", () => {
// Nothing that was already non-overlapping may move.
const cases: [string, string][] = [
["`costs $5`", "`costs $5`"],
+ ["``a ` \\$x\\$ b``", "``a ` \\$x\\$ b``"],
["`costs $5`\n\n`x`", "`costs $5`\n\n`x`"],
["```\ncosts $5\n```", "```\ncosts $5\n```"],
["```\ncosts $5\n```\n\n`x`", "```\ncosts $5\n```\n\n`x`"],
@@ -67,6 +78,26 @@ test("ordinary code spans and fences are unchanged", () => {
["costs $5 outside", "costs \\$5 outside"],
["costs $5 outside\n\n`x`", "costs \\$5 outside\n\n`x`"],
["```\n`inner`\n```", "```\n`inner`\n```"],
+ ["```tex\n\\(x\\)\n", "```tex\n\\(x\\)\n"],
+ ["```\n ```\n\\(x\\)\n```", "```\n ```\n\\(x\\)\n```"],
+ ["- ```\n \\(x\\)\n ```", "- ```\n \\(x\\)\n ```"],
+ ["> ```\n> \\(x\\)\n> ```", "> ```\n> \\(x\\)\n> ```"],
+ [
+ "- - ```\n costs $5 and \\(x\\)\n ```",
+ "- - ```\n costs $5 and \\(x\\)\n ```",
+ ],
+ ["```\n- ```\n\\(x\\)\n```", "```\n- ```\n\\(x\\)\n```"],
+ [
+ "- item\n ~~~tex\n \\(x\\)\n ~~~",
+ "- item\n ~~~tex\n \\(x\\)\n ~~~",
+ ],
+ [
+ "- item\n ```tex\n \\(x\\)\n ````",
+ "- item\n ```tex\n \\(x\\)\n ````",
+ ],
+ ["- item\n ~~~tex\n \\(x\\)", "- item\n ~~~tex\n \\(x\\)"],
+ ["# heading\n \\(x\\)", "# heading\n \\(x\\)"],
+ ["# heading\n \t\\(x\\)", "# heading\n \t\\(x\\)"],
["`\\(x\\)` and \\(y\\)", "`\\(x\\)` and $y$"],
["```\n\\(x\\)\n```\n\nthen \\(y\\)", "```\n\\(x\\)\n```\n\nthen $y$"],
];
@@ -78,3 +109,29 @@ test("ordinary code spans and fences are unchanged", () => {
);
}
});
+
+test("fences stop at their Markdown container boundary", () => {
+ const cases: [string, string][] = [
+ ["- ```txt\n code\noutside \\(x\\)", "- ```txt\n code\noutside $x$"],
+ ["> ```txt\n> code\noutside \\(x\\)", "> ```txt\n> code\noutside $x$"],
+ [
+ "paragraph\n2. ``` literal\n\\(x\\) after",
+ "paragraph\n2. ``` literal\n$x$ after",
+ ],
+ ];
+
+ for (const [input, expected] of cases) {
+ assert.equal(preprocessLaTeX(input), expected, input);
+ }
+});
+
+test("same-line nested items set the continuation content column", () => {
+ assert.equal(
+ preprocessLaTeX("- - item\n\n \\(x\\)"),
+ "- - item\n\n $x$",
+ );
+ assert.equal(
+ preprocessLaTeX("- - item\n\n \\(x\\)"),
+ "- - item\n\n $x$",
+ );
+});
diff --git a/studio/frontend/tests/latex-list-render.test.ts b/studio/frontend/tests/latex-list-render.test.ts
new file mode 100644
index 00000000000..4f540315635
--- /dev/null
+++ b/studio/frontend/tests/latex-list-render.test.ts
@@ -0,0 +1,208 @@
+// 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 { createMathPlugin } from "@streamdown/math";
+import React from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { Streamdown } from "streamdown";
+import { stabilizeStreamingMarkdown } from "../src/components/assistant-ui/streaming-markdown.ts";
+import { IncrementalMarkdownCache } from "../src/components/assistant-ui/streaming-render-schedule.ts";
+import { normalizeEscapedInlineMath } from "../src/lib/escaped-inline-math.ts";
+import { preprocessLaTeX } from "../src/lib/latex.ts";
+
+const math = createMathPlugin({ singleDollarTextMath: true });
+
+function renderResponse(
+ source: string,
+ isStreaming: boolean,
+ cache = new IncrementalMarkdownCache(),
+): string {
+ const processed = stabilizeStreamingMarkdown(
+ preprocessLaTeX(normalizeEscapedInlineMath(source)),
+ isStreaming,
+ );
+ const incremental = isStreaming ? cache.update(processed) : null;
+ return renderToStaticMarkup(
+ React.createElement(
+ Streamdown,
+ {
+ mode: "streaming",
+ parseIncompleteMarkdown: !incremental,
+ parseMarkdownIntoBlocksFn: incremental?.parseMarkdownIntoBlocks,
+ isAnimating: isStreaming,
+ plugins: { math },
+ },
+ incremental?.markdown ?? processed,
+ ),
+ );
+}
+
+function assertMath(html: string, sources: string[]): void {
+ for (const source of sources) {
+ assert.ok(
+ html.includes(
+ `<annotation encoding="application/x-tex">${source}</annotation>`,
+ ),
+ source,
+ );
+ }
+}
+
+const REALISTIC_RESPONSE = [
+ "$$",
+ "ds^2 = -c^2dt^2 + (dx-v_sf(r_s)dt)^2 + dy^2 + dz^2",
+ "$$",
+ "",
+ "where:",
+ "",
+ "- \\$v_s\\$ is the velocity of the bubble,",
+ "- \\$f(r_s)\\$ is a shape function, with \\$f \\to 0\\$ far away and \\$f \\to 1\\$ inside,",
+ "- \\$r_s\\$ is the radial coordinate.",
+].join("\n");
+
+const REALISTIC_MATH = ["v_s", "f(r_s)", "f \\to 0", "f \\to 1", "r_s"];
+
+test("completed generated lists reach KaTeX through the chat pipeline", () => {
+ const html = renderResponse(REALISTIC_RESPONSE, false);
+
+ assertMath(html, REALISTIC_MATH);
+ assert.ok(!html.includes("$v_s$"));
+ assert.ok(!html.includes("katex-error"));
+});
+
+test("streaming generated lists recover math after the escaped closer arrives", () => {
+ const cache = new IncrementalMarkdownCache();
+ const opener = REALISTIC_RESPONSE.indexOf("\\$v_s\\$");
+ const openTail = opener + "\\$v_s".length;
+ const beforeCloser = renderResponse(
+ REALISTIC_RESPONSE.slice(0, openTail),
+ true,
+ cache,
+ );
+ assert.ok(
+ !beforeCloser.includes(
+ '<annotation encoding="application/x-tex">v_s</annotation>',
+ ),
+ );
+
+ let html = beforeCloser;
+ for (let end = openTail + 7; end < REALISTIC_RESPONSE.length; end += 23) {
+ html = renderResponse(REALISTIC_RESPONSE.slice(0, end), true, cache);
+ assert.ok(!html.includes("katex-error"), `stream prefix ${end}`);
+ }
+ html = renderResponse(REALISTIC_RESPONSE, true, cache);
+
+ assertMath(html, REALISTIC_MATH);
+ assert.ok(!html.includes("$v_s$"));
+ assert.ok(!html.includes("katex-error"));
+});
+
+test("markdown literals and nested escaped math keep their rendered semantics", () => {
+ const markdown = [
+ "Normal prose renders \\$x_1\\$ inline.",
+ "",
+ "Price: $5, budget: $1,200, literal escaped dollar: \\$5.",
+ "",
+ "Code: `\\$code_1\\$` and an incomplete delimiter \\$unfinished",
+ "",
+ "[linked \\$y_2\\$](https://e.test/\\$literal\\$)",
+ "",
+ "> - **nested \\$z^2\\$ math**",
+ "",
+ "$$",
+ "E=mc^2",
+ "$$",
+ ].join("\n");
+ for (const isStreaming of [false, true]) {
+ const html = renderResponse(markdown, isStreaming);
+
+ assertMath(html, ["x_1", "y_2", "z^2", "E=mc^2"]);
+ for (const literal of ["code_1", "literal", "unfinished"]) {
+ assert.ok(
+ !html.includes(
+ `<annotation encoding="application/x-tex">${literal}</annotation>`,
+ ),
+ literal,
+ );
+ }
+ assert.ok(html.includes('data-streamdown="inline-code"'));
+ assert.ok(html.includes("\\$code_1\\$"));
+ assert.ok(html.includes("$5"));
+ assert.ok(html.indexOf("<blockquote") < html.indexOf(">z^2</annotation>"));
+ assert.ok(html.indexOf("<li") < html.indexOf(">z^2</annotation>"));
+ assert.ok(html.indexOf("<strong") < html.indexOf(">z^2</annotation>"));
+ assert.ok(!html.includes("katex-error"));
+ }
+});
+
+test("loose-list continuations reach KaTeX through completed and streaming paths", () => {
+ for (const isStreaming of [false, true]) {
+ const html = renderResponse("- item\n\n \\$x\\$", isStreaming);
+
+ assertMath(html, ["x"]);
+ assert.ok(html.indexOf("<li") < html.indexOf("<annotation"));
+ assert.ok(html.indexOf("<annotation") < html.indexOf("</li>"));
+ assert.ok(!html.includes("$x$"));
+ }
+});
+
+test("long existing display math renders as one intact KaTeX node", () => {
+ const displayBody = `${"z+".repeat(2050)}\\$w\\$`;
+ const html = renderResponse(`$$\n${displayBody}\n$$`, false);
+
+ assert.equal(html.match(/application\/x-tex/g)?.length, 1);
+ assert.ok(html.includes(`${displayBody}</annotation>`));
+ assert.ok(!html.includes("katex-error"));
+});
+
+test("normalization precedes streaming repair and currency escaping", () => {
+ const cases = [
+ {
+ markdown: String.raw`value \$v_{s}\$`,
+ annotation: "v_{s}",
+ },
+ {
+ markdown: String.raw`comparison \$x<y\$`,
+ annotation: String.raw`x\lt y`,
+ },
+ ];
+ for (const isStreaming of [false, true]) {
+ for (const { markdown, annotation } of cases) {
+ const html = renderResponse(markdown, isStreaming);
+ assert.ok(
+ html.includes(
+ `<annotation encoding="application/x-tex">${annotation}</annotation>`,
+ ),
+ `${markdown} in ${isStreaming ? "streaming" : "completed"} mode`,
+ );
+ assert.ok(!html.includes("katex-error"));
+ if (markdown.includes("x<y")) {
+ assert.ok(html.includes("<mo>&lt;</mo>"));
+ }
+ }
+
+ const subscript = renderResponse(String.raw`value \$v_{s}\$`, isStreaming);
+ const withoutAnnotation = subscript.replace(
+ /<annotation encoding="application\/x-tex">.*?<\/annotation>/g,
+ "",
+ );
+ assert.ok(!withoutAnnotation.includes("_"));
+
+ const currency = renderResponse(
+ "The package is $5 + a $10 add-on",
+ isStreaming,
+ );
+ assert.equal(currency.match(/application\/x-tex/g)?.length ?? 0, 0);
+ assert.ok(currency.includes("$5 + a $10 add-on"));
+
+ const mixedCurrency = renderResponse(
+ String.raw`Cost $5; variable \$x\$; cap $10`,
+ isStreaming,
+ );
+ assertMath(mixedCurrency, ["x"]);
+ assert.ok(mixedCurrency.includes("Cost $5; variable"));
+ assert.ok(mixedCurrency.includes("; cap $10"));
+ }
+});
diff --git a/studio/frontend/tests/markdown-streaming-scheduling.test.ts b/studio/frontend/tests/markdown-streaming-scheduling.test.ts
index 6385f0418e5..8ccfbac5b89 100644
--- a/studio/frontend/tests/markdown-streaming-scheduling.test.ts
+++ b/studio/frontend/tests/markdown-streaming-scheduling.test.ts
@@ -167,7 +167,10 @@ test("streaming reparses only the active Markdown tail", () => {
jsxAttribute(streamdown, "parseMarkdownIntoBlocksFn")?.initializer?.getText(
source,
),
- "{incrementalRender?.parseMarkdownIntoBlocks}",
+ "{\n" +
+ " incrementalRender?.parseMarkdownIntoBlocks ??\n" +
+ " parseMarkdownIntoRenderableBlocks\n" +
+ " }",
);
});
@@ -178,6 +181,6 @@ test("dropping retained blocks moves Streamdown's render identity", () => {
assert.ok(streamdown, "chat <Streamdown> is missing");
assert.equal(
jsxAttribute(streamdown, "key")?.initializer?.getText(source),
- "{`${messageId}:${incrementalCache.renderGeneration}`}",
+ "{`${messageId}:${incrementalCache.renderGeneration}:${renderKey}`}",
);
});
diff --git a/studio/frontend/tests/search-images.test.ts b/studio/frontend/tests/search-images.test.ts
index 24f0e349e15..e93b388a285 100644
--- a/studio/frontend/tests/search-images.test.ts
+++ b/studio/frontend/tests/search-images.test.ts
@@ -205,6 +205,20 @@ test("rewriteSearchImageTokens never touches code", () => {
assert.equal(rewriteSearchImageTokens(fenced, KNOWN), fenced);
});
+test("rewriteSearchImageTokens follows Markdown fence container boundaries", () => {
+ const falseFence = `Paragraph\n2. \`\`\`\n[[img:${ENTRY.id}]]`;
+ assert.equal(
+ rewriteSearchImageTokens(falseFence, KNOWN),
+ `Paragraph\n2. \`\`\`\n<search-image token="${ENTRY.id}"></search-image>`,
+ );
+
+ const listFence = `- \`\`\`\n [[img:${ENTRY.id}]]\n\n[[img:${OTHER.id}]]`;
+ assert.equal(
+ rewriteSearchImageTokens(listFence, KNOWN),
+ `- \`\`\`\n [[img:${ENTRY.id}]]\n\n<search-image token="${OTHER.id}"></search-image>`,
+ );
+});
+
test("rewriteSearchImageTokens is a no-op without tokens", () => {
const text = "plain [[not an image]] text";
assert.equal(rewriteSearchImageTokens(text, KNOWN), text);
diff --git a/studio/frontend/tests/streaming-latex-corpus.test.ts b/studio/frontend/tests/streaming-latex-corpus.test.ts
index ebf70ab838a..0a035cf9996 100644
--- a/studio/frontend/tests/streaming-latex-corpus.test.ts
+++ b/studio/frontend/tests/streaming-latex-corpus.test.ts
@@ -69,6 +69,10 @@ const NAMED_CASES: Array<[string, string]> = [
["adjacent-spans", "`a $5` `b $6` `c $7`\n\n"],
["link-parens", "See [docs](https://e.com/a_(b)) and $5.\n\n"],
["list-with-math", "- rate \\(\\alpha\\)\n- budget $250\n- decay \\(\\lambda\\)\n\n"],
+ [
+ "list-with-escaped-dollar-math",
+ "- rate \\$\\alpha\\$\n- budget $250\n- decay \\$\\lambda\\$\n\n",
+ ],
["loose-list", "- item one\n\n continued body $5\n\n- item two\n\n more \\(x\\)\n\n"],
["blockquote", "> quoted \\(x\\) and $5\n> more\n\nafter\n\n"],
["setext", "Heading text\n===\n\nBody with $5.\n\n"],
diff --git a/studio/frontend/tests/streaming-render-schedule.test.ts b/studio/frontend/tests/streaming-render-schedule.test.ts
index 4f28be17887..13509489624 100644
--- a/studio/frontend/tests/streaming-render-schedule.test.ts
+++ b/studio/frontend/tests/streaming-render-schedule.test.ts
@@ -9,6 +9,9 @@ import { Streamdown, parseMarkdownIntoBlocks } from "streamdown";
import { stabilizeStreamingMarkdown } from "../src/components/assistant-ui/streaming-markdown.ts";
import {
IncrementalMarkdownCache,
+ markdownRenderKey,
+ markdownRenderScope,
+ parseMarkdownIntoRenderableBlocks,
withoutStreamdownAnimationPlugin,
} from "../src/components/assistant-ui/streaming-render-schedule.ts";
import { preprocessLaTeX } from "../src/lib/latex.ts";
@@ -116,7 +119,7 @@ test("incremental blocks match a full Streamdown split at every prefix", () => {
const render = cache.update(input);
assert.deepEqual(
render.parseMarkdownIntoBlocks(render.markdown),
- parseMarkdownIntoBlocks(remend(input)),
+ parseMarkdownIntoRenderableBlocks(remend(input)),
`block mismatch at prefix ${length} of ${JSON.stringify(source)}`,
);
}
@@ -157,6 +160,31 @@ test("mid-string remend repairs use the sticky full-document fallback", () => {
}
});
+test("link references and definitions stay in one rendered document", () => {
+ const usage = `Before [reference][math-ref].\n\n${paragraphs(20)}`;
+ const cache = new IncrementalMarkdownCache();
+ cache.update(usage);
+ const generation = cache.renderGeneration;
+
+ const complete = `${usage}[math-ref]: https://example.com/reference`;
+ const render = cache.update(complete);
+ assert.equal(cache.renderGeneration, generation);
+ assert.notEqual(markdownRenderScope(usage), markdownRenderScope(complete));
+ assert.notEqual(
+ markdownRenderKey(`${usage}[math-ref]: `),
+ markdownRenderKey(complete),
+ );
+ assert.equal(render.markdown, remend(complete));
+ assert.deepEqual(render.parseMarkdownIntoBlocks(render.markdown), [
+ remend(complete),
+ ]);
+ assert.deepEqual(parseMarkdownIntoRenderableBlocks(complete), [complete]);
+ assert.equal(
+ (cache as unknown as { fullDocumentMode: boolean }).fullDocumentMode,
+ true,
+ );
+});
+
test("a transient marker imbalance can recover incremental parsing", () => {
const cache = new IncrementalMarkdownCache();
const unbalanced = `Match *.py files here.\n\n${paragraphs(20)}`;