Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
bbe6025
perf(ui-react): parse a streaming answer block by block (#2588)
schlessera Nov 17, 2026
af3773b
fix(ui-react): never split around a nested definition; no stale tail …
schlessera Nov 17, 2026
63229df
fix(ui-react): defer only a growing tail; find wrapped definition lab…
schlessera Nov 17, 2026
8b58803
fix(ui-react): split only at CommonMark blank lines (#2588)
schlessera Nov 17, 2026
6148259
fix(ui-react): never split around a fence or HTML block inside a cont…
schlessera Nov 17, 2026
2e48399
fix(ui-react): never split where a fence may sit inside an HTML block…
schlessera Nov 17, 2026
b4696f9
fix(ui-react): parse whole any text with an HTML line; keep blank lin…
schlessera Nov 17, 2026
bcc54ac
fix(ui-react): never split a text holding a carriage return (#2588)
schlessera Nov 17, 2026
8336e02
fix(ui-react): bound the deferred tail's lag; an autolink is not HTML…
schlessera Nov 17, 2026
1ff93e6
fix(ui-react): measure the tail's lag from committed renders only (#2…
schlessera Nov 17, 2026
c4ee76a
fix(ui-react): time the tail's lag from when it fell behind (#2588)
schlessera Nov 17, 2026
c2268a6
fix(ui-react): the streaming tail never steps back (#2588)
schlessera Nov 17, 2026
c8b5ac6
fix(ui-react): a tag still being typed does not collapse the split
schlessera Nov 17, 2026
9a58d81
fix(ui-react): a list item splits off unless the block above holds a …
schlessera Nov 17, 2026
5905bf3
Merge remote-tracking branch 'origin/main' into perf/2588-streaming-m…
schlessera Nov 17, 2026
7182edb
Merge remote-tracking branch 'origin/main' into perf/2588-streaming-m…
schlessera Nov 17, 2026
3e08638
Merge remote-tracking branch 'origin/main' into perf/2588-streaming-m…
schlessera Nov 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/2588-streaming-markdown-blocks.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@schlessera/brain-ui-react": patch
---

A streaming answer no longer re-parses its whole text on every frame. Each top-level markdown block now parses on its own, and a finished block is skipped while the answer grows, so only the growing last block re-parses, and its re-parse is deferred behind input and scrolling. Appending to a 24 KB answer went from a 23 ms median render to under 3 ms (desktop). What renders is unchanged. A text holding a link reference or footnote definition, or an HTML block that may contain blank lines, still parses whole, as does a single long growing block.
66 changes: 58 additions & 8 deletions packages/ui-react/src/components/chat/brain-markdown.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { MarkdownRangeContext, rehypeMarkdownRange } from "./markdown-range.js";
import { useBrainUiRoot } from "../../root-context.js";
import React, { memo, useContext, useEffect, useMemo } from "react";
import React, { memo, useContext, useDeferredValue, useEffect, useMemo, useRef } from "react";
import Markdown from "react-markdown";
import { splitMarkdownBlocks, tailText } from "./markdown-blocks.js";

import {
classifyRepoPath,
Expand Down Expand Up @@ -175,15 +176,64 @@ const BrainMarkdownInner = memo(function BrainMarkdownInner({ content, className
};
}, [entityTags, fileLinks, root]);

// A projected range maps offsets into the whole text, so it parses whole.
// Otherwise each top-level block parses on its own (#2588): a streaming
// answer grows only at its end, so its finished blocks keep their text and
// `MarkdownBlock`'s memo skips them, and only the last one re-parses.
const blocks = useMemo(() => range ? [processed] : splitMarkdownBlocks(processed), [processed, range]);
return (
<div className={className ?? "brain-prose"}>
<MarkdownRangeContext.Provider value={null}><Markdown
remarkPlugins={REMARK_PLUGINS}
rehypePlugins={projectedPlugins}
components={components}
>
{processed}
</Markdown></MarkdownRangeContext.Provider>
<MarkdownRangeContext.Provider value={null}>
{blocks.map((text, i) => (
<StreamedBlock key={i} text={text} last={i === blocks.length - 1} rehypePlugins={projectedPlugins} components={components} />
))}
</MarkdownRangeContext.Provider>
</div>
);
});

type BlockProps = { text: string; rehypePlugins: React.ComponentProps<typeof Markdown>["rehypePlugins"]; components: React.ComponentProps<typeof Markdown>["components"] };

/**
* One top-level block's parse. Memoized on its text and the (memoized)
* plugins and components, so a finished block is not re-parsed while the
* answer streams on, and its elements (a rendered Mermaid diagram) keep
* their state: its key is its index, which a growing text never changes.
*/
const MarkdownBlock = memo(function MarkdownBlock({ text, rehypePlugins, components }: BlockProps) {
return <Markdown remarkPlugins={REMARK_PLUGINS} rehypePlugins={rehypePlugins} components={components}>{text}</Markdown>;
});

/**
* A block in its place. Every block is this one component type, so the last
* block becoming an earlier one (a new block starts below it) changes no
* element type and remounts nothing. Only the last block's text is deferred,
* so input and scrolling outrank re-parsing the growing tail.
*/
function StreamedBlock({ text, last, ...rest }: BlockProps & { last: boolean }) {
// Deferred only while it grows as the last block: the deferred text must
// be what this text extends. A block that has just become the last one (a
// definition arrived and the text now parses whole) has none of its own,
// and replaced content (another file, a new briefing) does not extend it,
// so both show their current text at once instead of a stale one.
// A deferred tail that has lagged too long renders its current text
// urgently (`tailText`), so a slow parse under fast deltas still updates.
const deferred = useDeferredValue(last ? text : null);
// When a commit first showed this tail behind its text: written in an
// effect, so only committed renders count, never one React discards; a
// commit that shows it caught up clears it.
const behindSince = useRef<number | null>(null);
// The text the last commit showed: the tail never steps back behind it.
const committed = useRef<string | null>(null);
const shown = last ? tailText(text, deferred, committed.current, behindSince.current, performance.now()) : text;
useEffect(() => {
committed.current = shown;
if (shown === text) behindSince.current = null;
else behindSince.current ??= performance.now();
});
return <>
<MarkdownBlock text={shown} {...rest} />
{/* react-markdown separates top-level blocks with a newline; keep it between ours. */}
{last ? null : "\n"}
</>;
}
143 changes: 143 additions & 0 deletions packages/ui-react/src/components/chat/markdown-blocks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
/**
* Top-level markdown blocks of one text part, for rendering each through its
* own memoized parse (#2588). A streaming answer grows only at its end, so
* a finished block whose text has not changed is skipped by `memo` instead
* of re-parsed on every frame.
*
* Splitting must never change what renders: each block parsed alone, joined
* in order, must give the same HTML as the whole text parsed once. So the
* split points are conservative, and when in doubt the text is not split:
*
* - only at a blank line outside every fenced code block (backtick or tilde,
* any fence length, an unclosed fence running to the end);
* - only where the next line starts at column 0 and does not continue a
* blockquote (`>`) or a table (`|`), and does not start a list item
* (`-`, `*`, `+`, `1.`, `1)`) when the block above holds one: a new item
* after a blank line joins that list and makes it loose. Below a block
* with no list item, a new list cannot change it, so the split stands, and
* a paragraph being typed that starts with a number (`3`, `3.`, `3.14`)
* does not collapse and split again as it grows. After an indented line
* no list item splits: below an indented code block the whole text can
* parse an empty item (`1.`) or one not starting at 1 (`10. ten`) as a
* paragraph instead;
* - never in a text holding a link reference or footnote definition, which
* resolves across the whole document;
* - never in a text holding a line that starts with HTML (a tag, a comment,
* a processing instruction, a declaration or CDATA), at the top level or
* after a blockquote or list-item prefix: an HTML block can hold blank
* lines and fence markers, and how it ends depends on what follows;
* - never in a text holding a fence that is indented or inside a blockquote
* or list item. Only top-level fences are tracked, and a container fence
* can be closed or reopened at column 0 in ways only a full parse knows
* (a column-0 closer ends the list item and opens a new top-level fence);
* - never in a text holding a carriage return, which CommonMark also takes
* as a line ending while this scan reads lines at `\n` alone.
*/

/**
* A link reference or footnote definition, `[label]: …` or `[^note]: …`,
* anywhere a definition can stand: after any indentation and any blockquote
* (`>`) or list-item (`-`, `*`, `+`, `1.`, `1)`) prefixes, with escaped
* brackets in the label and a label that wraps across lines. Deliberately broad: a false match only means the
* text parses whole.
*/
const DEFINITION = /^(?:[ \t]|>|[-*+][ \t]|\d{1,9}[.)][ \t])*\[(?:[^\]\\]|\\[\s\S])+\]:/m;
/**
* A line that starts with HTML (a tag, open or closing, a comment, a
* declaration or a processing instruction), after any indentation and
* blockquote or list-item prefixes. An autolink (`<https://…>`) is not HTML.
* A tag name counts only once whitespace, `/` or `>` follows it, never at
* the end of the text: while a tag or an autolink is still being typed
* (`<h`, `<https`), it is not yet HTML, so the split does not collapse and
* split again under a streaming answer.
*/
const HTML_LINE = /^(?:[ \t]|>|[-*+][ \t]|\d{1,9}[.)][ \t])*<(?:\/?[A-Za-z][A-Za-z0-9-]*(?=[\s/>])|[!?])/m;
/** A fence marker that is indented or follows a blockquote or list-item prefix. */
const NESTED_FENCE = /^(?:[ \t]|>|[-*+][ \t]|\d{1,9}[.)][ \t])+(?:`{3,}|~{3,})/m;
/** A top-level fence opener or closer: three or more backticks or tildes at column 0. */
const FENCE = /^(`{3,}|~{3,})/;
/** A blank line as CommonMark counts one: spaces and tabs only (not NBSP or other Unicode space). */
const BLANK = /^[ \t]*$/;
/** A line that would continue the block above a blank line instead of starting a new one. */
const CONTINUES = /^(?:>|\||\s)/;
/** A list item marker at the start of a line. */
const LIST_ITEM = /^(?:[-*+]|\d{1,9}[.)])(?:\s|$)/;
/**
* A line that may belong to a list: a list item marker after any indentation
* and blockquote prefixes, in or out of a fence. Deliberately broad (a
* thematic break `* * *` counts too): a false match only means a following
* list item does not split.
*/
const LIST_LINE = /^(?:[ \t]|>)*(?:[-*+]|\d{1,9}[.)])(?:\s|$)/;

