fix(webui): preserve inferred file reference text (#6672)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-15 20:30:07 +08:00
1 parent 96eb1ace6f
commit 4ebd75623f
7 files changed
+138 -14

No files matched your search

+3
View File
@@ -27,6 +27,7 @@ import { DiagramFixture } from "./diagram-fixture";
import { TypographyFixture } from "./typography-fixture";
import { CodeWrappingFixture } from "./code-wrapping-fixture";
import { InlineReferencesFixture } from "./inline-references-fixture";
import { InlineFileReferenceFixture } from "./inline-file-reference-fixture";
import { HistoryBoundaryFixture } from "./history-boundary-fixture";
import { installHistoryBoundaryPreviewApi } from "./history-boundary-preview";
import { ChatFailureFixture } from "./chat-failure-fixture";
@@ -297,6 +298,8 @@ createRoot(document.getElementById("root")!).render(<TooltipProvider>
? <ClientProvider client={railClient} token="fixture"><TypographyFixture /></ClientProvider>
: parameters.get("case") === "inline-references"
? <ClientProvider client={railClient} token="fixture"><InlineReferencesFixture /></ClientProvider>
: parameters.get("case") === "inline-file-reference"
? <InlineFileReferenceFixture />
: parameters.get("case") === "idle-compaction"
? <IdleCompactionFixture />
: parameters.get("case") === "history-hydration"
@@ -0,0 +1,44 @@
import { useState } from "react";
import { FileActionsProvider } from "@/components/FileActions";
import { FilePreviewAvailabilityProvider } from "@/components/FilePreviewAvailabilityContext";
import { MessageBubble } from "@/components/MessageBubble";
import { ThemeProvider, useTheme } from "@/hooks/useTheme";
const references = [
"notes/ready.md",
`notes/${"long directory/".repeat(16)}report.md`,
String.raw`C:\Users\reader\My Docs\report.md`,
"pytest tests/test_agent.py",
"cat \t~/My Docs/report.md",
"这是一段说明文字,最后引用 /tmp/sample.txt",
"notes/chart.png",
`notes/${"segment".repeat(30)}.md`,
];
const source = references.map(text => `Before \`${text}\` after.`).join("\n\n")
+ "\n\n[Short report](notes/ready.md)";
const resolve = async (path: string) => path.startsWith("notes/");
export function InlineFileReferenceFixture() {
const { theme } = useTheme();
const [text, setText] = useState(source);
const [streaming, setStreaming] = useState(true);
const [opened, setOpened] = useState("");
return <ThemeProvider theme={theme}><FileActionsProvider value={{
resolveMetadata: async (path) => ({ path, relative_path: path }),
loadPreview: async (path) => ({
path, display_path: path, project_path: path, size: 68, kind: "image", mime_type: "image/png",
data_url: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/l9sAAAAASUVORK5CYII=",
}),
}}><FilePreviewAvailabilityProvider resolve={resolve}>
<main className="mx-auto space-y-4 p-4" style={{ maxWidth: 680 }}>
<textarea aria-label="Markdown source" className="h-24 w-full font-mono" value={text} onChange={event => setText(event.target.value)} />
<button onClick={() => setStreaming(false)}>Complete message</button>
<section aria-label="File references">
<MessageBubble message={{ id: "file-references", role: "assistant", createdAt: 1, content: text, isStreaming: streaming }}
onOpenFilePreview={setOpened} />
</section>
<output aria-label="Opened file">{opened}</output>
</main>
</FilePreviewAvailabilityProvider></FileActionsProvider></ThemeProvider>;
}
@@ -0,0 +1,59 @@
import { expect, test } from "@playwright/test";
test("inferred files wrap without losing copy text or preview actions", async ({ page, context }) => {
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
await page.addInitScript(() => localStorage.setItem("nanobot.locale", "en"));
await page.goto("/browser/fixture.html?case=inline-file-reference");
const files = page.getByRole("region", { name: "File references" }).getByTestId("inline-file-path");
await expect(files).toHaveCount(9);
for (const state of ["streaming", "complete"]) {
if (state === "complete") await page.getByRole("button", { name: "Complete message" }).click();
for (const width of [390, 1024]) {
await page.setViewportSize({ width, height: 1000 });
// Spaced and unbroken long paths exercise the two wrapping cases.
for (const index of [1, 7]) {
const metrics = await files.nth(index).locator("code").evaluate(node => {
const bounds = node.closest("p")!.getBoundingClientRect();
return {
lines: node.getClientRects().length,
contained: [...node.getClientRects()].every(rect => rect.left >= bounds.left - 1 && rect.right <= bounds.right + 1),
};
});
expect(metrics.lines).toBeGreaterThan(1);
expect(metrics.contained).toBe(true);
}
expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);
}
}
for (const [index, text] of [
[1, `notes/${"long directory/".repeat(16)}report.md`],
[2, String.raw`C:\Users\reader\My Docs\report.md`],
[4, "cat \t~/My Docs/report.md"],
] as const) {
const selected = await files.nth(index).locator("code").evaluate(node => {
const range = document.createRange();
range.selectNodeContents(node);
const selection = window.getSelection()!;
selection.removeAllRanges();
selection.addRange(range);
return selection.toString();
});
expect(selected).toBe(text);
await page.keyboard.press("ControlOrMeta+c");
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(text);
}
await page.evaluate(() => window.getSelection()?.removeAllRanges());
await expect(files.last()).toHaveText("Short report");
await files.nth(1).click();
await expect(page.getByLabel("Opened file")).toHaveText(`notes/${"long directory/".repeat(16)}report.md`);
await files.first().press("Enter");
await expect(page.getByLabel("Opened file")).toHaveText("notes/ready.md");
await files.first().press("Shift+F10");
await page.getByRole("menuitem", { name: "Copy absolute path", exact: true }).click();
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe("notes/ready.md");
await files.nth(6).hover();
await expect(page.getByTestId("file-image-quick-look").locator("img")).toBeVisible();
});
+10 -7
View File
@@ -35,7 +35,7 @@ export type FileReferenceKind =
interface FileReferenceChipProps {
path: string;
tooltipPath?: string;
display?: "name" | "path";
display?: "name" | "path" | "inline-code";
showIcon?: boolean;
truncateFromStart?: boolean;
active?: boolean;
@@ -62,7 +62,8 @@ export function FileReferenceChip({
const { t } = useTranslation();
const [tooltipOpen, setTooltipOpen] = useState(false);
const { directory, name } = splitFilePath(path);
const displayText = display === "path" ? path.replace(/\\/g, "/") : name;
const inlineCode = display === "inline-code";
const displayText = inlineCode ? path : display === "path" ? path.replace(/\\/g, "/") : name;
const fullPath = tooltipPath || path;
const targetPath = previewPath || tooltipPath || path;
const kind = fileKindForPath(targetPath);
@@ -75,19 +76,19 @@ export function FileReferenceChip({
setTooltipOpen(false);
onOpen(targetPath);
};
const Text = truncateFromStart ? StartTruncatedText : "span";
const Text = inlineCode ? "code" : truncateFromStart ? StartTruncatedText : "span";
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== "Enter" && event.key !== " ") return;
openPreview(event);
};
return (
<FileActions path={targetPath} className={truncateFromStart ? "min-w-0" : undefined}>
<FileActions path={targetPath} className={cn(truncateFromStart && "min-w-0", inlineCode && "inline")}>
<TooltipProvider>
<Tooltip open={tooltipOpen} onOpenChange={setTooltipOpen}>
<TooltipTrigger asChild>
<span
onContextMenuCapture={() => setTooltipOpen(false)}
className={cn("not-prose inline-flex max-w-full align-baseline leading-[inherit]", truncateFromStart && "min-w-0", className)}
className={cn("not-prose inline-flex max-w-full align-baseline leading-[inherit]", truncateFromStart && "min-w-0", inlineCode && "inline", className)}
>
<span
data-testid={testId}
@@ -99,6 +100,7 @@ export function FileReferenceChip({
className={cn(
"inline-flex max-w-full items-baseline gap-[0.28em] font-medium leading-[inherit]",
truncateFromStart && "min-w-0",
inlineCode && "inline",
interactive
? "text-content-link transition-colors hover:text-content-link-hover"
: "text-muted-foreground",
@@ -108,12 +110,13 @@ export function FileReferenceChip({
],
)}
>
{showIcon ? <FileReferenceIcon kind={kind} className="translate-y-[0.12em]" /> : null}
{showIcon ? <FileReferenceIcon kind={kind} className={cn("translate-y-[0.12em]", inlineCode && "mr-[0.28em] inline-block")} /> : null}
<Text
data-sheen-text={active ? displayText : undefined}
className={cn(
"min-w-0 max-w-full",
!truncateFromStart && "[overflow-wrap:anywhere] sm:truncate",
!inlineCode && !truncateFromStart && "[overflow-wrap:anywhere] sm:truncate",
inlineCode && "markdown-inline-code whitespace-break-spaces font-mono text-inherit [overflow-wrap:anywhere]",
active && !truncateFromStart && "streaming-text-sheen file-reference-sheen",
textClassName,
)}
@@ -555,6 +555,7 @@ export default function MarkdownTextRenderer({
return (
<AvailableFileReferenceChip
path={raw}
display="inline-code"
onOpen={onOpenFilePreview}
/>
);
@@ -138,7 +138,7 @@ describe("MarkdownTextRenderer", () => {
});
it.each([
{ kind: "inferred", markdown: "Future file: `notes/missing.md`", path: "notes/missing.md", label: "missing.md" },
{ kind: "inferred", markdown: "Future file: `notes/missing.md`", path: "notes/missing.md", label: "notes/missing.md" },
{ kind: "explicit", markdown: "[Future report](notes/missing.md)", path: "notes/missing.md", label: "Future report" },
{ kind: "malformed explicit", markdown: "[Python code](/home/example/workspace/model_check.py)", path: "/home/example/workspace/model_check.py", label: "Python code" },
])("keeps unavailable $kind file references non-interactive", async ({ markdown, path, label }) => {
@@ -188,6 +188,7 @@ describe("MarkdownTextRenderer", () => {
expect(reference).not.toHaveAttribute("role");
expect(reference).not.toHaveAttribute("tabindex");
expect(reference.textContent).toBe(kind === "inferred" ? "notes/locked.md" : "Unreadable report");
fireEvent.click(reference);
expect(onOpenFilePreview).not.toHaveBeenCalled();
});
@@ -209,16 +210,31 @@ describe("MarkdownTextRenderer", () => {
const reference = screen.getByTestId("inline-file-path");
expect(reference).not.toHaveAttribute("role");
expect(reference).toHaveClass("text-muted-foreground");
const label = kind === "inferred" ? "notes/ready.md" : "Existing report";
expect(reference.textContent).toBe(label);
await waitFor(() => expect(resolve).toHaveBeenCalledWith("notes/ready.md"));
await act(async () => resolveAvailability(true));
await waitFor(() => expect(reference).toHaveAttribute("role", "button"));
expect(reference).toHaveAttribute("tabindex", "0");
expect(reference.textContent).toBe(label);
fireEvent.click(reference);
expect(onOpenFilePreview).toHaveBeenCalledWith("notes/ready.md");
});
it.each([
"pytest tests/test_agent.py",
"这是一段说明文字,最后引用 /tmp/sample.txt",
String.raw`C:\Users\reader\My Docs\report.md`,
"cat \t~/My Docs/report.md",
])("preserves complete inferred file text: %s", (text) => {
const { container } = render(<MarkdownTextRenderer>{`Before \`${text}\` after.`}</MarkdownTextRenderer>);
expect(screen.getByTestId("inline-file-path").textContent).toBe(text);
expect(container.querySelector("p")?.textContent).toBe(`Before ${text} after.`);
});
it("does not treat non-file hrefs as previews just because the label looks like a file", () => {
const onOpenFilePreview = vi.fn();
render(
@@ -290,7 +306,7 @@ describe("MarkdownTextRenderer", () => {
render(<MarkdownTextRenderer onOpenFilePreview={onOpenFilePreview}>{`Open \`${path}\`.`}</MarkdownTextRenderer>);
const reference = screen.getByTestId("inline-file-path");
expect(reference).toHaveTextContent("report.md");
expect(reference.textContent).toBe(path);
expect(reference).toHaveAttribute("aria-label", path);
fireEvent.click(reference);
expect(onOpenFilePreview).toHaveBeenCalledWith(path);
+3 -5
View File
@@ -1295,7 +1295,7 @@ describe("MessageBubble", () => {
expect(container.querySelector("h3")).not.toBeInTheDocument();
});
it("renders inline file paths as compact file references", async () => {
it("keeps complete inline file paths and their preview hints", async () => {
await import("@/components/MarkdownTextRenderer");
const message: UIMessage = {
id: "a-file-path",
@@ -1314,10 +1314,8 @@ describe("MessageBubble", () => {
expect(references[0].parentElement).toHaveClass("align-baseline");
expect(references[0].parentElement).toHaveClass("leading-[inherit]");
expect(references[0]).toHaveClass("items-baseline");
expect(references[0]).toHaveTextContent("MarkdownTextRenderer.tsx");
expect(references[0]).not.toHaveTextContent("webui/src/components");
expect(screen.getByText("index.html")).toBeInTheDocument();
expect(references[1]).not.toHaveTextContent("/Users/renxubin");
expect(references[0].textContent).toBe("webui/src/components/MarkdownTextRenderer.tsx");
expect(references[1].textContent).toBe("/Users/renxubin/.nanobot/workspace/minecraft-fps/index.html");
expect(references[1]).not.toHaveAttribute("title");
expect(references[1]).toHaveAttribute(
"aria-label",