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: only treat a real link definition as one (#10223)

Nilayd530284a0a2c
diff --git a/.github/workflows/studio-frontend-ci.yml b/.github/workflows/studio-frontend-ci.yml
index c8d1067c112..b187a1da738 100644
--- a/.github/workflows/studio-frontend-ci.yml
+++ b/.github/workflows/studio-frontend-ci.yml
@@ -31,6 +31,7 @@ on:
- 'tests/studio/playwright_tool_activity.py'
- 'tests/studio/playwright_stream_pacing.py'
- 'tests/studio/playwright_code_block_flicker.py'
+ - 'tests/studio/playwright_link_definition_probe.py'
- 'tests/studio/_code_block_flicker_analysis.py'
- 'tests/studio/test_code_block_flicker_contract.py'
# Shared lifecycle helpers, and the contract tests that keep verdicts from going unread.
@@ -419,6 +420,13 @@ jobs:
SMOKE_FLICKER_ENGINES: chromium
run: python3 tests/studio/playwright_code_block_flicker.py
+ # The `plain` case inside is the positive control: a fence with no brackets that
+ # MUST keep its controls. A run where it has none measured nothing, and the two
+ # rows that matter mean nothing either.
+ - name: Browser smoke for code-block controls under a link-definition lookalike
+ working-directory: ${{ github.workspace }}
+ run: python3 tests/studio/playwright_link_definition_probe.py
+
# Two small sizes and one repetition on Chromium: enough to prove the fixture still
# renders every kind of content it claims to and that the curve still rises, which is all
# a PR gate can afford. The measurement this harness exists for is the three-engine,
diff --git a/studio/frontend/smoke-link-definition-probe-main.tsx b/studio/frontend/smoke-link-definition-probe-main.tsx
new file mode 100644
index 00000000000..6227ad5b410
--- /dev/null
+++ b/studio/frontend/smoke-link-definition-probe-main.tsx
@@ -0,0 +1,167 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Harness page for tests/studio/playwright_link_definition_probe.py: three settled replies
+// through the real Thread, selected by ?case=.
+
+/* eslint-disable no-restricted-imports -- a measurement entry point, not app code. */
+import "@/features/chat/stores/sidebar-organization-store";
+/* eslint-enable no-restricted-imports */
+
+import { Thread } from "@/components/assistant-ui/thread";
+import { TooltipProvider } from "@/components/ui/tooltip";
+import {
+ AssistantRuntimeProvider,
+ type ChatModelAdapter,
+ ExportedMessageRepository,
+ type ThreadMessageLike,
+ useAui,
+ useLocalRuntime,
+} from "@assistant-ui/react";
+import {
+ RouterProvider,
+ createMemoryHistory,
+ createRootRoute,
+ createRouter,
+} from "@tanstack/react-router";
+import { type ReactElement, useEffect } from "react";
+import { createRoot } from "react-dom/client";
+import "./src/index.css";
+
+const realFetch = window.fetch.bind(window);
+window.fetch = (input, init) => {
+ const url =
+ typeof input === "string"
+ ? input
+ : ((input as Request).url ?? String(input));
+ if (url.includes("/api/")) {
+ return Promise.resolve(
+ new Response("{}", {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ }
+ return realFetch(input, init);
+};
+
+const CODE_REPLY = [
+ "Here is the shape you asked for.",
+ "",
+ "```ts",
+ "interface Grid {",
+ " [key: string]: number[][];",
+ "}",
+ "",
+ "const cell = grid[row][col];",
+ "```",
+ "",
+ "And the helper that reads it.",
+ "",
+ "```python",
+ "def read(grid, row, col):",
+ " return grid[row][col]",
+ "```",
+ "",
+ "That is all.",
+].join("\n");
+
+const LINK_REPLY = [
+ "See the [handbook][hb] and the [spec][sp] for details.",
+ "",
+ "```ts",
+ "const x = 1;",
+ "```",
+ "",
+ "[hb]: https://example.com/handbook",
+ "[sp]: https://example.com/spec",
+].join("\n");
+
+const PLAIN_REPLY = [
+ "A plain fence with no brackets.",
+ "",
+ "```python",
+ "print('hello')",
+ "```",
+].join("\n");
+
+const CASES: Record<string, string> = {
+ code: CODE_REPLY,
+ link: LINK_REPLY,
+ plain: PLAIN_REPLY,
+};
+
+function reply(text: string): ThreadMessageLike[] {
+ return [
+ { role: "user", content: [{ type: "text", text: "show me" }] },
+ { role: "assistant", content: [{ type: "text", text }] },
+ ];
+}
+
+const adapter: ChatModelAdapter = {
+ async *run() {
+ yield { content: [{ type: "text", text: "" }] };
+ },
+};
+
+function ProbeApi(): null {
+ const aui = useAui();
+
+ useEffect(() => {
+ const which = new URLSearchParams(window.location.search).get("case") ?? "code";
+ const text = CASES[which] ?? CODE_REPLY;
+ void aui
+ .thread()
+ .import(ExportedMessageRepository.fromArray(reply(text)));
+
+ const api = {
+ ready(): boolean {
+ return document.querySelectorAll("[data-role='assistant']").length > 0;
+ },
+ counts(): Record<string, number | string> {
+ return {
+ case: which,
+ assistantMessages: document.querySelectorAll("[data-role='assistant']").length,
+ codeBlocks: document.querySelectorAll('[data-streamdown="code-block"]').length,
+ preElements: document.querySelectorAll("pre").length,
+ copyButtons: document.querySelectorAll('button[title="Copy code"]').length,
+ downloadButtons: document.querySelectorAll('button[title="Download file"]').length,
+ renderedLinks: document.querySelectorAll("[data-role='assistant'] a[href]").length,
+ text: (document.querySelector("[data-role='assistant']")?.textContent ?? "").slice(0, 120),
+ };
+ },
+ };
+ (window as unknown as { __probe: typeof api }).__probe = api;
+ }, [aui]);
+
+ return null;
+}
+
+function Harness(): ReactElement {
+ const runtime = useLocalRuntime(adapter);
+ return (
+ <TooltipProvider>
+ <AssistantRuntimeProvider runtime={runtime}>
+ <ProbeApi />
+ <div
+ data-smoke="link-definition-probe"
+ style={{ display: "flex", flexDirection: "column", height: "100vh" }}
+ >
+ <Thread hideWelcome={true} />
+ </div>
+ </AssistantRuntimeProvider>
+ </TooltipProvider>
+ );
+}
+
+const rootRoute = createRootRoute({ component: Harness });
+const router = createRouter({
+ routeTree: rootRoute,
+ history: createMemoryHistory({ initialEntries: ["/"] }),
+});
+
+const root = document.getElementById("root");
+if (!root) {
+ throw new Error("missing #root");
+}
+createRoot(root).render(<RouterProvider router={router as unknown as never} />);
diff --git a/studio/frontend/smoke-link-definition-probe.html b/studio/frontend/smoke-link-definition-probe.html
new file mode 100644
index 00000000000..ceaebc06440
--- /dev/null
+++ b/studio/frontend/smoke-link-definition-probe.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <script src="/crypto-boot.js"></script>
+ <title>link definition probe smoke</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/smoke-link-definition-probe-main.tsx"></script>
+ </body>
+</html>
diff --git a/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts b/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts
index 9da1a4c33eb..9a290d6aaee 100644
--- a/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts
+++ b/studio/frontend/src/components/assistant-ui/streaming-render-schedule.ts
@@ -69,34 +69,98 @@ const INLINE_LATEX_CONTEXT = "\\(\n\n";
const FOOTNOTE_REFERENCE_RE = /\[\^[\w-]{1,200}\](?!:)/;
const FOOTNOTE_DEFINITION_RE = /\[\^[\w-]{1,200}\]:/;
const LINK_DEFINITION_RE = /\[(?:\\.|[^\]\n\\]){1,200}\]:/;
+// Inside a block marked did not lex as code, the container markers and their indentation
+// have already been accounted for, so the label may sit behind any mix of them.
+// A block quote marker may be followed by nothing, but a list marker needs whitespace after
+// it or no list opens -- `-[label]:` is ordinary prose, not a bullet holding a definition.
+const LINK_DEFINITION_LINE_RE =
+ /^[ \t]*(?:(?:>[ \t]*)|(?:(?:[-*+]|\d{1,9}[.)])[ \t]+))*\[(?:\\.|[^\]\n\\]){1,200}\]:/m;
+// The two block shapes whose body is literal code: an opening fence, and an indent that
+// reaches column four -- four spaces, or a tab, which advances to the same column.
+const CODE_BLOCK_RE = /^(?: {0,3}(?:`{3,}|~{3,})|(?: {4,}| {0,3}\t)[ \t]*[^ \t\r\n])/;
+// A backtick opener may not carry a backtick in its info string, or it is not a fence at all
+// and the line is ordinary prose -- which is where a reference can still be waiting. Tilde
+// openers have no such rule, so their info string is left alone.
+const BACKTICK_OPENER_RE = /^ {0,3}`{3,}([^\n]*)/;
+
+function isCodeBlock(block: string): boolean {
+ if (!CODE_BLOCK_RE.test(block)) {
+ return false;
+ }
+ const backtick = BACKTICK_OPENER_RE.exec(block);
+ return backtick === null || !backtick[1].includes("`");
+}
const LINK_REFERENCE_RE =
/!?\[(?:\\.|[^\]\n\\]){1,200}\]\[(?:\\.|[^\]\n\\]){0,200}\]/;
+// Still the first line of a single block, for `updateLinkDefinitionParity` below.
const FENCED_CODE_BLOCK_RE = /^ {0,3}(?:```|~~~)/;
const WORD_CHARACTER_RE = /[\p{L}\p{N}_]/u;
const HTML_TAG_START_RE = /[a-zA-Z/]/;
-function hasGlobalLinkReference(markdown: string): boolean {
- return LINK_REFERENCE_RE.test(markdown) && LINK_DEFINITION_RE.test(markdown);
+// One split per reply, shared by all three exported entry points. markdown-text.tsx asks for
+// the key and then hands `parseMarkdownIntoRenderableBlocks` to Streamdown, which calls it with
+// the same string, so a single slot is all the reuse this needs -- and it keeps the blocks path
+// paying for exactly the one split it already paid for before any of this existed.
+let splitMarkdown: string | null = null;
+let splitBlocks: readonly string[] = [];
+
+function blocksOf(markdown: string): readonly string[] {
+ if (splitMarkdown !== markdown) {
+ splitMarkdown = markdown;
+ splitBlocks = parseMarkdownIntoBlocks(markdown);
+ }
+ return splitBlocks;
+}
+
+// Which replies have to be lexed in one piece.
+//
+// marked keeps link reference definitions in one document-wide map and emits no token for a
+// label it has already seen, so a `[label][ref]` and its `[ref]: url` must reach the lexer
+// together or the reference survives as literal text. The question is therefore whether a real
+// definition exists outside code -- and the earlier answer, a hand-rolled scan for fences,
+// containers and raw HTML, kept disagreeing with marked at the seams: nested fences, the seven
+// HTML block shapes, list continuation indentation, lone-CR line endings.
+//
+// marked has already resolved every one of those by the time it hands back blocks, so the split
+// is the answer rather than something to re-derive. A fenced or indented block is code; anything
+// else is prose, and a definition line anywhere in the prose counts.
+//
+// Being wrong is not symmetric, which is why the residual imprecision sits where it does. Saying
+// `blocks` when the reply needed one document splits the pair apart and loses content. Saying
+// `document` when blocks would have done only costs that reply its per-code-block Copy and
+// Download controls -- which is what this path did for EVERY reply containing a `]:` substring
+// before. See tests/link-definition-oracle.test.ts, which pins the first case exhaustively.
+function documentProse(markdown: string): string | null {
+ if (!LINK_REFERENCE_RE.test(markdown) || !LINK_DEFINITION_RE.test(markdown)) {
+ return null;
+ }
+ const prose = blocksOf(markdown)
+ .filter((block) => !isCodeBlock(block))
+ .join("\n");
+ return LINK_DEFINITION_LINE_RE.test(prose) && LINK_REFERENCE_RE.test(prose)
+ ? prose
+ : null;
}
export function markdownRenderScope(markdown: string): "blocks" | "document" {
- return hasGlobalLinkReference(markdown) ? "document" : "blocks";
+ return documentProse(markdown) === null ? "blocks" : "document";
}
export function markdownRenderKey(markdown: string): string {
- if (markdownRenderScope(markdown) === "blocks") {
+ const prose = documentProse(markdown);
+ if (prose === null) {
return "blocks";
}
- return `document:${markdown
+ return `document:${prose
.split("\n")
- .filter((line) => LINK_DEFINITION_RE.test(line))
+ .filter((line) => LINK_DEFINITION_LINE_RE.test(line))
.join("\n")}`;
}
export function parseMarkdownIntoRenderableBlocks(markdown: string): string[] {
return markdownRenderScope(markdown) === "document"
? [markdown]
- : parseMarkdownIntoBlocks(markdown);
+ : [...blocksOf(markdown)];
}
// Where remend believes the emphasis scan sits with respect to math.
@@ -1329,7 +1393,6 @@ export class IncrementalMarkdownCache {
// `"para\r"`, nothing is ever committed, and the whole reply re-repairs and
// re-lexes on every frame. Normalise first so both sides speak LF.
const markdown = normalizeLineEndings(rawMarkdown);
- const globalLinkReference = markdownRenderScope(markdown) === "document";
// Tokens arrive faster than frames, so the coalescer hands the same text to
// several renders. Nothing about the result can differ, and repeating the
@@ -1353,10 +1416,15 @@ export class IncrementalMarkdownCache {
// globally scoped definitions must stay in the same rendered document as
// their uses, so neither construct can retain an independently parsed prefix.
+ // Computed here rather than at the top of the method on purpose: both early returns above
+ // -- the coalescer handing the same text to several renders, and a reply already in
+ // full-document mode -- answer without it, and the precise scope costs a lex of everything
+ // received so far. Reaching this point means the reply is still a retention candidate,
+ // which is the only case where the answer is used.
if (
- globalLinkReference ||
FOOTNOTE_REFERENCE_RE.test(repaired) ||
- FOOTNOTE_DEFINITION_RE.test(repaired)
+ FOOTNOTE_DEFINITION_RE.test(repaired) ||
+ markdownRenderScope(markdown) === "document"
) {
return this.renderFullDocument(markdown);
}
diff --git a/studio/frontend/tests/link-definition-oracle.test.ts b/studio/frontend/tests/link-definition-oracle.test.ts
new file mode 100644
index 00000000000..537c9ef3781
--- /dev/null
+++ b/studio/frontend/tests/link-definition-oracle.test.ts
@@ -0,0 +1,222 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// `markdownRenderScope` decides whether a reply is lexed as one document or per block, and it
+// answers with a cheap line scan rather than a second markdown parse -- the render already
+// pays one inside `parseMarkdownIntoBlocks`, and doubling that on every streaming chunk is the
+// cost this path is written to avoid.
+//
+// A scan is an approximation of the block grammar, so what is worth pinning is not that it
+// agrees everywhere, but that it never errs in the direction that loses content. The oracle
+// below is not a second opinion about markdown; it is the rendered outcome, built from the
+// two pieces production actually uses -- streamdown's `parseMarkdownIntoBlocks` for the split
+// and the remark pipeline for the render, the same shape as math-block-marker-pipeline.test.ts.
+// Deliberately no `marked` import: the frontend does not depend on marked directly, and a bare
+// specifier resolves to the copy hoisted for mermaid rather than the one streamdown splits
+// with, so an oracle built on it would be measuring a different lexer from the renderer.
+//
+// The two errors are not symmetric:
+// blocks when the reply needed one document -> the reference/definition pair is split apart
+// and the reference survives as literal `[label][ref]` text. Content is lost.
+// one document when blocks would have done -> that reply loses its per-block Copy code and
+// Download file controls. Nothing is lost from the content, and it is what main did for
+// EVERY reply containing a `]:` substring, which is what this path set out to narrow.
+// So this file guards the expensive half, exhaustively.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import remarkGfm from "remark-gfm";
+import remarkParse from "remark-parse";
+import remarkRehype from "remark-rehype";
+import { parseMarkdownIntoBlocks } from "streamdown";
+import { unified } from "unified";
+
+import { markdownRenderScope } from "../src/components/assistant-ui/streaming-render-schedule.ts";
+
+const pipeline = unified().use(remarkParse).use(remarkGfm).use(remarkRehype);
+
+function anchorCount(markdown: string): number {
+ const tree = pipeline.runSync(pipeline.parse(markdown)) as unknown;
+ let found = 0;
+ const walk = (node: unknown): void => {
+ const element = node as {
+ tagName?: string;
+ properties?: { href?: unknown };
+ children?: unknown[];
+ };
+ if (element.tagName === "a" && element.properties?.href !== undefined) {
+ found += 1;
+ }
+ for (const child of element.children ?? []) {
+ walk(child);
+ }
+ };
+ walk(tree);
+ return found;
+}
+
+// The whole point of the document path: how many references resolve when the reply is lexed
+// in one piece, versus when streamdown splits it first.
+const asOneDocument = (markdown: string): number => anchorCount(markdown);
+const asBlocks = (markdown: string): number =>
+ parseMarkdownIntoBlocks(markdown).reduce(
+ (total, block) => total + anchorCount(block),
+ 0,
+ );
+
+const DEFINITION_CONTEXTS = [
+ "[g]: /guide",
+ " [g]: /guide",
+ " [g]: /guide",
+ "> [g]: /guide",
+ ">> [g]: /guide",
+ "> > [g]: /guide",
+ "> > > > > > > [g]: /guide",
+ "- [g]: /guide",
+ "* [g]: /guide",
+ "+ [g]: /guide",
+ "1. [g]: /guide",
+ "1) [g]: /guide",
+ "- > [g]: /guide",
+ "- - [g]: /guide",
+ "> - [g]: /guide",
+ "- > - > [g]: /guide",
+ // Indented quote content, and a definition on a list item's continuation line: four columns
+ // absolute, but flush with the content column `10. ` opened.
+ "> [g]: /guide",
+ "> [g]: /guide",
+ "10. item\n\n [g]: /guide",
+ "1. item\n\n [g]: /guide",
+];
+
+const NEUTRAL_BLOCKS = [
+ "",
+ "Some ordinary prose in between.",
+ "```ts\ninterface G {\n [key: string]: number[][];\n}\n```",
+ "```css\na[href]:hover { color: red; }\n```",
+ "```md\n[g]: /inside-a-fence\n```",
+ "````\n```python\n````",
+ "```text\n~~~\n```",
+ "```ts\nconst x = 1;\n``` \n```",
+ "<pre>\n```\n</pre>",
+ "<div>\n```\n</div>",
+ "<center>\n```\n",
+ "<summary>\n```\n",
+ "<div>\n \n```\n",
+ "<!--\n```\n-->",
+ "<?php\n```\n?>",
+ "<![CDATA[\n```\n]]>",
+ "<!DOCTYPE html>",
+ " [g]: /indented-code-block",
+ "\t[g]: /tab-indented-code-block",
+ "-[g]: /no-space-is-not-a-list",
+ "1.[g]: /no-space-is-not-a-list",
+ "| a | b |\n| - | - |\n| 1 | 2 |",
+ // A bare custom tag opens a type-7 HTML block, and raw HTML nests inside a list item.
+ "<x>\n```\n",
+ "<my-widget>\n```\n",
+ "- <pre>\n ```\n </pre>",
+ "> ```ts\n> [g]: number\n> ```",
+ // A backtick opener carrying a backtick in its info string is not a fence at all.
+ "```bad` still prose",
+ "````bad` still prose",
+ // A tilde opener has no such rule, so this one really is a fence.
+ "~~~bad` really a fence\n~~~",
+];
+
+test("a reply whose reference only resolves in one piece is never split into blocks", () => {
+ const failures: string[] = [];
+ for (const definition of DEFINITION_CONTEXTS) {
+ for (const neutral of NEUTRAL_BLOCKS) {
+ for (const reply of [
+ `See [guide][g].\n\n${neutral}\n\n${definition}\n`,
+ `See [guide][g].\n\n${definition}\n\n${neutral}\n`,
+ ]) {
+ // Only replies that actually lose an anchor when split are in scope here.
+ if (asOneDocument(reply) <= asBlocks(reply)) {
+ continue;
+ }
+ if (markdownRenderScope(reply) !== "document") {
+ failures.push(JSON.stringify(reply));
+ }
+ }
+ }
+ }
+ assert.deepEqual(
+ failures,
+ [],
+ "these replies resolve their reference only when rendered in one piece, but the scan " +
+ `split them into blocks, so the reference renders as literal text:\n${failures.join("\n")}`,
+ );
+});
+
+test("line endings other than LF do not hide the definition", () => {
+ for (const reply of [
+ "~~~ts\rconst x = 1;\r~~~\r\rSee [guide][g].\r\r[g]: /guide\r",
+ "```ts\r\nconst x = 1;\r\n```\r\n\r\nSee [guide][g].\r\n\r\n[g]: /guide\r\n",
+ "See [guide][g].\r\r```ts\rconst x = 1;\r```\r\r[g]: /guide\r",
+ ]) {
+ if (asOneDocument(reply) <= asBlocks(reply)) {
+ continue;
+ }
+ assert.equal(markdownRenderScope(reply), "document", JSON.stringify(reply));
+ }
+});
+
+test("a backtick opener carrying a backtick is prose, not a fence", () => {
+ // CommonMark forbids a backtick in a backtick fence's info string, so the line never opens a
+ // fence and the block is ordinary prose -- which is where a reference can still be waiting.
+ for (const opener of ["```bad`", "````bad`", "```js`x`"]) {
+ const reply = `${opener} See [guide][g].\n\n[g]: /guide\n`;
+ assert.ok(
+ asOneDocument(reply) > asBlocks(reply),
+ `${opener} should lose its anchor when split`,
+ );
+ assert.equal(markdownRenderScope(reply), "document", opener);
+ }
+
+ // A tilde opener has no such rule: backticks in its info string are fine and it is a fence,
+ // so the definition inside it is code and the reply keeps block rendering.
+ const tilde = "~~~bad` See [guide][g].\n\n[g]: /guide\n";
+ assert.equal(asOneDocument(tilde), asBlocks(tilde));
+ assert.equal(markdownRenderScope(tilde), "blocks");
+});
+
+test("a definition lookalike that no parser registers keeps block rendering", () => {
+ // These cost nothing if we get them wrong -- the reply keeps its content either way -- but
+ // each one that reaches `document` is a reply that loses its Copy/Download controls for no
+ // reason, which is the residue this path exists to shrink.
+ for (const lookalike of [
+ "\t[two]: /tab-indented-code-block",
+ " [two]: /indented-code-block",
+ "-[two]: /no-space-is-not-a-list",
+ "1.[two]: /no-space-is-not-a-list",
+ // An indented code block whose first content character is one CommonMark counts as
+ // ordinary content but JavaScript's `\S` calls whitespace.
+ " first\n [two]: /still-code",
+ " \u00a0\n [two]: /still-code",
+ ]) {
+ const reply = `Compare [one][two].\n\n${lookalike}\n\n\`\`\`ts\nconst x = 1;\n\`\`\`\n`;
+ assert.equal(asOneDocument(reply), asBlocks(reply), lookalike);
+ assert.equal(markdownRenderScope(reply), "blocks", lookalike);
+ }
+});
+
+test("ordinary code is still rendered per block", () => {
+ // The regression this path exists for: nothing here is a definition, so each of these must
+ // keep its per-block Copy code / Download file controls.
+ for (const reply of [
+ "Shape.\n\n```ts\ninterface G {\n [key: string]: number[][];\n}\n\nconst c = grid[row][col];\n```\n",
+ "Compare [one][two].\n\n```css\na[href]:hover { color: red; }\n```\n",
+ "Compare [one][two].\n\n [two]: not-a-definition\n",
+ "How:\n\n```md\n[two]: https://example.com/two\n```\n\nText [one][two].\n",
+ ]) {
+ assert.equal(markdownRenderScope(reply), "blocks", reply);
+ assert.equal(
+ asOneDocument(reply) > asBlocks(reply),
+ false,
+ `this reply does lose an anchor when split, so it belongs in the guard above:\n${reply}`,
+ );
+ }
+});
diff --git a/studio/frontend/tests/streaming-render-schedule.test.ts b/studio/frontend/tests/streaming-render-schedule.test.ts
index 13509489624..41cb07cb63d 100644
--- a/studio/frontend/tests/streaming-render-schedule.test.ts
+++ b/studio/frontend/tests/streaming-render-schedule.test.ts
@@ -160,6 +160,182 @@ test("mid-string remend repairs use the sticky full-document fallback", () => {
}
});
+test("code that only looks like a link definition keeps block-scoped rendering", () => {
+ const reply = [
+ "Here is the shape:",
+ "",
+ "```ts",
+ "interface Grid {",
+ " [key: string]: number[][];",
+ "}",
+ "const cell = grid[row][col];",
+ "```",
+ "",
+ "That is all.",
+ ].join("\n");
+
+ assert.equal(markdownRenderScope(reply), "blocks");
+ assert.equal(markdownRenderKey(reply), "blocks");
+ assert.deepEqual(
+ parseMarkdownIntoRenderableBlocks(reply),
+ parseMarkdownIntoBlocks(reply),
+ );
+});
+
+test("a css selector in a fence is not a link definition", () => {
+ const reply = [
+ "Compare [one][two] below.",
+ "",
+ "```css",
+ "a[href]:hover { color: red; }",
+ "```",
+ ].join("\n");
+
+ assert.equal(markdownRenderScope(reply), "blocks");
+});
+
+test("a definition-looking line indented into a code block is not a definition", () => {
+ const reply = "Compare [one][two] below.\n\n [two]: not-a-definition\n";
+
+ assert.equal(markdownRenderScope(reply), "blocks");
+});
+
+test("the document render key ignores definitions inside fences", () => {
+ const real = "See [one][two].\n\n[two]: https://example.com/two\n";
+ const withFence = `${real}\n\`\`\`ts\ntype T = { [k: string]: number };\n\`\`\`\n`;
+
+ assert.equal(markdownRenderScope(withFence), "document");
+ assert.equal(markdownRenderKey(withFence), markdownRenderKey(real));
+});
+
+test("a four-backtick wrapper around a fence example does not swallow the definition", () => {
+ const reply = [
+ "To open a Python block, type this line:",
+ "",
+ "````",
+ "```python",
+ "````",
+ "",
+ "Then see [the guide][d] for the rest.",
+ "",
+ "[d]: https://example.com/guide",
+ ].join("\n");
+
+ assert.equal(markdownRenderScope(reply), "document");
+});
+
+test("a tilde line inside a backtick fence does not close it", () => {
+ const reply = [
+ "Fence markers:",
+ "",
+ "```text",
+ "~~~",
+ "```",
+ "",
+ "See [the guide][d].",
+ "",
+ "[d]: https://example.com/guide",
+ ].join("\n");
+
+ assert.equal(markdownRenderScope(reply), "document");
+});
+
+test("a marker carrying an info string does not close a fence", () => {
+ const reply = [
+ "See [one][two].",
+ "",
+ "```ts",
+ "type T = { [k: string]: number };",
+ "```ts",
+ "const x: T = {};",
+ "```",
+ "",
+ "[two]: https://example.com/two",
+ ].join("\n");
+
+ assert.equal(markdownRenderScope(reply), "document");
+ assert.equal(
+ markdownRenderKey(reply),
+ "document:[two]: https://example.com/two",
+ );
+});
+
+test("a definition inside a block quote or a list is still document-wide", () => {
+ for (const container of [
+ "> [g]: /guide",
+ "- [g]: /guide",
+ "1. [g]: /guide",
+ "> > [g]: /guide",
+ ]) {
+ assert.equal(
+ markdownRenderScope(`See [guide][g].\n\n${container}\n`),
+ "document",
+ container,
+ );
+ }
+});
+
+test("only spaces and tabs may follow a closing fence marker", () => {
+ // U+00A0 after the marker is code content to marked, so the fence is still open and
+ // the marker on the next line is the one that closes it.
+ const reply =
+ "See [guide][g].\n\n```ts\nconst x = 1;\n```\u00a0\n```\n\n[g]: /guide\n";
+
+ assert.equal(markdownRenderScope(reply), "document");
+});
+
+test("a CRLF reply closes its fences", () => {
+ const reply =
+ "See [guide][g].\r\n\r\n```ts\r\nconst x = 1;\r\n```\r\n\r\n[g]: /guide\r\n";
+
+ assert.equal(markdownRenderScope(reply), "document");
+});
+
+test("a fence marker inside a raw HTML block is literal content", () => {
+ for (const html of ["<pre>\n```\n</pre>", "<div>\n```\n</div>"]) {
+ assert.equal(
+ markdownRenderScope(`See [guide][g].\n\n${html}\n\n[g]: /guide\n`),
+ "document",
+ html,
+ );
+ }
+});
+
+test("the block split is shared per reply without leaking between replies", () => {
+ // `blocksOf` keeps one slot at module scope. Two messages streaming at once interleave
+ // their calls through it, so the only thing keeping that honest is that the slot is keyed
+ // on the exact reply text: a miss recomputes, it never answers for the wrong reply.
+ const plain = "Message A.\n\n```ts\nconst a = grid[r][c];\n```\n";
+ const withReference = "Message B, see [guide][g].\n\n```py\nprint('b')\n```\n\n[g]: /guide\n";
+ const other = "Message C.\n\n```js\nconst c = 1;\n```\n";
+
+ for (const reply of [plain, withReference, other, withReference, plain]) {
+ markdownRenderKey(reply);
+ }
+
+ assert.equal(markdownRenderScope(plain), "blocks");
+ assert.equal(markdownRenderScope(other), "blocks");
+ assert.equal(markdownRenderScope(withReference), "document");
+ assert.deepEqual(
+ parseMarkdownIntoRenderableBlocks(plain),
+ parseMarkdownIntoBlocks(plain),
+ );
+ assert.deepEqual(parseMarkdownIntoRenderableBlocks(withReference), [
+ withReference,
+ ]);
+});
+
+test("the shared split is not handed out for the caller to mutate", () => {
+ const reply = "Message A.\n\n```ts\nconst a = 1;\n```\n";
+ const first = parseMarkdownIntoRenderableBlocks(reply);
+ first.push("mutated");
+
+ assert.deepEqual(
+ parseMarkdownIntoRenderableBlocks(reply),
+ parseMarkdownIntoBlocks(reply),
+ );
+});
+
test("link references and definitions stay in one rendered document", () => {
const usage = `Before [reference][math-ref].\n\n${paragraphs(20)}`;
const cache = new IncrementalMarkdownCache();
diff --git a/tests/studio/playwright_link_definition_probe.py b/tests/studio/playwright_link_definition_probe.py
new file mode 100644
index 00000000000..f5ed70f4461
--- /dev/null
+++ b/tests/studio/playwright_link_definition_probe.py
@@ -0,0 +1,153 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Does code that merely looks like a link definition cost a reply its code-block controls?
+
+On the document render path the whole reply lexes into one block, so no block is a fence:
+FenceBlock never mounts and the Copy code / Download file buttons go with it.
+
+ code two fences holding `[key: string]:` and `grid[row][col]`, so two of each button
+ link a genuine `[label][ref]` + `[ref]: url` reply, which must stay on the document path
+ plain a fence and no brackets. Positive control: no buttons here means nothing was measured
+
+Run:
+ python tests/studio/playwright_link_definition_probe.py
+"""
+
+import json
+import os
+import sys
+from pathlib import Path
+
+from playwright.sync_api import sync_playwright
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from _playwright_robust import ( # noqa: E402
+ chromium_launch_args,
+ start_vite,
+ stop_process,
+ wait_for_smoke_page,
+)
+
+PORT = int(os.environ.get("SMOKE_PORT", "5231"))
+_EXTERNAL = os.environ.get("SMOKE_BASE_URL", "").strip().rstrip("/")
+BASE = _EXTERNAL or f"http://127.0.0.1:{PORT}"
+OWNS_SERVER = not _EXTERNAL
+PAGE = "smoke-link-definition-probe.html"
+LABEL = os.environ.get("SMOKE_LABEL", "tree")
+
+CASES = ("code", "link", "plain")
+
+# Two fences in the code reply, one in each of the others.
+EXPECTED_FENCES = {"code": 2, "link": 1, "plain": 1}
+
+
+def info(message: str) -> None:
+ print(message, flush = True)
+
+
+def warm_up(page) -> None:
+ """Load the positive control first and wait for its controls to actually mount.
+
+ Shiki and the code action bar arrive as their own lazily loaded chunk. Until it has landed
+ once, every case reads zero buttons, and a quiet-interval wait cannot tell "not loaded yet"
+ apart from "settled at zero" -- three quiet samples can all land inside the load. The
+ `plain` case must end with controls on every branch, so waiting for them here is an
+ unambiguous readiness signal, and it leaves the chunk cached for the cases that follow.
+ """
+ page.goto(f"{BASE}/{PAGE}?case=plain", wait_until = "domcontentloaded")
+ page.wait_for_function("() => window.__probe && window.__probe.ready()", timeout = 60_000)
+ page.wait_for_function(
+ "() => window.__probe.counts().copyButtons >= 1",
+ timeout = 120_000,
+ polling = 250,
+ )
+
+
+def run_case(page, case: str) -> dict:
+ page.goto(f"{BASE}/{PAGE}?case={case}", wait_until = "domcontentloaded")
+ page.wait_for_function("() => window.__probe && window.__probe.ready()", timeout = 60_000)
+
+ # The fences themselves mount independently of the action bar, and their count is known per
+ # case, so this is a real completion signal rather than an interval. The button count is
+ # deliberately NOT waited on: `code` is legitimately zero before the fix, and waiting for a
+ # number that never arrives would fail the branch that is supposed to reproduce the defect.
+ expected = EXPECTED_FENCES[case]
+ page.wait_for_function(
+ f"() => window.__probe.counts().codeBlocks === {expected}",
+ timeout = 60_000,
+ polling = 250,
+ )
+ # Then let the action bar settle, which is quick now the chunk is warm.
+ page.wait_for_function(
+ """() => {
+ const now = JSON.stringify(window.__probe.counts());
+ const seen = window.__settled;
+ window.__settled = now === seen?.value
+ ? {value: now, hits: seen.hits + 1}
+ : {value: now, hits: 0};
+ return window.__settled.hits >= 3;
+ }""",
+ timeout = 60_000,
+ polling = 250,
+ )
+ return page.evaluate("() => window.__probe.counts()")
+
+
+def main() -> int:
+ proc = None
+ if OWNS_SERVER:
+ info(f"starting vite dev server on port {PORT}")
+ proc = start_vite(PORT)
+ wait_for_smoke_page(
+ f"{BASE}/{PAGE}", "smoke-link-definition-probe-main.tsx", proc = proc, info = info
+ )
+ results = {}
+ try:
+ with sync_playwright() as pw:
+ browser = pw.chromium.launch(args = chromium_launch_args())
+ page = browser.new_page(viewport = {"width": 1280, "height": 900})
+ warm_up(page)
+ for case in CASES:
+ results[case] = run_case(page, case)
+ info(f"{case}: {json.dumps(results[case])}")
+ browser.close()
+ finally:
+ if proc is not None:
+ stop_process(proc)
+ info("vite stopped")
+
+ print(json.dumps({"label": LABEL, "results": results}, indent = 2))
+
+ failures = []
+ plain = results["plain"]
+ if plain["copyButtons"] < 1 or plain["downloadButtons"] < 1:
+ failures.append(
+ "the `plain` control has no code-block controls, so the fixture measured nothing "
+ "and no other row means anything"
+ )
+ code = results["code"]
+ if code["copyButtons"] != EXPECTED_FENCES["code"]:
+ failures.append(
+ f"`code` mounted {code['copyButtons']} Copy code buttons, expected "
+ f"{EXPECTED_FENCES['code']}: ordinary code took the document render path"
+ )
+ if code["downloadButtons"] != EXPECTED_FENCES["code"]:
+ failures.append(
+ f"`code` mounted {code['downloadButtons']} Download file buttons, expected "
+ f"{EXPECTED_FENCES['code']}"
+ )
+ link = results["link"]
+ if link["renderedLinks"] < 2:
+ failures.append(
+ f"`link` resolved {link['renderedLinks']} anchors, expected 2: a real reference "
+ "link stopped resolving"
+ )
+
+ for line in failures:
+ info("FAIL: " + line)
+ return 1 if failures else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())