/** The text's top-level blocks, in order; `[text]` when it cannot be split safely. */
export function splitMarkdownBlocks(text: string): string[] {
if (text.includes("\r") || DEFINITION.test(text) || HTML_LINE.test(text) || NESTED_FENCE.test(text)) return [text];
const lines = text.split("\n");
const blocks: string[] = [];
let start = 0;
let fence: { char: string; length: number } | null = null;
let blank = false;
let content = false;
let list = false;
// Whether the last line with content outside a fence was indented.
let indented = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i]!;
const marker = FENCE.exec(line);
const listLine = LIST_LINE.test(line);
if (fence) {
list ||= listLine;
// A closing fence: the same character, at least as long, nothing after it.
if (marker && marker[1]![0] === fence.char && marker[1]!.length >= fence.length && BLANK.test(line.slice(marker[0].length))) fence = null;
indented = false;
blank = false;
continue;
}
if (BLANK.test(line)) { blank = true; continue; }
if (blank && content && !CONTINUES.test(line) && !((list || indented) && LIST_ITEM.test(line))) {
// The blank lines stay with the block before, exactly as the whole
// text has them: how a block ends (an indented code block's trailing
// whitespace lines) can depend on them.
blocks.push(lines.slice(start, i).join("\n"));
start = i;
list = false;
}
list ||= listLine;
indented = /^[ \t]/.test(line);
blank = false;
content = true;
if (marker) {
// A backtick fence's info string cannot hold a backtick; then it is no fence.
const info = line.slice(marker[0].length);
if (marker[1]![0] !== "`" || !info.includes("`")) fence = { char: marker[1]![0]!, length: marker[1]!.length };
}
}
blocks.push(lines.slice(start).join("\n"));
return blocks;
}

