Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: stop a failed markdown chunk from taking the whole app down (#9236)

Daniel Hand3acce846b31
diff --git a/studio/frontend/src/components/assistant-ui/markdown-block-boundary.tsx b/studio/frontend/src/components/assistant-ui/markdown-block-boundary.tsx
new file mode 100644
index 00000000000..c83233ad5ba
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/markdown-block-boundary.tsx
@@ -0,0 +1,147 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"use client";
+
+import { Component, type ReactNode } from "react";
+import { markdownBlockFallback } from "./markdown-block-fallback";
+
+/**
+ * One Markdown block that fails to render must not take the application with it.
+ *
+ * Streamdown renders both the syntax highlighted code body and the Mermaid
+ * diagram through `React.lazy` inside its own `<Suspense>`
+ * (`streamdown/dist/chunk-*.js`). The chunks are fetched the first time a reply
+ * contains a fence or a diagram, so the fetch happens mid-reply, on the network
+ * the app happens to have at that moment. A rejected lazy import rethrows during
+ * render, and until this boundary existed the nearest catcher was TanStack
+ * Router's `CatchBoundaryImpl`: one chunk that would not load replaced the whole
+ * of Studio with "Something went wrong!", unmounted the assistant-ui runtime
+ * with it, and left the reply's own stream with nothing consuming it. The reply
+ * that was already on screen went too.
+ *
+ * Measured, by aborting exactly that one request on an otherwise unmodified
+ * tree: the document went from 114 elements to 21, the thinking pane
+ * disappeared, and the generator feeding the reply stopped two chunks later and
+ * never resumed. It was also seen once with nothing injected at all.
+ *
+ * SCOPE. Per BLOCK, not per message, so a fence that cannot be highlighted
+ * costs its own colours and nothing else: every other block in the same reply
+ * keeps rendering normally. The runtime, the thread and the stream are all
+ * outside and are untouched, so the reply carries on arriving.
+ *
+ * NO RETRY, ON PURPOSE. React and the browser's module map both cache a failed
+ * dynamic import, so re-importing rethrows without issuing a new request
+ * (whatwg/html#6768). `SettingsPanelBoundary` in the settings dialog reaches the
+ * same conclusion for the same reason. Retrying here would throw on every frame
+ * of a streaming reply for nothing. The failure is therefore sticky for the life
+ * of the block, and a reader who wants the colours back reloads.
+ */
+
+type Props = {
+ /** The block's Markdown source, shown as text if rendering it fails. */
+ content: string;
+ children: ReactNode;
+};
+
+type State = { failed: boolean };
+
+/**
+ * The INNER boundary: the renderer fails, the block's controls survive.
+ *
+ * `MarkdownBlockBoundary` below is the catch-all and wraps the whole block, so
+ * when it fires it necessarily takes the block's siblings with it: the copy and
+ * download bar, and a completed SVG fence's already-sanitized preview. Those are
+ * exactly the affordances a reader wants at the moment a block failed to render,
+ * because the next thing they do with a block they cannot read here is take it
+ * somewhere else.
+ *
+ * So the throw-prone renderer gets its own boundary, inside the wrapper that
+ * carries the controls. `Block` is the only thing in a block that loads code at
+ * render time, so it is the only thing that needs one.
+ *
+ * The fallback is an ELEMENT built by the caller, not something computed here.
+ * React does not catch a throw in a boundary's own render, so the less this
+ * render does the better: this one branches and returns. If the fallback element
+ * itself throws while rendering, it throws as this boundary's own output and
+ * `MarkdownBlockBoundary` catches it, degrading the whole block to text the way
+ * it does today. Two rungs, and the bottom one is the behaviour already shipped.
+ */
+export class MarkdownRendererBoundary extends Component<
+ { fallback: ReactNode; children: ReactNode },
+ State
+> {
+ state: State = { failed: false };
+
+ static getDerivedStateFromError(): State {
+ return { failed: true };
+ }
+
+ componentDidCatch(error: unknown): void {
+ console.error(
+ "[markdown] a block renderer failed, showing its source instead",
+ error,
+ );
+ }
+
+ render(): ReactNode {
+ return this.state.failed ? this.props.fallback : this.props.children;
+ }
+}
+
+export class MarkdownBlockBoundary extends Component<Props, State> {
+ state: State = { failed: false };
+
+ static getDerivedStateFromError(): State {
+ return { failed: true };
+ }
+
+ componentDidCatch(error: unknown): void {
+ // Still reported. Degrading quietly is right for the READER and wrong for
+ // anyone trying to find out why a reply lost its highlighting.
+ console.error(
+ "[markdown] a block failed to render, showing it as text",
+ error,
+ );
+ }
+
+ render(): ReactNode {
+ if (!this.state.failed) {
+ return this.props.children;
+ }
+ return <MarkdownBlockFallbackView content={this.props.content} />;
+ }
+}
+
+/**
+ * A block shown as its own source.
+ *
+ * Extracted so that the whole-block boundary and the narrower renderer boundary
+ * degrade a block to exactly the same thing. They are reached by different
+ * routes: a fence that is still STREAMING has no closing fence yet, so
+ * `getCodeFence` does not match it and it renders through the plain `Block`
+ * rather than through `FenceBlock`, which is the route that carries the
+ * controls. Both routes have to land the reader in the same place.
+ */
+export function MarkdownBlockFallbackView({ content }: { content: string }) {
+ const fallback = markdownBlockFallback(content);
+ if (fallback.fenced) {
+ return (
+ <div className="my-4 w-full overflow-x-auto rounded-xl border border-border bg-sidebar p-2">
+ {fallback.language && (
+ <div className="flex h-8 items-center text-muted-foreground text-xs">
+ <span className="ml-1 font-mono lowercase">
+ {fallback.language}
+ </span>
+ </div>
+ )}
+ <pre className="overflow-x-auto rounded-md border border-border bg-background p-4 text-sm">
+ <code>{fallback.text}</code>
+ </pre>
+ </div>
+ );
+ }
+ return (
+ <div className="my-4 whitespace-pre-wrap break-words">{fallback.text}</div>
+ );
+}
diff --git a/studio/frontend/src/components/assistant-ui/markdown-block-fallback.ts b/studio/frontend/src/components/assistant-ui/markdown-block-fallback.ts
new file mode 100644
index 00000000000..83a45e4df07
--- /dev/null
+++ b/studio/frontend/src/components/assistant-ui/markdown-block-fallback.ts
@@ -0,0 +1,223 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/**
+ * What one Markdown block should show when it cannot be RENDERED.
+ *
+ * Streamdown loads two parts of a reply through `React.lazy`: the syntax
+ * highlighted code body and the Mermaid renderer. Both are fetched at the
+ * moment a reply first contains that construct, and a lazy import that rejects
+ * rethrows during render. Nothing between the thread and the router catches
+ * that today, so one chunk that will not load replaces the whole application
+ * with the router's error page and takes the reply that was already on screen
+ * with it.
+ *
+ * The answer is to keep the CONTENT. A fence whose highlighter is missing is
+ * still perfectly readable as text: it is the same characters in the same
+ * order, which is what the model actually said. So the degraded form of a block
+ * is its own source, with the Markdown fence scaffolding removed so a reader
+ * sees code rather than backticks.
+ *
+ * Deliberately NOT an error card and deliberately not blank. A reader who asked
+ * a model for a shell command needs the command, not an apology, and least of
+ * all an empty box where their answer used to be.
+ */
+
+export type MarkdownBlockFallback = {
+ /** The text to show. Empty only when the block itself carried no content. */
+ text: string;
+ /** The fence's language tag, when the block was a fence and named one. */
+ language: string | null;
+ /** Whether the source was a fenced block, so the caller can pick `pre` over prose. */
+ fenced: boolean;
+};
+
+type OpeningFence = {
+ /** The opening run, whose CHARACTER and LENGTH both constrain the close. */
+ marker: string;
+ /** Everything after the run on the opening line, the info string. */
+ info: string;
+ /** The block after the opening line. */
+ body: string;
+ /** The opener's own indentation, which every content line is measured against. */
+ indent: number;
+};
+
+/**
+ * Scanned rather than matched.
+ *
+ * The regex this replaces put `[^\r\n]*` straight after `` `{3,} ``, and the two
+ * compete for the same backticks, so an opening run with no line break after it
+ * backtracks quadratically. Scanning takes the run greedily once and never
+ * reconsiders, which is linear by construction on any input.
+ */
+function openingFence(content: string): OpeningFence | null {
+ let i = 0;
+ while (i < 3 && content[i] === " ") i += 1;
+ const char = content[i];
+ if (char !== "`" && char !== "~") return null;
+ let run = 0;
+ while (content[i + run] === char) run += 1;
+ if (run < 3) return null;
+ const lineEnd = content.indexOf("\n", i + run);
+ // A reply that ENDS on the opening line has still opened a fence. CommonMark
+ // 0.31.2 closes an unclosed block at the end of the document, so the opening
+ // line is the whole fence and the body is empty. Returning null here showed
+ // the delimiter and the language tag as prose instead.
+ const rest = lineEnd === -1 ? content.length : lineEnd;
+ const info = content.slice(i + run, rest).replace(/\r$/, "");
+ // "If the info string comes after a backtick fence, it may not contain any
+ // backtick characters" (CommonMark 0.31.2). Such a line is a PARAGRAPH, so
+ // the block is not a whole-block fence and belongs to the caller unchanged;
+ // treating it as one drops the opening line and the reader loses that text.
+ // Tilde fences carry no such restriction. `CODE_FENCE_RE` in
+ // `features/chat/artifacts/html-fences` already spells the same rule.
+ if (char === "`" && info.includes("`")) return null;
+ const body = lineEnd === -1 ? "" : content.slice(lineEnd + 1);
+ return { marker: char.repeat(run), info, body, indent: i };
+}
+
+/**
+ * The body with the opener's indentation taken off each line.
+ *
+ * "If the leading code fence is indented N spaces, then up to N spaces of
+ * indentation are removed from each line of the content" (CommonMark 0.31.2).
+ * UP TO: a line indented less than the opener loses only what it has, and a line
+ * indented more keeps the remainder, which is the code's own structure.
+ *
+ * Recognising the indent when opening the fence and then not removing it is the
+ * half of the rule that shows. The rendered block reads `x = 1`, the degraded
+ * one reads ` x = 1`, and a reader who copies that into a file gets an
+ * IndentationError from text their model never wrote. `extractHtmlFences`
+ * already applies the same rule to the same construct.
+ */
+function stripIndent(body: string, indent: number): string {
+ if (indent === 0 || body === "") return body;
+ const lines = body.split("\n");
+ for (let n = 0; n < lines.length; n += 1) {
+ let take = 0;
+ while (take < indent && lines[n][take] === " ") take += 1;
+ lines[n] = lines[n].slice(take);
+ }
+ return lines.join("\n");
+}
+
+/**
+ * Whether the line `[from, to)` of `text` closes a fence opened with `marker`.
+ *
+ * CommonMark 0.31.2 requires the closing fence to use the same character and
+ * "at least as many" of it, so the opening length is a MINIMUM and not a match:
+ * a four-backtick close is how a model closes a fence whose body contains a
+ * three-backtick one. The previous back-reference demanded the exact same run
+ * and left the close on screen as if it were code.
+ *
+ * Bounds rather than a line STRING because the caller has thousands of lines and
+ * the only thing most of them need is a look at their first character. Slicing
+ * each one, and testing each one against a regex, cost more than everything else
+ * in the scan put together.
+ */
+function closesFenceAt(
+ text: string,
+ from: number,
+ to: number,
+ marker: string,
+): boolean {
+ let i = from;
+ while (i < from + 3 && text[i] === " ") i += 1;
+ let run = 0;
+ while (i + run < to && text[i + run] === marker[0]) run += 1;
+ if (run < marker.length) return false;
+ // A closing fence carries no info string; only trailing spaces and tabs are
+ // allowed, plus the carriage return of a CRLF line, which is the LAST
+ // character of the line and only ever one. Accepting a CR anywhere in the tail
+ // instead would quietly close fences the line-based code did not.
+ const last = text[to - 1] === "\r" ? to - 1 : to;
+ for (let j = i + run; j < last; j += 1) {
+ const c = text[j];
+ if (c !== " " && c !== "\t") return false;
+ }
+ return true;
+}
+
+/**
+ * The readable form of a block that failed to render.
+ *
+ * Falls back to the block's own source unchanged for anything that is not a
+ * whole-block fence: a paragraph, a list or a table is already readable as
+ * Markdown, and inventing a renderer here would be a second thing to go wrong.
+ *
+ * This runs only once rendering has ALREADY failed, so it is the last thing
+ * between the reader and a lost block. Getting the fence wrong here does not
+ * cost a nicety, it puts stray backticks in the only view of the answer that
+ * still exists.
+ */
+export function markdownBlockFallback(content: string): MarkdownBlockFallback {
+ const open = openingFence(content);
+ if (!open) {
+ return { text: content, language: null, fenced: false };
+ }
+ const body = fenceBody(open.body, open.marker);
+ // The fence closed with the block still running, so the block is a DOCUMENT
+ // that merely starts with a fence. Its own source is the readable form.
+ if (body === null) {
+ return { text: content, language: null, fenced: false };
+ }
+ const language = open.info.trim().split(/\s+/)[0] || null;
+ return { text: stripIndent(body, open.indent), language, fenced: true };
+}
+
+/**
+ * The fence's content, or null when the fence does not own the whole block.
+ *
+ * One block is usually one construct, but not always: Streamdown 2.5's
+ * `parseMarkdownIntoBlocks` returns an ENTIRE reply as a single block once it
+ * contains a footnote (measured: the same reply splits into 5 blocks without one
+ * and 1 with). A fence at the top of such a block is followed by its own close
+ * and then by prose, and reading the whole thing as the fence's body put the
+ * closing delimiter, the prose and the footnote on screen as if the model had
+ * written them as Python.
+ *
+ * So the close is looked for from the TOP, and where it falls decides:
+ * last line the fence is the block. Its content is everything above.
+ * earlier the block continues past the fence, so it is not a whole-block
+ * fence and belongs to the caller unchanged.
+ * never still streaming. All of it is content, which is the case the
+ * reader needs most: the failure happens mid-fence, long before it
+ * closes.
+ *
+ * Driven by `indexOf` on the delimiter rather than walked line by line. A close
+ * has to carry at least three of the opening character, so the only lines worth
+ * looking at are the ones holding such a run, and an ordinary code block has
+ * exactly one: its own. Walking every line instead cost ~50ns per LINE, which a
+ * long block pays in full every time it re-renders.
+ */
+function fenceBody(body: string, marker: string): string | null {
+ // The line break before the closing fence belongs to the fence's line, and a
+ // block may or may not carry a trailing one of its own.
+ const withoutTrailingBreak = body.replace(/\r?\n$/, "");
+ // Three, not the marker itself: the opening run can be enormous, and a needle
+ // that long is both slow to build and slow to search for. This is a superset
+ // of the candidates, and `closesFenceAt` is what decides.
+ const probe = marker.slice(0, 3);
+ let from = 0;
+ for (;;) {
+ const hit = withoutTrailingBreak.indexOf(probe, from);
+ if (hit === -1) return body;
+ const start = withoutTrailingBreak.lastIndexOf("\n", hit) + 1;
+ const nl = withoutTrailingBreak.indexOf("\n", hit);
+ const end = nl === -1 ? withoutTrailingBreak.length : nl;
+ if (closesFenceAt(withoutTrailingBreak, start, end, marker)) {
+ if (nl !== -1) return null;
+ // An empty fence closes on the line after it opens, so there is no body at
+ // all. Returning the closing run here is what showed ``` as its own code.
+ if (start === 0) return "";
+ const cut =
+ withoutTrailingBreak[start - 2] === "\r" ? start - 2 : start - 1;
+ return withoutTrailingBreak.slice(0, cut);
+ }
+ if (nl === -1) return body;
+ // Past the whole LINE, not past the run: every delimiter left on a line the
+ // scan has already rejected would be re-examined for nothing.
+ from = nl + 1;
+ }
+}
diff --git a/studio/frontend/src/components/assistant-ui/markdown-text.tsx b/studio/frontend/src/components/assistant-ui/markdown-text.tsx
index ad2859e0fd3..4d573c231d7 100644
--- a/studio/frontend/src/components/assistant-ui/markdown-text.tsx
+++ b/studio/frontend/src/components/assistant-ui/markdown-text.tsx
@@ -47,6 +47,11 @@ import {
useFenceReached,
} from "./code-fence-defer";
import { createCodePlugin } from "./code-plugin";
+import {
+ MarkdownBlockBoundary,
+ MarkdownBlockFallbackView,
+ MarkdownRendererBoundary,
+} from "./markdown-block-boundary";
import "katex/dist/katex.min.css";
import { AudioPlayer } from "./audio-player";
import { unslothDarkTheme, unslothLightTheme } from "./code-themes";
@@ -373,7 +378,18 @@ function StreamdownBlockContent(props: BlockProps) {
if (mermaidSource) {
return (
<div className="relative isolate">
- <Block {...blockProps} />
+ {/*
+ * The Mermaid renderer is the app's other lazy chunk, so the diagram is
+ * the second thing that can fail at render time. Degraded, it is its own
+ * source as readable code, and the copy button beside it still works.
+ */}
+ <MarkdownRendererBoundary
+ fallback={
+ <DeferredFenceShell language="mermaid" source={mermaidSource} />
+ }
+ >
+ <Block {...blockProps} />
+ </MarkdownRendererBoundary>
<MermaidCopyButton source={mermaidSource} />
</div>
);
@@ -411,7 +427,29 @@ function StreamdownBlockContent(props: BlockProps) {
);
}
- return <Block {...blockProps} />;
+ /*
+ * THE STREAMING ROUTE, and the one that actually fires.
+ *
+ * `getCodeFence` needs the CLOSING fence, so a fence that is still arriving
+ * has no `codeFence` and falls all the way through to here rather than to
+ * `FenceBlock`. This bare `Block` is therefore what first asks for the
+ * highlighter chunk on a streamed reply, which is exactly when it fails.
+ *
+ * Left unguarded, the whole-block boundary catches that and latches with no
+ * reset, so the block never re-enters `FenceBlock` when its closing fence
+ * finally lands and the copy and download bar never mounts at all. Measured:
+ * with this unguarded, a streamed abort produced an identical document to the
+ * commit before the inner boundary existed, 0 copy and 0 download buttons on
+ * both. Guarding it keeps the failure inside the renderer boundary, so the
+ * completed block mounts `FenceBlock` normally and keeps its controls.
+ */
+ return (
+ <MarkdownRendererBoundary
+ fallback={<MarkdownBlockFallbackView content={props.content} />}
+ >
+ <Block {...blockProps} />
+ </MarkdownRendererBoundary>
+ );
}
/*
@@ -474,20 +512,38 @@ function FenceBlock({
const pretokenize = mode === "tokenize" && !reached;
useEffect(() => {
if (!pretokenize) return;
- code.highlight({
- code: trimTrailingNewlines(source),
- language: (languageToken ?? "text") as never,
- themes: STREAMDOWN_SHIKI_THEME,
- }, () => {});
+ code.highlight(
+ {
+ code: trimTrailingNewlines(source),
+ language: (languageToken ?? "text") as never,
+ themes: STREAMDOWN_SHIKI_THEME,
+ },
+ () => {},
+ );
}, [pretokenize, source, languageToken]);
return (
<div className="relative isolate" ref={host}>
- {reached ? (
- <Block {...blockProps} />
- ) : (
- <DeferredFenceShell language={languageToken} source={source} />
- )}
+ {/*
+ * Only `Block` can fail here, because only `Block` loads the highlighter
+ * at render time. Boundary it on its own so that a fence whose chunk will
+ * not load keeps the copy and download bar below, which is the control a
+ * reader reaches for precisely when a block did not render. The degraded
+ * form is the SAME plain shell an unreached fence already shows, so the
+ * failure looks like a fence that has not been highlighted rather than
+ * like a broken block.
+ */}
+ <MarkdownRendererBoundary
+ fallback={
+ <DeferredFenceShell language={languageToken} source={source} />
+ }
+ >
+ {reached ? (
+ <Block {...blockProps} />
+ ) : (
+ <DeferredFenceShell language={languageToken} source={source} />
+ )}
+ </MarkdownRendererBoundary>
<CodeBlockActions
disabled={Boolean(isIncomplete)}
language={language}
@@ -496,7 +552,20 @@ function FenceBlock({
</div>
);
}
-const StreamdownBlock = memo(StreamdownBlockContent);
+/**
+ * Every block is rendered inside a boundary. Streamdown fetches the code
+ * highlighter and the Mermaid renderer with `React.lazy` the first time a reply
+ * needs them, and a rejected import rethrows during render; without this the
+ * nearest catcher is the ROUTER's, which replaces all of Studio and takes the
+ * reply and its runtime with it. Per block, so one fence losing its colours
+ * costs only that fence.
+ */
+const StreamdownBlock = memo((props: BlockProps) => (
+ <MarkdownBlockBoundary content={props.content}>
+ <StreamdownBlockContent {...props} />
+ </MarkdownBlockBoundary>
+));
+StreamdownBlock.displayName = "StreamdownBlock";
const AUDIO_PLAYER_RE = /<audio-player\s+src="([^"]+)"\s*\/>/;
// Coalesce only token events that arrive before the browser's next paint, as
diff --git a/studio/frontend/tests/markdown-block-boundary.test.ts b/studio/frontend/tests/markdown-block-boundary.test.ts
new file mode 100644
index 00000000000..362859bec96
--- /dev/null
+++ b/studio/frontend/tests/markdown-block-boundary.test.ts
@@ -0,0 +1,469 @@
+// 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 { readFileSync } from "node:fs";
+import test from "node:test";
+
+import ts from "typescript";
+
+import {
+ markdownBlockFallback,
+} from "../src/components/assistant-ui/markdown-block-fallback.ts";
+
+/**
+ * Streamdown loads the syntax highlighted code body and the Mermaid renderer
+ * through `React.lazy`, and it fetches them the first time a reply contains
+ * that construct. A rejected import rethrows during render. Before the boundary
+ * these tests protect, the nearest catcher was TanStack Router's, so ONE chunk
+ * that would not load replaced all of Studio with "Something went wrong!",
+ * unmounted the assistant-ui runtime with it, and left the reply's stream with
+ * nothing consuming it.
+ *
+ * Measured on an unmodified tree by aborting exactly that one request: the
+ * document went from 122 elements to 21, the pane's readable text went from
+ * 11,968 characters to 0, and the stream stopped at 720 of 12,000 characters
+ * and never resumed.
+ *
+ * So what these tests hold is not "the app does not crash". It is that the
+ * READER STILL HAS THE CONTENT. A degraded fence has to be the same characters
+ * in the same order, because that is the answer they asked for, and an error
+ * card or an empty box in its place is a worse outcome than missing colour.
+ */
+
+const FENCE_BODY = [
+ "def score(rows, cap):",
+ " total = 0.0",
+ "",
+ " for row in rows:",
+ " total += min(cap, row.weight)",
+ " return total",
+].join("\n");
+
+test("a fenced block degrades to the code itself, without the fence scaffolding", () => {
+ const fallback = markdownBlockFallback("```python\n" + FENCE_BODY + "\n```");
+
+ assert.equal(
+ fallback.text,
+ FENCE_BODY,
+ "the degraded fence is not the code it was carrying, so the reader lost the answer",
+ );
+ assert.equal(fallback.language, "python");
+ assert.equal(
+ fallback.fenced,
+ true,
+ "a fence that is not reported as fenced renders as prose, so its indentation and line breaks collapse",
+ );
+});
+
+test("the degraded fence keeps every character and every blank line", () => {
+ const fallback = markdownBlockFallback("```python\n" + FENCE_BODY + "\n```");
+
+ assert.equal(
+ fallback.text.split("\n").length,
+ FENCE_BODY.split("\n").length,
+ "the degraded fence lost a line, and a blank line inside a function is not decoration",
+ );
+ assert.ok(
+ fallback.text.includes(" total = 0.0"),
+ "the degraded fence lost its leading whitespace, which in python is the program",
+ );
+});
+
+test("a fence that is still arriving degrades too", () => {
+ // The failure happens MID-fence: the chunk is fetched when the fence first
+ // renders, which is long before it closes. A fallback that only handled
+ // closed fences would show backticks at exactly the moment it is needed.
+ const fallback = markdownBlockFallback("```python\n" + FENCE_BODY);
+
+ assert.equal(
+ fallback.text,
+ FENCE_BODY,
+ "an unclosed fence was not recognised, so a reader sees the opening backticks and the language tag as text",
+ );
+ assert.equal(fallback.fenced, true);
+});
+
+test("a fence with no language tag still degrades to its body", () => {
+ const fallback = markdownBlockFallback("```\n" + FENCE_BODY + "\n```");
+
+ assert.equal(fallback.text, FENCE_BODY);
+ assert.equal(
+ fallback.language,
+ null,
+ "an absent language tag has to be absent, not the empty string, or the header renders blank",
+ );
+});
+
+test("a tilde fence degrades the same way", () => {
+ const fallback = markdownBlockFallback("~~~ts\nconst a = 1;\n~~~");
+
+ assert.equal(fallback.text, "const a = 1;");
+ assert.equal(fallback.language, "ts");
+});
+
+test("prose is handed back unchanged and is not treated as a fence", () => {
+ const prose = "The scorer skips empty rows, then applies the cap.";
+ const fallback = markdownBlockFallback(prose);
+
+ assert.equal(
+ fallback.text,
+ prose,
+ "a paragraph was rewritten on its way to the fallback",
+ );
+ assert.equal(
+ fallback.fenced,
+ false,
+ "prose rendered as a code block is a visible change to a reply that had nothing wrong with it",
+ );
+});
+
+test("a closing fence longer than the opening one still closes the block", () => {
+ // CommonMark 0.31.2 requires the close to carry AT LEAST as many characters
+ // as the open, so a four-backtick close is legitimate and is how a model
+ // closes a fence whose body contains a three-backtick one. Demanding the same
+ // run left the close on screen as though it were the last line of the code.
+ const fallback = markdownBlockFallback("```python\n" + FENCE_BODY + "\n````");
+
+ assert.equal(
+ fallback.text,
+ FENCE_BODY,
+ "a longer closing fence was not recognised, so the reader sees stray backticks below their code",
+ );
+ assert.equal(fallback.language, "python");
+ assert.equal(fallback.fenced, true);
+});
+
+test("a fence closed by a longer run keeps an inner fence in the body", () => {
+ // The reason the rule exists: the four-backtick fence is carrying a
+ // three-backtick one, which has to survive as content.
+ const fallback = markdownBlockFallback("````md\n```py\nx = 1\n```\n````");
+
+ assert.equal(fallback.text, "```py\nx = 1\n```");
+ assert.equal(fallback.language, "md");
+});
+
+test("an empty fence degrades to nothing, not to its own closing backticks", () => {
+ const fallback = markdownBlockFallback("```\n```");
+
+ assert.equal(
+ fallback.text,
+ "",
+ "the closing fence was returned as the body, so an empty code block renders ``` as if the model had written it",
+ );
+ assert.equal(fallback.fenced, true);
+});
+
+test("an opening fence the reply ends on is still a fence", () => {
+ // The repository's own parser (`mdast-util-from-markdown`, via Streamdown's
+ // `parseMarkdownIntoBlocks`) reads "```python" with no line break as
+ // code(lang="python", value=""), so the highlighter chunk IS requested for it
+ // and this fallback is reachable. CommonMark 0.31.2 closes an unclosed block
+ // at the end of the document. Read as prose, the reader gets the delimiter and
+ // the language tag as literal text where their answer should be.
+ for (const [content, language] of [
+ ["```python", "python"],
+ ["```", null],
+ ["~~~py", "py"],
+ [" ```py", "py"],
+ ] as const) {
+ const fallback = markdownBlockFallback(content);
+ assert.equal(
+ fallback.fenced,
+ true,
+ `an EOF terminated opening fence rendered as prose: ${JSON.stringify(content)}`,
+ );
+ assert.equal(fallback.text, "");
+ assert.equal(fallback.language, language);
+ }
+});
+
+test("a backtick fence whose info string carries a backtick is prose", () => {
+ // "If the info string comes after a backtick fence, it may not contain any
+ // backtick characters" (CommonMark 0.31.2), so this line does not open a
+ // fence and the parser keeps it as a paragraph. Accepting it as an opener
+ // discarded the opening line AND the closing one, which is the model's answer
+ // silently going missing in the one view of it that still exists.
+ const content = "```py`bad\nabc\n```";
+ const fallback = markdownBlockFallback(content);
+
+ assert.equal(
+ fallback.text,
+ content,
+ "an invalid backtick fence opener was accepted, so the block degraded to part of itself",
+ );
+ assert.equal(fallback.fenced, false);
+ assert.equal(fallback.language, null);
+});
+
+test("a backtick anywhere in the info string disqualifies the opener", () => {
+ // Not just the first word: the restriction is on the whole info string.
+ const content = "```py meta`x\nabc\n```";
+ assert.equal(markdownBlockFallback(content).text, content);
+ assert.equal(markdownBlockFallback("```py`bad").text, "```py`bad");
+});
+
+test("a tilde fence may carry backticks in its info string", () => {
+ // The restriction is backtick fences only, and the parser agrees:
+ // "~~~py`ok\nabc\n~~~" is code(lang="py`ok", value="abc").
+ const fallback = markdownBlockFallback("~~~py`ok\nabc\n~~~");
+
+ assert.equal(fallback.text, "abc");
+ assert.equal(fallback.fenced, true);
+ assert.equal(fallback.language, "py`ok");
+});
+
+test("an indented fence loses the opener's indentation, as the renderer does", () => {
+ // "If the leading code fence is indented N spaces, then up to N spaces of
+ // indentation are removed from each line of the content" (CommonMark 0.31.2),
+ // and the parser agrees: " ```python\n x = 1\n ```" is code(value="x = 1").
+ // Leaving it on gives the reader text their model did not write, and pasting
+ // it into a file is an IndentationError.
+ const fallback = markdownBlockFallback(" ```python\n x = 1\n ```");
+
+ assert.equal(fallback.text, "x = 1");
+ assert.equal(fallback.language, "python");
+ assert.equal(fallback.fenced, true);
+});
+
+test("only the opener's own indentation comes off, never the code's", () => {
+ // UP TO N. A line indented deeper than the opener keeps the remainder, which
+ // in Python is the program, and a line indented less loses only what it has.
+ assert.equal(
+ markdownBlockFallback(" ```py\n def f():\n return 1\n ```").text,
+ "def f():\n return 1",
+ "an indented fence lost the body's own indentation, so the code changed meaning",
+ );
+ assert.equal(
+ markdownBlockFallback(" ```py\nx = 1\n ```").text,
+ "x = 1",
+ "a content line shallower than the opener was over-stripped",
+ );
+ assert.equal(
+ markdownBlockFallback("```py\n x = 1\n```").text,
+ " x = 1",
+ "an unindented fence must not strip anything at all",
+ );
+});
+
+test("a block that continues past its fence is not read as one fence", () => {
+ // Streamdown 2.5's parseMarkdownIntoBlocks returns the WHOLE reply as a single
+ // block once it contains a footnote. Measured on the installed version: the
+ // same reply is 5 blocks without the footnote and 1 block with it. So a fence
+ // followed by prose really does arrive here as one string, and reading it all
+ // as the fence's body showed the closing delimiter, the prose and the footnote
+ // as though the model had written them as Python.
+ const content = "```python\nx=1\n```\n\nAfter code.[^1]\n\n[^1]: note";
+ const fallback = markdownBlockFallback(content);
+
+ assert.equal(
+ fallback.text,
+ content,
+ "a multi-construct block was degraded as a single fence, so prose rendered as code",
+ );
+ assert.equal(fallback.fenced, false);
+ assert.equal(fallback.language, null);
+});
+
+test("the close still has to be the last line, not merely present", () => {
+ // The three positions the close can take, which are the whole rule.
+ assert.equal(markdownBlockFallback("```py\nx\n```").text, "x");
+ assert.equal(markdownBlockFallback("```py\nx\n```\n").text, "x");
+ assert.equal(markdownBlockFallback("```py\nx").text, "x");
+ assert.equal(
+ markdownBlockFallback("```py\nx\n```\ntail").fenced,
+ false,
+ "content after the closing fence was swallowed into the code body",
+ );
+});
+
+test("an inner fence shorter than the opener does not end the block early", () => {
+ // The scan runs from the top now, so the first line that could be mistaken for
+ // a close is a four-backtick fence's three-backtick content.
+ const fallback = markdownBlockFallback("````md\n```py\nx = 1\n```\n````");
+
+ assert.equal(fallback.text, "```py\nx = 1\n```");
+ assert.equal(fallback.language, "md");
+ assert.equal(fallback.fenced, true);
+});
+
+test("a block with content never degrades to nothing", () => {
+ for (const content of [
+ "```python\nx = 1\n```",
+ "plain",
+ "| a | b |\n|---|---|\n| 1 | 2 |",
+ ]) {
+ const fallback = markdownBlockFallback(content);
+ assert.ok(
+ fallback.text.length > 0,
+ `a non-empty block degraded to an empty string: ${JSON.stringify(content)}`,
+ );
+ }
+});
+
+const MARKDOWN_TEXT_PATH = new URL(
+ "../src/components/assistant-ui/markdown-text.tsx",
+ import.meta.url,
+);
+const source = ts.createSourceFile(
+ MARKDOWN_TEXT_PATH.pathname,
+ readFileSync(MARKDOWN_TEXT_PATH, "utf8"),
+ ts.ScriptTarget.ESNext,
+ true,
+ ts.ScriptKind.TSX,
+);
+
+/** The JSX element names that wrap `StreamdownBlockContent` where it is rendered. */
+function wrappersAroundBlockContent(): string[] {
+ const wrappers: string[] = [];
+ const visit = (node: ts.Node, open: string[]): void => {
+ if (
+ ts.isJsxSelfClosingElement(node) &&
+ node.tagName.getText(source) === "StreamdownBlockContent"
+ ) {
+ wrappers.push(...open);
+ }
+ const next =
+ ts.isJsxElement(node)
+ ? [...open, node.openingElement.tagName.getText(source)]
+ : open;
+ node.forEachChild((child) => visit(child, next));
+ };
+ source.forEachChild((node) => visit(node, []));
+ return wrappers;
+}
+
+test("every markdown block is rendered inside the boundary", () => {
+ // A source check because no output test can tell them apart: an unwrapped tree
+ // renders identically until a lazy chunk fails, and then it takes the whole
+ // application with it. This is the only thing standing between that and a
+ // quiet revert.
+ assert.ok(
+ wrappersAroundBlockContent().includes("MarkdownBlockBoundary"),
+ "the block component is rendered outside MarkdownBlockBoundary, so a fence whose highlighter fails to load unmounts all of Studio through the router's error boundary again",
+ );
+});
+
+/** The JSX element names enclosing every occurrence of `tag`, innermost last. */
+function wrappersAround(tag: string): string[][] {
+ const found: string[][] = [];
+ const visit = (node: ts.Node, open: string[]): void => {
+ const name =
+ ts.isJsxSelfClosingElement(node) || ts.isJsxOpeningElement(node)
+ ? node.tagName.getText(source)
+ : null;
+ if (name === tag) found.push(open);
+ const next = ts.isJsxElement(node)
+ ? [...open, node.openingElement.tagName.getText(source)]
+ : open;
+ node.forEachChild((child) => visit(child, next));
+ };
+ source.forEachChild((node) => visit(node, []));
+ return found;
+}
+
+const INNER_BOUNDARY = "MarkdownRendererBoundary";
+
+test("no Block renders outside the renderer boundary", () => {
+ /*
+ * The test that was missing, and its absence shipped a boundary that never
+ * fired on the path it was written for.
+ *
+ * `Block` is the only thing that loads a chunk at render time, so EVERY place
+ * it is rendered has to be inside the narrower boundary. Checking only the
+ * places that have controls beside them is not enough: `getCodeFence` needs
+ * the CLOSING fence, so a fence that is still streaming falls past the fence
+ * branch to the bare `Block` at the end of `StreamdownBlockContent`, and that
+ * is precisely when the highlighter is first requested and fails. Leaving that
+ * one unguarded let the whole-block boundary catch and LATCH, so the block
+ * never re-entered `FenceBlock` when its closing fence arrived and the copy
+ * and download bar never mounted.
+ *
+ * Measured before this assertion existed: a streamed abort produced a document
+ * identical to the commit before the inner boundary was added, 1350 elements
+ * and 0 copy buttons on both.
+ */
+ const sites = wrappersAround("Block");
+ assert.ok(sites.length > 0, "no <Block> is rendered at all");
+ const unguarded = sites.filter((open) => !open.includes(INNER_BOUNDARY));
+ assert.deepEqual(
+ unguarded,
+ [],
+ `a <Block> renders outside ${INNER_BOUNDARY}, so a rejected chunk there escapes to the whole-block boundary and latches it for the rest of the stream`,
+ );
+});
+
+test("a failed renderer does not take the block's controls with it", () => {
+ /*
+ * The whole point, asserted as a RELATIONSHIP so it cannot pass vacuously: a
+ * tree with no inner boundary at all would satisfy "the control is not inside
+ * one", which is exactly the tree this test exists to reject.
+ *
+ * `Block` is the only thing in a block that loads a chunk at render time, so
+ * it is what the rejected `React.lazy` throws from. `CodeBlockActions` (copy
+ * and download) and `MermaidCopyButton` are independent of it, and they are
+ * what a reader reaches for when a block did not render. So each control must
+ * be a SIBLING of the boundary that catches the renderer, not a descendant:
+ * the control's ancestors must be exactly the Block's ancestors with the
+ * boundary taken out.
+ */
+ for (const control of ["CodeBlockActions", "MermaidCopyButton"]) {
+ const sites = wrappersAround(control);
+ assert.ok(sites.length > 0, `${control} is not rendered at all`);
+ for (const open of sites) {
+ assert.ok(
+ !open.includes(INNER_BOUNDARY),
+ `${control} is rendered inside ${INNER_BOUNDARY}, so it is unmounted along with the renderer that failed and the reader loses it exactly when they need it`,
+ );
+ assert.ok(
+ wrappersAround("Block").some(
+ (blockOpen) =>
+ blockOpen.includes(INNER_BOUNDARY) &&
+ blockOpen.filter((w) => w !== INNER_BOUNDARY).join(">") ===
+ open.join(">"),
+ ),
+ `no boundaried <Block> sits beside ${control}, so a rejected lazy chunk still escapes to the whole-block boundary and takes ${control} down with it`,
+ );
+ }
+ }
+});
+
+test("the whole-block boundary is still the catch-all above them", () => {
+ // The inner boundary narrows what is REPLACED, never what is CAUGHT. Anything
+ // that throws outside `Block` -- a hook, a sanitizer, an artifact card -- must
+ // still reach the outer boundary rather than the router.
+ assert.ok(
+ wrappersAroundBlockContent().includes("MarkdownBlockBoundary"),
+ "the outer boundary no longer wraps the block, so narrowing the inner one narrowed the coverage too",
+ );
+});
+
+test("the boundary does not retry the import it caught", () => {
+ const boundary = readFileSync(
+ new URL(
+ "../src/components/assistant-ui/markdown-block-boundary.tsx",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+
+ // React and the browser's module map both cache a rejected dynamic import
+ // (whatwg/html#6768), so a boundary that resets on new props rethrows on every
+ // frame of a streaming reply and issues no new request for its trouble.
+ assert.ok(
+ !boundary.includes("getDerivedStateFromProps"),
+ "the boundary resets itself from props, which on a streaming reply means throwing and catching on every chunk for an import that can never succeed again",
+ );
+});
+
+test("a carriage return only closes a fence as the closing line's last character", () => {
+ // A rewrite of the closing-fence scan once accepted a CR ANYWHERE in the tail,
+ // silently closing fences on 393,620 inputs of a differential corpus. Nothing
+ // failed, because nothing asserted the rule.
+ const trailing = markdownBlockFallback("```py\nx\n```\r ");
+ assert.equal(trailing.text, "x\n```\r ", "a CR before other tail text does not close the fence");
+ assert.equal(trailing.fenced, true);
+
+ const closing = markdownBlockFallback("```py\nx\n```\r");
+ assert.equal(closing.text, "x", "a CR as the closing line's last character does close it");
+});
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 67f5f8ef392..a3467e5a960 100644
--- a/studio/frontend/tests/markdown-block-remount-on-complete.test.ts
+++ b/studio/frontend/tests/markdown-block-remount-on-complete.test.ts
@@ -34,8 +34,16 @@ function findFunction(name: string): ts.FunctionDeclaration | null {
const ANIMATION_FREE_BLOCK_PROPS_RE = /^<Block\s+\{\.\.\.blockProps\}/;
const ANIMATION_FREE_HELPER_RE = /withoutStreamdownAnimationPlugin/;
const NULL_ANIMATION_PLUGIN_RE = /animatePlugin:\s*null/;
+// The block component is now rendered inside MarkdownBlockBoundary, because a
+// lazy chunk that fails to load anywhere in a reply used to unmount all of
+// Studio through the router's error boundary. `memo` is still the OUTERMOST
+// wrapper, which is the property this pins: on a memo hit React skips the
+// boundary and the block together, exactly as it did before. Pinned to the new
+// spelling rather than loosened, because a version with memo INSIDE the boundary
+// would render one component per block per token and no output test could tell
+// the two apart.
const MEMOISED_BLOCK_RE =
- /const\s+StreamdownBlock\s*=\s*memo\(StreamdownBlockContent\)/;
+ /const\s+StreamdownBlock\s*=\s*memo\(\s*\(props: BlockProps\) => \(\s*<MarkdownBlockBoundary content=\{props\.content\}>\s*<StreamdownBlockContent \{\.\.\.props\} \/>/;
test("the block props use the animation-free plugin list", () => {
const helper = findFunction("useAnimationFreeBlockProps");