A local-first multi-agent app development platform, built on PenguinHarness
fix(web): copy works on a plain-HTTP origin, and the check means it happened (#523)
Myriad-Dreamin76ead1f81b93
diff --git a/changelog/unreleased/2026-08-27-copy-on-plain-http.md b/changelog/unreleased/2026-08-27-copy-on-plain-http.mdnew file mode 100644index 00000000..7935935e--- /dev/null+++ b/changelog/unreleased/2026-08-27-copy-on-plain-http.md@@ -0,0 +1,19 @@+# Copy works on a plain-HTTP origin, and the check means it happened++- **Date:** 2026-08-27+- **Type:** fix+- **Scope:** `web`+- **PR:** [#523](https://github.com/Prism-Shadow/penguin-harness/pull/523)+- **Issue:** [#468](https://github.com/Prism-Shadow/penguin-harness/issues/468)++[中文版](2026-08-27-copy-on-plain-http.zh.md)++Every copy control in the Web App — a reply, a user message, a code block, a Session id, an Agent State path, a terminal selection, a copy row in a menu — reached for the async Clipboard API alone, which browsers expose only in a secure context. On a plain-HTTP origin that is not localhost, the shape a non-loopback `HOST` bind serves, the write was a no-op while the control still flashed its check (or its toast) and announced a copy to screen readers: the text went nowhere and the control said it had landed. Writes now go through the `copy-to-clipboard` package, which falls back to the document's own copy command where the Clipboard API is missing or refused, and the check, the tooltip, the announcement and the toast all wait for the write to report that it succeeded.++## Details++- Every copy control, the terminal's copy-selection keys and a program's own copy (OSC 52) call one module, `packages/web/src/lib/clipboard.ts`, which alone imports the package; a test asserts no other module under `packages/web/src` writes to `navigator.clipboard` or imports the package.+- The absent-API path reaches the document's copy command without suspending, inside the click's own task, because that command is only honoured while a user gesture is in progress.+- The element the fallback borrows is fixed-positioned and clipped to nothing, so selecting it cannot scroll the page; it is removed whether the copy succeeds or not, and the page's selection and the focused input — the terminal's, when copying a terminal selection — are handed back afterwards.+- A copy the browser refuses outright leaves the control idle instead of showing the check, so the copy can be retried rather than being reported as done. The package's `window.prompt` last resort stays off.+- Terminal paste was left as it was: `Ctrl+V`, `Ctrl+Shift+V` and `Shift+Insert` ride the browser's native paste event, which involves no clipboard permission.diff --git a/changelog/unreleased/2026-08-27-copy-on-plain-http.zh.md b/changelog/unreleased/2026-08-27-copy-on-plain-http.zh.mdnew file mode 100644index 00000000..4b25fe73--- /dev/null+++ b/changelog/unreleased/2026-08-27-copy-on-plain-http.zh.md@@ -0,0 +1,19 @@+# 纯 HTTP 源下复制可用,对勾代表复制真的发生了++- **Date:** 2026-08-27+- **Type:** fix+- **Scope:** `web`+- **PR:** [#523](https://github.com/Prism-Shadow/penguin-harness/pull/523)+- **Issue:** [#468](https://github.com/Prism-Shadow/penguin-harness/issues/468)++[English](2026-08-27-copy-on-plain-http.md)++Web App 里的每一个复制控件——回复、用户消息、代码块、Session id、Agent State 路径、终端选区、菜单里的复制行——都只走异步 Clipboard API,而浏览器仅在安全上下文中提供它。在非 localhost 的纯 HTTP 源上(也就是把 `HOST` 绑到非回环地址后所提供的形态),写入是一次空操作,控件却照样闪出对勾(或弹出 toast)、并向屏幕阅读器播报已复制:文本哪儿也没去,控件却说它到位了。现在写入交给 `copy-to-clipboard` 包,在 Clipboard API 缺失或被拒时退到文档自带的复制命令;对勾、tooltip、读屏播报与 toast 都改为等写入报告成功之后才出现。++## 细节++- 所有复制控件、终端的「复制所选」按键以及终端里程序自己发起的复制(OSC 52)都调用同一个模块 `packages/web/src/lib/clipboard.ts`,只有它导入该包;一个测试断言 `packages/web/src` 下再无其他模块向 `navigator.clipboard` 写入或导入该包。+- API 缺失这条路径不经挂起、就在点击自身的任务内到达文档的复制命令,因为该命令只在用户手势进行中才被接受。+- 回退借用的元素采用 fixed 定位并裁成零尺寸,选中它不会滚动页面;无论复制成败它都会被移除,页面原有的选区与获得焦点的输入框(复制终端选区时即终端自己的输入框)随后归还。+- 浏览器彻底拒绝的复制让控件停在空闲态而不显示对勾,于是可以重试,而不是被报告为已完成。该包的 `window.prompt` 兜底保持关闭。+- 终端粘贴维持原样:`Ctrl+V`、`Ctrl+Shift+V` 与 `Shift+Insert` 走浏览器原生 paste 事件,不涉及剪贴板权限。diff --git a/packages/web/package.json b/packages/web/package.jsonindex 811ac321..7af5edec 100644--- a/packages/web/package.json+++ b/packages/web/package.json@@ -20,6 +20,7 @@"@xterm/addon-fit": "^0.10.0","@xterm/addon-web-links": "^0.11.0","@xterm/xterm": "^5.5.0",+ "copy-to-clipboard": "^4.0.2","katex": "^0.16.47","react": "^19.1.0","react-dom": "^19.1.0",diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex cb28a4bc..b2a0ccc0 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -156,7 +156,7 @@ import {} from "../ui/group-list";import type { GroupMode } from "../ui/group-list";import { toastError, toastInfo, toastSuccess } from "../ui/toast";-import { writeClipboard } from "../ui/copy-button";+import { writeClipboard } from "../../lib/clipboard";import { Truncated } from "../ui/truncated";import { Badge } from "../ui/badge";import {@@ -3010,10 +3010,10 @@ function SessionRow({rename: onRename,// The copy affordance's feedback normally rides on the button itself (copy-button.tsx),// which a menu row cannot do: the row acts and the panel closes under it. A toast is- // the confirmation that survives that, and it says the same word.+ // the confirmation that survives that, and it says the same word — once the write+ // has landed.copy: (x) => {- writeClipboard(x.sessionId);- toastSuccess(S.common.copied);+ void writeClipboard(x.sessionId).then((ok) => ok && toastSuccess(S.common.copied));},messaging: onMessaging,archive: onToggleArchive,diff --git a/packages/web/src/components/ui/copy-button.tsx b/packages/web/src/components/ui/copy-button.tsxindex 4d4a9ef9..45534f8e 100644--- a/packages/web/src/components/ui/copy-button.tsx+++ b/packages/web/src/components/ui/copy-button.tsx@@ -2,8 +2,9 @@* Copy-to-clipboard button and the hook behind it — the single place the app's "copy"* affordance and its feedback live, so every copy control behaves the same:*- * - the write is optimistic (an insecure context or denied permission must not leave the- * control stuck), matching the clipboard convention used across the chat views;+ * - the feedback follows the WRITE: the check appears only once the text has actually+ * reached the clipboard (writeClipboard reports that), so a copy the browser refused+ * never reads as one that succeeded;* - the feedback is ALWAYS shown AT THE BUTTON, and it is the icon alone: copy swaps to* the check for COPIED_MS and the tooltip flips to "已复制" (#312 — no transient* "已复制" text is rendered, and the feedback never replaces an unrelated label/title@@ -13,6 +14,7 @@* region beside itself — that is the screen-reader half of the same feedback.*/import { useEffect, useRef, useState } from "react";+import { writeClipboard } from "../../lib/clipboard";import { S } from "../../lib/strings";import { STAT_ICONS } from "../../lib/stat-icons";import { GlyphIcon } from "./glyph-icon";@@ -20,15 +22,10 @@ import { GlyphIcon } from "./glyph-icon";/** How long the copied state (check icon + flipped tooltip) stays after a click. */const COPIED_MS = 1500;-/** Best-effort clipboard write (never throws; no-op where the API is unavailable). */-export function writeClipboard(text: string): void {- void navigator.clipboard?.writeText(text);-}-/**- * Transient "just copied" flag: `flash()` writes the text and turns `copied` on for- * COPIED_MS. Exposed for the caller whose copy trigger is not a plain CopyButton- * (e.g. a text button rendering CopyCheckGlyph next to its label); most callers+ * Transient "just copied" flag: `flash()` writes the text and, if the write landed, turns+ * `copied` on for COPIED_MS. Exposed for the caller whose copy trigger is not a plain+ * CopyButton (e.g. a text button rendering CopyCheckGlyph next to its label); most callers* should use CopyButton directly.*/export function useCopied(): { copied: boolean; flash: (text: string) => void } {@@ -47,13 +44,17 @@ export function useCopied(): { copied: boolean; flash: (text: string) => void }[],);const flash = (text: string) => {- writeClipboard(text);- setCopied(true);- if (resetTimer.current !== null) clearTimeout(resetTimer.current);- resetTimer.current = setTimeout(() => {- resetTimer.current = null;- setCopied(false);- }, COPIED_MS);+ void writeClipboard(text).then((ok) => {+ // A refused write shows nothing rather than a check: the control returns to idle, so+ // the copy can simply be retried — there is no state to be stuck in.+ if (!ok) return;+ setCopied(true);+ if (resetTimer.current !== null) clearTimeout(resetTimer.current);+ resetTimer.current = setTimeout(() => {+ resetTimer.current = null;+ setCopied(false);+ }, COPIED_MS);+ });};return { copied, flash };}diff --git a/packages/web/src/features/chat/stream-selection-menu.tsx b/packages/web/src/features/chat/stream-selection-menu.tsxindex 26a7a789..e476de08 100644--- a/packages/web/src/features/chat/stream-selection-menu.tsx+++ b/packages/web/src/features/chat/stream-selection-menu.tsx@@ -45,7 +45,7 @@ import {import type { ComposerReference } from "../../lib/workspace-tree";import { useAuth } from "../../state/auth";import { useRowContextMenu } from "../../components/ui/context-menu";-import { writeClipboard } from "../../components/ui/copy-button";+import { writeClipboard } from "../../lib/clipboard";import { Dropdown } from "../../components/ui/dropdown";import {ADD_TO_CHAT_ICON,@@ -97,8 +97,7 @@ export function SelectionMenuRows({type="button"className={overflowMenuRowClass}onClick={() => {- writeClipboard(selection.text);- toastSuccess(S.common.copied);+ void writeClipboard(selection.text).then((ok) => ok && toastSuccess(S.common.copied));onDone(selection);}}>@@ -185,8 +184,7 @@ export function LinkMenuRows({type="button"className={overflowMenuRowClass}onClick={run(() => {- writeClipboard(href);- toastSuccess(S.common.copied);+ void writeClipboard(href).then((ok) => ok && toastSuccess(S.common.copied));})}>{overflowMenuGlyph(LINK_ICON)}diff --git a/packages/web/src/features/chat/workspace-browser.tsx b/packages/web/src/features/chat/workspace-browser.tsxindex f8771611..e317a64b 100644--- a/packages/web/src/features/chat/workspace-browser.tsx+++ b/packages/web/src/features/chat/workspace-browser.tsx@@ -57,6 +57,7 @@ import { apiErrorText } from "../../lib/api-error";import { isDesktopShellWindow } from "../../lib/account-menu";import { useShortcutLabel } from "../../lib/shortcuts/use-keymap";import { joinWorkspacePath } from "../../lib/file-path";+import { writeClipboard } from "../../lib/clipboard";import { dropRegionAction, isFileDrag } from "../../lib/file-drop";import type { DragSignal } from "../../lib/file-drop";import { MB_BYTES, splitBySize } from "../../lib/upload-limits";@@ -102,12 +103,7 @@ import { isContextMenuKey, isLongPressPointer } from "../../lib/context-menu";import { Button } from "../../components/ui/button";import { ConfirmModal } from "../../components/ui/confirm-modal";import { useRowContextMenu } from "../../components/ui/context-menu";-import {- CopiedStatus,- CopyCheckGlyph,- useCopied,- writeClipboard,-} from "../../components/ui/copy-button";+import { CopiedStatus, CopyCheckGlyph, useCopied } from "../../components/ui/copy-button";import { Dropdown } from "../../components/ui/dropdown";import { EmptyState } from "../../components/ui/empty-state";import { GlyphIcon } from "../../components/ui/glyph-icon";@@ -1505,9 +1501,9 @@ export function WorkspaceBrowser({const copyPath = (target: FileMenuTarget): void => {// A menu row cannot carry the copy button's own at-the-control feedback: the row acts and// the panel closes out from under it. A toast is the confirmation that survives that, and- // it says the same word (sidebar.tsx's copy-id row does the same).- writeClipboard(target.path);- toastSuccess(S.common.copied);+ // it says the same word (sidebar.tsx's copy-id row does the same) — only once the write+ // has landed.+ void writeClipboard(target.path).then((ok) => ok && toastSuccess(S.common.copied));};const addToChat = (target: FileMenuTarget): void => {diff --git a/packages/web/src/features/chat/workspace-finder.tsx b/packages/web/src/features/chat/workspace-finder.tsxindex 5a020023..150efd5a 100644--- a/packages/web/src/features/chat/workspace-finder.tsx+++ b/packages/web/src/features/chat/workspace-finder.tsx@@ -26,6 +26,7 @@ import type {import type { DesktopPrivacyPane, DirListResponse } from "@prismshadow/penguin-server/api";import * as api from "../../api/endpoints";import { ApiError } from "../../api/client";+import { writeClipboard } from "../../lib/clipboard";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";import { isContextMenuKey, isLongPressPointer } from "../../lib/context-menu";@@ -40,7 +41,6 @@ import { useSessions } from "../../state/sessions";import { Modal } from "../../components/ui/modal";import { Button } from "../../components/ui/button";import { useRowContextMenu } from "../../components/ui/context-menu";-import { writeClipboard } from "../../components/ui/copy-button";import { Dropdown } from "../../components/ui/dropdown";import { GlyphIcon } from "../../components/ui/glyph-icon";import { CLOCK_ICON, FOLDER_ICON, FOLDER_OPEN_ICON } from "../../components/ui/group-list";@@ -551,8 +551,7 @@ export function WorkspaceFinder({case "copyPath":// A menu row cannot show the copy button's own feedback — the panel closes out from// under it — so a toast confirms, as the Files panel's copy-path row does.- writeClipboard(target.path);- toastSuccess(S.common.copied);+ void writeClipboard(target.path).then((ok) => ok && toastSuccess(S.common.copied));break;case "refresh":refresh();diff --git a/packages/web/src/features/company/org-session-groups.tsx b/packages/web/src/features/company/org-session-groups.tsxindex 5e2bb7eb..f81309c9 100644--- a/packages/web/src/features/company/org-session-groups.tsx+++ b/packages/web/src/features/company/org-session-groups.tsx@@ -41,7 +41,7 @@ import { useLiveSessionStatuses } from "../../state/sessions";import { AgentAvatar } from "../../components/ui/agent-avatar";import { Button } from "../../components/ui/button";import { useRowContextMenu } from "../../components/ui/context-menu";-import { writeClipboard } from "../../components/ui/copy-button";+import { writeClipboard } from "../../lib/clipboard";import { Dropdown } from "../../components/ui/dropdown";import { FolderSection, Icon } from "../../components/ui/group-list";import { CloseIcon, MESSAGING_RELAY_ICON } from "../../components/ui/icons";@@ -168,9 +168,9 @@ function DeskRow({}if (action === "copy") {// The panel closes under the click, so the confirmation is a toast rather than- // feedback on the row that ran it — the development list's rule for the same action.- writeClipboard(sessionId);- toastSuccess(S.common.copied);+ // feedback on the row that ran it — the development list's rule for the same action —+ // and it appears only once the write has landed.+ void writeClipboard(sessionId).then((ok) => ok && toastSuccess(S.common.copied));}};/**diff --git a/packages/web/src/features/terminal/terminal-view.tsx b/packages/web/src/features/terminal/terminal-view.tsxindex 858bd7e5..c3fb699c 100644--- a/packages/web/src/features/terminal/terminal-view.tsx+++ b/packages/web/src/features/terminal/terminal-view.tsx@@ -17,6 +17,7 @@ import "@xterm/xterm/css/xterm.css";import type { ITheme, Terminal as XTerminal } from "@xterm/xterm";import { TerminalOpcode, decodeFrame, encodeFrame, encodeResize } from "./terminal-frames";import { LinkClickTracker, openTerminalLink, positionFromPointer } from "./terminal-links";+import { writeClipboard } from "../../lib/clipboard";import { useTheme } from "../../state/theme";import { currentPlatform } from "../../lib/shortcuts/platform";import { keymap } from "../../lib/shortcuts/store";@@ -324,8 +325,9 @@ export function TerminalView({term.loadAddon(new ClipboardAddon({readText: () => Promise.resolve(""),- writeText: (_selection, text) =>- navigator.clipboard?.writeText(text).catch(() => {}) ?? Promise.resolve(),+ writeText: async (_selection, text) => {+ await writeClipboard(text);+ },}),);termRef.current = term;@@ -370,7 +372,7 @@ export function TerminalView({const copySelection = (): void => {const selection = term.getSelection();if (!selection) return;- void navigator.clipboard?.writeText(selection).catch(() => {});+ void writeClipboard(selection);term.clearSelection();};/** Async-clipboard paste (the paths where no native paste event exists). */diff --git a/packages/web/src/lib/clipboard.ts b/packages/web/src/lib/clipboard.tsnew file mode 100644index 00000000..3f6df518--- /dev/null+++ b/packages/web/src/lib/clipboard.ts@@ -0,0 +1,28 @@+/**+ * Clipboard writes for the whole Web App — the one place that knows the async Clipboard+ * API is not always there.+ *+ * `navigator.clipboard` is secure-context-only: it is `undefined` on a plain-HTTP origin+ * that is not localhost, which is exactly the shape a non-loopback `HOST` bind serves (a+ * LAN address, a remote install reached at `http://<host>:7364`). Reaching straight for+ * it there writes nothing at all, so every copy affordance goes through this entry.+ *+ * The write itself is `copy-to-clipboard`'s: the Clipboard API in a secure context, and+ * otherwise (or when the API refuses) a hidden, out-of-layout element selected and copied+ * with the document's own copy command — reached without suspending, inside the click's+ * own task, because that command is only honoured while a user gesture is in progress —+ * with the page's selection and focused input handed back afterwards. The module stays so+ * callers never name the package or its options, and a later change of implementation+ * touches this file alone.+ */+import copy from "copy-to-clipboard";++/**+ * Copies `text`, resolving to whether it actually reached the clipboard. Never rejects, and+ * never reports a write it did not make — the callers show their "copied" feedback on this+ * result. The library's `window.prompt` last resort stays off (its default): a copy that+ * failed shows no check, not an unexpected dialog.+ */+export function writeClipboard(text: string): Promise<boolean> {+ return copy(text);+}diff --git a/packages/web/test/clipboard.test.ts b/packages/web/test/clipboard.test.tsnew file mode 100644index 00000000..6e68c2a2--- /dev/null+++ b/packages/web/test/clipboard.test.ts@@ -0,0 +1,329 @@+/**+ * writeClipboard unit tests: the copy path that has to work on the origins this app is+ * actually served from.+ *+ * `navigator.clipboard` is secure-context-only, so it is absent on every plain-HTTP origin+ * that is not localhost — a LAN bind, a remote install opened at `http://<host>:7364`. The+ * entry hands the write to `copy-to-clipboard`, and the three groups below pin three+ * different things:+ *+ * - the entry's contract, against a module double: the text goes to the library as is,+ * its boolean comes back as is, and its `window.prompt` last resort stays off;+ * - the library's behaviour, against the REAL library with only `window`, `navigator`+ * and `document` replaced: these are the properties this app chose it for, so an+ * upgrade that changes one of them fails here rather than in a browser;+ * - the seam itself, against the source text: a copy affordance that reaches for+ * `navigator.clipboard.writeText` on its own would reintroduce exactly the silent no-op+ * this module exists to prevent, and nothing in a node-only suite would notice+ * (context-menu.test.ts convention).+ */+import { readFileSync, readdirSync } from "node:fs";+import { dirname, join, relative, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++type WriteClipboard = (text: string) => Promise<boolean>;++/** A fresh import of the entry, so a module double (or its removal) takes effect. */+async function loadEntry(): Promise<WriteClipboard> {+ vi.resetModules();+ return (await import("../src/lib/clipboard")).writeClipboard;+}++afterEach(() => {+ vi.unstubAllGlobals();+ vi.doUnmock("copy-to-clipboard");+ vi.resetModules();+});++describe("writeClipboard: the entry's contract", () => {+ const copy =+ vi.fn<(text: string, options?: { fallbackToPrompt?: boolean }) => Promise<boolean>>();++ beforeEach(() => {+ copy.mockReset();+ vi.doMock("copy-to-clipboard", () => ({ default: copy }));+ });++ it("hands the text to the library unchanged and returns its true", async () => {+ copy.mockResolvedValue(true);+ const writeClipboard = await loadEntry();++ await expect(writeClipboard(" reply\ttext\n")).resolves.toBe(true);+ expect(copy).toHaveBeenCalledTimes(1);+ expect(copy.mock.calls[0]?.[0]).toBe(" reply\ttext\n");+ });++ it("returns the library's false as is", async () => {+ copy.mockResolvedValue(false);+ const writeClipboard = await loadEntry();++ await expect(writeClipboard("x")).resolves.toBe(false);+ });++ it("leaves the library's prompt fallback off", async () => {+ copy.mockResolvedValue(false);+ const writeClipboard = await loadEntry();++ await writeClipboard("x");+ expect(copy.mock.calls[0]?.[1]?.fallbackToPrompt).toBeFalsy();+ });+});++interface FakeElement {+ tagName: string;+ textContent: string;+ style: Record<string, string>;+ parentElement: null;+ addEventListener(): void;+}++interface FakeRange {+ node: FakeElement | null;+ selectNodeContents(node: FakeElement): void;+}++interface FakeDom {+ /** The document's copy command calls, each with what the selection held at that moment. */+ execCalls: { command: string; selected: (FakeElement | null)[] }[];+ appended: FakeElement[];+ /** Elements still attached to the body. */+ attached: FakeElement[];+ /** The page's own selection, before any copy. */+ pageRange: FakeRange;+ ranges: FakeRange[];+ /** Focus history of the input that had focus before the copy. */+ focusLog: string[];+}++/**+ * Installs the three globals the library touches. The page starts with one selected range+ * and a focused textarea (xterm's input), so the library's hand-back is observable.+ */+function stubDom(opts: {+ secure: boolean;+ clipboard?: { writeText: (text: string) => Promise<void> };+ exec?: () => boolean;+}): FakeDom {+ const range = (): FakeRange => ({+ node: null,+ selectNodeContents(node) {+ this.node = node;+ },+ });+ const pageRange = range();+ const dom: FakeDom = {+ execCalls: [],+ appended: [],+ attached: [],+ pageRange,+ ranges: [pageRange],+ focusLog: [],+ };+ const focused = {+ tagName: "TEXTAREA",+ parentElement: null,+ blur: () => dom.focusLog.push("blur"),+ focus: () => dom.focusLog.push("focus"),+ };+ const selection = {+ type: "Range",+ get rangeCount() {+ return dom.ranges.length;+ },+ getRangeAt: (i: number) => dom.ranges[i],+ addRange: (r: FakeRange) => dom.ranges.push(r),+ removeRange: (r: FakeRange) => {+ dom.ranges = dom.ranges.filter((x) => x !== r);+ },+ removeAllRanges: () => {+ dom.ranges = [];+ },+ };+ vi.stubGlobal("window", { isSecureContext: opts.secure, prompt: vi.fn() });+ vi.stubGlobal("navigator", opts.clipboard ? { clipboard: opts.clipboard } : {});+ vi.stubGlobal("document", {+ activeElement: focused,+ fullscreenElement: null,+ body: {+ appendChild(el: FakeElement) {+ dom.appended.push(el);+ dom.attached.push(el);+ return el;+ },+ removeChild(el: FakeElement) {+ dom.attached = dom.attached.filter((x) => x !== el);+ return el;+ },+ },+ createElement: (tagName: string): FakeElement => ({+ tagName: tagName.toUpperCase(),+ textContent: "",+ style: {},+ parentElement: null,+ addEventListener() {},+ }),+ createRange: range,+ getSelection: () => selection,+ execCommand(command: string) {+ dom.execCalls.push({ command, selected: dom.ranges.map((r) => r.node) });+ return (opts.exec ?? (() => true))();+ },+ });+ return dom;+}++describe("writeClipboard: the library's behaviour contract", () => {+ it("reaches the copy command without suspending on a non-secure origin", async () => {+ const dom = stubDom({ secure: false });+ const writeClipboard = await loadEntry();++ // Deliberately not awaited: the copy command has to have run by the time the call+ // returns, inside the click's own task, not on some later turn of the microtask queue.+ const result = writeClipboard("reply text");+ expect(dom.execCalls.map((c) => c.command)).toEqual(["copy"]);+ await expect(result).resolves.toBe(true);+ });++ it("copies exactly the text, from an element kept out of layout", async () => {+ const dom = stubDom({ secure: false });+ const writeClipboard = await loadEntry();++ await writeClipboard("line one\nline two");+ const mark = dom.appended[0];+ expect(mark?.textContent).toBe("line one\nline two");+ expect(dom.execCalls[0]?.selected).toEqual([mark]);+ expect(mark?.style.position).toBe("fixed");+ expect(mark?.style.clip).toBe("rect(0, 0, 0, 0)");+ });++ it("resolves false, not a rejection, when the copy command reports failure", async () => {+ const dom = stubDom({ secure: false, exec: () => false });+ const writeClipboard = await loadEntry();++ await expect(writeClipboard("x")).resolves.toBe(false);+ expect(dom.execCalls).toHaveLength(1);+ });++ it("resolves false, not a rejection, when the copy command throws — and never prompts", async () => {+ stubDom({+ secure: false,+ exec: () => {+ throw new Error("blocked");+ },+ });+ const writeClipboard = await loadEntry();++ await expect(writeClipboard("x")).resolves.toBe(false);+ expect(+ (window as unknown as { prompt: ReturnType<typeof vi.fn> }).prompt,+ ).not.toHaveBeenCalled();+ });++ it.each([+ ["succeeds", () => true],+ ["fails", () => false],+ [+ "throws",+ () => {+ throw new Error("blocked");+ },+ ],+ ])("removes the borrowed element when the copy %s", async (_label, exec) => {+ const dom = stubDom({ secure: false, exec });+ const writeClipboard = await loadEntry();++ await writeClipboard("x");+ expect(dom.appended).toHaveLength(1);+ expect(dom.attached).toEqual([]);+ });++ it.each([+ ["succeeds", () => true],+ [+ "throws",+ () => {+ throw new Error("blocked");+ },+ ],+ ])(+ "hands the page's selection and the focused input back when the copy %s",+ async (_label, exec) => {+ const dom = stubDom({ secure: false, exec });+ const writeClipboard = await loadEntry();++ await writeClipboard("x");+ expect(dom.ranges).toEqual([dom.pageRange]);+ expect(dom.focusLog).toEqual(["blur", "focus"]);+ },+ );++ it("uses the Clipboard API in a secure context, and runs no copy command", async () => {+ const writeText = vi.fn(async (_text: string) => {});+ const dom = stubDom({ secure: true, clipboard: { writeText } });+ const writeClipboard = await loadEntry();++ await expect(writeClipboard("hello")).resolves.toBe(true);+ expect(writeText).toHaveBeenCalledWith("hello");+ expect(dom.execCalls).toEqual([]);+ expect(dom.appended).toEqual([]);+ });++ it("falls back to the copy command when the Clipboard API refuses the write", async () => {+ const dom = stubDom({+ secure: true,+ clipboard: {+ writeText: async () => {+ throw new Error("NotAllowedError");+ },+ },+ });+ const writeClipboard = await loadEntry();++ await expect(writeClipboard("x")).resolves.toBe(true);+ expect(dom.execCalls.map((c) => c.command)).toEqual(["copy"]);+ });+});++const SRC = resolve(dirname(fileURLToPath(import.meta.url)), "../src");+const ENTRY = join(SRC, "lib", "clipboard.ts");++function sourceFiles(dir: string): string[] {+ return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {+ const full = join(dir, entry.name);+ if (entry.isDirectory()) return sourceFiles(full);+ return /\.tsx?$/.test(entry.name) ? [full] : [];+ });+}++/** Clipboard writes (`writeText` / `write`, optional chaining included); `readText` is not one. */+const CLIPBOARD_WRITE = /navigator\s*\.\s*clipboard[\s\S]{0,40}?\.\s*write(?:Text)?\s*\(/;+const LIBRARY_IMPORT = /from\s+["']copy-to-clipboard["']|import\(\s*["']copy-to-clipboard["']\s*\)/;++function offenders(pattern: RegExp): string[] {+ return sourceFiles(SRC)+ .filter((file) => file !== ENTRY)+ .filter((file) => pattern.test(readFileSync(file, "utf8")))+ .map((file) => relative(SRC, file));+}++describe("clipboard writes go through one entry", () => {+ it("has no other module writing to navigator.clipboard", () => {+ expect(offenders(CLIPBOARD_WRITE)).toEqual([]);+ });++ it("has no other module importing copy-to-clipboard", () => {+ // Not vacuous: the entry itself is the one import the pattern must see.+ expect(LIBRARY_IMPORT.test(readFileSync(ENTRY, "utf8"))).toBe(true);+ expect(offenders(LIBRARY_IMPORT)).toEqual([]);+ });++ it("leaves reads alone: the terminal's mouse paste still reads the Clipboard API", () => {+ const reads = sourceFiles(SRC).filter((file) =>+ /navigator\s*\.\s*clipboard[\s\S]{0,40}?\.\s*readText\s*\(/.test(readFileSync(file, "utf8")),+ );+ expect(reads.map((file) => relative(SRC, file))).toContain(+ join("features", "terminal", "terminal-view.tsx"),+ );+ });+});diff --git a/packages/web/test/copy-button.test.ts b/packages/web/test/copy-button.test.tsnew file mode 100644index 00000000..7cd0f339--- /dev/null+++ b/packages/web/test/copy-button.test.ts@@ -0,0 +1,110 @@+/**+ * The copy button's feedback follows the WRITE: the check (and the tooltip's flip to the+ * copied label) appears only once writeClipboard reports the text reached the clipboard,+ * and a refused write leaves the control idle. clipboard.test.ts pins the entry itself; this+ * pins the one place its answer is consumed, so dropping the `if (!ok) return;` guard in+ * useCopied (back to an unconditional check) fails here.+ *+ * vitest runs node-only here (`environment: "node"`, no jsdom), so nothing mounts the+ * component: React's hooks are replaced by a minimal slot store — useState / useRef keep+ * their value across calls in call order, useEffect is inert (it only arms the unmount+ * cleanup) — and CopyButton is called as a plain function, its button's onClick driven+ * directly and the button re-read on the next "render". Both directions are asserted, or a+ * button that never shows the check would pass too.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { ReactElement, ReactNode } from "react";+import { CopyButton } from "../src/components/ui/copy-button";+import { S } from "../src/lib/strings";++/** Hook slots in call order, the cursor rewound on each render, and every value `copied` was set to. */+const hooks = vi.hoisted(() => ({+ slots: [] as unknown[],+ cursor: 0,+ copiedSets: [] as unknown[],+}));++vi.mock("react", async (importOriginal) => {+ const actual = await importOriginal<typeof import("react")>();+ return {+ ...actual,+ useState: <T>(initial: T) => {+ const i = hooks.cursor++;+ if (!(i in hooks.slots)) hooks.slots[i] = initial;+ const set = (value: T) => {+ hooks.slots[i] = value;+ hooks.copiedSets.push(value);+ };+ return [hooks.slots[i] as T, set];+ },+ useRef: <T>(initial: T) => {+ const i = hooks.cursor++;+ if (!(i in hooks.slots)) hooks.slots[i] = { current: initial };+ return hooks.slots[i];+ },+ useEffect: () => {},+ };+});++/** The clipboard entry's answer for the next write (its own behaviour is clipboard.test.ts's). */+const writeClipboard = vi.hoisted(() => vi.fn<(text: string) => Promise<boolean>>());++vi.mock("../src/lib/clipboard", () => ({ writeClipboard }));++type Button = ReactElement<{ title: string; onClick: () => void }>;++const LABEL = "Copy session id";++/** One render of the button, returning the <button> element (the fragment's first child). */+function render(): Button {+ hooks.cursor = 0;+ const fragment = CopyButton({ text: "sess-42", label: LABEL }) as ReactElement<{+ children: ReactNode[];+ }>;+ return fragment.props.children[0] as Button;+}++/** Lets the write's resolution and the `.then` behind it run. */+async function settle() {+ for (let i = 0; i < 3; i++) await Promise.resolve();+}++beforeEach(() => {+ vi.useFakeTimers();+ hooks.slots = [];+ hooks.copiedSets = [];+});++afterEach(() => {+ vi.useRealTimers();+ writeClipboard.mockReset();+});++describe("CopyButton: the check follows the write", () => {+ it("shows no check when the write is refused", async () => {+ writeClipboard.mockResolvedValue(false);+ const idle = render();+ expect(idle.props.title).toBe(LABEL);++ idle.props.onClick();+ await settle();++ expect(writeClipboard).toHaveBeenCalledTimes(1);+ expect(writeClipboard.mock.calls[0]?.[0]).toBe("sess-42");+ expect(hooks.copiedSets).not.toContain(true);+ expect(render().props.title).toBe(LABEL);+ });++ it("shows the check once the write landed, and clears it after the window", async () => {+ writeClipboard.mockResolvedValue(true);+ render().props.onClick();+ await settle();++ expect(hooks.copiedSets).toEqual([true]);+ expect(render().props.title).toBe(S.common.copied);++ vi.runAllTimers();+ expect(hooks.copiedSets).toEqual([true, false]);+ expect(render().props.title).toBe(LABEL);+ });+});diff --git a/packages/web/test/stream-selection-menu.test.ts b/packages/web/test/stream-selection-menu.test.tsindex 7c64b809..4abaf280 100644--- a/packages/web/test/stream-selection-menu.test.ts+++ b/packages/web/test/stream-selection-menu.test.ts@@ -3,9 +3,9 @@* element tree for their click handlers — node env, no DOM): the rows it draws, and what each* does with the selection or the link it was opened on. "Add to conversation" stages a chip* through the composer's control — the same `addReference` the Files panel stages through —- * and that chip shows the excerpt rather than a path; Copy writes the selection and confirms- * with a toast, the menu-row convention. A link's rows open it in the built-in browser or- * outside the app, or copy its address.+ * and that chip shows the excerpt rather than a path; Copy writes the selection through the+ * clipboard entry and confirms with a toast, the menu-row convention — once the write landed.+ * A link's rows open it in the built-in browser or outside the app, or copy its address.** Reading the selection and the link off the page and anchoring the panel are DOM work this* environment cannot run; the rules deciding them are pinned in selection-menu.test.ts.@@ -51,6 +51,11 @@ vi.mock("../src/features/builtin-browser/browser-actions", async (importOriginal};});+/** The clipboard entry's answer for the next write (its own behaviour is clipboard.test.ts's). */+const writeClipboard = vi.hoisted(() => vi.fn<(text: string) => Promise<boolean>>());++vi.mock("../src/lib/clipboard", () => ({ writeClipboard }));+const EXCERPT = "Run the migration first.\nThen restart the server so it picks up the new schema.";/** A selection as the stream captures it: the text as selected (a trailing newline included). */@@ -81,6 +86,7 @@ afterEach(() => {setActiveStrings(zh);toasts.length = 0;openedInBrowser.length = 0;+ writeClipboard.mockReset();vi.unstubAllGlobals();});@@ -156,17 +162,30 @@ describe("Add to conversation", () => {});describe("Copy", () => {- it("writes the selection as it was selected, and confirms with a toast", () => {- const writeText = vi.fn(async () => {});- vi.stubGlobal("navigator", { clipboard: { writeText } });+ it("writes the selection as it was selected, and confirms with a toast", async () => {+ writeClipboard.mockResolvedValue(true);+ const onDone = vi.fn();+ const copy = rows({ selection: SELECTION, onAddExcerpt: () => {}, onDone }).find(+ (row) => label(row) === S.common.copy,+ );+ copy!.props.onClick();++ expect(writeClipboard).toHaveBeenCalledExactlyOnceWith(SELECTION.text);+ expect(onDone).toHaveBeenCalledExactlyOnceWith(SELECTION);+ await vi.waitFor(() => expect(toasts).toEqual([S.common.copied]));+ });++ it("raises no toast when the write was refused", async () => {+ writeClipboard.mockResolvedValue(false);const onDone = vi.fn();const copy = rows({ selection: SELECTION, onAddExcerpt: () => {}, onDone }).find((row) => label(row) === S.common.copy,);copy!.props.onClick();+ await writeClipboard.mock.results[0]?.value;+ await Promise.resolve();- expect(writeText).toHaveBeenCalledExactlyOnceWith(SELECTION.text);- expect(toasts).toEqual([S.common.copied]);+ expect(toasts).toEqual([]);expect(onDone).toHaveBeenCalledExactlyOnceWith(SELECTION);});});@@ -245,16 +264,15 @@ describe("LinkMenuRows", () => {expect(onDone).toHaveBeenCalledOnce();});- it("copies the address and confirms with a toast, as Copy does", () => {- const writeText = vi.fn(async () => {});- vi.stubGlobal("navigator", { clipboard: { writeText } });+ it("copies the address and confirms with a toast, as Copy does", async () => {+ writeClipboard.mockResolvedValue(true);const onDone = vi.fn();const row = linkRows({ href: HREF, builtinBrowser: true, desktopShell: true, onDone }).find((r) => label(r) === S.chat.linkMenu.copyLink,);row!.props.onClick();- expect(writeText).toHaveBeenCalledExactlyOnceWith(HREF);- expect(toasts).toEqual([S.common.copied]);+ expect(writeClipboard).toHaveBeenCalledExactlyOnceWith(HREF);expect(onDone).toHaveBeenCalledOnce();+ await vi.waitFor(() => expect(toasts).toEqual([S.common.copied]));});});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 2c6a004b..d3e093d0 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -505,6 +505,9 @@ importers:'@xterm/xterm':specifier: ^5.5.0version: 5.5.0+ copy-to-clipboard:+ specifier: ^4.0.2+ version: 4.0.2katex:specifier: ^0.16.47version: 0.16.47@@ -2499,6 +2502,9 @@ packages:resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==}engines: {node: '>= 0.6'}+ resolution: {integrity: sha512-gklSft7IuhriZKHKpuoA1fpJSLPNgvUMWMo5BlnzAJm0zNKnznoSv23IjtNqclx8eKi6ZcdvFFzYEER/+U1LoQ==}+resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==}@@ -6607,6 +6613,8 @@ snapshots:+ [email protected]: {}+