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.

Fix Studio CPU saturation on long streaming replies (#8750)

oobaboogad8c1145f3bbd
diff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsx
index 2fa6f9e373c..58f46d2ab1b 100644
--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx
+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx
@@ -23,12 +23,19 @@ import { Copy01Icon, Download01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { createMathPlugin } from "@streamdown/math";
import { mermaid } from "@streamdown/mermaid";
-import { useContext, useEffect, useMemo, useRef, useState } from "react";
+import {
+ type ComponentProps,
+ memo,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import {
Block,
type BlockProps,
Streamdown,
- StreamdownContext,
type StreamdownProps,
} from "streamdown";
import { createCodePlugin } from "./code-plugin";
@@ -36,24 +43,44 @@ import "katex/dist/katex.min.css";
import { AudioPlayer } from "./audio-player";
import { unslothDarkTheme, unslothLightTheme } from "./code-themes";
import { stabilizeStreamingMarkdown } from "./streaming-markdown";
+import {
+ IncrementalMarkdownCache,
+ withoutStreamdownAnimationPlugin,
+} from "./streaming-render-schedule";
const math = createMathPlugin({ singleDollarTextMath: true });
const code = createCodePlugin({
themes: [unslothLightTheme, unslothDarkTheme],
});
+const STREAMDOWN_PLUGINS = { code, math, mermaid } satisfies NonNullable<
+ StreamdownProps["plugins"]
+>;
+const STREAMDOWN_CONTROLS = {
+ code: false,
+ mermaid: {
+ fullscreen: true,
+ download: true,
+ copy: false,
+ panZoom: true,
+ },
+} satisfies NonNullable<StreamdownProps["controls"]>;
+const STREAMDOWN_SHIKI_THEME = [
+ unslothLightTheme,
+ unslothDarkTheme,
+] satisfies NonNullable<StreamdownProps["shikiTheme"]>;
const { withSmoothContextProvider } = INTERNAL;
// Streamdown 2.5 schedules ordinary streaming blocks in an interruptible React
// transition. A continuous token stream can starve that transition for seconds.
-// Its animated path commits every block update directly; zero duration preserves
-// that scheduling behavior without adding a visible text animation.
+// Its animated path commits every block update directly. StreamdownBlock removes
+// the animation transformer while retaining this direct scheduling path.
const STREAMDOWN_IMMEDIATE_UPDATES = {
duration: 0,
stagger: 0,
} satisfies NonNullable<StreamdownProps["animated"]>;
const STREAMDOWN_COMPONENTS = {
- a: ({ href, children, ...props }: React.ComponentProps<"a">) => (
+ a: ({ href, children, ...props }: ComponentProps<"a">) => (
<a
href={href}
rel="noopener noreferrer"
@@ -245,15 +272,31 @@ function CodeBlockActions({
);
}
+function useAnimationFreeBlockProps(props: BlockProps): BlockProps {
+ // `animated` is needed only to bypass Streamdown's starvable React transition.
+ // Its rehype plugin still wraps every word even with duration and stagger set
+ // to zero. Remove that one plugin before parsing so long streams do not create
+ // thousands of animation spans. Keep the filtered array stable so completed
+ // blocks remain memoised while the final block continues streaming.
+ const rehypePlugins = useMemo(
+ () =>
+ withoutStreamdownAnimationPlugin(
+ props.rehypePlugins,
+ props.animatePlugin,
+ ),
+ [props.animatePlugin, props.rehypePlugins],
+ );
+ return {
+ ...props,
+ animatePlugin: null,
+ rehypePlugins,
+ } satisfies BlockProps;
+}
+
// Collapse a full-HTML answer in place into an artifact card. Diffusion keeps the
// raw code visible instead (the trailing MessageHtmlArtifacts appends its card).
-function StreamdownBlock(props: BlockProps) {
- // Streamdown memoises each block on its content, so a block that finished
- // streaming is never re-parsed and keeps the per-word animation wrappers the
- // animated path added. Keying the block on the animating flag re-parses each
- // one once when the message completes, without remounting the whole message.
- const { isAnimating } = useContext(StreamdownContext);
- const blockKey = isAnimating ? "live" : "done";
+function StreamdownBlockContent(props: BlockProps) {
+ const blockProps = useAnimationFreeBlockProps(props);
const shouldCollapseHtmlArtifacts = useChatRuntimeStore(
(state) =>
(state.artifactsEnabled || state.collapseHtmlArtifacts) &&
@@ -307,7 +350,7 @@ function StreamdownBlock(props: BlockProps) {
if (mermaidSource) {
return (
<div className="relative isolate">
- <Block {...props} />
+ <Block {...blockProps} />
<MermaidCopyButton source={mermaidSource} />
</div>
);
@@ -335,7 +378,7 @@ function StreamdownBlock(props: BlockProps) {
return (
<>
<div className="relative isolate">
- <Block {...props} />
+ <Block {...blockProps} />
<CodeBlockActions
disabled={props.isIncomplete}
language={codeFence.language}
@@ -347,65 +390,99 @@ function StreamdownBlock(props: BlockProps) {
);
}
- return <Block {...props} key={blockKey} />;
+ return <Block {...blockProps} />;
}
+const StreamdownBlock = memo(StreamdownBlockContent);
const AUDIO_PLAYER_RE = /<audio-player\s+src="([^"]+)"\s*\/>/;
-// Coalesce markdown re-parses to one per frame while streaming: tokens arrive
-// hundreds/sec, faster than the monitor can paint. When not streaming we return
-// live text (not the throttled state) so final text never lags and a reused
-// instance (parts keyed by index) shows completed text instead of a stale frame.
-function useRafCoalescedText(text: string, isStreaming: boolean): string {
- const [displayed, setDisplayed] = useState(text);
- const pendingRef = useRef(text);
+// Coalesce only token events that arrive before the browser's next paint, as
+// textgen does. There is no time or length throttle. Incremental block parsing
+// bounds the work performed per paint, and completion returns immediately.
+function useCoalescedStreamingText(
+ text: string,
+ isStreaming: boolean,
+ messageId: string,
+): string {
+ const [displayed, setDisplayed] = useState({ messageId, text });
+ const pendingRef = useRef({ messageId, text });
const rafRef = useRef<number | null>(null);
+ const activeMessageIdRef = useRef(messageId);
+
+ const cancelScheduledRender = useCallback(() => {
+ if (rafRef.current !== null) {
+ cancelAnimationFrame(rafRef.current);
+ rafRef.current = null;
+ }
+ }, []);
useEffect(() => {
- pendingRef.current = text;
+ pendingRef.current = { messageId, text };
+ if (activeMessageIdRef.current !== messageId) {
+ cancelScheduledRender();
+ activeMessageIdRef.current = messageId;
+ }
if (!isStreaming) {
- if (rafRef.current !== null) {
- cancelAnimationFrame(rafRef.current);
- rafRef.current = null;
- }
+ cancelScheduledRender();
return;
}
- if (rafRef.current === null) {
- rafRef.current = requestAnimationFrame(() => {
- rafRef.current = null;
- setDisplayed(pendingRef.current);
- });
+
+ if (rafRef.current !== null) {
+ return;
}
- }, [text, isStreaming]);
- // Unmount cleanup: cancel the in-flight rAF and null the handle so a
- // StrictMode remount isn't gated by a stale id. Separate from the scheduling
- // effect so it doesn't cancel mid-stream and defeat the throttle.
- useEffect(() => {
- return () => {
- if (rafRef.current !== null) {
- cancelAnimationFrame(rafRef.current);
- rafRef.current = null;
- }
- };
- }, []);
+ rafRef.current = requestAnimationFrame(() => {
+ rafRef.current = null;
+ setDisplayed(pendingRef.current);
+ });
+ }, [cancelScheduledRender, messageId, text, isStreaming]);
- if (isStreaming && text.startsWith(displayed)) {
- return displayed;
+ useEffect(() => {
+ return cancelScheduledRender;
+ }, [cancelScheduledRender]);
+
+ // Holding the last painted text is only correct while the reply is being
+ // appended to. A running message can also be replaced, as the audio path does
+ // when it swaps its placeholder for the player, and that must show at once.
+ // The length check rejects most of those before the prefix scan runs; the
+ // scan itself costs about 59 ms across a 175,000 character stream.
+ if (
+ isStreaming &&
+ displayed.messageId === messageId &&
+ text.length >= displayed.text.length &&
+ text.startsWith(displayed.text)
+ ) {
+ return displayed.text;
}
return text;
}
const MarkdownTextImpl = () => {
const { text, status } = useMessagePartText();
- // Parts are keyed by index, so switching conversations hands this instance a different
- // message, and Streamdown only extends its parsed blocks: key it per message instead.
+ // Parts are keyed by index, so switching conversations hands this instance a
+ // different message, and Streamdown only extends its parsed blocks: key it per
+ // message. The cache generation joins the key for the case the Markdown string
+ // cannot express, an edit that drops retained blocks without changing the tail.
const messageId = useAuiState(({ message }) => message.id);
const isStreaming = status.type === "running";
- const displayText = useRafCoalescedText(text, isStreaming);
+ const displayText = useCoalescedStreamingText(text, isStreaming, messageId);
const processedText = useMemo(
() => stabilizeStreamingMarkdown(preprocessLaTeX(displayText), isStreaming),
[displayText, isStreaming],
);
+ const incrementalCacheRef = useRef({
+ messageId,
+ cache: new IncrementalMarkdownCache(),
+ });
+ if (incrementalCacheRef.current.messageId !== messageId) {
+ incrementalCacheRef.current = {
+ messageId,
+ cache: new IncrementalMarkdownCache(),
+ };
+ }
+ const incrementalCache = incrementalCacheRef.current.cache;
+ const incrementalRender = isStreaming
+ ? incrementalCache.update(processedText)
+ : null;
const audioMatch = displayText.match(AUDIO_PLAYER_RE);
if (audioMatch) {
@@ -415,26 +492,20 @@ const MarkdownTextImpl = () => {
return (
<div data-status={status.type} className="min-w-0 max-w-full">
<Streamdown
- key={messageId}
+ key={`${messageId}:${incrementalCache.renderGeneration}`}
mode="streaming"
+ parseIncompleteMarkdown={!incrementalRender}
+ parseMarkdownIntoBlocksFn={incrementalRender?.parseMarkdownIntoBlocks}
isAnimating={isStreaming}
animated={STREAMDOWN_IMMEDIATE_UPDATES}
- plugins={{ code, math, mermaid }}
+ plugins={STREAMDOWN_PLUGINS}
components={STREAMDOWN_COMPONENTS}
urlTransform={safeMarkdownUrl}
- controls={{
- code: false,
- mermaid: {
- fullscreen: true,
- download: true,
- copy: false,
- panZoom: true,
- },
- }}
- shikiTheme={[unslothLightTheme, unslothDarkTheme]}
+ controls={STREAMDOWN_CONTROLS}
+ shikiTheme={STREAMDOWN_SHIKI_THEME}
BlockComponent={StreamdownBlock}
>
- {processedText}
+ {incrementalRender?.markdown ?? processedText}
</Streamdown>
</div>
);
diff --git a/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts b/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts
new file mode 100644
index 00000000000..628bd9a13ac
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts
@@ -0,0 +1,778 @@
+// 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 remend from "remend";
+import { type BlockProps, parseMarkdownIntoBlocks } from "streamdown";
+
+// How far behind the live edge a block has to be before it can be retained.
+// The block list interleaves "\n\n" separators, so this is about four
+// paragraphs of slack for a construct that a later line can still reinterpret.
+const ROLLBACK_BLOCKS = 8;
+// A marker the reply never closes leaves the tail growing with nothing to
+// retain, and the boundary scan is then paid on top of the full repair it was
+// meant to replace. Give up at a character budget, since characters are what
+// that scan costs, and a transient imbalance closes far below this. The budget
+// is spent before giving up and that spending grows with the square of the tail,
+// so the value matters. Measured on an emphasis marker that only closes 40,000
+// characters later, 420 updates, five repetitions: the median cost against the
+// full-document path is +73% at 32,768 and +1.6% at 8,192. 8,192 characters is
+// still around 1,300 words of slack, well beyond a marker a later line closes.
+const STALLED_TAIL_CHARACTERS = 8_192;
+// Balanced marker prefixes preserve the whole-document facts that remend uses
+// to decide how an incomplete tail should close, without changing parity.
+const MULTILINE_KATEX_CONTEXT = "$$\n$$\n\n";
+const BOLD_CONTEXT = "**x**\n\n";
+const SINGLE_ASTERISK_CONTEXT = "*x*\n\n";
+const SINGLE_UNDERSCORE_CONTEXT = "_x_\n\n";
+const INLINE_CODE_ASTERISK_CONTEXT = "`a *b* c`\n\n";
+const INLINE_CODE_UNDERSCORE_CONTEXT = "`a _b_ c`\n\n";
+const FOOTNOTE_REFERENCE_RE = /\[\^[\w-]{1,200}\](?!:)/;
+const FOOTNOTE_DEFINITION_RE = /\[\^[\w-]{1,200}\]:/;
+const LINK_DEFINITION_RE = /\[(?:\\.|[^\]\n\\]){1,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/]/;
+
+type RepairParity = {
+ bold: boolean;
+ boldCandidate: boolean;
+ boldFence: boolean;
+ bracketDepth: number;
+ linkDefinition: boolean;
+ doubleUnderscore: boolean;
+ emphasisDisplayMath: boolean;
+ emphasisInlineCode: boolean;
+ emphasisInlineMath: boolean;
+ firstBoldOrSingleUnderscore: "bold" | "singleUnderscore" | null;
+ singleAsterisk: boolean;
+ singleAsteriskCandidate: boolean;
+ firstSingleAsteriskCandidate: "inlineCode" | "normal" | null;
+ singleUnderscore: boolean;
+ singleUnderscoreCandidate: boolean;
+ firstSingleUnderscoreCandidate: "inlineCode" | "normal" | null;
+ tripleAsterisk: boolean;
+ displayMathInlineCode: boolean;
+ inlineCode: boolean;
+ inlineMathInlineCode: boolean;
+ strikethrough: boolean;
+ displayMath: boolean;
+ inlineMath: boolean;
+};
+
+const createRepairParity = (): RepairParity => ({
+ bold: false,
+ boldCandidate: false,
+ boldFence: false,
+ bracketDepth: 0,
+ linkDefinition: false,
+ doubleUnderscore: false,
+ emphasisDisplayMath: false,
+ emphasisInlineCode: false,
+ emphasisInlineMath: false,
+ firstBoldOrSingleUnderscore: null,
+ singleAsterisk: false,
+ singleAsteriskCandidate: false,
+ firstSingleAsteriskCandidate: null,
+ singleUnderscore: false,
+ singleUnderscoreCandidate: false,
+ firstSingleUnderscoreCandidate: null,
+ tripleAsterisk: false,
+ displayMathInlineCode: false,
+ inlineCode: false,
+ inlineMathInlineCode: false,
+ strikethrough: false,
+ displayMath: false,
+ inlineMath: false,
+});
+
+// Marked keeps link reference definitions in one document-wide map and emits
+// no token for a label it has already seen, so a definition that is retained
+// while its twin is still live would be lexed apart and shown as a literal
+// line. Keeping every definition in the live tail makes the two lexes agree.
+// Marked reads a fenced block as code, so those do not count; anything else
+// that merely looks like a definition costs retention, never correctness.
+function updateLinkDefinitionParity(parity: RepairParity, text: string): void {
+ if (!FENCED_CODE_BLOCK_RE.test(text) && LINK_DEFINITION_RE.test(text)) {
+ parity.linkDefinition = true;
+ }
+}
+
+const isTripleBacktick = (text: string, index: number): boolean =>
+ (index >= 2 && text.slice(index - 2, index + 1) === "```") ||
+ (index >= 1 && text.slice(index - 1, index + 2) === "```") ||
+ text.slice(index, index + 3) === "```";
+
+const isWordCharacter = (character: string | undefined): boolean =>
+ character !== undefined && WORD_CHARACTER_RE.test(character);
+
+function findLinkDestinationStart(text: string, index: number): number {
+ for (let cursor = index - 1; cursor >= 0; cursor -= 1) {
+ const character = text[cursor];
+ if (character === ")" || character === "\n") {
+ return -1;
+ }
+ if (character === "(") {
+ return cursor > 0 && text[cursor - 1] === "]" ? cursor : -1;
+ }
+ }
+ return -1;
+}
+
+function hasLinkDestinationEnd(text: string, index: number): boolean {
+ for (let cursor = index; cursor < text.length; cursor += 1) {
+ if (text[cursor] === ")") {
+ return true;
+ }
+ if (text[cursor] === "\n") {
+ return false;
+ }
+ }
+ return false;
+}
+
+const isWithinLinkDestination = (text: string, index: number): boolean =>
+ findLinkDestinationStart(text, index) >= 0 &&
+ hasLinkDestinationEnd(text, index);
+
+function isWithinHtmlTag(text: string, index: number): boolean {
+ for (let cursor = index - 1; cursor >= 0; cursor -= 1) {
+ if (text[cursor] === ">") {
+ return false;
+ }
+ if (text[cursor] === "<") {
+ return HTML_TAG_START_RE.test(text[cursor + 1] ?? "");
+ }
+ if (text[cursor] === "\n") {
+ return false;
+ }
+ }
+ return false;
+}
+
+function updateEmphasisMathParity(
+ parity: RepairParity,
+ text: string,
+ index: number,
+): number {
+ if (text[index] === "\\" && text[index + 1] === "$") {
+ return index + 1;
+ }
+ if (text[index] !== "$") {
+ return index;
+ }
+ if (text[index + 1] === "$") {
+ parity.emphasisDisplayMath = !parity.emphasisDisplayMath;
+ parity.emphasisInlineMath = false;
+ return index + 1;
+ }
+ if (!parity.emphasisDisplayMath) {
+ parity.emphasisInlineMath = !parity.emphasisInlineMath;
+ }
+ return index;
+}
+
+function countsAsSingleAsterisk(
+ parity: RepairParity,
+ text: string,
+ index: number,
+): boolean {
+ const previous = text[index - 1];
+ const next = text[index + 1];
+ if (
+ previous === "\\" ||
+ parity.emphasisDisplayMath ||
+ parity.emphasisInlineMath
+ ) {
+ return false;
+ }
+ if (previous !== "*" && next === "*") {
+ return text[index + 2] === "*";
+ }
+ if (
+ previous === "*" ||
+ (isWordCharacter(previous) && isWordCharacter(next))
+ ) {
+ return false;
+ }
+ const previousIsBoundary =
+ previous === undefined ||
+ previous === " " ||
+ previous === "\t" ||
+ previous === "\n";
+ const nextIsBoundary =
+ next === undefined || next === " " || next === "\t" || next === "\n";
+ return !(previousIsBoundary && nextIsBoundary);
+}
+
+function isSingleAsteriskCandidate(
+ parity: RepairParity,
+ text: string,
+ index: number,
+): boolean {
+ const previous = text[index - 1];
+ const next = text[index + 1];
+ if (
+ previous === "\\" ||
+ previous === "*" ||
+ next === "*" ||
+ parity.emphasisDisplayMath ||
+ parity.emphasisInlineMath
+ ) {
+ return false;
+ }
+ const previousIsBoundary =
+ previous === undefined ||
+ previous === " " ||
+ previous === "\t" ||
+ previous === "\n";
+ const nextIsBoundary =
+ next === undefined || next === " " || next === "\t" || next === "\n";
+ return !(
+ (previousIsBoundary && nextIsBoundary) ||
+ (isWordCharacter(previous) && isWordCharacter(next))
+ );
+}
+
+function countsAsSingleUnderscore(
+ parity: RepairParity,
+ text: string,
+ index: number,
+): boolean {
+ const previous = text[index - 1];
+ const next = text[index + 1];
+ return !(
+ previous === "\\" ||
+ parity.emphasisDisplayMath ||
+ parity.emphasisInlineMath ||
+ isWithinLinkDestination(text, index) ||
+ isWithinHtmlTag(text, index) ||
+ previous === "_" ||
+ next === "_" ||
+ (isWordCharacter(previous) && isWordCharacter(next))
+ );
+}
+
+function isSingleUnderscoreCandidate(
+ parity: RepairParity,
+ text: string,
+ index: number,
+): boolean {
+ const previous = text[index - 1];
+ const next = text[index + 1];
+ return !(
+ previous === "\\" ||
+ previous === "_" ||
+ next === "_" ||
+ parity.emphasisDisplayMath ||
+ parity.emphasisInlineMath ||
+ isWithinLinkDestination(text, index) ||
+ (isWordCharacter(previous) && isWordCharacter(next))
+ );
+}
+
+// Remend decides these closers from marker parity over the whole document, so a
+// retained prefix must end with neutral parity: repairing the tail alone could
+// otherwise add or omit a closer that a full repair would place differently.
+function updateAsteriskParity(
+ parity: RepairParity,
+ text: string,
+ index: number,
+): number {
+ if (isSingleAsteriskCandidate(parity, text, index)) {
+ parity.singleAsteriskCandidate = true;
+ parity.firstSingleAsteriskCandidate ??= parity.emphasisInlineCode
+ ? "inlineCode"
+ : "normal";
+ }
+ if (countsAsSingleAsterisk(parity, text, index)) {
+ parity.singleAsterisk = !parity.singleAsterisk;
+ }
+ if (text[index + 1] === "*") {
+ parity.boldCandidate = true;
+ parity.firstBoldOrSingleUnderscore ??= "bold";
+ parity.bold = !parity.bold;
+ return index + 1;
+ }
+ return index;
+}
+
+function updateUnderscoreParity(
+ parity: RepairParity,
+ text: string,
+ index: number,
+): number {
+ if (isSingleUnderscoreCandidate(parity, text, index)) {
+ parity.singleUnderscoreCandidate = true;
+ parity.firstSingleUnderscoreCandidate ??= parity.emphasisInlineCode
+ ? "inlineCode"
+ : "normal";
+ parity.firstBoldOrSingleUnderscore ??= "singleUnderscore";
+ }
+ if (text[index + 1] === "_") {
+ parity.doubleUnderscore = !parity.doubleUnderscore;
+ return index + 1;
+ }
+ if (countsAsSingleUnderscore(parity, text, index)) {
+ parity.singleUnderscore = !parity.singleUnderscore;
+ }
+ return index;
+}
+
+// Remend finds the marker that orders its closers with a raw indexOf("**") but
+// counts pairs only outside fenced code, so a `**` in a fence has to seed the
+// bold context without reaching the fence-aware counter in updateAsteriskParity.
+function recordBoldMarker(
+ parity: RepairParity,
+ text: string,
+ index: number,
+): void {
+ if (text[index] === "*" && text[index + 1] === "*") {
+ parity.boldCandidate = true;
+ parity.firstBoldOrSingleUnderscore ??= "bold";
+ }
+}
+
+// Remend completes a dangling link by appending to the end of the whole
+// document, so a retained block still holding an unmatched bracket would move
+// that completion out of the tail. Brackets in code do not count, as in remend.
+function updateBracketDepth(parity: RepairParity, character: string): void {
+ if (character === "[") {
+ parity.bracketDepth += 1;
+ } else if (character === "]" && parity.bracketDepth > 0) {
+ parity.bracketDepth -= 1;
+ }
+}
+
+// Remend consumes an escaped backtick before testing for a fence, so a fence
+// that starts one character after a backslash is not a fence. Returns the index
+// to resume from, or the same index when neither applies.
+function skipEscapeOrFence(
+ parity: RepairParity,
+ text: string,
+ index: number,
+): number {
+ if (text[index] === "\\" && text[index + 1] === "`") {
+ return index + 1;
+ }
+ if (text.slice(index, index + 3) === "```") {
+ parity.boldFence = !parity.boldFence;
+ return index + 2;
+ }
+ return index;
+}
+
+function updateEmphasisParity(parity: RepairParity, text: string): void {
+ for (let index = 0; index < text.length; index += 1) {
+ index = updateEmphasisMathParity(parity, text, index);
+ const skipped = skipEscapeOrFence(parity, text, index);
+ if (skipped !== index) {
+ index = skipped;
+ continue;
+ }
+ recordBoldMarker(parity, text, index);
+ if (parity.boldFence) {
+ continue;
+ }
+ if (text[index] === "`") {
+ parity.emphasisInlineCode = !parity.emphasisInlineCode;
+ continue;
+ }
+ if (!parity.emphasisInlineCode) {
+ updateBracketDepth(parity, text[index]);
+ }
+ if (text[index] === "*") {
+ index = updateAsteriskParity(parity, text, index);
+ continue;
+ }
+ if (text[index] === "_") {
+ index = updateUnderscoreParity(parity, text, index);
+ }
+ }
+}
+
+function updateTripleAsteriskParity(parity: RepairParity, text: string): void {
+ let inFence = false;
+ let runLength = 0;
+ const finishRun = () => {
+ if (Math.floor(runLength / 3) % 2 === 1) {
+ parity.tripleAsterisk = !parity.tripleAsterisk;
+ }
+ runLength = 0;
+ };
+ for (let index = 0; index < text.length; index += 1) {
+ if (text.slice(index, index + 3) === "```") {
+ finishRun();
+ inFence = !inFence;
+ index += 2;
+ } else if (!inFence && text[index] === "*") {
+ runLength += 1;
+ } else {
+ finishRun();
+ }
+ }
+ finishRun();
+}
+
+function updateInlineCodeParity(parity: RepairParity, text: string): void {
+ for (let index = 0; index < text.length; index += 1) {
+ if (text[index] === "\\" && text[index + 1] === "`") {
+ index += 1;
+ continue;
+ }
+ if (text[index] === "`" && !isTripleBacktick(text, index)) {
+ parity.inlineCode = !parity.inlineCode;
+ }
+ }
+}
+
+function updateStrikethroughParity(parity: RepairParity, text: string): void {
+ const strikeMarkers = text.match(/~~/g)?.length ?? 0;
+ if (strikeMarkers % 2 === 1) {
+ parity.strikethrough = !parity.strikethrough;
+ }
+}
+
+// Remend's display-math scan stops one character early: it only reads whole
+// documents, where the last character cannot open a pair. This one runs per
+// retained block, whose boundaries are interior, so it counts to text.length.
+function updateDisplayMathParity(parity: RepairParity, text: string): void {
+ for (let index = 0; index < text.length; index += 1) {
+ if (text[index] === "`" && !isTripleBacktick(text, index)) {
+ parity.displayMathInlineCode = !parity.displayMathInlineCode;
+ continue;
+ }
+ if (
+ !parity.displayMathInlineCode &&
+ text[index] === "$" &&
+ text[index + 1] === "$"
+ ) {
+ parity.displayMath = !parity.displayMath;
+ index += 1;
+ }
+ }
+}
+
+function updateInlineMathParity(parity: RepairParity, text: string): void {
+ for (let index = 0; index < text.length; index += 1) {
+ if (text[index] === "\\") {
+ index += 1;
+ continue;
+ }
+ if (text[index] === "`" && !isTripleBacktick(text, index)) {
+ parity.inlineMathInlineCode = !parity.inlineMathInlineCode;
+ continue;
+ }
+ if (parity.inlineMathInlineCode || text[index] !== "$") {
+ continue;
+ }
+ if (text[index + 1] === "$") {
+ index += 1;
+ } else {
+ parity.inlineMath = !parity.inlineMath;
+ }
+ }
+}
+
+function updateRepairParity(parity: RepairParity, text: string): void {
+ updateLinkDefinitionParity(parity, text);
+ updateEmphasisParity(parity, text);
+ updateTripleAsteriskParity(parity, text);
+ updateInlineCodeParity(parity, text);
+ updateStrikethroughParity(parity, text);
+ updateDisplayMathParity(parity, text);
+ updateInlineMathParity(parity, text);
+}
+
+const hasNeutralRepairParity = (parity: RepairParity): boolean =>
+ ![
+ parity.bracketDepth > 0,
+ parity.linkDefinition,
+ parity.bold,
+ parity.boldFence,
+ parity.emphasisInlineCode,
+ parity.doubleUnderscore,
+ parity.emphasisDisplayMath,
+ parity.emphasisInlineMath,
+ parity.singleAsterisk,
+ parity.singleUnderscore,
+ parity.tripleAsterisk,
+ parity.displayMathInlineCode,
+ parity.inlineCode,
+ parity.inlineMathInlineCode,
+ parity.strikethrough,
+ parity.displayMath,
+ parity.inlineMath,
+ ].includes(true);
+
+export type IncrementalMarkdownRender = {
+ markdown: string;
+ parseMarkdownIntoBlocks: (markdown: string) => string[];
+};
+
+// Marker facts the retained prefix carries into the tail repair.
+type RetainedContext = {
+ multilineKatex: boolean;
+ bold: boolean;
+ singleAsterisk: boolean;
+ singleUnderscore: boolean;
+ firstSingleAsterisk: "inlineCode" | "normal" | null;
+ firstSingleUnderscore: "inlineCode" | "normal" | null;
+ firstBoldOrSingleUnderscore: "bold" | "singleUnderscore" | null;
+};
+
+const createRetainedContext = (): RetainedContext => ({
+ multilineKatex: false,
+ bold: false,
+ singleAsterisk: false,
+ singleUnderscore: false,
+ firstSingleAsterisk: null,
+ firstSingleUnderscore: null,
+ firstBoldOrSingleUnderscore: null,
+});
+
+const singleUnderscoreContext = (context: RetainedContext): string => {
+ if (!context.singleUnderscore) {
+ return "";
+ }
+ return context.firstSingleUnderscore === "inlineCode"
+ ? INLINE_CODE_UNDERSCORE_CONTEXT
+ : SINGLE_UNDERSCORE_CONTEXT;
+};
+
+const singleAsteriskContext = (context: RetainedContext): string => {
+ if (!context.singleAsterisk) {
+ return "";
+ }
+ return context.firstSingleAsterisk === "inlineCode"
+ ? INLINE_CODE_ASTERISK_CONTEXT
+ : SINGLE_ASTERISK_CONTEXT;
+};
+
+const emphasisContext = (context: RetainedContext): string => {
+ const bold = context.bold ? BOLD_CONTEXT : "";
+ const underscore = singleUnderscoreContext(context);
+ return context.firstBoldOrSingleUnderscore === "singleUnderscore"
+ ? underscore + bold
+ : bold + underscore;
+};
+
+// Taking the context as a value lets a candidate commit be priced before it is
+// applied, which the repeated-Markdown check in update() needs.
+function repairTail(tail: string, context: RetainedContext): string {
+ const prefix =
+ emphasisContext(context) +
+ singleAsteriskContext(context) +
+ (context.multilineKatex ? MULTILINE_KATEX_CONTEXT : "");
+ if (!prefix) {
+ return remend(tail);
+ }
+ return remend(prefix + tail).slice(prefix.length);
+}
+
+const advanceContext = (
+ context: RetainedContext,
+ parity: RepairParity,
+ committedText: string,
+): RetainedContext => ({
+ multilineKatex: context.multilineKatex || committedText.includes("$$"),
+ bold: context.bold || parity.boldCandidate,
+ singleAsterisk: context.singleAsterisk || parity.singleAsteriskCandidate,
+ singleUnderscore:
+ context.singleUnderscore || parity.singleUnderscoreCandidate,
+ firstSingleAsterisk:
+ context.firstSingleAsterisk ?? parity.firstSingleAsteriskCandidate,
+ firstSingleUnderscore:
+ context.firstSingleUnderscore ?? parity.firstSingleUnderscoreCandidate,
+ firstBoldOrSingleUnderscore:
+ context.firstBoldOrSingleUnderscore ?? parity.firstBoldOrSingleUnderscore,
+});
+
+type CommitBoundary = {
+ count: number;
+ length: number;
+ // The parity at the boundary, or null when no block can be retained.
+ parity: RepairParity | null;
+ repairBroke: boolean;
+};
+
+// Remend may synthesize closing syntax at the end of an incomplete tail.
+// Never retain synthetic or mid-string repaired text. Scan forward once,
+// recording the latest exact boundary whose global repair parity is neutral.
+function findCommitBoundary(
+ tail: string,
+ blocks: string[],
+ candidateCount: number,
+): CommitBoundary {
+ const parity = createRepairParity();
+ const commit: CommitBoundary = {
+ count: 0,
+ length: 0,
+ parity: null,
+ repairBroke: false,
+ };
+ let exactLength = 0;
+
+ for (let index = 0; index < candidateCount; index += 1) {
+ const block = blocks[index];
+ if (!tail.startsWith(block, exactLength)) {
+ commit.repairBroke = true;
+ break;
+ }
+ exactLength += block.length;
+ updateRepairParity(parity, block);
+ if (hasNeutralRepairParity(parity)) {
+ commit.count = index + 1;
+ commit.length = exactLength;
+ commit.parity = { ...parity };
+ }
+ }
+
+ return commit;
+}
+
+// Streamdown normally repairs and lexes the entire growing reply on every
+// update. Retain blocks that are safely behind a rollback window and give
+// Streamdown only the active tail. The parser callback puts the retained blocks
+// back into its block list, so output and React keys stay identical.
+export class IncrementalMarkdownCache {
+ private source = "";
+ private tail = "";
+ private committedBlocks: string[] = [];
+ private context = createRetainedContext();
+ private fullDocumentMode = false;
+ private lastMarkdown: string | null = null;
+ private droppedRetainedBlocks = false;
+ // Bumped only when the Markdown string alone cannot signal a changed render.
+ renderGeneration = 0;
+
+ readonly parseMarkdownIntoBlocks = (markdown: string): string[] => [
+ ...this.committedBlocks,
+ ...parseMarkdownIntoBlocks(markdown),
+ ];
+
+ // Streamdown memoises the whole component on the Markdown string and ignores
+ // the parser callback, so the string is the only thing that can schedule a
+ // render. Retaining a block can wait for a string that differs, but dropping
+ // retained blocks cannot, so that case moves the render identity instead.
+ private render(markdown: string): IncrementalMarkdownRender {
+ if (this.droppedRetainedBlocks && markdown === this.lastMarkdown) {
+ this.renderGeneration += 1;
+ }
+ this.droppedRetainedBlocks = false;
+ this.lastMarkdown = markdown;
+ return { markdown, parseMarkdownIntoBlocks: this.parseMarkdownIntoBlocks };
+ }
+
+ private resetIncrementalState(markdown: string): void {
+ this.droppedRetainedBlocks ||= this.committedBlocks.length > 0;
+ this.source = markdown;
+ this.tail = markdown;
+ this.committedBlocks = [];
+ this.context = createRetainedContext();
+ }
+
+ private renderFullDocument(markdown: string): IncrementalMarkdownRender {
+ this.resetIncrementalState(markdown);
+ this.fullDocumentMode = true;
+ return this.render(remend(markdown));
+ }
+
+ private updateTail(markdown: string): void {
+ if (markdown.startsWith(this.source)) {
+ this.tail += markdown.slice(this.source.length);
+ } else {
+ this.resetIncrementalState(markdown);
+ this.fullDocumentMode = false;
+ }
+ this.source = markdown;
+ }
+
+ update(markdown: string): IncrementalMarkdownRender {
+ // Tokens arrive faster than frames, so the coalescer hands the same text to
+ // several renders. Nothing about the result can differ, and repeating the
+ // work would be the whole reply again once the document path is in use.
+ if (markdown === this.source && this.lastMarkdown !== null) {
+ return {
+ markdown: this.lastMarkdown,
+ parseMarkdownIntoBlocks: this.parseMarkdownIntoBlocks,
+ };
+ }
+
+ if (this.fullDocumentMode && markdown.startsWith(this.source)) {
+ this.source = markdown;
+ return this.renderFullDocument(markdown);
+ }
+
+ this.updateTail(markdown);
+
+ const repaired = 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.
+ if (
+ FOOTNOTE_REFERENCE_RE.test(repaired) ||
+ FOOTNOTE_DEFINITION_RE.test(repaired)
+ ) {
+ return this.renderFullDocument(markdown);
+ }
+
+ const blocks = parseMarkdownIntoBlocks(repaired);
+
+ const candidateCount = Math.max(0, blocks.length - ROLLBACK_BLOCKS);
+ if (candidateCount === 0) {
+ return this.render(repaired);
+ }
+
+ const commit = findCommitBoundary(this.tail, blocks, candidateCount);
+
+ // A mid-string repair can never become a raw prefix on a later append, so
+ // make that fallback sticky, and do the same once the tail grows past the
+ // budget with nothing to show for it. A temporarily unbalanced marker can
+ // close in a later block, so below the budget keep the tail live and retry.
+ if (!commit.parity) {
+ if (commit.repairBroke || this.tail.length > STALLED_TAIL_CHARACTERS) {
+ return this.renderFullDocument(markdown);
+ }
+ return this.render(repaired);
+ }
+
+ const committedText = this.tail.slice(0, commit.length);
+ const nextContext = advanceContext(
+ this.context,
+ commit.parity,
+ committedText,
+ );
+ const nextTail = this.tail.slice(commit.length);
+ const nextMarkdown = repairTail(nextTail, nextContext);
+
+ // A repeating reply can leave the tail unchanged once a block is retained.
+ // Streamdown would then see the Markdown it already holds and skip the
+ // render, so the retained blocks would never be displayed. Keep them in the
+ // live tail instead; the next update commits them with a longer string.
+ if (nextMarkdown === this.lastMarkdown) {
+ return this.render(repaired);
+ }
+
+ this.committedBlocks.push(...blocks.slice(0, commit.count));
+ this.context = nextContext;
+ this.tail = nextTail;
+
+ return this.render(nextMarkdown);
+ }
+}
+
+export function withoutStreamdownAnimationPlugin(
+ rehypePlugins: BlockProps["rehypePlugins"],
+ animatePlugin: BlockProps["animatePlugin"],
+): BlockProps["rehypePlugins"] {
+ const animationPlugin = animatePlugin?.rehypePlugin;
+ if (!animationPlugin) {
+ return rehypePlugins;
+ }
+
+ return rehypePlugins?.filter((plugin) => {
+ const pluginFunction = Array.isArray(plugin) ? plugin[0] : plugin;
+ return pluginFunction !== animationPlugin;
+ });
+}
diff --git a/studio/frontend/tests/markdown-block-remount-on-complete.test.ts b/studio/frontend/tests/markdown-block-remount-on-complete.test.ts
index 91a1bed7e34..67f5f8ef392 100644
--- a/studio/frontend/tests/markdown-block-remount-on-complete.test.ts
+++ b/studio/frontend/tests/markdown-block-remount-on-complete.test.ts
@@ -3,8 +3,8 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
import test from "node:test";
+import { fileURLToPath } from "node:url";
import ts from "typescript";
@@ -31,91 +31,54 @@ function findFunction(name: string): ts.FunctionDeclaration | null {
return found;
}
-function findJsx(
- scope: ts.Node,
- tagName: string,
-): ts.JsxOpeningLikeElement | null {
- let found: ts.JsxOpeningLikeElement | null = null;
- const visit = (node: ts.Node): void => {
- if (
- (ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) &&
- node.tagName.getText(source) === tagName &&
- !found
- ) {
- found = node;
- }
- node.forEachChild(visit);
- };
- scope.forEachChild(visit);
- return found;
-}
-
-function jsxAttribute(
- opening: ts.JsxOpeningLikeElement,
- name: string,
-): ts.JsxAttribute | null {
- for (const attribute of opening.attributes.properties) {
- if (
- ts.isJsxAttribute(attribute) &&
- attribute.name.getText(source) === name
- ) {
- return attribute;
- }
- }
- return null;
-}
+const ANIMATION_FREE_BLOCK_PROPS_RE = /^<Block\s+\{\.\.\.blockProps\}/;
+const ANIMATION_FREE_HELPER_RE = /withoutStreamdownAnimationPlugin/;
+const NULL_ANIMATION_PLUGIN_RE = /animatePlugin:\s*null/;
+const MEMOISED_BLOCK_RE =
+ /const\s+StreamdownBlock\s*=\s*memo\(StreamdownBlockContent\)/;
-test("StreamdownBlock reads the animating flag from Streamdown's context", () => {
- const block = findFunction("StreamdownBlock");
- assert.ok(block, "StreamdownBlock is missing");
+test("the block props use the animation-free plugin list", () => {
+ const helper = findFunction("useAnimationFreeBlockProps");
+ assert.ok(helper, "useAnimationFreeBlockProps is missing");
- const body = block.getText(source);
+ const body = helper.getText(source);
assert.match(
body,
- /useContext\(\s*StreamdownContext\s*\)/,
- "StreamdownBlock must read StreamdownContext to know when the message is still streaming",
+ ANIMATION_FREE_HELPER_RE,
+ "the helper must filter Streamdown's animation rehype plugin",
);
assert.match(
body,
- /isAnimating/,
- "StreamdownBlock must derive its key from isAnimating",
+ NULL_ANIMATION_PLUGIN_RE,
+ "the filtered animation plugin must not reach Streamdown's Block",
);
});
-test("the streamed block is re-keyed once the message completes", () => {
- const block = findFunction("StreamdownBlock");
- assert.ok(block, "StreamdownBlock is missing");
+test("every Markdown block receives the animation-free props", () => {
+ const block = findFunction("StreamdownBlockContent");
+ assert.ok(block, "StreamdownBlockContent is missing");
- // The last <Block> in the function is the default (non-artifact) return; it is
- // the one that renders ordinary prose, so it is the one that accumulates the
- // per-word animation wrappers while streaming.
- let last: ts.JsxOpeningLikeElement | null = null;
+ const renderedBlocks: ts.JsxOpeningLikeElement[] = [];
const visit = (node: ts.Node): void => {
if (
(ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node)) &&
node.tagName.getText(source) === "Block"
) {
- last = node;
+ renderedBlocks.push(node);
}
node.forEachChild(visit);
};
block.forEachChild(visit);
- assert.ok(last, "the default <Block> return is missing");
-
- const key = jsxAttribute(last, "key");
- assert.ok(
- key,
- "the default <Block> must carry a key so completed blocks re-parse without the animation wrappers",
- );
+ assert.ok(renderedBlocks.length > 0, "StreamdownBlock renders no blocks");
+ for (const renderedBlock of renderedBlocks) {
+ assert.match(
+ renderedBlock.getText(source),
+ ANIMATION_FREE_BLOCK_PROPS_RE,
+ "every <Block> path must use the animation-free props",
+ );
+ }
+});
- // The key is either isAnimating itself or a local declared from it.
- const identifier = (key.initializer?.getText(source) ?? "")
- .replace(/[{}]/g, "")
- .trim();
- assert.ok(identifier, "the key must not be empty");
- assert.match(
- block.getText(source),
- new RegExp(`${identifier}\\s*=\\s*isAnimating`),
- `the key ${identifier} must be derived from isAnimating`,
- );
+test("completed custom blocks are memoised while the tail streams", () => {
+ assert.match(source.getText(), MEMOISED_BLOCK_RE);
});
diff --git a/studio/frontend/tests/markdown-streaming-scheduling.test.ts b/studio/frontend/tests/markdown-streaming-scheduling.test.ts
index 9d5dd807256..320cca8fe29 100644
--- a/studio/frontend/tests/markdown-streaming-scheduling.test.ts
+++ b/studio/frontend/tests/markdown-streaming-scheduling.test.ts
@@ -100,3 +100,66 @@ test("chat streaming bypasses Streamdown's starvable transition without visible
"{STREAMDOWN_IMMEDIATE_UPDATES}",
);
});
+
+test("token updates keep Streamdown's expensive configuration props stable", () => {
+ const streamdown = findChatStreamdown();
+ assert.ok(streamdown, "chat <Streamdown> is missing");
+
+ for (const [attribute, constant] of [
+ ["plugins", "STREAMDOWN_PLUGINS"],
+ ["controls", "STREAMDOWN_CONTROLS"],
+ ["shikiTheme", "STREAMDOWN_SHIKI_THEME"],
+ ]) {
+ assert.equal(
+ jsxAttribute(streamdown, attribute)?.initializer?.getText(source),
+ `{${constant}}`,
+ `${attribute} must retain object identity while raw tokens arrive`,
+ );
+ }
+});
+
+test("stream updates are paint-coalesced without a time or length throttle", () => {
+ const markdownSource = source.getText();
+ const hookStart = markdownSource.indexOf(
+ "function useCoalescedStreamingText",
+ );
+ const hookEnd = markdownSource.indexOf("const MarkdownTextImpl", hookStart);
+ assert.ok(hookStart >= 0 && hookEnd > hookStart);
+ const hook = markdownSource.slice(hookStart, hookEnd);
+
+ assert.ok(hook.includes("requestAnimationFrame"));
+ assert.ok(!hook.includes("setTimeout"));
+
+ // A running message can be replaced rather than appended to, as the audio
+ // path does when it swaps its placeholder for the player, so holding the last
+ // painted text has to be gated on the new text extending it.
+ assert.ok(hook.includes("text.startsWith(displayed.text)"));
+});
+
+test("streaming reparses only the active Markdown tail", () => {
+ const streamdown = findChatStreamdown();
+ assert.ok(streamdown, "chat <Streamdown> is missing");
+ assert.equal(
+ jsxAttribute(streamdown, "parseIncompleteMarkdown")?.initializer?.getText(
+ source,
+ ),
+ "{!incrementalRender}",
+ );
+ assert.equal(
+ jsxAttribute(streamdown, "parseMarkdownIntoBlocksFn")?.initializer?.getText(
+ source,
+ ),
+ "{incrementalRender?.parseMarkdownIntoBlocks}",
+ );
+});
+
+test("dropping retained blocks moves Streamdown's render identity", () => {
+ // Streamdown compares only the Markdown string, so an edit that clears the
+ // retained blocks while leaving the live tail alone has to remount instead.
+ const streamdown = findChatStreamdown();
+ assert.ok(streamdown, "chat <Streamdown> is missing");
+ assert.equal(
+ jsxAttribute(streamdown, "key")?.initializer?.getText(source),
+ "{`${messageId}:${incrementalCache.renderGeneration}`}",
+ );
+});
diff --git a/studio/frontend/tests/streaming-render-schedule.test.ts b/studio/frontend/tests/streaming-render-schedule.test.ts
new file mode 100644
index 00000000000..4f28be17887
--- /dev/null
+++ b/studio/frontend/tests/streaming-render-schedule.test.ts
@@ -0,0 +1,417 @@
+// 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 remend from "remend";
+import { Streamdown, parseMarkdownIntoBlocks } from "streamdown";
+
+import { stabilizeStreamingMarkdown } from "../src/components/assistant-ui/streaming-markdown.ts";
+import {
+ IncrementalMarkdownCache,
+ withoutStreamdownAnimationPlugin,
+} from "../src/components/assistant-ui/streaming-render-schedule.ts";
+import { preprocessLaTeX } from "../src/lib/latex.ts";
+
+test("only Streamdown's animation transformer is removed", () => {
+ const first = () => undefined;
+ const animation = () => undefined;
+ const configured: [typeof first, { enabled: boolean }] = [
+ first,
+ {
+ enabled: true,
+ },
+ ];
+ const plugins = [first, animation, configured];
+
+ assert.deepEqual(
+ withoutStreamdownAnimationPlugin(plugins, {
+ name: "animate",
+ type: "animate",
+ rehypePlugin: animation,
+ getLastRenderCharCount: () => 0,
+ setPrevContentLength: () => undefined,
+ }),
+ [first, configured],
+ );
+});
+
+const paragraphs = (count: number, label = "part") =>
+ Array.from({ length: count }, (_, index) => `${label} ${index}\n\n`).join("");
+const retainedCase = (fragment: string) =>
+ `${paragraphs(12, "before")} ${fragment}\n\n${paragraphs(12, "after")}`;
+// Just past the rollback window, since the block list interleaves separators.
+const SHORT_GAP = "\n\np0\n\np1\n\np2\n\np3\n\n";
+
+const MARKDOWN_CASES = [
+ retainedCase(
+ "# Heading\n\nParagraph with **bold** and [link](https://x.test).",
+ ),
+ retainedCase("Before\n\n```ts\nconst x = 1;\n```\n\nAfter"),
+ retainedCase("Math \\(x+1\\)\n\n\\[a=b\\]\n\nend"),
+ retainedCase("> quote\n> next\n\nparagraph\n\n---\n\nend"),
+ retainedCase("<div>\ninside\n\nmore\n</div>\n\nafter"),
+ retainedCase("A [ref][x]\n\n[x]: https://example.com"),
+ retainedCase("one\n\n$$\na+b\n$$\n\ntwo"),
+ retainedCase("a\n\n* item\n * nested\n\nb"),
+ paragraphs(30),
+ `${paragraphs(20)}term[^note]\n\n[^note]: detail`,
+ `$$\nx+y\n$$\n\n${paragraphs(20)}$$\nz`,
+ `In Python 2 ** 3 is eight.\n\n${paragraphs(12)}x** y **bold`,
+ `Match *.py files here.\n\n${paragraphs(12)}x *y and *italic`,
+ `Call _private first.\n\n${paragraphs(12)}x _y and _italic`,
+ `A ***** marker run.\n\n${paragraphs(12)}x ***y and ***bold`,
+ `Plain **bold** and *italic*.\n\n$$\nx+y\n$$\n\n${paragraphs(12)}A ***** marker.\n\n${paragraphs(4, "later")}\`\`\``,
+ `Plain **bold** and *italic*.\n\n$$\nx+y\n$$\n\n${paragraphs(12)}Call _private first.\n\n${paragraphs(4, "later")}Plain **b`,
+ `\`\`\`sh\necho $HOME\n\`\`\`\n\n${paragraphs(12)}see *italic`,
+ `\`\`\`text\ncost $$ each\n\`\`\`\n\n${paragraphs(12)}see *italic`,
+ `use \`a *b\` here\n\n${paragraphs(12)}see *italic`,
+ `use \`a _b\` here\n\n${paragraphs(12)}see _italic`,
+ `Call _private first.\n\n${paragraphs(12)}Plain **bold`,
+ `$$E=mc^2$$ is famous\n\n${paragraphs(12)}$$`,
+ `A stray \` marker in prose.\n\n${paragraphs(12)}\`tail`,
+ `A stray __ marker in prose.\n\n${paragraphs(12)}x__ y __tail`,
+ `A stray ~~ marker in prose.\n\n${paragraphs(12)}x~~ y ~~tail`,
+ `A stray $ marker in prose.\n\n${paragraphs(12)}$tail`,
+ `\`\`\`text\n$$\n\`\`\`\n\n${paragraphs(12)}$$\nx`,
+ `takes 5~10 minutes\n\n${paragraphs(20)}`,
+ `- >= 16 GB of RAM\n\n${paragraphs(20)}`,
+ // Remend completes a dangling link, or truncates at a dangling image, using
+ // the end of the whole document.
+ `Pick x in the interval [0, 1) for the ratio.\n\n${paragraphs(14)}done`,
+ `see ![alt text\n\n${paragraphs(12)}later y](`,
+ // A backtick that ends a retained block still closes inline code for remend.
+ `Escape a backtick as \\\`\n\n${paragraphs(10)}$$\nE=mc^2\n$$`,
+ // Remend orders its closers from a raw "**" search, fenced code included.
+ `\`\`\`c\nchar **argv;\n\`\`\`\n\n${paragraphs(12)}set _flag to **on`,
+ // Reduced shapes, one per whole-document rule the retained prefix has to
+ // reproduce. Reported by @mahiatlinux on the PR.
+ `\`\`\`x\`\`\`\`${SHORT_GAP}~~ y`,
+ `see [note${SHORT_GAP}tail`,
+ `\\\`${SHORT_GAP}$$`,
+ `********${SHORT_GAP}*a`,
+ `\`\`\`\n**\n\`\`\`${SHORT_GAP}_u then **v then **`,
+ `use \`a *b* c\` here${SHORT_GAP}****x`,
+ `a \`\`\` b\n\nc \\\`\`\` d${SHORT_GAP}- >= 4 GB`,
+ `[x]: https://e.test\n\n${paragraphs(12)}[x]: https://e.test\n\nq\n\n`,
+ `\`\`\`md\n[x]: https://e.test\n\`\`\`\n\n${paragraphs(12)}[x]: https://e.test\n\nq\n\n`,
+ // A label may contain an escaped bracket, and Marked registers it.
+ `[foo\\]bar]: /url\n\n${paragraphs(12)}[foo\\]bar]: /url\n\nq\n\n`,
+ // Retained-prefix contexts that nothing else reaches: a balanced single
+ // underscore, one first seen inside inline code, and an underscore that
+ // precedes the first bold marker.
+ `Use _snake_ case.${SHORT_GAP}see _italic`,
+ `use \`a _b_ c\` here${SHORT_GAP}see _italic`,
+ `Set _flag_ and **mode** now.${SHORT_GAP}see _italic and **bold`,
+];
+
+const processStreamingText = (text: string): string =>
+ stabilizeStreamingMarkdown(preprocessLaTeX(text), true);
+
+test("incremental blocks match a full Streamdown split at every prefix", () => {
+ for (const source of MARKDOWN_CASES) {
+ const cache = new IncrementalMarkdownCache();
+ for (let length = 0; length <= source.length; length += 1) {
+ const input = processStreamingText(source.slice(0, length));
+ const render = cache.update(input);
+ assert.deepEqual(
+ render.parseMarkdownIntoBlocks(render.markdown),
+ parseMarkdownIntoBlocks(remend(input)),
+ `block mismatch at prefix ${length} of ${JSON.stringify(source)}`,
+ );
+ }
+ }
+});
+
+test("incremental parsing bounds the live tail and resets after an edit", () => {
+ const source = Array.from(
+ { length: 100 },
+ (_, index) => `paragraph ${index}\n\n`,
+ ).join("");
+ const cache = new IncrementalMarkdownCache();
+ const streamed = cache.update(source);
+ assert.ok(streamed.markdown.length < source.length / 4);
+
+ const edited = source.replace("paragraph 0", "changed 0");
+ const reset = cache.update(edited);
+ assert.deepEqual(
+ reset.parseMarkdownIntoBlocks(reset.markdown),
+ parseMarkdownIntoBlocks(remend(edited)),
+ );
+});
+
+test("mid-string remend repairs use the sticky full-document fallback", () => {
+ for (const firstBlock of ["takes 5~10 minutes", "- >= 16 GB of RAM"]) {
+ const cache = new IncrementalMarkdownCache();
+ const source = `${firstBlock}\n\n${paragraphs(100)}`;
+ const first = cache.update(source);
+ assert.equal(first.markdown, remend(source));
+ assert.equal(
+ (cache as unknown as { fullDocumentMode: boolean }).fullDocumentMode,
+ true,
+ );
+
+ const appended = `${source}one more paragraph\n\n`;
+ const next = cache.update(appended);
+ assert.equal(next.markdown, remend(appended));
+ }
+});
+
+test("a transient marker imbalance can recover incremental parsing", () => {
+ const cache = new IncrementalMarkdownCache();
+ const unbalanced = `Match *.py files here.\n\n${paragraphs(20)}`;
+ cache.update(unbalanced);
+ assert.equal(
+ (cache as unknown as { fullDocumentMode: boolean }).fullDocumentMode,
+ false,
+ );
+
+ const balanced = `${unbalanced}Finish the *italic example.\n\n${paragraphs(20, "later")}`;
+ const render = cache.update(balanced);
+ assert.ok(render.markdown.length < balanced.length / 2);
+});
+
+test("a non-prefix replacement clears the sticky fallback", () => {
+ const cache = new IncrementalMarkdownCache();
+ cache.update(`takes 5~10 minutes\n\n${paragraphs(100)}`);
+ assert.equal(
+ (cache as unknown as { fullDocumentMode: boolean }).fullDocumentMode,
+ true,
+ );
+
+ const replacement = paragraphs(100, "replacement");
+ const render = cache.update(replacement);
+ assert.equal(
+ (cache as unknown as { fullDocumentMode: boolean }).fullDocumentMode,
+ false,
+ );
+ assert.ok(render.markdown.length < replacement.length / 4);
+});
+
+test("single-dollar parity affects the retained tail repair", () => {
+ const source = `A $ marker in prose.\n\n${paragraphs(12)}x$ y $tail`;
+ const cache = new IncrementalMarkdownCache();
+ for (let length = 0; length <= source.length; length += 1) {
+ const input = source.slice(0, length);
+ const render = cache.update(input);
+ assert.deepEqual(
+ render.parseMarkdownIntoBlocks(render.markdown),
+ parseMarkdownIntoBlocks(remend(input)),
+ );
+ }
+});
+
+test("a code character class matches Streamdown's own footnote short-circuit", () => {
+ // `\s` is outside `[\w-]`, so this never looks like a footnote and retains.
+ const escaped = `\`\`\`js\nconst token = /[^\\s]+/;\n\`\`\`\n\n${paragraphs(100)}`;
+ const render = new IncrementalMarkdownCache().update(escaped);
+ assert.ok(render.markdown.length < escaped.length / 4);
+
+ // `[^a-z]` does match, and Streamdown's splitter short-circuits on the same
+ // pair of raw regexes and returns the whole reply as one block, so the
+ // full-document path is the answer that agrees with it.
+ const matching = `\`\`\`js\nconst re = /[^a-z]/;\n\`\`\`\n\n${paragraphs(100)}`;
+ assert.equal(parseMarkdownIntoBlocks(remend(matching)).length, 1);
+ const fallback = new IncrementalMarkdownCache().update(matching);
+ assert.equal(fallback.markdown, remend(matching));
+ assert.deepEqual(
+ fallback.parseMarkdownIntoBlocks(fallback.markdown),
+ parseMarkdownIntoBlocks(remend(matching)),
+ );
+});
+
+test("a marker the reply never closes gives up on the retained prefix", () => {
+ // Without this the boundary scan is paid on every update on top of the full
+ // repair it exists to replace, which is slower than not being there at all.
+ const source = `\`\`\`sh\necho $HOME\n\`\`\`\n\n${paragraphs(4000)}`;
+ const cache = new IncrementalMarkdownCache();
+ const render = cache.update(source);
+
+ assert.equal(
+ (cache as unknown as { fullDocumentMode: boolean }).fullDocumentMode,
+ true,
+ );
+ assert.deepEqual(
+ render.parseMarkdownIntoBlocks(render.markdown),
+ parseMarkdownIntoBlocks(remend(source)),
+ );
+
+ // A short-lived imbalance still recovers, so the budget has to be well above
+ // an ordinary unclosed marker.
+ const transient = `Match *.py files here.\n\n${paragraphs(20)}`;
+ const transientCache = new IncrementalMarkdownCache();
+ transientCache.update(transient);
+ assert.equal(
+ (transientCache as unknown as { fullDocumentMode: boolean })
+ .fullDocumentMode,
+ false,
+ );
+});
+
+test("an edit that drops retained blocks moves the render identity", () => {
+ // Deleting exactly the retained prefix leaves the live tail, and with it the
+ // only thing Streamdown compares, unchanged.
+ const source = paragraphs(30);
+ const cache = new IncrementalMarkdownCache();
+ const streamed = cache.update(source);
+ assert.ok(streamed.markdown.length < source.length / 3);
+ const streamedGeneration = cache.renderGeneration;
+
+ const edited = cache.update(streamed.markdown);
+ assert.equal(edited.markdown, streamed.markdown);
+ assert.notEqual(cache.renderGeneration, streamedGeneration);
+ assert.deepEqual(
+ edited.parseMarkdownIntoBlocks(edited.markdown),
+ parseMarkdownIntoBlocks(remend(streamed.markdown)),
+ );
+
+ // A reply that only grows never remounts, including while the stabilizer
+ // withholds an ambiguous trailing line.
+ const streaming = new IncrementalMarkdownCache();
+ for (let length = 1; length <= source.length; length += 5) {
+ streaming.update(source.slice(0, length));
+ streaming.update(`${source.slice(0, length)}* **`);
+ }
+ assert.equal(streaming.renderGeneration, 0);
+});
+
+test("a definition shown inside a fenced example still retains", () => {
+ // Marked reads that line as code, so treating it as a definition would stall
+ // retention for the rest of the reply.
+ const shown = `\`\`\`md\n[x]: https://e.test\n\`\`\`\n\n${paragraphs(30)}end`;
+ const shownCache = new IncrementalMarkdownCache();
+ let render = shownCache.update("");
+ for (let length = 1; length <= shown.length; length += 1) {
+ render = shownCache.update(processStreamingText(shown.slice(0, length)));
+ }
+ assert.ok(render.markdown.length < shown.length / 3);
+
+ // A real definition is never retained, whatever block it sits in, so Marked
+ // always lexes it together with a later twin and absorbs the duplicate.
+ for (const first of ["[x]: https://e.test", "> [x]: https://e.test"]) {
+ const repeated = `${first}\n\n${paragraphs(30)}[x]: https://e.test\n\nend`;
+ const cache = new IncrementalMarkdownCache();
+ let repeatedRender = cache.update("");
+ for (let length = 1; length <= repeated.length; length += 1) {
+ repeatedRender = cache.update(
+ processStreamingText(repeated.slice(0, length)),
+ );
+ }
+ assert.deepEqual(
+ repeatedRender.parseMarkdownIntoBlocks(repeatedRender.markdown),
+ parseMarkdownIntoBlocks(remend(processStreamingText(repeated))),
+ );
+ }
+});
+
+test("an update with unchanged text repeats no work", () => {
+ // Tokens arrive faster than frames, so the coalescer hands the same text to
+ // several renders. Redoing the repair there is the whole reply again once the
+ // full-document path is in use.
+ const source = `A claim[^note]\n\n${"a paragraph of reply text\n\n".repeat(6000)}`;
+ const cache = new IncrementalMarkdownCache();
+ const first = cache.update(source);
+
+ const started = performance.now();
+ for (let repeat = 0; repeat < 200; repeat += 1) {
+ assert.equal(cache.update(source).markdown, first.markdown);
+ }
+ assert.ok(performance.now() - started < 100);
+});
+
+test("Streamdown re-renders only when the Markdown string changes", () => {
+ // Its memo comparator is what decides whether the parser callback runs again,
+ // and it does not compare that callback. Retaining a block therefore has to
+ // change the Markdown too, or the retained block never reaches the DOM.
+ const { compare } = Streamdown as unknown as {
+ compare: (previous: object, next: object) => boolean;
+ };
+ const shared = { mode: "streaming", isAnimating: true, children: "reply" };
+
+ assert.equal(
+ compare(
+ { ...shared, parseMarkdownIntoBlocksFn: () => [] },
+ { ...shared, parseMarkdownIntoBlocksFn: () => [] },
+ ),
+ true,
+ );
+ assert.equal(compare(shared, { ...shared, children: "longer reply" }), false);
+});
+
+test("a repeating reply keeps displaying every retained block", () => {
+ // A reply that repeats a line leaves the tail unchanged when an update
+ // retains exactly what it appended, so the cache must not hand Streamdown a
+ // Markdown string it already holds.
+ const line = "I cannot provide that information.\n\n";
+ const step = line.length;
+ const source = `Here is the answer.\n\n${line.repeat(60)}`;
+ const cache = new IncrementalMarkdownCache();
+ let displayedMarkdown: string | null = null;
+ let displayed: string[] = [];
+
+ for (let length = step; length <= source.length; length += step) {
+ const input = source.slice(0, length);
+ const render = cache.update(input);
+ if (render.markdown !== displayedMarkdown) {
+ displayedMarkdown = render.markdown;
+ displayed = render.parseMarkdownIntoBlocks(render.markdown);
+ }
+ assert.deepEqual(displayed, parseMarkdownIntoBlocks(remend(input)));
+ // Retaining one update later must not let the live tail track the reply.
+ assert.ok(render.markdown.length < step * 6);
+ }
+});
+
+// The stalled-tail budget is only reachable once the live tail holds more than
+// ROLLBACK_BLOCKS blocks, so a single long fenced block never reaches it: while
+// the fence is open the tail lexes to a handful of blocks and stays retainable.
+// What reaches it is an inline marker with many paragraphs before its closer,
+// and since the budget is spent before giving up, that shape sizes the budget.
+test("an emphasis marker that closes far later stays near the full-repair cost", () => {
+ const source = `An *opening\n\n${paragraphs(3_600)}closing* marker.\n\n${paragraphs(200)}`;
+ const cache = new IncrementalMarkdownCache();
+ const step = Math.ceil(source.length / 420);
+ let render = cache.update(processStreamingText(""));
+ for (let length = 0; length <= source.length; length += step) {
+ render = cache.update(processStreamingText(source.slice(0, length)));
+ }
+ const input = processStreamingText(source);
+ render = cache.update(input);
+
+ assert.deepEqual(
+ render.parseMarkdownIntoBlocks(render.markdown),
+ parseMarkdownIntoBlocks(remend(input)),
+ );
+ // Retaining nothing is the correct answer here; retaining the attempt is not.
+ assert.equal(
+ (cache as unknown as { fullDocumentMode: boolean }).fullDocumentMode,
+ true,
+ );
+});
+
+// A long fenced block is the shape most likely to be mistaken for the budget's
+// trigger. It is not one: it keeps retaining, so a code-heavy answer does not
+// quietly lose the optimisation.
+test("a fenced block larger than the budget keeps retaining", () => {
+ const body = "const value = compute(argument, options, fallback);\n".repeat(
+ 1_700,
+ );
+ const source = `\`\`\`js\n${body}\`\`\`\n\n${paragraphs(200)}`;
+ const cache = new IncrementalMarkdownCache();
+ let render = cache.update(processStreamingText(""));
+ for (let length = 0; length <= source.length; length += 512) {
+ render = cache.update(processStreamingText(source.slice(0, length)));
+ }
+ const input = processStreamingText(source);
+ render = cache.update(input);
+
+ assert.equal(
+ (cache as unknown as { fullDocumentMode: boolean }).fullDocumentMode,
+ false,
+ );
+ assert.ok(render.markdown.length < source.length / 4);
+ assert.deepEqual(
+ render.parseMarkdownIntoBlocks(render.markdown),
+ parseMarkdownIntoBlocks(remend(input)),
+ );
+});