diff --git a/.changeset/2588-streaming-markdown-blocks.md b/.changeset/2588-streaming-markdown-blocks.md new file mode 100644 index 0000000000..ca8b55854f --- /dev/null +++ b/.changeset/2588-streaming-markdown-blocks.md @@ -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. diff --git a/packages/ui-react/src/components/chat/brain-markdown.tsx b/packages/ui-react/src/components/chat/brain-markdown.tsx index c05c55efe2..0b33981ee2 100644 --- a/packages/ui-react/src/components/chat/brain-markdown.tsx +++ b/packages/ui-react/src/components/chat/brain-markdown.tsx @@ -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, @@ -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 (
- - {processed} - + + {blocks.map((text, i) => ( + + ))} +
); }); + +type BlockProps = { text: string; rehypePlugins: React.ComponentProps["rehypePlugins"]; components: React.ComponentProps["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 {text}; +}); + +/** + * 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(null); + // The text the last commit showed: the tail never steps back behind it. + const committed = useRef(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 <> + + {/* react-markdown separates top-level blocks with a newline; keep it between ours. */} + {last ? null : "\n"} + ; +} diff --git a/packages/ui-react/src/components/chat/markdown-blocks.ts b/packages/ui-react/src/components/chat/markdown-blocks.ts new file mode 100644 index 0000000000..7d91cf0ab5 --- /dev/null +++ b/packages/ui-react/src/components/chat/markdown-blocks.ts @@ -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 (``) 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 + * (`|[-*+][ \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; +} diff --git a/packages/ui-react/tests/browser/code-fences-plain.layout.tsx b/packages/ui-react/tests/browser/code-fences-plain.layout.tsx index 17ace7984d..c240694eab 100644 --- a/packages/ui-react/tests/browser/code-fences-plain.layout.tsx +++ b/packages/ui-react/tests/browser/code-fences-plain.layout.tsx @@ -35,7 +35,8 @@ test("before highlighting and after a real lazy-module failure, streamed fences flushSync(() => renderer!.render()); 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); } }); diff --git a/packages/ui-react/tests/markdown-blocks.test.tsx b/packages/ui-react/tests/markdown-blocks.test.tsx new file mode 100644 index 0000000000..b1871022b5 --- /dev/null +++ b/packages/ui-react/tests/markdown-blocks.test.tsx @@ -0,0 +1,181 @@ +/** + * Streaming markdown parses block by block (#2588): the split must never + * change what renders. Each fixture below renders identically split and + * whole; the whole render comes from the same component with the splitter + * swapped for one that never splits. + */ +import { afterAll, describe, expect, mock, test } from "bun:test"; +import { renderToStaticMarkup } from "react-dom/server"; +import Markdown from "react-markdown"; +import { REMARK_PLUGINS } from "../src/components/chat/use-markdown-highlight.js"; +import * as blocks from "../src/components/chat/markdown-blocks.js"; +import { MAX_TAIL_LAG_MS, tailText } from "../src/components/chat/markdown-blocks.js"; +import { BrainMarkdown } from "../src/components/chat/brain-markdown.js"; +import { BrainUiProvider } from "../src/root-context.js"; +import { createBrainUiRoot } from "../src/root.js"; + +const realSplit = blocks.splitMarkdownBlocks; +let whole = false; +mock.module("../src/components/chat/markdown-blocks.js", () => ({ + splitMarkdownBlocks: (text: string) => (whole ? [text] : realSplit(text)), +})); +afterAll(() => mock.restore()); + +const root = createBrainUiRoot({ storage: null }); +function html(content: string, props: { fileLinks?: boolean; entityTags?: boolean }, asWhole: boolean): string { + whole = asWhole; + try { + return renderToStaticMarkup(); + } finally { whole = false; } +} + +describe("splitMarkdownBlocks", () => { + test("splits paragraphs and headings at blank lines, keeping the blank lines with the block before", () => { + expect(realSplit("# Ithaca\n\nThe raft is ready.\n\n\nPenelope weaves.")).toEqual(["# Ithaca\n", "The raft is ready.\n\n", "Penelope weaves."]); + }); + test("never splits inside a fence, backtick or tilde, any length, nor after an unclosed one", () => { + expect(realSplit("Before.\n\n```js\nconst a = 1;\n\nconst b = 2;\n```\n\nAfter.")).toEqual(["Before.\n", "```js\nconst a = 1;\n\nconst b = 2;\n```\n", "After."]); + expect(realSplit("~~~~\nsail\n\n~~~\nstill inside\n~~~~\n\nAfter.")).toEqual(["~~~~\nsail\n\n~~~\nstill inside\n~~~~\n", "After."]); + expect(realSplit("Before.\n\n```\nopen fence\n\nstill streaming")).toEqual(["Before.\n", "```\nopen fence\n\nstill streaming"]); + }); + test("keeps lists, blockquotes, tables and indented continuations whole", () => { + expect(realSplit("- one\n\n- two\n\n more of two\n\n3. three\n\n4) four\n\n> quote\n\n> more\n\n| a |\n\n code")).toHaveLength(1); + }); + test("does not split a text with a link reference or footnote definition, nor a long HTML block", () => { + expect(realSplit("See [the log][l].\n\n[l]: https://ithaca.example/log")).toHaveLength(1); + expect(realSplit("A claim.[^1]\n\nMore.\n\n[^1]: The source.")).toHaveLength(1); + expect(realSplit("
\na\n\nb\n
\n\nAfter.")).toHaveLength(1); + expect(realSplit("\n\nAfter.")).toHaveLength(1); + }); + test("finds definitions inside blockquotes and list items, and with escaped brackets", () => { + for (const text of ["See [the log][l].\n\n> [l]: https://ithaca.example/log", "A claim.[^1]\n\nMore.\n\n> [^1]: The source.", "See [x].\n\n>> [x]: /u", "See [the log][l].\n\n- [l]: https://ithaca.example/log", "See [a\\]b].\n\n[a\\]b]: https://ithaca.example/"]) + expect(realSplit(text), text).toHaveLength(1); + }); + test("a tag or an autolink still being typed at a line start does not collapse the split", () => { + const answer = "Plan:\n\n```mermaid\ngraph LR; Troy-->Ithaca\n```\n\nThe voyage.\n\n"; + const blocks = realSplit(answer + "Sources:").length; + for (const tail of ["", "", "")).toHaveLength(1); + expect(realSplit(answer + "Shipwrights")).toHaveLength(1); + }); + test("a paragraph being typed that starts with a number does not collapse the split", () => { + const answer = "Plan:\n\n```mermaid\ngraph LR; Troy-->Ithaca\n```\n\n"; + for (const tail of ["3.14 leagues to Ithaca", "2) the strait", "- a raft", "* oars"]) { + for (let i = 1; i <= tail.length; i++) { + expect(realSplit(answer + tail.slice(0, i)), `while "${tail.slice(0, i)}" streams`).toHaveLength(3); + } + } + // After a list, a new item after a blank line joins it (and makes it loose), so it stays with it. + expect(realSplit("- oars\n\n- sails")).toHaveLength(1); + expect(realSplit("> - oars\n\n3. sails")).toHaveLength(1); + expect(realSplit("- oars\n\nThe crew.")).toHaveLength(2); + // After an indented code block the whole text can read an item as a paragraph. + expect(realSplit(" oars\n\n1.")).toHaveLength(1); + expect(realSplit(" oars\n\n10. sails")).toHaveLength(1); + }); + test("leading blank lines start no empty block", () => { + expect(realSplit("\n\nFirst.\n\nSecond.")).toEqual(["\n\nFirst.\n", "Second."]); + }); +}); + +/** The issue's corpus. Each entry must split, except those that must not. */ +const CORPUS: Record = { + "reference links and footnotes": { text: "Odysseus kept [a log][log] of the voyage.[^1]\n\nThe crew read it.\n\n[log]: https://ithaca.example/log\n[^1]: Written at Ogygia.", splits: false }, + "loose and tight lists, an ordered list from 3": { text: "Supplies:\n\n- water\n- bread\n\nTasks:\n\n3. caulk the raft\n\n4. raise the mast\n\nDone.\n\n* oars\n\n* rope", splits: true }, + "fences with blank lines, backtick and tilde": { text: "Code:\n\n```ts\nconst raft = 1;\n\nconst mast = 2;\n```\n\nAnd:\n\n~~~~sh\nsail\n\nhome\n~~~~\n\nEnd.", splits: true }, + "an unclosed fence mid-stream": { text: "Plan:\n\nFirst step.\n\n```js\nconst wind = 'west';\n\nif (wind)", splits: true }, + "blockquotes, tables, setext headings": { text: "Athena\n======\n\n> Go home.\n>\n> Now.\n\nVoyage\n------\n\n| Day | Port |\n| --- | --- |\n| 1 | Troy |\n\nAfter the table.", splits: true }, + "an HTML block": { text: "Before.\n\n
\nraw\n
\n\nAfter the div.", splits: false }, + "entity tags": { text: "Met

Penelope

at the loom.\n\nThen Ithaca Shipwrights and The Raft.\n\nOn 2026-07-12.", splits: true, props: { fileLinks: true, entityTags: true } }, + "share blocks": { text: "Here it is:\n\n```share md \"Voyage log\"\n# Day one\n\nCalm seas.\n```\n\nThat is the log.\n\nAnd more.", splits: true }, + "definitions inside a blockquote and a list item": { text: "Odysseus kept [a log][log].[^1]\n\nThe crew read it.\n\n> [log]: https://ithaca.example/log\n\n- [^1]: Written at Ogygia.", splits: false }, + "a definition whose label wraps across lines": { text: "See [the raft][long\nlabel].\n\nIt floats.\n\n[long\nlabel]: https://ithaca.example/raft", splits: false }, + "a definition with an escaped bracket": { text: "See [the raft\\]][r].\n\nIt floats.\n\n[the raft\\]]: https://ithaca.example/raft", splits: false }, + "a line of Unicode space continues a paragraph": { text: "Para one\n\u00a0\nstill para one.\n\nPara two\n\u3000\nstill two.\n\nThree\n\ufeff\nstill three.\n\nFour\n\u000b\nstill four.\n\nFive.", splits: true }, + "a closing fence followed by a Unicode space does not close": { text: "Before.\n\n```\ncode\n```\u00a0\n\nstill code\n\n```\n\nAfter.", splits: true }, + "a definition label wrapped after a backslash": { text: "See [a\\\nb].\n\nMore.\n\n[a\\\nb]: /u", splits: false }, + "a list-item fence closed at column 0": { text: "1. Install:\n\n ```bash\n npm i\n```\n\n2. Run it\n\nDone.", splits: false }, + "a fence indented at the top level": { text: "Before.\n\n ```\ncode at column 0\n\nstill code\n ```\n\nAfter.", splits: false }, + "a pre or comment block inside a list item": { text: "-
\n\n  x\n\ny\n\n- ", "[r]: /u", "> [q]: /q", "[^1]: note", "see [x][r] and [^1]",
+  "\u00a0", " ", "\t", "
", "Term\n: def", "1. a\n2. b", "- a\n - b", "text with `code`", "***bold***", "\\", "- [ ] task", "|x|", "a | b", "-- | --", + "hard break ", "back\\", "", "*emph", "**", "[link](/u)", "![img](/i.png)", "&", "1.", "-", ">", "#", "======", "| --- |", "\t- tab item", "10. ten", "~~~~ ~", "```` js", " > quote", "\u3000", "a\u00a0b", +]; +function seeded(seed: number) { return () => { seed = (Math.imul(seed, 1103515245) + 12345) >>> 0; return seed / 0x100000000; }; } +const parse = (text: string) => renderToStaticMarkup({text}).replace(/]*\/>/g, ""); + +test("generated documents parse the same split and whole", () => { + const differing: string[] = []; + let split = 0; + for (const seed of [2588, 7, 4242]) { + const random = seeded(seed); + for (let n = 0; n < 5000 && differing.length < 5; n++) { + const parts: string[] = []; + for (let i = 0, length = 2 + Math.floor(random() * 10); i < length; i++) { + parts.push(LINES[Math.floor(random() * LINES.length)]!, random() < 0.55 ? "\n\n" : "\n"); + } + const text = parts.join(""); + const pieces = realSplit(text); + if (pieces.length < 2) continue; + split++; + if (parse(text) !== pieces.map(parse).join("\n")) differing.push(JSON.stringify(text)); + } + } + expect(split, "the generator produces documents that split").toBeGreaterThan(1000); + expect(differing).toEqual([]); +}, 60_000); + +describe("tailText", () => { + test("a tail that has just fallen behind shows its deferred text, however long the stream paused before", () => { + expect(tailText("abc", "ab", null, null, 1_000_000), "no commit has shown it behind yet").toBe("ab"); + }); + test("shows the deferred tail while it has been behind for no longer than the bound", () => { + expect(tailText("abcd", "ab", "ab", 1000, 1000 + MAX_TAIL_LAG_MS)).toBe("ab"); + }); + test("renders the current tail once it has been behind for longer than the bound", () => { + expect(tailText("abcde", "ab", "ab", 1000, 1001 + MAX_TAIL_LAG_MS)).toBe("abcde"); + }); + test("never steps back behind what it last committed, though the deferred value is older", () => { + // The bound forced "abcde"; the deferred value is still "ab"; a new delta arrives. + expect(tailText("abcdef", "ab", "abcde", null, 2000)).toBe("abcde"); + }); + test("caught up, replaced or with no deferred text, shows the current text", () => { + expect(tailText("abc", "abc", "abc", null, 5000)).toBe("abc"); + expect(tailText("xyz", "ab", "ab", 1000, 1001)).toBe("xyz"); + expect(tailText("abc", null, null, 1000, 1001)).toBe("abc"); + }); +}); diff --git a/packages/ui-react/tests/render/streaming-markdown-dom.ts b/packages/ui-react/tests/render/streaming-markdown-dom.ts new file mode 100644 index 0000000000..941d2413df --- /dev/null +++ b/packages/ui-react/tests/render/streaming-markdown-dom.ts @@ -0,0 +1,16 @@ +// happy-dom registration for the streaming markdown render test (#2588); a +// sibling of `dom.ts` for the reason `ask-user-dom.ts` states: that module's +// body runs once per process, so each render test file registers its own DOM +// and unregisters it in `afterAll`. Import it FIRST, before any component. +import { GlobalRegistrator } from "@happy-dom/global-registrator"; + +export function registerStreamingMarkdownDom(): void { + if (!GlobalRegistrator.isRegistered) GlobalRegistrator.register({ url: "http://localhost/" }); + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; +} + +registerStreamingMarkdownDom(); + +export async function unregisterStreamingMarkdownDom(): Promise { + if (GlobalRegistrator.isRegistered) await GlobalRegistrator.unregister(); +} diff --git a/packages/ui-react/tests/render/streaming-markdown.test.tsx b/packages/ui-react/tests/render/streaming-markdown.test.tsx new file mode 100644 index 0000000000..8ff90f7dd7 --- /dev/null +++ b/packages/ui-react/tests/render/streaming-markdown.test.tsx @@ -0,0 +1,113 @@ +/** + * A streaming answer re-parses only its growing tail (#2588). react-markdown + * is wrapped to record the text of every parse; appending to the last block + * of a 24 KB answer must parse that block alone, never an earlier one, and + * an earlier block's elements must keep their DOM identity (a rendered + * Mermaid diagram keeps its SVG state). + */ +import { registerStreamingMarkdownDom, unregisterStreamingMarkdownDom } from "./streaming-markdown-dom.js"; + +registerStreamingMarkdownDom(); + +import { afterAll, afterEach, expect, mock, test } from "bun:test"; +import { act, cleanup, render } from "@testing-library/react"; +import { flushSync } from "react-dom"; +import { createRoot } from "react-dom/client"; +import RealMarkdown from "react-markdown"; + +const parsed: string[] = []; +// The function itself, before the mock replaces the module's binding. +const realMarkdown = RealMarkdown; +mock.module("react-markdown", () => ({ + default: (props: Parameters[0]) => { + parsed.push(String(props.children ?? "")); + return realMarkdown(props); + }, +})); + +const { BrainMarkdown } = await import("../../src/components/chat/brain-markdown.js"); +const { splitMarkdownBlocks } = await import("../../src/components/chat/markdown-blocks.js"); +const { BrainUiProvider } = await import("../../src/root-context.js"); +const { createBrainUiRoot } = await import("../../src/root.js"); + +// File links ask the host for wikilinks once; nothing here is on the network. +const root = createBrainUiRoot({ storage: null, request: async () => Response.json({ slugs: {}, entries: [] }) }); +afterEach(async () => { await act(async () => cleanup()); parsed.length = 0; }); +afterAll(async () => { mock.restore(); root.dispose(); await unregisterStreamingMarkdownDom(); }); + +const answer = (paragraphs: number) => Array.from({ length: paragraphs }, (_, i) => + i % 9 === 4 ? "```js\nconst day = " + i + ";\n\nconst port = 'Ithaca';\n```" : `Day ${i}: the raft drifts east past the headland, and Odysseus counts the stars to keep his course for Ithaca.`).join("\n\n"); +/** + * Waits until rendering is quiet: the highlighter loads asynchronously and, + * once it has, every block parses one more time with it. That is the first + * render's cost, not streaming's; the appends below are measured after it. + */ +async function settled() { + for (let quiet = 0, seen = -1; quiet < 3;) { + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); }); + if (parsed.length === seen) quiet++; else { quiet = 0; seen = parsed.length; } + } +} +const view = (content: string) => ; + +test("appending to the last block of a 24 KB answer parses only that block", async () => { + let text = answer(240); + expect(text.length, "a 24 KB answer").toBeGreaterThan(24_000); + // The splitter's view of it, independent of the renderer under test. + expect(splitMarkdownBlocks(text).length, "the answer has many top-level blocks").toBeGreaterThan(100); + const r = render(view(text)); + await settled(); + for (const word of [" and the wind", " turns west", " at dusk."]) { + parsed.length = 0; + text += word; + r.rerender(view(text)); + await act(async () => {}); + expect(parsed.length, "one parse per append").toBeGreaterThan(0); + // The growing tail may parse twice (deferred, then current), but nothing else parses. + expect(parsed.length, "at most the tail's two parses").toBeLessThanOrEqual(2); + expect(parsed.every((source) => source.endsWith(word) && source.length < 400), `only the grown tail block re-parses: ${parsed.map((s) => s.length).join(", ")}`).toBe(true); + } +}); + +test("a new block below leaves the earlier ones parsed once and their elements in place", async () => { + let text = "```mermaid\ngraph LR; Troy-->Ithaca\n```\n\nThe voyage begins."; + const r = render(view(text)); + await settled(); + const first = r.container.querySelector(".brain-prose")!.firstElementChild!; + expect(first, "the diagram block is drawn").toBeTruthy(); + for (const more of ["\n\nDay one: calm.", "\n\nDay two: a storm.", " The mast holds."]) { + parsed.length = 0; + text += more; + r.rerender(view(text)); + await act(async () => {}); + expect(parsed.some((source) => source.includes("mermaid")), "the diagram's block is not parsed again").toBe(false); + expect(r.container.querySelector(".brain-prose")!.firstElementChild, "its element is the same node: nothing remounted").toBe(first); + } +}); + +test("when a definition arrives and the text must parse whole, the first commit shows the whole text", async () => { + // The split collapses to one block, so block 0 becomes the last one. Its + // deferred value must not paint block 0's old text alone for a commit. + const host = document.createElement("div"); + document.body.append(host); + const reactRoot = createRoot(host); + const split = "First para.[^1]\n\nSecond para.\n\nThird para."; + await act(async () => { reactRoot.render(view(split)); }); + expect(host.textContent).toContain("Third para."); + flushSync(() => reactRoot.render(view(split + "\n\n[^1]: Source."))); + expect(host.textContent, "the urgent commit holds every block, not block 0 alone").toContain("Third para."); + await act(async () => { reactRoot.unmount(); }); + host.remove(); +}); + +test("replaced content (another document) shows at once, not the previous document's last block", async () => { + const host = document.createElement("div"); + document.body.append(host); + const reactRoot = createRoot(host); + await act(async () => { reactRoot.render(view("Penelope weaves by day.\n\nShe unpicks it by night.")); }); + flushSync(() => reactRoot.render(view("Telemachus sails to Pylos.\n\nNestor receives him."))); + expect(host.textContent, "the new document in the urgent commit").toContain("Nestor receives him."); + expect(host.textContent, "nothing of the old one").not.toContain("unpicks"); + await act(async () => { reactRoot.unmount(); }); + host.remove(); +});