/** How long the growing tail may show deferred text before its current text renders urgently. */
export const MAX_TAIL_LAG_MS = 200;

/**
* Which text the growing last block shows. Its deferred text, while that is
* what the current text extends and the tail has not been behind for longer
* than `MAX_TAIL_LAG_MS`: React restarts a deferred render on every new
* delta, so when the tail's parse outlasts the gap between deltas it would
* otherwise not update until the stream paused. Past the bound the current
* text renders urgently.
*
* `behindSince` is when a commit first showed the tail behind its text, or
* `null` while the last commit showed it caught up; `committed` is the text
* the last commit showed. Both come from committed renders only, so a render
* React discards cannot move them, and a pause in the stream (no commits,
* but nothing behind either) does not count as lag. The tail never shows
* less than it last committed: after the bound forced the current text, the
* deferred value can still be older, and the tail must not step back to it.
*/
export function tailText(text: string, deferred: string | null, committed: string | null, behindSince: number | null, now: number): string {
if (deferred === null || deferred === text || !text.startsWith(deferred)) return text;
if (behindSince !== null && now - behindSince > MAX_TAIL_LAG_MS) return text;
return committed !== null && committed.length > deferred.length && text.startsWith(committed) ? committed : deferred;
}
3 changes: 2 additions & 1 deletion packages/ui-react/tests/browser/code-fences-plain.layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ test("before highlighting and after a real lazy-module failure, streamed fences
flushSync(() => renderer!.render(<BrainUiProvider root={root!}><BrainMarkdown content={'```bash\n'+complete+'\n```'}/></BrainUiProvider>));
expect(host.querySelector('[data-kit-code-block]'),"streaming preserves the component").toBe(card);
expect(host.querySelectorAll('[class*="hljs-"]')).toHaveLength(0);
const pre=card.querySelector('pre')!; expect(pre.textContent?.trimEnd()).toBe(complete); expect(pre.scrollWidth).toBeLessThanOrEqual(pre.clientWidth+1);
// The growing last block's re-parse is deferred behind input (#2588): it lands on the next render.
const pre=card.querySelector('pre')!; await expect.poll(() => card.querySelector('pre')!.textContent?.trimEnd()).toBe(complete); expect(card.querySelector('pre')).toBe(pre); expect(pre.scrollWidth).toBeLessThanOrEqual(pre.clientWidth+1);
await userEvent.click(card.querySelector('button')!); expect(writes.at(-1)).toBe(complete);
}
});
Loading
Loading