Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(web,ui): 回复能复制成纯文本,不再只有 Markdown 源码

lmlihengd03446df0af4
diff --git a/changelog/unreleased/2026-10-11-reply-plain-text-copy.md b/changelog/unreleased/2026-10-11-reply-plain-text-copy.md
new file mode 100644
index 00000000..6d349058
--- /dev/null
+++ b/changelog/unreleased/2026-10-11-reply-plain-text-copy.md
@@ -0,0 +1,29 @@
+# A reply can be copied as plain text, not only as Markdown
+
+- **Date:** 2026-10-11
+- **Type:** feat
+- **Scope:** `web`, `ui`
+
+[中文版](2026-10-11-reply-plain-text-copy.zh.md)
+
+A reply's footer had one copy button, and it handed over the reply's Markdown source. Pasted into a
+chat, a ticket or a doc, the reader got the markers themselves — `##`, `**`, `| --- |` — and had to
+clean them up by hand. The footer now carries two copy buttons: the first still copies the
+Markdown, and a new "Copy as plain text" beside it gives the same words with the markup taken out.
+
+## Details
+
+- The two are told apart by their marks — the familiar copy glyph, and three lines. Hovering names
+ what each one copies; on a successful copy both swap to a check and the screen-reader region
+ beside them says 已复制.
+- The plain text unwraps the same dialect the transcript renders: heading, bold, italic,
+ strikethrough and inline-code markers go; a list keeps its bullet or number and its nesting as an
+ indent; a table comes out row by row, without the edge pipes or the `| --- |` alignment row; a
+ blockquote loses its `>`; a link reads `label (url)`, while a bare URL that was autolinked still
+ appears once; an image gives its alt text; a fenced block keeps its code verbatim, unfenced;
+ a footnote stays `[^id]`; math keeps its TeX source; raw HTML passes through as written.
+- "Copy as plain text" only appears when the turn actually said something — with no reply body the
+ first button falls back to the turn's usage stats, and there is no plain text to offer.
+- The conversion walks the same syntax tree the transcript renders
+ (`packages/ui/src/components/content/prose/plain-text.ts`), so a construct the renderer typesets
+ is a construct this knows how to unwrap.
diff --git a/changelog/unreleased/2026-10-11-reply-plain-text-copy.zh.md b/changelog/unreleased/2026-10-11-reply-plain-text-copy.zh.md
new file mode 100644
index 00000000..689bf440
--- /dev/null
+++ b/changelog/unreleased/2026-10-11-reply-plain-text-copy.zh.md
@@ -0,0 +1,16 @@
+# 回复可以复制成纯文本,不再只有 Markdown 源码
+
+- **Date:** 2026-10-11
+- **Type:** feat
+- **Scope:** `web`, `ui`
+
+[English](2026-10-11-reply-plain-text-copy.md)
+
+AI 回复的页脚原本只有一个复制按钮,它给出的是回复的 Markdown 源码。粘到聊天窗口、工单或文档里,对方看到的是 `##`、`**` 和 `| --- |` 这些标记本身,还得自己删一遍。现在页脚上有两个复制按钮:原来的那个照旧复制 Markdown,旁边新增的「复制纯文本」给出把标记去掉之后的正文。
+
+## 细节
+
+- 两个按钮靠图形区分:一个是原来的复制图标,一个是三横线。把鼠标停在按钮上,提示文字(tooltip)写明各自复制什么;复制成功时两者都换成对勾,旁边的读屏区域报「已复制」。
+- 纯文本按渲染时的同一套方言来拆:标题、粗体、斜体、删除线、行内代码去掉标记;列表保留 `- ` 与编号并按层级缩进;表格按行给出,去掉首尾竖线和那条对齐用的 `| --- |`;引用去 `>`;链接写成 `标签 (地址)`,而回复里本就是裸链接的仍只出现一次;图片取 alt 文字;围栏代码块里的代码原样保留(围栏本身去掉);脚注留 `[^id]`;数学取 TeX 源码;HTML 原样。
+- 只有这一轮确实说了话时,「复制纯文本」才出现 —— 没有任何正文时原本复制的是用量统计,那种情况不提供纯文本按钮。
+- 转换与渲染共用同一棵语法树(`packages/ui/src/components/content/prose/plain-text.ts`),所以能渲染出来的写法,这里都认得。
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 0e2e50c6..57ca608a 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -46,10 +46,13 @@
"rehype-katex": "^7.0.1",
"remark-gfm": "^4.0.0",
"remark-math": "^6.0.0",
+ "remark-parse": "^11.0.0",
"shiki": "^4.3.1",
+ "unified": "^11.0.5",
"zustand": "^5.0.15"
},
"devDependencies": {
+ "@types/mdast": "^4.0.4",
"@types/node": "^24.0.0",
"@types/react": "^19.1.0",
"@types/react-dom": "^19.1.0",
diff --git a/packages/ui/src/components/actions/copy-button/copy-button.tsx b/packages/ui/src/components/actions/copy-button/copy-button.tsx
index ff36f4ca..cb4f69ab 100644
--- a/packages/ui/src/components/actions/copy-button/copy-button.tsx
+++ b/packages/ui/src/components/actions/copy-button/copy-button.tsx
@@ -94,8 +94,17 @@ export function useCopied(): { copied: boolean; flash: (text: string) => void }
}
/** The glyph pair every copy affordance shows: the copy icon, swapping to the check while copied. */
-export function CopyCheckGlyph({ copied, size }: { copied: boolean; size?: number }) {
- return <GlyphIcon d={copied ? ICONS.check : ICONS.copy} size={size} />;
+export function CopyCheckGlyph({
+ copied,
+ size,
+ glyph,
+}: {
+ copied: boolean;
+ size?: number;
+ /** The idle mark, when this control copies a VARIANT of what the copy glyph means (plain text beside a Markdown copy); the check still replaces it. */
+ glyph?: string;
+}) {
+ return <GlyphIcon d={copied ? ICONS.check : (glyph ?? ICONS.copy)} size={size} />;
}
/**
@@ -141,6 +150,7 @@ export function CopyButton({
text,
label,
size = "md",
+ glyph,
className = "",
}: {
/** The string to copy, or a getter for content computed at click time (a formatted stats line). */
@@ -148,6 +158,12 @@ export function CopyButton({
/** Accessible name and tooltip of the copy action; neither changes while copied. */
label: string;
size?: keyof typeof SIZE;
+ /**
+ * The idle mark, for a control that copies a variant rather than the plain thing — a conversation
+ * offers a reply both as Markdown and as plain text, and two copy glyphs side by side would name
+ * neither. The check still replaces whatever is passed here while copied.
+ */
+ glyph?: string;
/** Layout the caller's row needs (`shrink-0`, a margin); the look is the button's own. */
className?: string;
}) {
@@ -161,7 +177,7 @@ export function CopyButton({
onClick={() => flash(typeof text === "function" ? text() : text)}
className={`${LOOK} ${SIZE[size]} ${className}`}
>
- <CopyCheckGlyph copied={copied} />
+ <CopyCheckGlyph copied={copied} glyph={glyph} />
</button>
{/* Sibling, not a child: the button's accessible name stays `label`, and `sr-only` is
position:absolute, so it is not a flex item and disturbs no caller's layout. */}
diff --git a/packages/ui/src/components/content/prose/plain-text.ts b/packages/ui/src/components/content/prose/plain-text.ts
new file mode 100644
index 00000000..d37abfb5
--- /dev/null
+++ b/packages/ui/src/components/content/prose/plain-text.ts
@@ -0,0 +1,197 @@
+/**
+ * Reading a Markdown reply as plain text — what the conversation's 「复制纯文本」 puts on the
+ * clipboard, next to the same reply copied as Markdown.
+ *
+ * Why the two differ at all: the reply on screen is typeset — a heading is bigger, `**this**` is
+ * bold, `- item` is a bullet — and pasting the SOURCE into a chat, a ticket or a doc hands the
+ * reader the punctuation instead (`## `, `**`, `| --- |`). Plain text is for that destination:
+ * the words, with the structure kept as layout rather than as markers.
+ *
+ * It reads the SAME tree the transcript renders (the dialect lives in markdown-plugins.ts, so a
+ * construct the renderer typesets is a construct this knows how to unwrap), and it walks that
+ * tree the way the channel renderers walk theirs — one branch per node type, no substitution
+ * pass over the text.
+ *
+ * Kept, because dropping any of them would lose something the reply deliberately carried:
+ *
+ * - a list item's bullet or number, and its nesting as an indent;
+ * - a link's address, when its label does not already read as the address (a bare URL that
+ * remark-gfm autolinked arrives with the two equal, and keeps just the one);
+ * - an image's alt text — or its address when it has none: a picture cannot travel as text,
+ * and the reply's own pictures are files the transcript carries outside the body;
+ * - a fenced block's code, verbatim and unfenced (the fence is markup; the code is content);
+ * - a table's cells, row by row;
+ * - a footnote reference as `[^id]`, with the definition's own words where it was written.
+ *
+ * Dropped, because each one only ever told the renderer what to draw: the `#` of a heading, the
+ * emphasis / strong / strikethrough markers, backticks, the `>` of a blockquote, a thematic
+ * break (a rule has nothing to say as text), front matter, and a link definition, whose address
+ * already travels with the label referring to it.
+ *
+ * Raw HTML passes through as its own characters: it is text the author wrote, and stripping tags
+ * would silently delete whatever sat between them.
+ */
+import { unified } from "unified";
+import remarkParse from "remark-parse";
+import type {
+ BlockContent,
+ DefinitionContent,
+ ListItem,
+ PhrasingContent,
+ RootContent,
+ TableRow,
+} from "mdast";
+import { REMARK_PLUGINS } from "./markdown-plugins";
+
+/**
+ * One processor for the whole app: `unified` compiles its extension lists on first use, and a
+ * fresh one per copy would redo that work. Parsing is stateless, so one instance serves every
+ * copy.
+ */
+const processor = unified().use(remarkParse).use(REMARK_PLUGINS);
+
+/** One nesting step inside a list, as a reading indent — layout, not syntax. */
+const INDENT = " ";
+
+/** What a list marks its items with: a bullet, or the number counted from the list's own start. */
+function marker(list: { ordered?: boolean | null; start?: number | null }, index: number): string {
+ return list.ordered ? `${(list.start ?? 1) + index}. ` : "- ";
+}
+
+/** Inline content as text: the words, with nothing that only marked them up. */
+function inline(nodes: PhrasingContent[]): string {
+ let out = "";
+ for (const node of nodes) {
+ switch (node.type) {
+ case "text":
+ case "inlineCode":
+ out += node.value;
+ break;
+ case "strong":
+ case "emphasis":
+ case "delete":
+ out += inline(node.children);
+ break;
+ case "link": {
+ // The label, plus the address behind it only when the label does not already read as
+ // that address.
+ const label = inline(node.children);
+ out += label === node.url ? label : `${label} (${node.url})`;
+ break;
+ }
+ case "image":
+ out += node.alt ? node.alt : node.url;
+ break;
+ case "break":
+ out += "\n";
+ break;
+ case "inlineMath":
+ // The TeX source is the readable form once nothing typesets it.
+ out += node.value;
+ break;
+ case "html":
+ out += node.value;
+ break;
+ case "footnoteReference":
+ out += `[^${node.identifier}]`;
+ break;
+ case "linkReference":
+ case "imageReference":
+ out += "children" in node ? inline(node.children) : (node.label ?? node.identifier);
+ break;
+ default:
+ break;
+ }
+ }
+ return out;
+}
+
+/** A table row: its cells, in order, on one line. */
+function tableRow(row: TableRow): string {
+ return row.children.map((cell) => inline(cell.children)).join(" | ");
+}
+
+/** One block as its own lines: trailing blanks scrubbed, the indent it was drawn at kept. */
+function trimmed(text: string): string {
+ return text.replace(/[ \t]+$/gm, "").replace(/^\n+|\n+$/g, "");
+}
+
+/**
+ * One list item: its marker at the list's own indent, then its blocks on the following lines.
+ * They are joined with a single newline rather than a blank line — a blank line inside an item
+ * would read as the item ending, which is exactly where a nested list has to stay put.
+ */
+function listItem(item: ListItem, depth: number, mark: string): string {
+ const parts = item.children
+ .map((child) => block(child, depth + 1))
+ .map(trimmed)
+ .filter((text) => text !== "");
+ return `${INDENT.repeat(depth)}${mark}${parts.join("\n")}`;
+}
+
+/**
+ * Block content as text. `depth` is the list nesting it sits at, and only list rendering reads
+ * it: a paragraph, a heading, a table row and a code block are the same text wherever they
+ * appear.
+ */
+function block(node: BlockContent | DefinitionContent | RootContent, depth: number): string {
+ const pad = INDENT.repeat(depth);
+ switch (node.type) {
+ case "paragraph":
+ // Continuation lines of a wrapped paragraph line up under its first line, so a paragraph
+ // inside a list item stays visually part of that item.
+ return inline(node.children).split("\n").join(`\n${pad}`);
+ case "heading":
+ return inline(node.children);
+ case "code":
+ return node.value.replace(/\n$/, "");
+ case "math":
+ return node.value;
+ case "blockquote":
+ return children(node.children, depth);
+ case "list":
+ return node.children
+ .map((item, index) => listItem(item, depth, marker(node, index)))
+ .join("\n");
+ case "table":
+ return node.children.map(tableRow).join("\n");
+ case "footnoteDefinition":
+ return `[^${node.identifier}] ${children(node.children, depth)}`;
+ case "html":
+ return node.value;
+ // A rule, front matter, a link definition, and anything a later dialect adds carry nothing a
+ // reader needs.
+ case "thematicBreak":
+ case "definition":
+ case "yaml":
+ return "";
+ default:
+ return "";
+ }
+}
+
+/** Several blocks as text, blank-line separated — the shape every container here joins in. */
+function children(
+ nodes: (BlockContent | DefinitionContent | RootContent)[],
+ depth: number,
+): string {
+ return nodes
+ .map((node) => block(node, depth))
+ .map(trimmed)
+ .filter((text) => text !== "")
+ .join("\n\n");
+}
+
+/**
+ * A reply (or any Markdown) as plain text. Never throws — every string is a valid document — and
+ * a document with nothing readable in it (blank space, a single rule) comes back empty, which
+ * the caller reads as "there is nothing to copy".
+ */
+export function markdownToPlainText(markdown: string): string {
+ const tree = processor.parse(markdown);
+ return tree.type === "root"
+ ? children(tree.children, 0)
+ .replace(/\n{3,}/g, "\n\n")
+ .trim()
+ : "";
+}
diff --git a/packages/ui/src/components/icons/icons.ts b/packages/ui/src/components/icons/icons.ts
index 72308240..594269d6 100644
--- a/packages/ui/src/components/icons/icons.ts
+++ b/packages/ui/src/components/icons/icons.ts
@@ -237,6 +237,12 @@ export const ICONS = {
* the serifs that tell it apart from a plain bar. The mark for selecting text by hand.
*/
textCursor: "M9 5h6M12 5v14M9 19h6",
+ /**
+ * Three lines of text with the last one short: a paragraph of words and nothing around them —
+ * no `#`, no `**`, no fence. The mark for taking a reply as plain text. The short last line is
+ * what keeps it from being a hamburger: `menu` is the same three lines, all full width.
+ */
+ textLines: "M4 6h16M4 12h16M4 18h9",
// --- Messages and actions -----------------------------------------------------------------
diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts
index 8de68acd..8e1eb4d1 100644
--- a/packages/ui/src/index.ts
+++ b/packages/ui/src/index.ts
@@ -104,6 +104,7 @@ export * from "./components/overlays/toaster/toaster";
// `./highlighter` subpath, so no static import of this barrel reaches it.
export * from "./components/content/prose/prose";
export * from "./components/content/prose/markdown-plugins";
+export * from "./components/content/prose/plain-text";
export * from "./components/content/code-block/code-block";
export * from "./components/content/code-block/code-languages";
export * from "./components/content/typography/typography";
diff --git a/packages/ui/test/copy-button.test.ts b/packages/ui/test/copy-button.test.ts
index 7d534013..43b20dbd 100644
--- a/packages/ui/test/copy-button.test.ts
+++ b/packages/ui/test/copy-button.test.ts
@@ -61,6 +61,20 @@ describe("the copy feedback", () => {
);
});
+ it("marks a variant's button with the caller's glyph, which the check still replaces", () => {
+ const idle = renderStatic(
+ createElement(CopyButton, { text: "x", label: "Copy as plain text", glyph: ICONS.textLines }),
+ );
+ expect(idle).toContain(`d="${ICONS.textLines}"`);
+ expect(idle).not.toContain(`d="${ICONS.copy}"`);
+
+ const variant = renderStatic(
+ createElement(CopyCheckGlyph, { copied: true, glyph: ICONS.textLines }),
+ );
+ expect(variant).toContain(`d="${ICONS.check}"`);
+ expect(variant).not.toContain(`d="${ICONS.textLines}"`);
+ });
+
it("announces in the interface's words, or the caller's, once copied", () => {
expect(renderStatic(createElement(CopiedStatus, { copied: false }))).not.toContain("Copied");
expect(renderStatic(createElement(CopiedStatus, { copied: true }))).toContain(">Copied<");
diff --git a/packages/ui/test/plain-text.test.ts b/packages/ui/test/plain-text.test.ts
new file mode 100644
index 00000000..230254d7
--- /dev/null
+++ b/packages/ui/test/plain-text.test.ts
@@ -0,0 +1,108 @@
+/**
+ * Reading a reply as plain text: the conversation offers a copy of the reply both as the
+ * Markdown it was written in and as the words alone, and this is the second one.
+ *
+ * What each case pins is the difference between the two copies, so the cases are the constructs
+ * whose markers would otherwise land in a chat or a doc verbatim: a heading, emphasis, inline
+ * and fenced code, a link, a list, a table, a quote, a rule. Two of them argue for the parser
+ * rather than a substitution pass on the text and are worth keeping even if the rest is
+ * rewritten: a fenced block keeps its asterisks and backticks EXACTLY (that code is the content
+ * — stripping it would corrupt the one thing the reader came for), and a bare URL that
+ * remark-gfm autolinked does not gain an address it already is.
+ */
+import { describe, expect, it } from "vitest";
+import { markdownToPlainText } from "../src/components/content/prose/plain-text";
+
+describe("markdownToPlainText", () => {
+ it("takes the markers off headings and emphasis", () => {
+ expect(markdownToPlainText("# Title\n\nSome **bold**, *soft* and ~~struck~~ words.")).toBe(
+ "Title\n\nSome bold, soft and struck words.",
+ );
+ expect(markdownToPlainText("## Deeper\n\n### Deepest")).toBe("Deeper\n\nDeepest");
+ });
+
+ it("unwraps inline code but keeps a fenced block exactly as it was written", () => {
+ const md = [
+ "Run `npm test`, then:",
+ "",
+ "```sh",
+ "echo '*' | grep '**bold**' # never stripped",
+ "```",
+ "",
+ "Done.",
+ ].join("\n");
+ expect(markdownToPlainText(md)).toBe(
+ [
+ "Run npm test, then:",
+ "",
+ "echo '*' | grep '**bold**' # never stripped",
+ "",
+ "Done.",
+ ].join("\n"),
+ );
+ });
+
+ it("keeps an address behind a label, and a bare URL as the one address it is", () => {
+ expect(markdownToPlainText("See [the docs](https://example.com/docs).")).toBe(
+ "See the docs (https://example.com/docs).",
+ );
+ // remark-gfm autolinks a bare URL: its label IS the address, so it is written once.
+ expect(markdownToPlainText("See https://example.com/docs for more.")).toBe(
+ "See https://example.com/docs for more.",
+ );
+ });
+
+ it("carries an image as its description, or as its address when it has none", () => {
+ expect(markdownToPlainText("![a red swan](https://example.com/swan.png)")).toBe("a red swan");
+ expect(markdownToPlainText("![](https://example.com/swan.png)")).toBe(
+ "https://example.com/swan.png",
+ );
+ });
+
+ it("keeps list markers, numbering and nesting as layout", () => {
+ const md = ["- first", "- second", " - nested", "", "3. three", "4. four"].join("\n");
+ expect(markdownToPlainText(md)).toBe(
+ ["- first", "- second", " - nested", "", "3. three", "4. four"].join("\n"),
+ );
+ });
+
+ it("writes a table a row per line", () => {
+ const md = ["| Name | Size |", "| --- | --- |", "| a.md | 12 |", "| b.md | 3 |"].join("\n");
+ expect(markdownToPlainText(md)).toBe(["Name | Size", "a.md | 12", "b.md | 3"].join("\n"));
+ });
+
+ it("drops the markers of a quote, and a rule with nothing behind it", () => {
+ expect(markdownToPlainText("> quoted words\n> more of them\n\n---\n\nAfter.")).toBe(
+ "quoted words\nmore of them\n\nAfter.",
+ );
+ });
+
+ it("shows the TeX source where nothing typesets a formula, and leaves a dollar alone", () => {
+ // Inline math is written `\(…\)`, not `$…$`: single-dollar math is off in the shared pipeline
+ // (markdown-plugins.ts), so `$PATH` and a price stay the text they are.
+ expect(markdownToPlainText("The area is \\(a^2\\) here.\n\n$$\\int_0^1 x\\,dx$$")).toBe(
+ "The area is a^2 here.\n\n\\int_0^1 x\\,dx",
+ );
+ expect(markdownToPlainText("Set $PATH and $HOME first.")).toBe("Set $PATH and $HOME first.");
+ });
+
+ it("keeps a footnote reference with the definition's own words", () => {
+ // Not a construct this product's replies lean on, but the definition carries words, and
+ // dropping a node the reply wrote is the one thing this must never do.
+ expect(markdownToPlainText("A claim.[^1]\n\n[^1]: The source.")).toBe(
+ "A claim.[^1]\n\n[^1] The source.",
+ );
+ });
+
+ it("passes raw HTML through as its own characters", () => {
+ expect(markdownToPlainText("<b>kept</b> as written")).toBe("<b>kept</b> as written");
+ });
+
+ it("comes back empty when there is nothing to read", () => {
+ expect(markdownToPlainText("")).toBe("");
+ expect(markdownToPlainText(" \n\n ")).toBe("");
+ expect(markdownToPlainText("---")).toBe("");
+ // Padding lines are scrubbed, so a copied reply never opens or closes with blank space.
+ expect(markdownToPlainText("\n\n# Title\n\n\n\nBody\n\n")).toBe("Title\n\nBody");
+ });
+});
diff --git a/packages/web/e2e/reply-copy-plain.spec.mjs b/packages/web/e2e/reply-copy-plain.spec.mjs
new file mode 100644
index 00000000..9a49ee14
--- /dev/null
+++ b/packages/web/e2e/reply-copy-plain.spec.mjs
@@ -0,0 +1,86 @@
+/**
+ * A reply's two copy actions, in a real browser: the reply as the Markdown it was written in, and
+ * the same words as plain text — pasted where `| --- |` would otherwise show up literally.
+ * - 复制回复 writes the source: the table keeps its pipes and its alignment row.
+ * - 复制纯文本 writes the words with the markup taken out: no row of dashes, no pipe at a row's
+ * edge, and a bare URL that was autolinked still appearing once.
+ * - Each button names itself and confirms on its own (the copy glyph swaps to a check, the
+ * screen-reader region beside it says 已复制) only once the write landed.
+ * The mock's default branch drives it: one tool call, then the reply carrying the Markdown table
+ * (mock-llm.mjs).
+ */
+import { test, expect } from "@playwright/test";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const MOCK = process.env.MOCK_URL;
+const U = "replycopyuser";
+const P = "password123";
+const SENTENCE = "Command finished; the result looks as expected.";
+const TABLE_HEAD = "指标 | 标识 | 说明";
+const URL =
+ "https://example.com/penguin-harness/reports/2026-07/agent-session-0123456789abcdef0123456789abcdef/artifacts/deep-verification-run-with-a-very-long-descriptive-file-name-v3.html";
+
+/** The text currently on the clipboard. */
+const clipboard = (page) => page.evaluate(() => navigator.clipboard.readText());
+
+test("a reply copies as Markdown, and beside it as plain text", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ const projectId = (await (await page.request.get(`${BASE}/api/projects`)).json()).projects[0]
+ .projectId;
+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {
+ data: {
+ defaultModel: { provider: "custom", modelId: "claude-4-8" },
+ models: [
+ {
+ provider: "custom",
+ modelId: "claude-4-8",
+ apiKey: "sk-mock",
+ baseUrl: MOCK,
+ contextWindow: 200000,
+ },
+ ],
+ },
+ });
+ expect(put.ok(), "put models").toBeTruthy();
+ const sess = await (
+ await page.request.post(`${BASE}/api/projects/${projectId}/agents/default_agent/sessions`, {
+ data: { provider: "custom", modelId: "claude-4-8", approvalMode: "allow-all" },
+ })
+ ).json();
+
+ await page.goto(`${BASE}/chat/${sess.session.sessionId}`);
+ const composer = page.getByPlaceholder(/输入消息/);
+ await composer.waitFor();
+ await composer.fill("check the directory");
+ await page.getByRole("button", { name: "发送" }).click();
+ const reply = page.getByText(SENTENCE, { exact: true });
+ await expect(reply).toBeVisible({ timeout: 30_000 });
+
+ // Two copies sit at the reply's footer, and the plain-text one is announced as its own action.
+ const plainCopy = page.getByRole("button", { name: "复制纯文本" }).first();
+ await reply.hover();
+ await expect(plainCopy).toBeVisible();
+
+ // The Markdown copy is unchanged: the source, pipes and alignment row included.
+ await page.getByRole("button", { name: "复制回复" }).first().click();
+ const markdown = await clipboard(page);
+ expect(markdown).toContain(SENTENCE);
+ expect(markdown).toContain(`| ${TABLE_HEAD} |`);
+ expect(markdown).toContain("| --- | --- | --- |");
+
+ // The plain-text copy: the same reply, with the markup taken out. The footer copies the whole
+ // turn (the note sent before the tool call included), so the comparison is per construct.
+ await plainCopy.click();
+ const plain = await clipboard(page);
+ expect(plain).toContain(SENTENCE);
+ expect(plain).toContain(TABLE_HEAD);
+ expect(plain).not.toContain("| ---");
+ expect(plain.split("\n").some((line) => line.trimStart().startsWith("|"))).toBe(false);
+ // An autolinked bare URL keeps its one copy, rather than reading as "address (address)".
+ expect(plain.split(URL)).toHaveLength(2);
+ // Feedback follows the write: the check replaces this button's own glyph, and the live region
+ // beside it (a sibling of the button, never inside it) is what says so.
+ const announcement = page.locator('button[aria-label="复制纯文本"] + span[aria-live="polite"]');
+ await expect(announcement).toHaveText("已复制");
+});
diff --git a/packages/web/src/features/chat/task-stats-line.tsx b/packages/web/src/features/chat/task-stats-line.tsx
index 224be584..6db1e035 100644
--- a/packages/web/src/features/chat/task-stats-line.tsx
+++ b/packages/web/src/features/chat/task-stats-line.tsx
@@ -3,10 +3,12 @@
* **bottom-left** of the AI reply — input, output, output TPS, elapsed time, and cost (converted
* in real time from the current Model's pricing, hidden if no pricing is configured); all five
* share the same basis (this turn's usage), each expressed uniformly as icon + value (no text
- * labels); the reply timestamp and a copy button sit at the end (copies this turn's assistant
- * text, falling back to the stats themselves when there's no text), with the fork action to the
- * right of copy — forking asks for confirmation first (it duplicates the conversation into a new
- * Session up to this reply), while copy stays a plain immediate click. Below sm the row is slimmed
+ * labels); the reply timestamp and the copy buttons sit at the end (the first copies this turn's
+ * assistant text as the Markdown it was written in, falling back to the stats themselves when
+ * there's no text; the second copies the same words as plain text and appears only when there is
+ * a reply body to strip), with the fork action to the right of copy — forking asks for
+ * confirmation first (it duplicates the conversation into a new Session up to this reply), while
+ * copy stays a plain immediate click. Below sm the row is slimmed
* to fit the width: the TPS chip is dropped and cost/elapsed lose excess decimals (compact
* formatter variants); desktop shows all five, formatted as always.
* At ≥sm the whole line is invisible but takes up space by default, surfacing only on hovering
@@ -28,7 +30,14 @@
*/
import { useState } from "react";
import type { TracePosition } from "@lmliheng/penguin-server/api";
-import { ConfirmModal, CopyButton, Spinner, StatChip } from "@lmliheng/penguin-ui";
+import {
+ ConfirmModal,
+ CopyButton,
+ ICONS,
+ Spinner,
+ StatChip,
+ markdownToPlainText,
+} from "@lmliheng/penguin-ui";
import { formatTaskStats } from "../../lib/omni/task-stats";
import type { TaskStats } from "../../lib/omni/task-stats";
import {
@@ -149,8 +158,21 @@ export function TaskStatsLine({
</>
)}
</span>
- {/* Pinned at the row's end, outside the scrollable stats span. */}
+ {/* Pinned at the row's end, outside the scrollable stats span. Two copies, because a
+ reply travels to two kinds of destination: the Markdown as it was written (the copy
+ glyph), and the same words with the markup taken out (plain text) — for pasting where
+ `##` and `**` would otherwise show up literally. They are told apart by their glyphs,
+ since two copy icons side by side would name neither. */}
<CopyButton text={copyText} label={S.chat.copyReply} size="sm" className="shrink-0" />
+ {assistantText?.trim() && (
+ <CopyButton
+ text={() => markdownToPlainText(assistantText)}
+ label={S.chat.copyReplyPlain}
+ glyph={ICONS.textLines}
+ size="sm"
+ className="shrink-0"
+ />
+ )}
{/* Fork sits to the RIGHT of copy (review request): copy is the frequent action and
keeps its accustomed spot; the click only opens the confirmation below — the fork
request fires on Confirm, never directly. */}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 988343d9..509cba6b 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -3430,6 +3430,7 @@ export const en: Strings = {
approvalWaiting: "awaiting approval",
copyCode: "Copy code",
copyReply: "Copy reply",
+ copyReplyPlain: "Copy as plain text",
forkSession: "Fork chat from here",
forkSessionConfirmBody:
"This copies the conversation up to this reply into a new chat. The original chat stays unchanged.",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index cf07a84e..97e82979 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -3475,6 +3475,8 @@ export const zh = {
approvalWaiting: "待审批",
copyCode: "复制代码",
copyReply: "复制回复",
+ /** The reply again, with the Markdown taken out — for pasting where `##` and `**` would show. */
+ copyReplyPlain: "复制纯文本",
forkSession: "从这里分叉对话",
forkSessionConfirmBody: "将把这段对话(截至这条回复)复制为一个新对话,原对话保持不变。",
forkSessionConfirmAction: "分叉",
diff --git a/packages/web/test/reply-copy.test.ts b/packages/web/test/reply-copy.test.ts
new file mode 100644
index 00000000..728a2955
--- /dev/null
+++ b/packages/web/test/reply-copy.test.ts
@@ -0,0 +1,74 @@
+/**
+ * A reply's footer carries TWO copy actions (react-dom/server static markup, node env, no DOM):
+ * the reply as the Markdown it was written in (the copy glyph, as before), and the same words as
+ * plain text (its own glyph — three lines — since two copy icons side by side would name
+ * neither). The plain-text one appears only when there is a reply body to strip; with nothing
+ * said yet there is no second copy to offer, and the first falls back to the turn's stats.
+ *
+ * What each button hands the clipboard is decided at click time through the ui package's
+ * CopyButton, and markdownToPlainText's own rules are pinned in the ui package's
+ * plain-text.test.ts; the click itself is driven in the real browser by
+ * e2e/reply-copy-plain.spec.mjs.
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { ICONS } from "@lmliheng/penguin-ui";
+import { TaskStatsLine } from "../src/features/chat/task-stats-line";
+import { S, setActiveStrings, zh } from "../src/lib/strings";
+import { en } from "../src/lib/strings-en";
+
+// The theme and locale contexts throw outside their providers, and this footer reads a currency
+// and a locale out of them; only the strings it draws matter here.
+vi.mock("../src/state/theme", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../src/state/theme")>()),
+ useTheme: () => ({ currency: "USD" }),
+}));
+vi.mock("../src/state/locale", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../src/state/locale")>()),
+ useLocale: () => ({ locale: "zh" }),
+}));
+
+const REPLY = "## 结论\n\n**可以发了**。\n\n| 项 | 值 |\n| --- | --- |\n| 版本 | 0.3.6 |";
+
+const footer = (assistantText: string) =>
+ renderToStaticMarkup(createElement(TaskStatsLine, { stats: null, assistantText }));
+
+/** One button's markup, up to its closing tag. */
+function buttonFor(html: string, label: string): string {
+ const at = html.indexOf(`aria-label="${label}"`);
+ expect(at).toBeGreaterThan(-1);
+ return html.slice(at, html.indexOf("</button>", at));
+}
+
+afterEach(() => setActiveStrings(zh));
+
+describe("the reply footer's copy actions", () => {
+ it("offers the reply as Markdown, and beside it as plain text", () => {
+ const html = footer(REPLY);
+ const markdown = buttonFor(html, S.chat.copyReply);
+ const plain = buttonFor(html, S.chat.copyReplyPlain);
+
+ // Told apart by their marks, since neither button says anything on screen.
+ expect(markdown).toContain(`d="${ICONS.copy}"`);
+ expect(plain).toContain(`d="${ICONS.textLines}"`);
+ expect(plain).not.toContain(`d="${ICONS.copy}"`);
+ // Markdown first: the familiar action keeps its spot at the row's end.
+ expect(html.indexOf(`aria-label="${S.chat.copyReply}"`)).toBeLessThan(
+ html.indexOf(`aria-label="${S.chat.copyReplyPlain}"`),
+ );
+ });
+
+ it("leaves the plain-text copy out when the turn said nothing", () => {
+ const html = footer("");
+ expect(html).toContain(`aria-label="${S.chat.copyReply}"`);
+ expect(html).not.toContain(S.chat.copyReplyPlain);
+ });
+
+ it("names both actions in the interface's language", () => {
+ setActiveStrings(en);
+ const html = footer(REPLY);
+ expect(html).toContain(`aria-label="${en.chat.copyReply}"`);
+ expect(html).toContain(`aria-label="${en.chat.copyReplyPlain}"`);
+ });
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 313d0b5d..d929aa9b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -507,13 +507,22 @@ importers:
remark-math:
specifier: ^6.0.0
version: 6.0.0([email protected])
+ remark-parse:
+ specifier: ^11.0.0
+ version: 11.0.0([email protected])
shiki:
specifier: ^4.3.1
version: 4.3.1
+ unified:
+ specifier: ^11.0.5
+ version: 11.0.5
zustand:
specifier: ^5.0.15
version: 5.0.15(@types/[email protected])([email protected])
devDependencies:
+ '@types/mdast':
+ specifier: ^4.0.4
+ version: 4.0.4
'@types/node':
specifier: ^24.0.0
version: 24.13.3