Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(web): add hover copy for agent code and tables (#18136)

Nimar9cdd025239df
diff --git a/web/src/features/in-app-agent/components/InAppAgentMessage.module.css b/web/src/features/in-app-agent/components/InAppAgentMessage.module.css
index 29a2b5e873..f033113f97 100644
--- a/web/src/features/in-app-agent/components/InAppAgentMessage.module.css
+++ b/web/src/features/in-app-agent/components/InAppAgentMessage.module.css
@@ -30,6 +30,7 @@
.Streamdown pre {
@apply bg-muted text-foreground dark:bg-card leading-tight;
+ padding-right: 2.75rem;
}
.Streamdown code {
diff --git a/web/src/features/in-app-agent/components/InAppAgentMessage.stories.tsx b/web/src/features/in-app-agent/components/InAppAgentMessage.stories.tsx
index ff02d491a6..e576c3e616 100644
--- a/web/src/features/in-app-agent/components/InAppAgentMessage.stories.tsx
+++ b/web/src/features/in-app-agent/components/InAppAgentMessage.stories.tsx
@@ -1,5 +1,5 @@
import preview from "../../../../.storybook/preview";
-import { expect, fn, userEvent, waitFor, within } from "storybook/test";
+import { expect, fn, spyOn, userEvent, waitFor, within } from "storybook/test";
import { InAppAgentMessage } from "./InAppAgentMessage";
const meta = preview.meta({
@@ -711,3 +711,98 @@ export const UserTextWithoutActionsInteraction = meta.story({
).not.toBeInTheDocument();
},
});
+
+const tableAndCodeMessage = [
+ "Proposed metric",
+ "",
+ "| Priority | Status | Note |",
+ "| --- | --- | --- |",
+ '| 1 | New | say "hi", please |',
+ "| 2 | Open | a\\|b |",
+ "",
+ "```ts",
+ "const bottleneck = 'document-reranking';",
+ "```",
+].join("\n");
+
+export const TableAndCode = meta.story({
+ args: {
+ role: "assistant",
+ content: {
+ type: "text",
+ text: tableAndCodeMessage,
+ },
+ timestamp: storyTimestamp,
+ onSubmitFeedback: fn(),
+ },
+});
+
+export const CopyTableAndCodeInteraction = meta.story({
+ name: "(Test) Copy Table And Code",
+ args: {
+ role: "assistant",
+ content: {
+ type: "text",
+ text: tableAndCodeMessage,
+ },
+ timestamp: storyTimestamp,
+ },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement);
+ const copy = spyOn(navigator.clipboard, "writeText").mockResolvedValue();
+ const csvButton = canvas.getByRole("button", { name: "Copy table as CSV" });
+ const markdownButton = canvas.getByRole("button", {
+ name: "Copy table as Markdown",
+ });
+ const codeButton = canvas.getByRole("button", { name: "Copy code" });
+ const table = canvas.getByRole("table");
+ const codeBlock = canvasElement.querySelector("pre");
+ if (!codeBlock) {
+ throw new Error("Missing code block");
+ }
+
+ try {
+ await expect(csvButton).not.toBeVisible();
+ await expect(markdownButton).not.toBeVisible();
+ await expect(codeButton).not.toBeVisible();
+
+ csvButton.click();
+ expect(copy).toHaveBeenLastCalledWith(
+ [
+ "Priority,Status,Note",
+ '1,New,"say ""hi"", please"',
+ "2,Open,a|b",
+ ].join("\n"),
+ );
+
+ markdownButton.click();
+ expect(copy).toHaveBeenLastCalledWith(
+ [
+ "| Priority | Status | Note |",
+ "| --- | --- | --- |",
+ '| 1 | New | say "hi", please |',
+ "| 2 | Open | a\\|b |",
+ ].join("\n"),
+ );
+
+ codeButton.click();
+ expect(copy).toHaveBeenLastCalledWith(
+ "const bottleneck = 'document-reranking';\n",
+ );
+
+ const block = table.parentElement?.parentElement;
+ if (!block) {
+ throw new Error("Missing table block");
+ }
+ const { clipboardData } = copySelectedNode(
+ block,
+ canvasElement.ownerDocument,
+ );
+ expect(clipboardData.getData("text/html")).not.toContain("button");
+ expect(clipboardData.getData("text/html")).not.toContain(".csv");
+ expect(clipboardData.getData("text/html")).not.toContain(".md");
+ } finally {
+ copy.mockRestore();
+ }
+ },
+});
diff --git a/web/src/features/in-app-agent/components/InAppAgentMessage.tsx b/web/src/features/in-app-agent/components/InAppAgentMessage.tsx
index 4c0799c99e..e5263ddc2e 100644
--- a/web/src/features/in-app-agent/components/InAppAgentMessage.tsx
+++ b/web/src/features/in-app-agent/components/InAppAgentMessage.tsx
@@ -47,6 +47,11 @@ import {
getMarkdownSourceRangeFromRenderedOffsets,
projectMarkdownToRenderedText,
} from "./utils/markdown";
+import {
+ readRenderedTable,
+ tableToCsv,
+ tableToMarkdown,
+} from "./utils/tableCopy";
import styles from "./InAppAgentMessage.module.css";
import { InAppAgentToolCallDetails } from "./InAppAgentToolCallDetails";
import {
@@ -290,7 +295,7 @@ function TextMessageWithActions({
| HTMLElement
| undefined;
htmlContainer
- ?.querySelectorAll("[data-in-app-agent-code-copy-button]")
+ ?.querySelectorAll("[data-in-app-agent-block-copy-button]")
.forEach((node) => {
node.remove();
});
@@ -923,11 +928,7 @@ function MessageText({
tr: ({ children }) => <tr>{children}</tr>,
th: ({ children }) => <th>{children}</th>,
td: ({ children }) => <td>{children}</td>,
- table: ({ children }) => (
- <div className="overflow-x-auto rounded">
- <table>{children}</table>
- </div>
- ),
+ table: ({ children }) => <TableBlock>{children}</TableBlock>,
}}
>
{text}
@@ -960,19 +961,16 @@ function getSelectedMarkdownFromSource(
const projection = projectMarkdownToRenderedText(markdown);
- const renderedStart = (() => {
- const prefixRange = root.ownerDocument.createRange();
- prefixRange.selectNodeContents(root);
- prefixRange.setEnd(range.startContainer, range.startOffset);
- return prefixRange.toString().length;
- })();
-
- const renderedEnd = (() => {
- const prefixRange = root.ownerDocument.createRange();
- prefixRange.selectNodeContents(root);
- prefixRange.setEnd(range.endContainer, range.endOffset);
- return prefixRange.toString().length;
- })();
+ const renderedStart = renderedTextOffset(
+ root,
+ range.startContainer,
+ range.startOffset,
+ );
+ const renderedEnd = renderedTextOffset(
+ root,
+ range.endContainer,
+ range.endOffset,
+ );
const fallbackStart = projection.plain.indexOf(selectedText, renderedStart);
const exactTextSelection =
@@ -1005,7 +1003,7 @@ function getSelectedMarkdownFromSource(
const htmlContainer = root.ownerDocument.createElement("div");
htmlContainer.append(range.cloneContents());
htmlContainer
- .querySelectorAll("[data-in-app-agent-code-copy-button]")
+ .querySelectorAll("[data-in-app-agent-block-copy-button]")
.forEach((node) => {
node.remove();
});
@@ -1016,6 +1014,39 @@ function getSelectedMarkdownFromSource(
};
}
+function renderedTextOffset(
+ root: HTMLElement,
+ container: Node,
+ offset: number,
+) {
+ const prefixRange = root.ownerDocument.createRange();
+ prefixRange.selectNodeContents(root);
+ prefixRange.setEnd(container, offset);
+
+ let length = prefixRange.toString().length;
+ root
+ .querySelectorAll("[data-in-app-agent-block-copy-button]")
+ .forEach((button) => {
+ if (!prefixRange.intersectsNode(button)) {
+ return;
+ }
+
+ const buttonRange = root.ownerDocument.createRange();
+ buttonRange.selectNodeContents(button);
+ const buttonText = buttonRange.toString();
+ const containsButton =
+ buttonText.length > 0 &&
+ prefixRange.compareBoundaryPoints(Range.START_TO_START, buttonRange) <=
+ 0 &&
+ prefixRange.compareBoundaryPoints(Range.END_TO_END, buttonRange) >= 0;
+ if (containsButton) {
+ length -= buttonText.length;
+ }
+ });
+
+ return Math.max(0, length);
+}
+
function trimTrailingFenceNewline(
markdown: string,
start: number,
@@ -1043,6 +1074,18 @@ function trimTrailingFenceNewline(
return selectedMarkdown.slice(0, -1);
}
+const codeCopyVisibilityClass =
+ "pointer-events-none opacity-0 transition-opacity group-hover/code-block:pointer-events-auto group-hover/code-block:opacity-100 group-focus-within/code-block:pointer-events-auto group-focus-within/code-block:opacity-100 focus-visible:pointer-events-auto focus-visible:opacity-100 data-[state=copied]:pointer-events-auto data-[state=copied]:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100";
+
+const tableCopyRowClass =
+ "flex h-0 justify-end overflow-hidden group-hover/table:h-8 group-focus-within/table:h-8 data-[state=copied]:h-8 [@media(hover:none)]:h-8";
+
+const tableCopyVisibilityClass =
+ "pointer-events-none mb-1 opacity-0 transition-opacity group-hover/table:pointer-events-auto group-hover/table:opacity-100 group-focus-within/table:pointer-events-auto group-focus-within/table:opacity-100 focus-visible:pointer-events-auto focus-visible:opacity-100 data-[state=copied]:pointer-events-auto data-[state=copied]:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100";
+
+const tableCopyHitTargetClass =
+ "pointer-events-none group-hover/table:pointer-events-auto group-focus-within/table:pointer-events-auto focus-visible:pointer-events-auto [@media(hover:none)]:pointer-events-auto";
+
function CodeBlock({ children }: { children: ReactNode }) {
const { copy, isCopied } = useCopyToClipboard({ successDuration: 1_500 });
@@ -1062,10 +1105,11 @@ function CodeBlock({ children }: { children: ReactNode }) {
);
return (
- <pre className="group/code-block relative pr-10">
+ <pre className="group/code-block relative">
<button
type="button"
- data-in-app-agent-code-copy-button="true"
+ data-in-app-agent-block-copy-button="true"
+ data-state={isCopied ? "copied" : undefined}
aria-label={isCopied ? "Copied code" : "Copy code"}
title={isCopied ? "Copied" : "Copy code"}
contentEditable={false}
@@ -1073,7 +1117,10 @@ function CodeBlock({ children }: { children: ReactNode }) {
onClick={() => {
copy(code).catch(() => undefined);
}}
- className="bg-background/90 text-muted-foreground hover:text-foreground focus-visible:ring-ring absolute top-1.5 right-1.5 z-10 inline-flex size-6 items-center justify-center rounded-md border opacity-80 shadow-sm transition select-none hover:opacity-100 focus-visible:ring-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-40"
+ className={cn(
+ "bg-background/90 text-muted-foreground hover:text-foreground focus-visible:ring-ring absolute top-1.5 right-1.5 z-10 inline-flex size-6 items-center justify-center rounded-md border shadow-sm select-none focus-visible:ring-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-40",
+ codeCopyVisibilityClass,
+ )}
>
{isCopied ? (
<Check className="size-3.5" />
@@ -1086,6 +1133,113 @@ function CodeBlock({ children }: { children: ReactNode }) {
);
}
+function TableBlock({ children }: { children: ReactNode }) {
+ const tableRef = useRef<HTMLTableElement>(null);
+ const csvCopy = useCopyToClipboard({ successDuration: 1_500 });
+ const markdownCopy = useCopyToClipboard({ successDuration: 1_500 });
+ const isCopied = csvCopy.isCopied || markdownCopy.isCopied;
+
+ const copyTable = (format: "csv" | "md") => {
+ const table = tableRef.current;
+ if (!table) {
+ return;
+ }
+
+ const rendered = readRenderedTable(
+ table,
+ format === "csv" ? "text" : "markdown",
+ );
+ const text =
+ format === "csv" ? tableToCsv(rendered) : tableToMarkdown(rendered);
+ const copy = format === "csv" ? csvCopy.copy : markdownCopy.copy;
+ copy(text).catch(() => undefined);
+ };
+
+ const handleCopyTableCsv = () => {
+ copyTable("csv");
+ };
+
+ const handleCopyTableMarkdown = () => {
+ copyTable("md");
+ };
+
+ return (
+ <div className="group/table max-w-full">
+ <div
+ data-state={isCopied ? "copied" : undefined}
+ className={tableCopyRowClass}
+ >
+ <div
+ data-state={isCopied ? "copied" : undefined}
+ className={cn(
+ "bg-background/90 flex items-center divide-x overflow-hidden rounded-md border shadow-sm select-none",
+ tableCopyVisibilityClass,
+ )}
+ >
+ <TableCopyButton
+ label="Copy table as CSV"
+ copiedLabel="Copied table as CSV"
+ isCopied={csvCopy.isCopied}
+ isInteractive={isCopied}
+ caption=".csv"
+ onClick={handleCopyTableCsv}
+ />
+ <TableCopyButton
+ label="Copy table as Markdown"
+ copiedLabel="Copied table as Markdown"
+ isCopied={markdownCopy.isCopied}
+ isInteractive={isCopied}
+ caption=".md"
+ onClick={handleCopyTableMarkdown}
+ />
+ </div>
+ </div>
+ <div className="overflow-x-auto rounded">
+ <table ref={tableRef}>{children}</table>
+ </div>
+ </div>
+ );
+}
+
+function TableCopyButton({
+ caption,
+ copiedLabel,
+ isCopied,
+ isInteractive,
+ label,
+ onClick,
+}: {
+ caption: string;
+ copiedLabel: string;
+ isCopied: boolean;
+ isInteractive: boolean;
+ label: string;
+ onClick: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ data-in-app-agent-block-copy-button="true"
+ aria-label={isCopied ? copiedLabel : label}
+ title={isCopied ? "Copied" : label}
+ contentEditable={false}
+ onClick={onClick}
+ className={cn(
+ "text-muted-foreground hover:text-foreground focus-visible:ring-ring inline-flex h-6 items-center gap-1 px-1.5 text-xs focus-visible:ring-2 focus-visible:outline-none",
+ tableCopyHitTargetClass,
+ isInteractive && "pointer-events-auto",
+ )}
+ >
+ {isCopied ? (
+ <Check className="size-3.5" />
+ ) : (
+ <Copy className="size-3.5" />
+ )}
+ <span>{caption}</span>
+ </button>
+ );
+}
+
function ThinkingIndicator({
className,
label = "Thinking...",
diff --git a/web/src/features/in-app-agent/components/utils/tableCopy.clienttest.ts b/web/src/features/in-app-agent/components/utils/tableCopy.clienttest.ts
new file mode 100644
index 0000000000..4a0eb9cc1f
--- /dev/null
+++ b/web/src/features/in-app-agent/components/utils/tableCopy.clienttest.ts
@@ -0,0 +1,117 @@
+import { describe, expect, it } from "vitest";
+import { readRenderedTable, tableToCsv, tableToMarkdown } from "./tableCopy";
+
+function tableFromHtml(html: string) {
+ const container = document.createElement("div");
+ container.innerHTML = html;
+ const table = container.querySelector("table");
+ if (!table) {
+ throw new Error("Missing table");
+ }
+ return table;
+}
+
+describe("table copy", () => {
+ it("keeps the header row when the markup has no thead", () => {
+ const table = readRenderedTable(
+ tableFromHtml(`
+ <table>
+ <tbody>
+ <tr><td>Priority</td><td>Status</td></tr>
+ <tr><td>1</td><td>New, now</td></tr>
+ </tbody>
+ </table>
+ `),
+ );
+
+ expect(tableToCsv(table)).toBe('Priority,Status\n1,"New, now"');
+ expect(tableToMarkdown(table)).toBe(
+ ["| Priority | Status |", "| --- | --- |", "| 1 | New, now |"].join("\n"),
+ );
+ });
+
+ it("reads header cells separately from body cells", () => {
+ const table = readRenderedTable(
+ tableFromHtml(`
+ <table>
+ <thead>
+ <tr><th>Note</th><th>Value</th></tr>
+ </thead>
+ <tbody>
+ <tr><td>say "hi"<br>please</td><td>a|b\\c</td></tr>
+ </tbody>
+ </table>
+ `),
+ );
+
+ expect(tableToCsv(table)).toBe('Note,Value\n"say ""hi"" please",a|b\\c');
+ expect(tableToMarkdown(table)).toBe(
+ [
+ "| Note | Value |",
+ "| --- | --- |",
+ '| say "hi" please | a\\|b\\\\c |',
+ ].join("\n"),
+ );
+ });
+
+ it("pads a short header so every column still has a header cell", () => {
+ expect(
+ tableToCsv({
+ headers: ["Only"],
+ rows: [["1", "2"]],
+ }),
+ ).toBe("Only,\n1,2");
+ expect(
+ tableToMarkdown({
+ headers: ["Only"],
+ rows: [["1", "2"]],
+ }),
+ ).toBe(["| Only | |", "| --- | --- |", "| 1 | 2 |"].join("\n"));
+ });
+
+ it("keeps a safe link target when copying markdown", () => {
+ const table = tableFromHtml(`
+ <table>
+ <thead>
+ <tr><th>Where</th></tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>see <a href="https://example.com/a)b">a|b\\c]</a> and <a href="javascript:alert(1)">skip</a></td>
+ </tr>
+ </tbody>
+ </table>
+ `);
+
+ expect(tableToCsv(readRenderedTable(table))).toBe(
+ "Where\nsee a|b\\c] and skip",
+ );
+ expect(tableToMarkdown(readRenderedTable(table, "markdown"))).toBe(
+ [
+ "| Where |",
+ "| --- |",
+ "| see [a\\|b\\\\c\\]](https://example.com/a\\)b) and skip |",
+ ].join("\n"),
+ );
+ });
+
+ it("ignores copy controls nested in a cell", () => {
+ const table = readRenderedTable(
+ tableFromHtml(`
+ <table>
+ <thead>
+ <tr>
+ <th>Priority<button data-in-app-agent-block-copy-button="true">.csv</button></th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr><td>1</td></tr>
+ </tbody>
+ </table>
+ `),
+ );
+
+ expect(table.headers).toEqual(["Priority"]);
+ expect(tableToCsv(table)).toBe("Priority\n1");
+ });
+});
diff --git a/web/src/features/in-app-agent/components/utils/tableCopy.ts b/web/src/features/in-app-agent/components/utils/tableCopy.ts
new file mode 100644
index 0000000000..6cd6f61a68
--- /dev/null
+++ b/web/src/features/in-app-agent/components/utils/tableCopy.ts
@@ -0,0 +1,174 @@
+import { getSafeLinkUrl } from "@/src/components/ui/safe-url";
+
+export type RenderedTable = {
+ headers: string[];
+ rows: string[][];
+ /**
+ * Cells are already safe to place in a Markdown table. Plain-text callers
+ * leave this unset so `tableToMarkdown` still escapes `|` and `\`.
+ */
+ markdownReady?: boolean;
+};
+
+const BLOCK_COPY_BUTTON_SELECTOR = "[data-in-app-agent-block-copy-button]";
+
+function normalizeCell(value: string) {
+ return value.replace(/\s+/g, " ").trim();
+}
+
+function cellValue(cell: Element, format: "text" | "markdown") {
+ const clone = cell.cloneNode(true);
+ if (!(clone instanceof HTMLElement)) {
+ const text = normalizeCell(cell.textContent ?? "");
+ return format === "markdown" ? escapeMarkdownCell(text) : text;
+ }
+
+ clone.querySelectorAll(BLOCK_COPY_BUTTON_SELECTOR).forEach((node) => {
+ node.remove();
+ });
+
+ return normalizeCell(renderInline(clone, format));
+}
+
+function renderInline(node: Node, format: "text" | "markdown"): string {
+ if (node.nodeType === Node.TEXT_NODE) {
+ const text = node.textContent ?? "";
+ return format === "markdown" ? escapeMarkdownCell(text) : text;
+ }
+
+ if (!(node instanceof HTMLElement)) {
+ return [...node.childNodes]
+ .map((child) => renderInline(child, format))
+ .join("");
+ }
+
+ if (node.tagName === "BR") {
+ return "\n";
+ }
+
+ const children = [...node.childNodes]
+ .map((child) => renderInline(child, format))
+ .join("");
+ if (format !== "markdown" || node.tagName !== "A") {
+ return children;
+ }
+
+ const href = getSafeLinkUrl(node.getAttribute("href"));
+ const label = normalizeCell(
+ [...node.childNodes].map((child) => renderInline(child, "text")).join(""),
+ );
+ if (!href || !label) {
+ return children;
+ }
+
+ return `[${escapeMarkdownLinkLabel(label)}](${escapeMarkdownLinkDestination(href)})`;
+}
+
+function escapeMarkdownLinkLabel(value: string) {
+ return value.replace(/\\/g, "\\\\").replace(/[[\]|]/g, "\\$&");
+}
+
+function escapeMarkdownLinkDestination(value: string) {
+ return value.replace(/\\/g, "\\\\").replace(/[()|]/g, "\\$&");
+}
+
+function rowCells(row: Element, format: "text" | "markdown") {
+ return [...row.querySelectorAll(":scope > th, :scope > td")].map((cell) =>
+ cellValue(cell, format),
+ );
+}
+
+export function readRenderedTable(
+ table: HTMLTableElement,
+ format: "text" | "markdown" = "text",
+): RenderedTable {
+ const sectionRows = [
+ ...table.querySelectorAll(":scope > thead > tr"),
+ ...table.querySelectorAll(":scope > tbody > tr"),
+ ...table.querySelectorAll(":scope > tfoot > tr"),
+ ].map((row) => rowCells(row, format));
+ const looseRows = [...table.querySelectorAll(":scope > tr")].map((row) =>
+ rowCells(row, format),
+ );
+ const [headers = [], ...rows] = [...sectionRows, ...looseRows].filter(
+ (row) => row.length > 0,
+ );
+
+ return {
+ headers,
+ rows,
+ markdownReady: format === "markdown",
+ };
+}
+
+function columnCount(table: RenderedTable) {
+ let width = table.headers.length;
+ for (const row of table.rows) {
+ if (row.length > width) {
+ width = row.length;
+ }
+ }
+ return width;
+}
+
+function paddedRows(table: RenderedTable) {
+ const width = columnCount(table);
+ if (width === 0) {
+ return null;
+ }
+
+ const pad = (cells: string[]) => {
+ const padded = cells.slice(0, width).map(normalizeCell);
+ while (padded.length < width) {
+ padded.push("");
+ }
+ return padded;
+ };
+
+ return {
+ headers: pad(table.headers),
+ rows: table.rows.map(pad),
+ };
+}
+
+function escapeCsvCell(value: string) {
+ if (/[",\n\r]/.test(value)) {
+ return `"${value.replace(/"/g, '""')}"`;
+ }
+ return value;
+}
+
+function escapeMarkdownCell(value: string) {
+ return value.replace(/\\/g, "\\\\").replace(/\|/g, "\\|");
+}
+
+export function tableToCsv(table: RenderedTable) {
+ const padded = paddedRows(table);
+ if (!padded) {
+ return "";
+ }
+
+ return [padded.headers, ...padded.rows]
+ .map((row) => row.map(escapeCsvCell).join(","))
+ .join("\n");
+}
+
+export function tableToMarkdown(table: RenderedTable) {
+ const padded = paddedRows(table);
+ if (!padded) {
+ return "";
+ }
+
+ const escape = table.markdownReady
+ ? (value: string) => value
+ : escapeMarkdownCell;
+ const header = padded.headers.map(escape);
+ const separator = padded.headers.map(() => "---");
+ const body = padded.rows.map((row) => row.map(escape));
+
+ return [
+ `| ${header.join(" | ")} |`,
+ `| ${separator.join(" | ")} |`,
+ ...body.map((row) => `| ${row.join(" | ")} |`),
+ ].join("\n");
+}