graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(gui): add copy action to assistant responses (#1104)
yxlyx73b1f91b4f61
diff --git a/gui/src/components/chat/AssistantResponseCopyButton.tsx b/gui/src/components/chat/AssistantResponseCopyButton.tsxnew file mode 100644index 00000000..c7b3eca4--- /dev/null+++ b/gui/src/components/chat/AssistantResponseCopyButton.tsx@@ -0,0 +1,37 @@+import { Check, Copy } from "lucide-react";++import { Button } from "@/components/ui/Button";+import { useCopyToClipboard } from "@/hooks/useCopyToClipboard";++interface AssistantResponseCopyButtonProps {+ text: string;+}++export function AssistantResponseCopyButton({+ text,+}: AssistantResponseCopyButtonProps) {+ const { copied, copy } = useCopyToClipboard();++ if (text.length === 0) {+ return null;+ }++ const label = copied ? "Copied" : "Copy response";++ return (+ <Button+ type="button"+ variant="ghost"+ size="xs"+ aria-label={label}+ title={label}+ onClick={() => {+ void copy(text);+ }}+ className="-ml-1 rounded-full px-1.5 text-muted-foreground hover:text-foreground"+ >+ {copied ? <Check className="size-3" /> : <Copy className="size-3" />}+ <span aria-live="polite">{label}</span>+ </Button>+ );+}diff --git a/gui/src/components/chat/ChatMarkdownMessage.tsx b/gui/src/components/chat/ChatMarkdownMessage.tsxnew file mode 100644index 00000000..d45ba0fc--- /dev/null+++ b/gui/src/components/chat/ChatMarkdownMessage.tsx@@ -0,0 +1,29 @@+import { AssistantResponseCopyButton } from "./AssistantResponseCopyButton";+import { ChatMarkdown } from "./ChatMarkdown";++interface ChatMarkdownMessageProps {+ copyText?: string;+ text: string;+ toneClassName: string;+ workspacePath: string | null;+}++export function ChatMarkdownMessage({+ copyText,+ text,+ toneClassName,+ workspacePath,+}: ChatMarkdownMessageProps) {+ return (+ <article className="flex max-w-3xl flex-col items-start gap-2">+ <ChatMarkdown+ text={text}+ className={`cg-stream-in ${toneClassName}`}+ workspacePath={workspacePath}+ />+ {copyText == null ? null : (+ <AssistantResponseCopyButton text={copyText} />+ )}+ </article>+ );+}diff --git a/gui/src/components/chat/ChatMessageRow.test.tsx b/gui/src/components/chat/ChatMessageRow.test.tsxnew file mode 100644index 00000000..54e63b48--- /dev/null+++ b/gui/src/components/chat/ChatMessageRow.test.tsx@@ -0,0 +1,335 @@+import {+ afterAll,+ beforeAll,+ beforeEach,+ describe,+ expect,+ mock,+ test,+} from "bun:test";+import type { ReactNode } from "react";+import ReactDOM from "react-dom";++import type { TranscriptMessage } from "@/services/desktop/types/contracts";+import type { ChatThreadRenderItem } from "./types/chatComponents";++mock.module("./ChatCommandResultRow", () => ({+ ChatCommandResultRow: () => null,+}));+mock.module("./ChatWorkRow", () => ({+ ChatWorkRow: () => null,+}));++const { flushSync } = ReactDOM;++let unregisterDom: (() => Promise<void>) | null = null;+let createRoot: typeof import("react-dom/client").createRoot;+let ChatMarkdownMessage: typeof import("./ChatMarkdownMessage").ChatMarkdownMessage;+let ChatMessageRow: typeof import("./ChatMessageRow").ChatMessageRow;+let renderChatThreadItem: typeof import("./utils/chatThreadList").renderChatThreadItem;++beforeAll(async () => {+ const { GlobalRegistrator } = await import("@happy-dom/global-registrator");+ GlobalRegistrator.register();+ unregisterDom = () => GlobalRegistrator.unregister();+ Object.defineProperty(document, "compatMode", {+ value: "CSS1Compat",+ configurable: true,+ });+ ({ createRoot } = await import("react-dom/client"));+ ({ ChatMarkdownMessage } = await import("./ChatMarkdownMessage"));+ ({ ChatMessageRow } = await import("./ChatMessageRow"));+ ({ renderChatThreadItem } = await import("./utils/chatThreadList"));+});++afterAll(async () => {+ await unregisterDom?.();+});++beforeEach(() => {+ document.body.replaceChildren();+ Object.defineProperty(navigator, "clipboard", {+ value: undefined,+ configurable: true,+ });+});++function mount(node: ReactNode) {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ flushSync(() => {+ root.render(node);+ });++ return {+ container,+ rerender: (nextNode: ReactNode) => {+ flushSync(() => {+ root.render(nextNode);+ });+ },+ unmount: () => {+ flushSync(() => root.unmount());+ container.remove();+ },+ };+}++function contentMessage(+ kind: "user" | "assistant" | "reasoning",+ text: string,+): Extract<TranscriptMessage, { kind: "user" | "assistant" | "reasoning" }> {+ return {+ kind,+ id: `${kind}-1`,+ requestId: "request-1",+ text,+ };+}++function renderThreadMessage(message: TranscriptMessage) {+ return renderChatThreadItem(+ {+ item: {+ kind: "message",+ key: message.id,+ message,+ },+ index: 0,+ } as ChatThreadRenderItem,+ {+ itemCount: 1,+ requestTimingsById: {},+ workspacePath: null,+ },+ );+}++function mountMarkdownMessage(text: string, copyText?: string) {+ return mount(+ <ChatMarkdownMessage+ copyText={copyText}+ text={text}+ toneClassName="text-foreground"+ workspacePath={null}+ />,+ );+}++function setClipboard(writeText: (value: string) => Promise<void>) {+ Object.defineProperty(navigator, "clipboard", {+ value: { writeText },+ configurable: true,+ });+}++async function flushUpdates(delayMs = 10) {+ await new Promise((resolve) => window.setTimeout(resolve, delayMs));+}++describe("chat response copy dispatch", () => {+ test("the thread adds the action only to assistant messages", () => {+ const messages: Array<[TranscriptMessage, boolean]> = [+ [contentMessage("assistant", "Answer"), true],+ [contentMessage("user", "Question"), false],+ [contentMessage("reasoning", "Private reasoning"), false],+ [+ {+ kind: "status",+ id: "status-1",+ requestId: "request-1",+ title: "Working",+ subtitle: "Still working",+ category: "info",+ },+ false,+ ],+ [+ {+ kind: "tool_start",+ id: "tool-1",+ requestId: "request-1",+ name: "shell",+ callId: "call-1",+ detail: {+ kind: "shell",+ command: "pwd",+ cwd: null,+ description: null,+ },+ },+ false,+ ],+ ];++ for (const [message, shouldCopy] of messages) {+ const row = mount(renderThreadMessage(message));+ try {+ expect(+ row.container.querySelector('button[aria-label="Copy response"]') !=+ null,+ ).toBe(shouldCopy);+ } finally {+ row.unmount();+ }+ }+ });++ test("an assistant row streamed in place copies the latest response only", async () => {+ const writeText = mock(async () => {});+ setClipboard(writeText);+ const row = mount(+ <ChatMessageRow+ message={contentMessage("assistant", "")}+ workspacePath={null}+ />,+ );++ try {+ expect(row.container.querySelector("button")).toBeNull();++ row.rerender(+ <ChatMessageRow+ message={contentMessage("assistant", "Partial")}+ workspacePath={null}+ />,+ );+ expect(+ row.container.querySelector('button[aria-label="Copy response"]'),+ ).not.toBeNull();++ const finalText = "Final **answer**\n\n```ts\nconst value = 1;\n```";+ row.rerender(+ <ChatMessageRow+ message={contentMessage("assistant", finalText)}+ workspacePath={null}+ />,+ );+ const button = row.container.querySelector<HTMLButtonElement>(+ 'button[aria-label="Copy response"]',+ );+ expect(button).not.toBeNull();++ button!.click();+ await flushUpdates();++ expect(writeText).toHaveBeenCalledTimes(1);+ expect(writeText).toHaveBeenCalledWith(finalText);+ } finally {+ row.unmount();+ }+ });+});++describe("assistant response copy behavior", () => {+ test("copies the exact raw output, including Markdown, whitespace, and Unicode", async () => {+ const text = "## Result\n\n```ts\nconst café = \"☕\";\n```\n\nDone. ";+ const writeText = mock(async () => {});+ setClipboard(writeText);+ const { container, unmount } = mountMarkdownMessage(text, text);++ try {+ const button = container.querySelector<HTMLButtonElement>(+ 'button[aria-label="Copy response"]',+ );+ expect(button).not.toBeNull();++ button!.click();+ await flushUpdates();++ expect(writeText).toHaveBeenCalledTimes(1);+ expect(writeText).toHaveBeenCalledWith(text);+ expect(button!.getAttribute("aria-label")).toBe("Copied");+ expect(button!.textContent).toBe("Copied");+ } finally {+ unmount();+ }+ });++ test("does not add a copy action without an assistant copy payload", () => {+ const { container, unmount } = mountMarkdownMessage("Private reasoning text");+ try {+ expect(container.querySelector('button[aria-label="Copy response"]')).toBeNull();+ } finally {+ unmount();+ }+ });++ test("adds the action during streaming and copies whitespace exactly", async () => {+ const writeText = mock(async () => {});+ setClipboard(writeText);+ const message = mountMarkdownMessage("", "");++ try {+ expect(message.container.querySelector("button")).toBeNull();++ message.rerender(+ <ChatMarkdownMessage+ copyText={" \n\t "}+ text={" \n\t "}+ toneClassName="text-foreground"+ workspacePath={null}+ />,+ );++ const button = message.container.querySelector<HTMLButtonElement>(+ 'button[aria-label="Copy response"]',+ );+ expect(button).not.toBeNull();+ button!.click();+ await flushUpdates();+ expect(writeText).toHaveBeenCalledWith(" \n\t ");+ } finally {+ message.unmount();+ }+ });++ test("keeps the default label when clipboard access is unavailable or rejects", async () => {+ const unavailable = mountMarkdownMessage("Hello", "Hello");+ try {+ const button = unavailable.container.querySelector<HTMLButtonElement>("button");+ expect(button).not.toBeNull();+ button!.click();+ await flushUpdates();+ expect(button!.getAttribute("aria-label")).toBe("Copy response");+ } finally {+ unavailable.unmount();+ }++ setClipboard(async () => {+ throw new Error("clipboard denied");+ });+ const rejected = mountMarkdownMessage("Hello again", "Hello again");+ try {+ const button = rejected.container.querySelector<HTMLButtonElement>("button");+ expect(button).not.toBeNull();+ button!.click();+ await flushUpdates();+ expect(button!.getAttribute("aria-label")).toBe("Copy response");+ expect(button!.textContent).toBe("Copy response");+ } finally {+ rejected.unmount();+ }+ });++ test("returns copied feedback to the default label after the reset delay", async () => {+ setClipboard(async () => {});+ const { container, unmount } = mountMarkdownMessage("Reset me", "Reset me");++ try {+ const button = container.querySelector<HTMLButtonElement>("button");+ expect(button).not.toBeNull();+ button!.click();+ await flushUpdates();+ expect(button!.getAttribute("aria-label")).toBe("Copied");++ await flushUpdates(1_250);++ expect(button!.getAttribute("aria-label")).toBe("Copy response");+ expect(button!.textContent).toBe("Copy response");+ } finally {+ unmount();+ }+ });+});diff --git a/gui/src/components/chat/ChatMessageRow.tsx b/gui/src/components/chat/ChatMessageRow.tsxindex a48b5ba6..b0beaf90 100644--- a/gui/src/components/chat/ChatMessageRow.tsx+++ b/gui/src/components/chat/ChatMessageRow.tsx@@ -2,17 +2,15 @@ import {CHAT_BODY_TONE_CLASS,CHAT_REASONING_TONE_CLASS,} from "./constants/chatStyles";-import { ChatMarkdown } from "./ChatMarkdown";+import { ChatMarkdownMessage } from "./ChatMarkdownMessage";import { ChatInlineText } from "./ChatInlineText";import { AttachmentTray } from "@/components/attachments/AttachmentTray";import {classifyPath,parseAttachmentBlock,} from "@/components/attachments/attachmentTypes";-import { openPathDefault } from "@/services/desktop/client";import type {ChatMessageRowProps,- MarkdownChatMessageProps,TextOnlyMessageProps,} from "./types/chatComponents";@@ -21,9 +19,11 @@ interface UserChatMessageProps extends TextOnlyMessageProps {}function handleOpenAttachment(path: string) {- void openPathDefault(path).catch((error) => {- console.error("Failed to open attachment", error);- });+ void import("@/services/desktop/client")+ .then(({ openPathDefault }) => openPathDefault(path))+ .catch((error) => {+ console.error("Failed to open attachment", error);+ });}function UserChatMessage({ text, workspacePath }: UserChatMessageProps) {@@ -53,29 +53,14 @@ function UserChatMessage({ text, workspacePath }: UserChatMessageProps) {);}-function MarkdownChatMessage({- text,- toneClassName,- workspacePath,-}: MarkdownChatMessageProps) {- return (- <article className="max-w-3xl">- <ChatMarkdown- text={text}- className={`cg-stream-in ${toneClassName ?? ""}`}- workspacePath={workspacePath}- />- </article>- );-}-export function ChatMessageRow({ message, workspacePath }: ChatMessageRowProps) {switch (message.kind) {case "user":return <UserChatMessage text={message.text} workspacePath={workspacePath} />;case "assistant":return (- <MarkdownChatMessage+ <ChatMarkdownMessage+ copyText={message.text}text={message.text}toneClassName={CHAT_BODY_TONE_CLASS}workspacePath={workspacePath}@@ -83,7 +68,7 @@ export function ChatMessageRow({ message, workspacePath }: ChatMessageRowProps));case "reasoning":return (- <MarkdownChatMessage+ <ChatMarkdownMessagetext={message.text}toneClassName={CHAT_REASONING_TONE_CLASS}workspacePath={workspacePath}diff --git a/gui/src/components/chat/ChatTranscriptMessage.tsx b/gui/src/components/chat/ChatTranscriptMessage.tsxnew file mode 100644index 00000000..1215b189--- /dev/null+++ b/gui/src/components/chat/ChatTranscriptMessage.tsx@@ -0,0 +1,23 @@+import type { TranscriptMessage } from "@/services/desktop/types/contracts";++import { ChatEventRow } from "./ChatEventRow";+import { ChatMessageRow } from "./ChatMessageRow";++interface ChatTranscriptMessageProps {+ message: TranscriptMessage;+ workspacePath: string | null;+}++export function ChatTranscriptMessage({+ message,+ workspacePath,+}: ChatTranscriptMessageProps) {+ switch (message.kind) {+ case "user":+ case "assistant":+ case "reasoning":+ return <ChatMessageRow message={message} workspacePath={workspacePath} />;+ default:+ return <ChatEventRow message={message} />;+ }+}diff --git a/gui/src/components/chat/types/chatComponents.ts b/gui/src/components/chat/types/chatComponents.tsindex dfea505f..74bda118 100644--- a/gui/src/components/chat/types/chatComponents.ts+++ b/gui/src/components/chat/types/chatComponents.ts@@ -157,12 +157,6 @@ export interface FileDiffResultProps {workspacePath: string | null;}-export interface MarkdownChatMessageProps {- text: string;- toneClassName: string;- workspacePath: string | null;-}-export interface FilePathButtonProps {label: string;path: string;diff --git a/gui/src/components/chat/utils/chatThreadList.tsx b/gui/src/components/chat/utils/chatThreadList.tsxindex a201c03a..cdbd73fc 100644--- a/gui/src/components/chat/utils/chatThreadList.tsx+++ b/gui/src/components/chat/utils/chatThreadList.tsx@@ -1,8 +1,7 @@import type { TranscriptMessage } from "@/services/desktop/types/contracts";import { ChatCommandResultRow } from "../ChatCommandResultRow";-import { ChatEventRow } from "../ChatEventRow";-import { ChatMessageRow } from "../ChatMessageRow";+import { ChatTranscriptMessage } from "../ChatTranscriptMessage";import { ChatWorkRow } from "../ChatWorkRow";import { THREAD_ITEM_GAP } from "../constants/chatThread";import type {@@ -73,17 +72,6 @@ function estimateCommandResultItemSize(return Math.min(520, 64 + lineCount * 20);}-function renderChatMessage(message: TranscriptMessage, workspacePath: string | null) {- switch (message.kind) {- case "user":- case "assistant":- case "reasoning":- return <ChatMessageRow message={message} workspacePath={workspacePath} />;- default:- return <ChatEventRow message={message} />;- }-}-export function estimateChatThreadItemSize(item: ChatThreadItem): number {const contentSize =item.kind === "message"@@ -106,7 +94,10 @@ export function renderChatThreadItem() {const row =item.kind === "message" ? (- renderChatMessage(item.message, workspacePath)+ <ChatTranscriptMessage+ message={item.message}+ workspacePath={workspacePath}+ />) : item.kind === "request_work" ? (<ChatWorkRowkey={item.key}