fix(webui): wrap long inline code in plain paragraphs (#6670)

* fix(webui): wrap long inline code in plain paragraphs

Keep long single-line inline code inside top-level paragraphs flowing with surrounding text while preserving consecutive spaces and tabs.

Apply the same whitespace preservation to short inline code in those paragraphs. Lists, quotes, headings, tables, and multiline code blocks retain their existing behavior.

Refs #6662

* test(webui): load code-wrapping renderer lazily

Keep the shared fixture from eagerly loading MarkdownTextRenderer, so history-boundary tests can defer it without blocking page navigation.

Refs #6662
This commit is contained in:
chenz authored and GitHub committed 2026-11-15 19:03:42 +08:00
1 parent 12a86eaa86
commit 2c669935a5
5 files changed
+306 -3

No files matched your search

+37 -1
View File
@@ -1,7 +1,27 @@
import { useState } from "react";
import { lazy, Suspense, useState } from "react";
import { MessageBubble } from "@/components/MessageBubble";
// Keep this lazy: history-boundary tests hold the renderer request while the fixture loads.
const MarkdownTextRenderer = lazy(() => import("@/components/MarkdownTextRenderer"));
const outsideCode = `begin \t${"word ".repeat(25)}end`;
const inlineSource = [
`Before \`${"word ".repeat(23)}wordx\` after.`,
`Before \`${"word ".repeat(24)}x\` after.`,
`Spaces \`begin \t${"word ".repeat(30)}end\` after.`,
`Token \`${"x".repeat(180)}\` after.`,
`CJK \`${"中文".repeat(70)}\` after.`,
"Short `one \ttwo` after.",
`Link [\`${"x".repeat(180)}\`](https://example.com) after.`,
`| Identifier | One | Two | Three | Four | Five |\n| --- | --- | --- | --- | --- | --- |\n| ${"identifier".repeat(4)} | \`default\` | \`release\` | \`private\` | \`enabled\` | \`compact\` |`,
`\`\`\`text\n${"f".repeat(180)}\nsecond line\n\`\`\``,
` ${"i".repeat(180)}\n indented line two`,
`| Label | Code |\n| --- | --- |\n| Long | \`${outsideCode}\` |`,
`## Heading \`${outsideCode}\``,
`- List \`${outsideCode}\``,
].join("\n\n");
const source = [
"# Environment",
"",
@@ -13,6 +33,8 @@ const source = [
export function CodeWrappingFixture() {
const [code, setCode] = useState(source);
const [streaming, setStreaming] = useState(true);
const [inlineMessage, setInlineMessage] = useState("Before `");
const [inlineStreaming, setInlineStreaming] = useState(true);
return <main className="mx-auto max-w-3xl space-y-4 p-4">
<textarea aria-label="Code source" className="h-24 w-full font-mono text-code" value={code}
onChange={event => setCode(event.target.value)} />
@@ -21,5 +43,19 @@ export function CodeWrappingFixture() {
id: "wrapped-code", role: "assistant", createdAt: 1, isStreaming: streaming,
content: `\`\`\`markdown\n${code}\n\`\`\``,
}} />
<section data-testid="inline-code-wrapping">
<Suspense fallback={null}>
<MarkdownTextRenderer streaming={streaming} highlightCode={false}>{inlineSource}</MarkdownTextRenderer>
</Suspense>
</section>
<textarea aria-label="Inline message source" value={inlineMessage}
onChange={event => setInlineMessage(event.target.value)} />
<button onClick={() => setInlineStreaming(false)}>Complete inline message</button>
<section data-testid="inline-message-wrapping">
<MessageBubble message={{
id: "inline-code", role: "assistant", createdAt: 1, isStreaming: inlineStreaming,
content: inlineMessage,
}} />
</section>
</main>;
}
+218
View File
@@ -42,3 +42,221 @@ test("numbered Markdown code keeps mixed text flowing after stream completion",
await block.getByRole("button", { name: "Copy code", exact: true }).click();
await expect.poll(async () => (await page.evaluate(() => navigator.clipboard.readText())).replaceAll("\r\n", "\n")).toBe(source);
});
test("single-line inline code wraps in streaming and completed messages without losing whitespace", async ({ page }) => {
await page.goto("/browser/fixture.html?case=code-wrapping");
const inline = page.getByTestId("inline-code-wrapping");
const expected = [
{ prefix: "Before", text: `${"word ".repeat(23)}wordx` },
{ prefix: "Before", text: `${"word ".repeat(24)}x` },
{ prefix: "Spaces", text: `begin \t${"word ".repeat(30)}end` },
{ prefix: "Token", text: "x".repeat(180) },
{ prefix: "CJK", text: "中文".repeat(70) },
{ prefix: "Short", text: "one \ttwo" },
];
for (const state of ["streaming", "complete"]) {
if (state === "complete") await page.getByRole("button", { name: "Complete message" }).click();
for (const width of [390, 900]) {
await page.setViewportSize({ width, height: 900 });
for (const [index, { prefix, text }] of expected.entries()) {
const code = inline.locator("p").nth(index).locator("code");
await expect(code).toHaveText(text);
expect(await code.textContent()).toBe(text);
const metrics = await code.evaluate(element => {
const style = getComputedStyle(element);
const paragraph = element.parentElement!;
return {
display: style.display,
whiteSpace: style.whiteSpace,
lines: element.getClientRects().length,
contained: paragraph.scrollWidth <= paragraph.clientWidth + 1,
surrounding: paragraph.textContent,
};
});
expect(metrics.display).toBe("inline");
expect(metrics.whiteSpace).toBe("break-spaces");
expect(metrics.contained).toBe(true);
expect(metrics.surrounding).toBe(`${prefix} ${text} after.`);
if (width === 390 && index < 5) expect(metrics.lines).toBeGreaterThan(1);
}
const linkedCode = inline.locator('p a[href="https://example.com"] code');
expect(await linkedCode.textContent()).toBe("x".repeat(180));
const linkLayout = await linkedCode.evaluate(node => ({
display: getComputedStyle(node).display,
lines: node.getClientRects().length,
contained: node.closest("p")!.scrollWidth <= node.closest("p")!.clientWidth + 1,
}));
expect(linkLayout.display).toBe("inline");
expect(linkLayout.contained).toBe(true);
if (width === 390) expect(linkLayout.lines).toBeGreaterThan(1);
const selected = await inline.locator("p").nth(2).locator("code").evaluate(element => {
const range = document.createRange();
range.selectNodeContents(element);
const selection = window.getSelection()!;
selection.removeAllRanges();
selection.addRange(range);
return selection.toString();
});
expect(selected).toBe(expected[2].text);
const shortSelected = await inline.locator("p").nth(5).locator("code").evaluate(element => {
const range = document.createRange();
range.selectNodeContents(element);
const selection = window.getSelection()!;
selection.removeAllRanges();
selection.addRange(range);
return selection.toString();
});
expect(shortSelected).toBe(expected[5].text);
const table = inline.getByTestId("markdown-data-table").first();
await expect(table.locator("code")).toHaveText(["default", "release", "private", "enabled", "compact"]);
expect(await table.locator("code").evaluateAll(nodes => nodes.map(node => node.getClientRects().length))).toEqual([1, 1, 1, 1, 1]);
if (width === 390) {
expect(await table.evaluate(node => node.scrollWidth > node.clientWidth)).toBe(true);
await table.evaluate(node => { node.scrollLeft = node.scrollWidth; });
expect(await table.evaluate(node => {
const bounds = node.getBoundingClientRect();
const lastCell = node.querySelector("tbody td:last-child")!.getBoundingClientRect();
return lastCell.right <= bounds.right + 1 && lastCell.left >= bounds.left - 1;
})).toBe(true);
}
const outsideCode = `begin \t${"word ".repeat(25)}end`;
for (const code of [
inline.getByTestId("markdown-data-table").last().locator("code"),
inline.locator("h2 code"),
inline.locator("li code"),
]) {
expect(await code.textContent()).toBe(outsideCode);
const unchanged = await code.evaluate(node => {
const range = document.createRange();
range.selectNodeContents(node);
const selection = window.getSelection()!;
selection.removeAllRanges();
selection.addRange(range);
return { display: getComputedStyle(node).display, whiteSpace: getComputedStyle(node).whiteSpace, selected: selection.toString() };
});
expect(unchanged).toEqual({ display: "block", whiteSpace: "pre", selected: outsideCode });
}
const blocks = inline.locator("[data-language='text'] pre");
await expect(blocks).toHaveCount(2);
for (const [index, text] of [`${"f".repeat(180)}\nsecond line`, `${"i".repeat(180)}\nindented line two`].entries()) {
const block = blocks.nth(index);
const content = await block.locator("code").evaluate(node => {
const lines = [...node.querySelectorAll(":scope > span")];
return lines.map(line => line.children[1]?.textContent ?? "").join("\n");
});
expect(content).toBe(text);
expect(await block.evaluate(node => node.scrollWidth > node.clientWidth)).toBe(true);
}
}
}
});
test("streaming message keeps growing inline code in its paragraph through completion", async ({ page }) => {
await page.goto("/browser/fixture.html?case=code-wrapping");
const source = page.getByRole("textbox", { name: "Inline message source" });
const message = page.getByTestId("inline-message-wrapping");
for (const width of [390, 900]) {
await page.setViewportSize({ width, height: 900 });
for (const length of [1, 119, 120, 121, 122, 260]) {
const text = "x".repeat(length);
await source.fill(`Before \`${text}`);
const code = message.locator("p code");
await expect(code).toHaveText(text);
const layout = await code.evaluate(node => ({
display: getComputedStyle(node).display,
lines: node.getClientRects().length,
contained: node.parentElement!.scrollWidth <= node.parentElement!.clientWidth + 1,
}));
expect(layout.display).toBe("inline");
expect(layout.contained).toBe(true);
if (width === 390 && length === 260) expect(layout.lines).toBeGreaterThan(1);
}
}
const text = `begin \t${"word ".repeat(30)}end`;
await source.fill(`Before \`${text}\` after.`);
await page.getByRole("button", { name: "Complete inline message" }).click();
await expect(message.locator("[data-assistant-selectable]")).toHaveAttribute("data-assistant-selectable", "true");
for (const width of [390, 900]) {
await page.setViewportSize({ width, height: 900 });
const code = message.locator("p code");
await expect(code).toHaveText(text);
expect(await code.textContent()).toBe(text);
const result = await code.evaluate(node => {
const range = document.createRange();
range.selectNodeContents(node);
const selection = window.getSelection()!;
selection.removeAllRanges();
selection.addRange(range);
return {
display: getComputedStyle(node).display,
contained: node.parentElement!.scrollWidth <= node.parentElement!.clientWidth + 1,
selected: selection.toString(),
paragraph: node.parentElement!.textContent,
};
});
expect(result).toEqual({ display: "inline", contained: true, selected: text, paragraph: `Before ${text} after.` });
}
});
test("message lists and quotes retain their existing whitespace and scrolling", async ({ page }) => {
await page.goto("/browser/fixture.html?case=code-wrapping");
const source = page.getByRole("textbox", { name: "Inline message source" });
const message = page.getByTestId("inline-message-wrapping");
const text = `begin \t${"word ".repeat(25)}end`;
const cases = [
{ markdown: `- List \`${text}\` after`, target: "li", parent: "LI" },
{ markdown: `- List \`${text}\` after\n\n- Second`, target: "li", parent: "P" },
{ markdown: `> List \`${text}\` after`, target: "blockquote", parent: "P" },
{ markdown: `- List \`one \ttwo\` after\n\n- Second`, target: "li", parent: "P", short: true },
{ markdown: "> List `one \ttwo` after", target: "blockquote", parent: "P", short: true },
];
for (const width of [390, 900]) {
await page.setViewportSize({ width, height: 900 });
for (const item of cases) {
await source.fill(item.markdown);
const target = message.locator(item.target).first();
const code = target.locator("code");
const codeText = item.short ? "one \ttwo" : text;
await expect(code).toHaveText(codeText);
const result = await code.evaluate(node => {
const target = node.closest("li, blockquote")!;
const range = document.createRange();
range.selectNodeContents(target);
const selection = window.getSelection()!;
selection.removeAllRanges();
selection.addRange(range);
const style = getComputedStyle(node);
return {
text: node.textContent, parent: node.parentElement!.tagName,
display: style.display, whiteSpace: style.whiteSpace, overflowX: style.overflowX,
lines: node.getClientRects().length, scrollable: node.scrollWidth > node.clientWidth,
selected: selection.toString(),
};
});
expect(result).toEqual(item.short ? {
text: codeText, parent: item.parent, display: "inline", whiteSpace: "normal", overflowX: "visible",
lines: 1, scrollable: false, selected: "List one two after",
} : {
text: codeText, parent: item.parent, display: "block", whiteSpace: "pre", overflowX: "auto",
lines: 1, scrollable: true, selected: `List\n${text}\nafter`,
});
}
}
await source.fill(`> List \`${text}\` after`);
await page.getByRole("button", { name: "Complete inline message" }).click();
await expect(message.locator("[data-assistant-selectable]")).toHaveAttribute("data-assistant-selectable", "true");
const quote = message.locator("blockquote code");
await expect(quote).toHaveText(text);
expect(await quote.evaluate(node => ({
display: getComputedStyle(node).display,
whiteSpace: getComputedStyle(node).whiteSpace,
overflowX: getComputedStyle(node).overflowX,
}))).toEqual({ display: "block", whiteSpace: "pre", overflowX: "auto" });
});
@@ -559,13 +559,14 @@ export default function MarkdownTextRenderer({
/>
);
}
const widePlainBlock = raw.includes("\n") || raw.length > 120;
if (widePlainBlock) {
const multiline = raw.includes("\n");
if (multiline || raw.length > 120) {
return (
<code
className={cn(
"block min-w-0 max-w-full overflow-x-auto whitespace-pre bg-transparent p-0 font-mono text-code",
"text-inherit",
!multiline && "markdown-wide-inline-code",
cls,
)}
{...props}
+10
View File
@@ -941,6 +941,16 @@
word-wrap: break-word;
}
.markdown-content > p code.markdown-inline-code,
.markdown-content > p code.markdown-wide-inline-code {
white-space: break-spaces;
}
.markdown-content > p code.markdown-wide-inline-code {
display: inline;
overflow: visible;
}
.markdown-content pre,
.not-prose pre {
max-width: 100%;
@@ -258,6 +258,44 @@ describe("MarkdownTextRenderer", () => {
expect(screen.getByText("src/**/*.json").tagName).toBe("CODE");
});
it.each([120, 121, 260])("keeps %i-character inline code in the surrounding paragraph", (length) => {
const text = "x".repeat(length);
const { container } = render(<MarkdownTextRenderer>{`Before \`${text}\` after.`}</MarkdownTextRenderer>);
const code = container.querySelector("code");
expect(code).toHaveClass(length > 120 ? "markdown-wide-inline-code" : "markdown-inline-code");
expect(code?.textContent).toBe(text);
expect(code?.parentElement?.tagName).toBe("P");
expect(code?.parentElement?.textContent).toBe(`Before ${text} after.`);
});
it("preserves spaces and tabs in parsed inline code", () => {
const text = `begin \t${"word ".repeat(30)}end`;
const { container } = render(<MarkdownTextRenderer>{`Before \`${text}\` after.`}</MarkdownTextRenderer>);
expect(container.querySelector("code")?.textContent).toBe(text);
});
it("keeps long inline code within a Markdown document preview", () => {
const text = "x".repeat(160);
const { container } = render(<MarkdownTextRenderer documentPath="/workspace/notes.md">{`Before \`${text}\` after.`}</MarkdownTextRenderer>);
expect(container.querySelector("code")).toHaveClass("markdown-wide-inline-code");
expect(container.querySelector("code")?.textContent).toBe(text);
});
it("keeps a long inferred file reference previewable", () => {
const path = `${"segment/".repeat(20)}report.md`;
const onOpenFilePreview = vi.fn();
render(<MarkdownTextRenderer onOpenFilePreview={onOpenFilePreview}>{`Open \`${path}\`.`}</MarkdownTextRenderer>);
const reference = screen.getByTestId("inline-file-path");
expect(reference).toHaveTextContent("report.md");
expect(reference).toHaveAttribute("aria-label", path);
fireEvent.click(reference);
expect(onOpenFilePreview).toHaveBeenCalledWith(path);
});
it.each([
["complete", "\n```"],
["streaming", ""],