Skip to content

World's first open-source enterprise world model.

Let a chat answer and each code block in it be copied, also where the page has no Clipboard API (#954)

Maya Kidbd3ed5bb2494
diff --git a/web/src/clipboard.test.ts b/web/src/clipboard.test.ts
new file mode 100644
index 00000000..08f2ca93
--- /dev/null
+++ b/web/src/clipboard.test.ts
@@ -0,0 +1,100 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { copyText } from "./clipboard";
+
+afterEach(() => vi.unstubAllGlobals());
+
+interface FakeArea {
+ value: string;
+ readOnly: boolean;
+ attached: boolean;
+ selected: boolean;
+ style: Record<string, string>;
+ setAttribute(name: string): void;
+ focus(): void;
+ select(): void;
+ remove(): void;
+}
+
+/** node 里没有 DOM:一个只够 copyText 用的 document。`execCommand` 记下它被调的那一刻
+ * 页面上选中的是哪段字——那正是浏览器会放进剪贴板的东西 */
+function page(result: boolean | "throw") {
+ const before = { focus: vi.fn() };
+ const areas: FakeArea[] = [];
+ const copied: (string | undefined)[] = [];
+ vi.stubGlobal("document", {
+ activeElement: before,
+ body: {
+ appendChild: (area: FakeArea) => {
+ area.attached = true;
+ },
+ },
+ createElement: (): FakeArea => {
+ const area: FakeArea = {
+ value: "",
+ readOnly: false,
+ attached: false,
+ selected: false,
+ style: {},
+ setAttribute: (name) => {
+ if (name === "readonly") area.readOnly = true;
+ },
+ focus: () => {},
+ select: () => {
+ area.selected = true;
+ },
+ remove: () => {
+ area.attached = false;
+ },
+ };
+ areas.push(area);
+ return area;
+ },
+ execCommand: (command: string) => {
+ if (command === "copy") copied.push(areas.find((a) => a.attached && a.selected)?.value);
+ if (result === "throw") throw new Error("not allowed here");
+ return result;
+ },
+ });
+ return { before, areas, copied };
+}
+
+describe("copyText", () => {
+ it("writes through the Clipboard API when the page has it", async () => {
+ const writeText = vi.fn().mockResolvedValue(undefined);
+ vi.stubGlobal("navigator", { clipboard: { writeText } });
+ const { copied } = page(true);
+ expect(await copyText("SELECT 1")).toBe(true);
+ expect(writeText).toHaveBeenCalledWith("SELECT 1");
+ expect(copied).toEqual([]);
+ });
+
+ it("copies a selected text area where the API does not exist, as over plain http", async () => {
+ vi.stubGlobal("navigator", {});
+ const { before, areas, copied } = page(true);
+ expect(await copyText("SELECT 1")).toBe(true);
+ expect(copied).toEqual(["SELECT 1"]);
+ // 那个看不见的 textarea 用完就拿掉,焦点还给原来那个元素
+ expect(areas).toHaveLength(1);
+ expect(areas[0].readOnly).toBe(true);
+ expect(areas[0].attached).toBe(false);
+ expect(before.focus).toHaveBeenCalled();
+ });
+
+ it("falls back the same way when the API refuses", async () => {
+ vi.stubGlobal("navigator", {
+ clipboard: { writeText: vi.fn().mockRejectedValue(new Error("denied")) },
+ });
+ const { copied } = page(true);
+ expect(await copyText("SELECT 1")).toBe(true);
+ expect(copied).toEqual(["SELECT 1"]);
+ });
+
+ it("says it did not copy when neither way works", async () => {
+ for (const result of [false, "throw"] as const) {
+ vi.stubGlobal("navigator", {});
+ const { areas } = page(result);
+ expect(await copyText("SELECT 1")).toBe(false);
+ expect(areas.every((a) => !a.attached)).toBe(true);
+ }
+ });
+});
diff --git a/web/src/clipboard.ts b/web/src/clipboard.ts
new file mode 100644
index 00000000..5d9d5dea
--- /dev/null
+++ b/web/src/clipboard.ts
@@ -0,0 +1,37 @@
+/** 把一段文字放进剪贴板,交回放没放成。
+ *
+ * `navigator.clipboard` 只在安全上下文里有:https,或者 localhost。在局域网里用
+ * http 打开的部署上它是 undefined——自托管最常见的那种打开方式——这时候直接调它,
+ * 按钮按了什么也不发生,也不报错。那里退回 `execCommand("copy")`:选中一个看不见的
+ * textarea 再复制。这个接口已经不推荐了,但浏览器都还认,而且它只在剪贴板 API
+ * 用不了的时候才走到。两样都不成就交回 false,由调用方说出来,不静默。 */
+export async function copyText(text: string): Promise<boolean> {
+ try {
+ if (navigator.clipboard?.writeText) {
+ await navigator.clipboard.writeText(text);
+ return true;
+ }
+ } catch {
+ // 权限被拒、页面没有焦点:走下面的老办法
+ }
+ const focused = document.activeElement as HTMLElement | null;
+ const area = document.createElement("textarea");
+ area.value = text;
+ // 只读:手机上不弹键盘;固定在视口里、透明:不把页面滚走,也看不见
+ area.setAttribute("readonly", "");
+ area.style.position = "fixed";
+ area.style.top = "0";
+ area.style.left = "0";
+ area.style.opacity = "0";
+ document.body.appendChild(area);
+ try {
+ area.focus();
+ area.select();
+ return document.execCommand("copy");
+ } catch {
+ return false;
+ } finally {
+ area.remove();
+ focused?.focus?.();
+ }
+}
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 487419ae..a33820b3 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -824,6 +824,11 @@ export const en = {
noSources: "No sources cited",
// 预览浮窗右上角那条出路:看完这一段还想看整篇的人走这里
openOriginal: "Open original",
+ // 复制(#936):回答整段一个,代码块各一个
+ copyAnswer: "Copy answer",
+ copyCode: "Copy code",
+ copied: "Copied",
+ copyFailed: "Could not copy. Select the text and copy it by hand.",
},
graph: {
// 还没判出类型的实体(0009)。不是一个类,是"这一格还空着"
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index 232fe3c9..fa02e1c0 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -757,6 +757,10 @@ export const zh: Strings = {
cancel: "取消",
noSources: "未引用任何来源",
openOriginal: "打开原文",
+ copyAnswer: "复制回答",
+ copyCode: "复制代码",
+ copied: "已复制",
+ copyFailed: "无法复制,请选中文字后手动复制。",
},
graph: {
untyped: "未分类",
diff --git a/web/src/pages/Chat.tsx b/web/src/pages/Chat.tsx
index 6fdcd59f..cf9bd515 100644
--- a/web/src/pages/Chat.tsx
+++ b/web/src/pages/Chat.tsx
@@ -41,6 +41,7 @@ import { S } from "../i18n";
import { rehypeCitations } from "../citations";
import { followsBottom } from "../chatScroll";
import { chatMarkdown, SourceList, SourcesProvider } from "./chatCitations";
+import { CopyButton } from "./chatCopy";
import { toast } from "../toast";
import {
DropdownMenu,
@@ -1007,6 +1008,13 @@ function TurnView({ turn, live }: { turn: Turn; live?: boolean }) {
{answeredWithoutSources(turn, !!live) && (
<div className="mt-2 text-small text-ink-2">{S.ask.noSources}</div>
)}
+ {/* 回答上的动作(#936),同样等说完了才出。复制的是存下的 Markdown,
+ 角标 `[n]` 照写——表格、代码块贴到别处还是原样 */}
+ {!live && turn.content && (
+ <div className="mt-2 flex items-center">
+ <CopyButton label={S.ask.copyAnswer} text={() => turn.content} />
+ </div>
+ )}
</div>
</SourcesProvider>
);
diff --git a/web/src/pages/chatCitations.tsx b/web/src/pages/chatCitations.tsx
index 42f0061e..19b91c83 100644
--- a/web/src/pages/chatCitations.tsx
+++ b/web/src/pages/chatCitations.tsx
@@ -11,6 +11,7 @@ import { S } from "../i18n";
import { useKbId } from "../kb";
import { originLabel } from "../origin";
import { CiteChip, CiteMark, CiteRow, PreviewCard } from "../ui/citation";
+import { CodeBlock } from "./chatCopy";
/** 这一轮回答的来源。
*
@@ -47,6 +48,8 @@ export const chatMarkdown: Components = {
</>
);
},
+ // 代码块带一个复制(#936):人从回答里抄走的,最常见的就是 SQL
+ pre: ({ node: _node, ...rest }) => <CodeBlock {...rest} />,
};
function InlineCite({ n }: { n: number }) {
diff --git a/web/src/pages/chatCopy.tsx b/web/src/pages/chatCopy.tsx
new file mode 100644
index 00000000..1f346de1
--- /dev/null
+++ b/web/src/pages/chatCopy.tsx
@@ -0,0 +1,48 @@
+/* 对话里的复制(#936):一段回答一个,每个代码块一个。
+ 控件是外壳里的 IconButton;复制本身走 copyText,局域网里用 http 打开的部署上
+ 剪贴板 API 不存在,它会退回老办法,两样都不成就说出来。 */
+import { useEffect, useRef, useState, type ComponentProps } from "react";
+import { Check, Copy } from "lucide-react";
+import { copyText } from "../clipboard";
+import { S } from "../i18n";
+import { toast } from "../toast";
+import { IconButton } from "../ui";
+
+/** 复制按钮。`text` 在按下时才取:代码块的字要从渲染好的 DOM 里读 */
+export function CopyButton({ label, text }: { label: string; text: () => string }) {
+ const [copied, setCopied] = useState(false);
+ useEffect(() => {
+ if (!copied) return;
+ const timer = setTimeout(() => setCopied(false), 1500);
+ return () => clearTimeout(timer);
+ }, [copied]);
+ return (
+ <IconButton
+ size="sm"
+ label={copied ? S.ask.copied : label}
+ onClick={async () => {
+ if (await copyText(text())) setCopied(true);
+ else toast.error(S.ask.copyFailed);
+ }}
+ >
+ {copied ? <Check size={12} /> : <Copy size={12} />}
+ </IconButton>
+ );
+}
+
+/** 回答里的代码块,右上角一个复制。复制的是代码本身:`<pre>` 里的字,
+ * 高亮拆出来的那些 span 不影响它;围栏内容末尾那个换行不带走 */
+export function CodeBlock(props: ComponentProps<"pre">) {
+ const pre = useRef<HTMLPreElement>(null);
+ return (
+ <div className="u-codeblock">
+ <pre {...props} ref={pre} />
+ <div className="absolute top-1 right-1">
+ <CopyButton
+ label={S.ask.copyCode}
+ text={() => (pre.current?.textContent ?? "").replace(/\n$/, "")}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/styles.css b/web/src/styles.css
index 1b6ded15..8e95da6f 100644
--- a/web/src/styles.css
+++ b/web/src/styles.css
@@ -1614,6 +1614,17 @@ a:hover > .u-mark-arrow {
background: transparent;
padding: 0;
}
+/* 代码块外面的一层,复制按钮贴它的右上角(#936)。上下外边距从 pre 挪到这一层:
+ 它才是正文的直接子元素,`> :first-child` / `> :last-child` 的收边要管得到它。
+ 右内边距给按钮让位,短行不会被它盖住 */
+.u-chat-prose .u-codeblock {
+ position: relative;
+ margin: 0.5em 0;
+}
+.u-chat-prose .u-codeblock pre {
+ margin: 0;
+ padding-right: 2.75em;
+}
.u-chat-prose table {
border-collapse: collapse;
margin: 0.5em 0;
diff --git a/web/tests/chat-view.test.mjs b/web/tests/chat-view.test.mjs
index fb0f980c..43d85d15 100644
--- a/web/tests/chat-view.test.mjs
+++ b/web/tests/chat-view.test.mjs
@@ -90,10 +90,12 @@ test(
t.after(() => server.close());
await server.listen();
const origin = `http://127.0.0.1:${server.httpServer.address().port}`;
- async function open(path, custom) {
+ async function open(path, custom, init) {
const context = await browser.newContext();
const page = await context.newPage();
page.setDefaultTimeout(10000);
+ // Runs in the page before the app, e.g. to replace browser APIs
+ if (init) await page.addInitScript(init);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/api/**", async (route) => {
@@ -806,5 +808,52 @@ test(
await f.close();
}
});
+ await t.test("an answer and each of its code blocks can be copied, with or without the Clipboard API", async () => {
+ const sql = "SELECT month, sum(amount) AS revenue FROM orders GROUP BY month";
+ const answer = `Revenue by month:\n\n\`\`\`sql\n${sql}\n\`\`\`\n\nIt grew every month.`;
+ // A page served over https or localhost has navigator.clipboard
+ const withApi = () => {
+ Object.defineProperty(navigator, "clipboard", {
+ configurable: true,
+ value: { writeText: async (text) => { window.__copied = text; } },
+ });
+ };
+ // A base opened over plain http on a local network does not; record what
+ // execCommand("copy") would copy: the selected text of a text area
+ const withoutApi = () => {
+ Object.defineProperty(navigator, "clipboard", { configurable: true, value: undefined });
+ document.execCommand = (command) => {
+ const area = [...document.querySelectorAll("textarea")].find(
+ (a) => a.selectionEnd > a.selectionStart,
+ );
+ if (command !== "copy" || !area) return false;
+ window.__copied = area.value.slice(area.selectionStart, area.selectionEnd);
+ return true;
+ };
+ };
+ for (const init of [withApi, withoutApi]) {
+ const f = await open(
+ "/kb/one/chat/a",
+ async (route, p) => {
+ if (p.endsWith("/conversations/a")) {
+ await route.fulfill({ json: { messages: [message(answer)] } });
+ return true;
+ }
+ },
+ init,
+ );
+ try {
+ await f.page.getByText("It grew every month.", { exact: true }).waitFor();
+ await f.page.getByRole("button", { name: "Copy code", exact: true }).click();
+ await f.page.getByRole("button", { name: "Copied", exact: true }).waitFor();
+ assert.equal(await f.page.evaluate(() => window.__copied), sql, init.name);
+ await f.page.getByRole("button", { name: "Copy answer", exact: true }).click();
+ assert.equal(await f.page.evaluate(() => window.__copied), answer, init.name);
+ assert.deepEqual(f.errors, [], init.name);
+ } finally {
+ await f.close();
+ }
+ }
+ });
},
);