@devries-cameron20 / t3code-1 / commits / d6419d92a0
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(web): links to repeated headings work while a reply streams (#38017)

Co-authored-by: Grok 4.7 <noreply@x.ai> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Wout Stiens committed Nov 17, 2026 at 10:11 UTC d6419d92a0e2b90202d147d77816ee35989f43ed
3 files changed +85 -10
apps/web/src/components/chat/markdownFragments.ts
+1 -1
@@ -68,7 +68,7 @@ type HeadingHastNode = {
68 children?: HeadingHastNode[];
69 };
70
71 -function githubHeadingSlug(text: string): string {
71 +export function githubHeadingSlug(text: string): string {
72 return text
73 .trim()
74 .toLowerCase()
apps/web/src/components/chat/markdownStreamBlocks.test.tsx
+44 -6
@@ -5,16 +5,25 @@ import {
5 } from "@t3tools/shared/markdownPipeline";
6 import { renderToStaticMarkup } from "react-dom/server";
7 import ReactMarkdown from "react-markdown";
8 +import remarkMath from "remark-math";
9 +import type { PluggableList } from "unified";
10 import { describe, expect, it } from "vite-plus/test";
11
12 import { splitMarkdownBlocks } from "./markdownStreamBlocks";
13 +import { rehypeHeadingIds } from "./markdownFragments";
14 +
15 +const MATH_PLUGINS: PluggableList = [[remarkMath, { singleDollarTextMath: true }]];
16
17 // Whitespace between top-level blocks collapses in the rendered message.
13 -const html = (source: string) =>
18 +const renderMarkdown = (source: string, math = false) =>
19 renderToStaticMarkup(
20 <ReactMarkdown
16 - remarkPlugins={[remarkAssistantInsights, ...CHAT_MARKDOWN_REMARK_PLUGINS]}
17 - rehypePlugins={CHAT_MARKDOWN_REHYPE_PLUGINS}
21 + remarkPlugins={[
22 + remarkAssistantInsights,
23 + ...(math ? MATH_PLUGINS : []),
24 + ...CHAT_MARKDOWN_REMARK_PLUGINS,
25 + ]}
26 + rehypePlugins={[...CHAT_MARKDOWN_REHYPE_PLUGINS, rehypeHeadingIds]}
27 >
28 {source}
29 </ReactMarkdown>,
@@ -22,9 +31,27 @@ const html = (source: string) =>
31 .replace(/>\s+</g, "><")
32 .trim();
33
34 +const html = (source: string) => renderMarkdown(source);
35 +
36 +const punctuatedHeadings = ["Step 1: Install", "Done:", "apps/web", "Fix (web)", "What's next?"];
37 +
38 describe("splitMarkdownBlocks", () => {
39 it.each([
40 "# Title\n\nFirst paragraph with `code` and **bold**.\n\nSecond [link](https://example.com).",
41 + "## Step 1: Install\n\n## Step 1: Install\n\n[second](#step-1-install-1)",
42 + "## /home/a/b.ts\n\n## home/a/b.ts",
43 + "## see https://x.com/a\n\n## see httpsxcoma",
44 + "## Done:\n\n## Done",
45 + "## `Setup`\n\n## Setup",
46 + "## a ` x ` b\n\n## a x b",
47 + "# Setup\n\n# $$ Setup $$\n\n[second](#setup-1)",
48 + "# Setup\n\n# Setup\n\n[Second setup](#setup-1)",
49 + "\ufeff# Setup\n\n# Setup\n\n[second](#setup-1)",
50 + "> Setup\n> ===\n\n> Setup\n> ===",
51 + "# onetwo\n\none\ntwo\n===",
52 + "# Setup\n\n# &#83;etup\n\n[second](#setup-1)",
53 + "# Setup\n\npara\n\n- a\n\n ```\n b\nx\n\nSetup\n===\n",
54 + "Setup\n===\n\n> ## **Setup**\n\n- # [Setup](https://example.com)\n\n```sh\n# Setup\n```",
55 "- one\n- two\n\n- loose three\n\n continued\n\nAfter the list.",
56 "1. first\n\n2. second\n\nText\n\n3) restarted",
57 "```ts\nconst a = 1;\n\n\nconst b = 2;\n```\n\nafter\n\n~~~\nx\n\n~~~~\n\ny\n~~~\n\nend",
@@ -39,18 +66,29 @@ describe("splitMarkdownBlocks", () => {
66 ])("renders each block as the whole text renders it, at every streamed prefix: %j", (text) => {
67 for (let end = 0; end <= text.length; end++) {
68 const source = text.slice(0, end);
42 - const blocks = splitMarkdownBlocks(source);
43 - expect(blocks?.join("")).toBe(source);
44 - expect(blocks!.map(html).join("")).toBe(html(source));
69 + const blocks = splitMarkdownBlocks(source) ?? [source];
70 + expect(blocks.join("")).toBe(source);
71 + expect(blocks.map(html).join("")).toBe(html(source));
72 + expect(blocks.map((block) => renderMarkdown(block, true)).join("")).toBe(
73 + renderMarkdown(source, true),
74 + );
75 }
76 });
77
78 + it.each(punctuatedHeadings)("keeps splitting headings with prose punctuation: %s", (heading) => {
79 + expect(splitMarkdownBlocks(`## ${heading}\n\nNext paragraph.`)).toEqual([
80 + `## ${heading}\n\n`,
81 + "Next paragraph.",
82 + ]);
83 + });
84 +
85 it("splits only between closed blocks", () => {
86 expect(splitMarkdownBlocks("a\n\n```\nb\n\nc\n```\n\n- d\n\n- e\n\nf")).toEqual([
87 "a\n\n",
88 "```\nb\n\nc\n```\n\n- d\n\n- e\n\n",
89 "f",
90 ]);
91 + expect(splitMarkdownBlocks("a\n\n---\n\nb")).toEqual(["a\n\n", "---\n\n", "b"]);
92 });
93
94 it.each([
apps/web/src/components/chat/markdownStreamBlocks.ts
+40 -3
@@ -1,3 +1,5 @@
1 +import { githubHeadingSlug } from "./markdownFragments";
2 +
3 // Definitions, footnotes, raw HTML, container directives and display math can tie blocks together.
4 const DOCUMENT_WIDE_SYNTAX = /^ {0,3}(?:\[[^\]\n]+\]:|<[A-Za-z!?/]|:::|\$\$)|\[\^/m;
5 // A backtick fence's info string cannot contain a backtick, so "```a``` is inline" is a code span.
@@ -7,13 +9,22 @@ const CONTINUATION_PATTERN = /^(?:[ \t]|(?:[-*+]|\d{1,9}[.)])(?:[ \t]|$))/;
9 // Claude insight fences render as one callout, so they stay in one block until the closing rule.
10 const INSIGHT_OPEN_PATTERN = /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u;
11 const INSIGHT_CLOSE_PATTERN = /^( {0,3})(`?)─{3,}\2[ \t]*$/u;
12 +// An ATX heading, also inside a list item or blockquote; group 1 is its text.
13 +const ATX_HEADING_PATTERN =
14 + /^(?:[ \t]*(?:>|[-*+](?=[ \t])|\d{1,9}[.)](?=[ \t])))*[ \t]*#{1,6}(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/;
15 +// Setext headings may span a paragraph and containers, so leave their parsing to the renderer.
16 +const SETEXT_UNDERLINE_PATTERN =
17 + /^(?:[ \t]*(?:>|[-*+](?=[ \t])|\d{1,9}[.)](?=[ \t])))*[ \t]*(?:=+|-+)[ \t]*$/;
18
19 /**
20 * Cuts Markdown at blank lines that close every open block, so each piece renders exactly as it
13 - * would inside the whole text. Returns null when the text uses syntax that spans blocks.
21 + * would inside the whole text. Returns null when the text uses syntax that spans blocks, such as
22 + * headings with the same slug, whose ids are numbered across the whole text.
23 */
24 export function splitMarkdownBlocks(text: string): string[] | null {
16 - if (text.includes("\r") || DOCUMENT_WIDE_SYNTAX.test(text)) return null;
25 + // remark-parse strips a leading BOM before recognizing the first heading.
26 + if (text.startsWith("\ufeff") || text.includes("\r") || DOCUMENT_WIDE_SYNTAX.test(text))
27 + return null;
28 const blocks: string[] = [];
29 let blockStart = 0;
30 let lineStart = 0;
@@ -21,11 +32,35 @@ export function splitMarkdownBlocks(text: string): string[] | null {
32 let fenceIndent = 0;
33 let afterBlankLine = false;
34 let insightIndent: string | null = null;
35 + const headingKeys = new Set<string>();
36 + const needsWholeHeading = (headingText: string | undefined) => {
37 + if (headingText === undefined) return false;
38 + // Inline syntax and path/directive colons need the renderer before their slug is known.
39 + if (/[`*_~[\]<&\\!$]|:(?!\s|$)/.test(headingText)) return true;
40 + const key = githubHeadingSlug(headingText);
41 + if (!key) return false;
42 + if (headingKeys.has(key)) return true;
43 + headingKeys.add(key);
44 + return false;
45 + };
46 + const headingNeedsWholeDocument = (line: string, mayUnderline = true) =>
47 + (mayUnderline && SETEXT_UNDERLINE_PATTERN.test(line)) ||
48 + needsWholeHeading(ATX_HEADING_PATTERN.exec(line)?.[1]);
49 + // Only a line right after paragraph text can underline it; elsewhere "---" is a thematic break.
50 + let afterContentLine = false;
51 for (const line of text.split("\n")) {
52 const opener = FENCE_PATTERN.exec(line)?.[1];
53 + const mayUnderline = afterContentLine;
54 + afterContentLine = false;
55 if (fence !== null) {
56 // A line left of an indented fence may end the list item holding it, which isn't tracked.
28 - if (/\S/.test(line.slice(0, fenceIndent))) break;
57 + if (/\S/.test(line.slice(0, fenceIndent))) {
58 + const rest = text.slice(lineStart).split("\n");
59 + for (const restLine of rest) {
60 + if (headingNeedsWholeDocument(restLine)) return null;
61 + }
62 + break;
63 + }
64 if (
65 opener &&
66 opener[0] === fence[0] &&
@@ -40,6 +75,8 @@ export function splitMarkdownBlocks(text: string): string[] | null {
75 } else if (line.trim() === "") {
76 afterBlankLine = true;
77 } else {
78 + if (headingNeedsWholeDocument(line, mayUnderline)) return null;
79 + afterContentLine = opener === undefined;
80 if (
81 afterBlankLine &&
82 insightIndent === null &&