DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(web): stop the copy button reporting a success that never happened
Bingxi Zhao (Frank)895d2cce2552
diff --git a/web/components/reading/workspace/ReadingCompanion.tsx b/web/components/reading/workspace/ReadingCompanion.tsxindex c63dd67ea..c0cccdb07 100644--- a/web/components/reading/workspace/ReadingCompanion.tsx+++ b/web/components/reading/workspace/ReadingCompanion.tsx@@ -53,6 +53,7 @@ import { useMeasuredHeight } from "@/hooks/useMeasuredHeight";import { useResearchOutlineContinuation } from "@/hooks/useResearchOutlineContinuation";import { buildChatOutline, scrollToChatTurn } from "@/lib/chat-outline";import { downloadChatMarkdown } from "@/lib/chat-export";+import { copyText } from "@/lib/clipboard";import { buildConversationNotebookSave } from "@/lib/conversation-notebook-save";import { setReadingViewport } from "@/lib/reading-turn-state";import { workspaceActionNeedsConfiguration } from "@/lib/workspace-mode";@@ -296,9 +297,10 @@ export function ReadingCompanion({[state.messages],);- const copyAssistantMessage = useCallback(async (content: string) => {- await navigator.clipboard.writeText(content);- }, []);+ const copyAssistantMessage = useCallback(+ (content: string) => copyText(content),+ [],+ );return (<aside className="absolute inset-y-0 right-0 z-30 flex w-[min(420px,100%)] min-h-0 min-w-0 flex-col bg-[var(--card)] shadow-[-18px_0_42px_rgba(0,0,0,.12)] dark:bg-[var(--background)] xl:static xl:w-auto xl:shadow-none">diff --git a/web/components/reading/workspace/dialogs.tsx b/web/components/reading/workspace/dialogs.tsxindex 47a9f9c0a..8011d2e81 100644--- a/web/components/reading/workspace/dialogs.tsx+++ b/web/components/reading/workspace/dialogs.tsx@@ -16,6 +16,8 @@ import { useTranslation } from "react-i18next";import { SessionAvatar } from "@/components/sidebar/SessionAvatar";import { type NotebookSummary, listNotebooks } from "@/lib/notebook-api";import { formatRelativeTime } from "@/lib/relative-time";+import { copyText } from "@/lib/clipboard";+import { notify } from "@/lib/notifications";import {type OrganizedReadingNotes,type ReadingConversation,@@ -389,7 +391,13 @@ export function OrganizedNotesDialog({</span><buttontype="button"- onClick={() => void navigator.clipboard.writeText(notes.markdown)}+ onClick={() =>+ void copyText(notes.markdown).catch(() =>+ notify(t("The clipboard is not available in this browser."), {+ tone: "error",+ }),+ )+ }className="flex items-center gap-1.5 rounded-lg px-2 py-1 hover:bg-[var(--muted)]"><Copy size={11} /> {t("Copy Markdown")}diff --git a/web/components/space/learning/MasteryStudy.tsx b/web/components/space/learning/MasteryStudy.tsxindex 16eb35e70..67d69e8f8 100644--- a/web/components/space/learning/MasteryStudy.tsx+++ b/web/components/space/learning/MasteryStudy.tsx@@ -40,6 +40,7 @@ import {type MasteryTopic,} from "@/lib/learning-api";import { notify } from "@/lib/notifications";+import { copyText } from "@/lib/clipboard";import { consumePendingPrompt } from "@/lib/pending-prompt";import { buildChatOutline, scrollToChatTurn } from "@/lib/chat-outline";import { buildConversationNotebookSave } from "@/lib/conversation-notebook-save";@@ -536,9 +537,10 @@ export function MasteryStudy({[pathId, setMasterySessionMode, state.sessionId, t],);- const copyAssistantMessage = useCallback(async (content: string) => {- if (content.trim()) await navigator.clipboard.writeText(content);- }, []);+ const copyAssistantMessage = useCallback(+ (content: string) => copyText(content),+ [],+ );if (!topic && !topicError) {return (diff --git a/web/features/chat/components/ChatWorkspace.tsx b/web/features/chat/components/ChatWorkspace.tsxindex 12b6f413c..1541c0a4b 100644--- a/web/features/chat/components/ChatWorkspace.tsx+++ b/web/features/chat/components/ChatWorkspace.tsx@@ -78,6 +78,7 @@ import {REPLY_NOT_DELIVERED,} from "@/lib/ask-user-state";import { notify } from "@/lib/notifications";+import { copyText } from "@/lib/clipboard";import { useChatAutoScroll } from "@/hooks/useChatAutoScroll";import { useContextBudget } from "@/hooks/useContextBudget";import { useMeasuredHeight } from "@/hooks/useMeasuredHeight";@@ -998,14 +999,13 @@ export default function ChatWorkspace() {return () => cancelAnimationFrame(frame);}, [awaitingUserCard, scrollToBottom, shouldAutoScrollRef]);- const copyAssistantMessage = useCallback(async (content: string) => {- if (!content.trim()) return;- try {- await navigator.clipboard.writeText(content);- } catch (error) {- console.error("Failed to copy assistant message:", error);- }- }, []);+ // Deliberately does not catch. `CopyActionButton` renders 已复制 off this+ // promise resolving, so swallowing the failure here is what made the button+ // announce a success that never happened — to screen readers included.+ const copyAssistantMessage = useCallback(+ (content: string) => copyText(content),+ [],+ );/* ---- URL-driven session loading ---- */const navigateToHome = useCallback(() => {diff --git a/web/features/chat/messages/ChatMessageList.tsx b/web/features/chat/messages/ChatMessageList.tsxindex fa2f8e049..850cb7cf4 100644--- a/web/features/chat/messages/ChatMessageList.tsx+++ b/web/features/chat/messages/ChatMessageList.tsx@@ -855,15 +855,23 @@ export function RoughActionButton({);}+/**+ * ``Promise<void>`` and not ``void | Promise<void>``: this button reports+ * success to the user, so it needs a handler that can tell it about failure.+ * A synchronously-void handler has no way to, which is how a swallowed+ * clipboard error came to be rendered as 已复制.+ */+type CopyHandler = (content: string) => Promise<void>;+export function CopyActionButton({content,onCopy,}: {content: string;- onCopy: (content: string) => void | Promise<void>;+ onCopy: CopyHandler;}) {const { t } = useTranslation();- const [copied, setCopied] = useState(false);+ const [outcome, setOutcome] = useState<"idle" | "copied" | "failed">("idle");const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);useEffect(() => {@@ -873,28 +881,49 @@ export function CopyActionButton({}, []);const handleClick = useCallback(() => {- void Promise.resolve(onCopy(content)).then(() => {- setCopied(true);+ const settle = (next: "copied" | "failed") => {+ setOutcome(next);if (timerRef.current) clearTimeout(timerRef.current);- timerRef.current = setTimeout(() => setCopied(false), 1600);- });+ timerRef.current = setTimeout(() => setOutcome("idle"), 1600);+ };+ // `Promise.resolve().then(() => onCopy(...))` rather than+ // `Promise.resolve(onCopy(...))`: the latter runs the handler outside the+ // chain, so a *synchronous* throw — which is exactly what reading+ // `navigator.clipboard.writeText` on an insecure origin does — escapes it.+ void Promise.resolve()+ .then(() => onCopy(content))+ .then(+ () => settle("copied"),+ () => settle("failed"),+ );}, [content, onCopy]);+ const label =+ outcome === "copied"+ ? t("Copied")+ : outcome === "failed"+ ? t("Could not copy")+ : t("Copy");+return (- <Tooltip label={copied ? t("Copied") : t("Copy")} side="top">+ <Tooltip label={label} side="top"><buttontype="button"onClick={handleClick}aria-live="polite"- aria-label={copied ? t("Copied") : t("Copy")}+ aria-label={label}className={`inline-flex items-center justify-center rounded-md p-1 transition-colors ${- copied+ outcome === "copied"? "text-[var(--primary)]"- : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/50 hover:text-[var(--foreground)]"+ : outcome === "failed"+ ? "text-[var(--destructive)]"+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/50 hover:text-[var(--foreground)]"}`}>- {copied ? (+ {outcome === "copied" ? (<Check size={15} strokeWidth={2} />+ ) : outcome === "failed" ? (+ <X size={15} strokeWidth={2} />) : (<Copy size={15} strokeWidth={1.5} />)}@@ -1150,7 +1179,7 @@ export const UserMessage = memo(function UserMessage({msg: ChatMessageItem;index: number;onPreviewAttachment?: (attachment: MessageAttachment) => void;- onCopy?: (content: string) => void | Promise<void>;+ onCopy?: CopyHandler;onEdit?: (messageId: number, newContent: string) => void;editDisabled?: boolean;siblingInfo?: SiblingInfo;@@ -1440,7 +1469,7 @@ export const ChatMessageList = memo(function ChatMessageList({isStreaming: boolean;sessionId?: string | null;language?: string;- onCopyAssistantMessage: (content: string) => void | Promise<void>;+ onCopyAssistantMessage: CopyHandler;onRegenerateMessage: () => void;onConfirmOutline?: (outline: Array<{ title: string; overview: string }>,diff --git a/web/features/knowledge/components/engines/EngineDetail.tsx b/web/features/knowledge/components/engines/EngineDetail.tsxindex 6f827d62b..1bdbcbe14 100644--- a/web/features/knowledge/components/engines/EngineDetail.tsx+++ b/web/features/knowledge/components/engines/EngineDetail.tsx@@ -51,6 +51,7 @@ import {type RagProviderSummary,} from "@/features/knowledge/api/engines";import { canApplyGraphRagModelCandidate } from "@/lib/graphrag-model-compatibility";+import { copyText } from "@/lib/clipboard";import {kbDocCount,kbProvider,@@ -205,7 +206,7 @@ function Section({function CopyableCommand({ command }: { command: string }) {const { t } = useTranslation();- const [copied, setCopied] = useState(false);+ const [outcome, setOutcome] = useState<"idle" | "copied" | "failed">("idle");return (<div className="flex items-center justify-between gap-2 rounded-lg border border-[var(--border)] bg-[var(--muted)]/40 px-3 py-2"><code className="truncate font-mono text-[12px] text-[var(--foreground)]">@@ -214,14 +215,28 @@ function CopyableCommand({ command }: { command: string }) {<buttontype="button"onClick={() => {- void navigator.clipboard?.writeText(command);- setCopied(true);- window.setTimeout(() => setCopied(false), 1500);+ // The write is awaited before the label changes. This used to be+ // `void navigator.clipboard?.writeText(...)` followed by an+ // unconditional `setCopied(true)` — where the `?.` meant a missing+ // Clipboard API did not even throw, and the label said 已复制 anyway.+ void copyText(command).then(+ () => setOutcome("copied"),+ () => setOutcome("failed"),+ );+ window.setTimeout(() => setOutcome("idle"), 1500);}}className="inline-flex shrink-0 items-center gap-1 rounded-md px-1.5 py-1 text-[11px] font-medium text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]">- {copied ? <Check className="h-3 w-3" /> : <Copy className="h-3 w-3" />}- {copied ? t("Copied") : t("Copy")}+ {outcome === "copied" ? (+ <Check className="h-3 w-3" />+ ) : (+ <Copy className="h-3 w-3" />+ )}+ {outcome === "copied"+ ? t("Copied")+ : outcome === "failed"+ ? t("Could not copy")+ : t("Copy")}</button></div>);diff --git a/web/lib/clipboard.ts b/web/lib/clipboard.tsnew file mode 100644index 000000000..43e689441--- /dev/null+++ b/web/lib/clipboard.ts@@ -0,0 +1,95 @@+/**+ * One way to put text on the clipboard, and one way to learn that it failed.+ *+ * Two facts make this worth its own module.+ *+ * The async Clipboard API does not exist outside a secure context, and a+ * plain-http origin is an ordinary way to run DeepTutor rather than an exotic+ * one: the launcher binds the web app to `0.0.0.0` while printing a+ * `localhost` URL, so anyone opening the same instance from another machine+ * on the LAN gets `http://<lan-ip>:3782` — where `navigator.clipboard` is+ * `undefined` and touching `.writeText` throws a `TypeError` synchronously.+ * `document.execCommand("copy")` still works there, which is the whole reason+ * to keep a deprecated call around.+ *+ * And `writeText` rejects for reasons that have nothing to do with the caller+ * — the document lost focus, the permission was denied. Callers kept+ * swallowing those rejections next to a checkmark that said 已复制.+ *+ * So the contract here is: **this rejects when the text did not reach the+ * clipboard.** A caller that wants to stay quiet can catch; a caller that+ * tells the user it worked cannot do so without it having worked.+ */++/**+ * The pre-Clipboard-API path: put the text in an off-screen field, select it,+ * and let the browser copy the selection.+ *+ * It must stay synchronous. `execCommand` is only permitted while the user+ * activation from the click is still live, and an `await` before it can spend+ * that activation — which is why {@link copyText} decides whether to try the+ * async API *before* awaiting anything.+ */+function copyViaSelection(text: string): boolean {+ if (typeof document === "undefined" || !document.body) return false;++ const field = document.createElement("textarea");+ field.value = text;+ field.setAttribute("readonly", "");+ // Off-screen, but still laid out: an element that is `display:none` or+ // `visibility:hidden` cannot hold a selection, so the copy would quietly+ // succeed at copying nothing.+ field.style.position = "fixed";+ field.style.top = "0";+ field.style.left = "-9999px";+ field.style.opacity = "0";+ field.style.pointerEvents = "none";++ const previouslyFocused = document.activeElement;+ document.body.appendChild(field);+ try {+ field.select();+ field.setSelectionRange(0, text.length);+ return document.execCommand("copy");+ } catch {+ return false;+ } finally {+ field.remove();+ // Duck-typed rather than `instanceof HTMLElement`: the check runs inside a+ // `finally`, and referencing a global that may not exist would replace the+ // real outcome with a ReferenceError.+ const focus = (previouslyFocused as { focus?: () => void } | null)?.focus;+ if (typeof focus === "function") focus.call(previouslyFocused);+ }+}++/**+ * Copy `text`, or reject saying why.+ *+ * Call it from inside the event handler for the user's click — both paths+ * depend on that click's user activation.+ */+export async function copyText(text: string): Promise<void> {+ if (!text.trim()) throw new Error("There is nothing to copy.");++ // Decided before the first `await`, deliberately — see `copyViaSelection`.+ const asyncApiAvailable =+ typeof navigator !== "undefined" &&+ Boolean(navigator.clipboard) &&+ typeof window !== "undefined" &&+ window.isSecureContext;++ if (asyncApiAvailable) {+ try {+ await navigator.clipboard.writeText(text);+ return;+ } catch {+ // Focus lost, permission denied, or a policy block. The selection path+ // sometimes still works, so it is worth one try before giving up.+ }+ }++ if (!copyViaSelection(text)) {+ throw new Error("The clipboard is not available in this browser.");+ }+}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex fa4e7ab47..91a122860 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -3994,5 +3994,9 @@"readiness.detail.redis_unreachable": "Redis is unreachable","readiness.detail.redis_not_configured": "not configured","readiness.detail.multiple_workers_require_redis": "more than one backend worker needs Redis coordination",- "readiness.detail.redis_available_but_memory_selected": "Redis is reachable — coordination could be switched to it"+ "readiness.detail.redis_available_but_memory_selected": "Redis is reachable — coordination could be switched to it",+ "Could not copy": "Could not copy",+ "The clipboard is not available in this browser.": "The clipboard is not available in this browser.",+ "attachments": "attachments",+ "references": "references"}diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 6ace29590..6f054b0cd 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -3994,5 +3994,9 @@"readiness.detail.redis_unreachable": "Redis 连不上","readiness.detail.redis_not_configured": "未配置","readiness.detail.multiple_workers_require_redis": "多进程后端必须用 Redis 协调",- "readiness.detail.redis_available_but_memory_selected": "Redis 可用,可以把轮次协调切到它"+ "readiness.detail.redis_available_but_memory_selected": "Redis 可用,可以把轮次协调切到它",+ "Could not copy": "复制失败",+ "The clipboard is not available in this browser.": "当前浏览器环境无法使用剪贴板。",+ "attachments": "附件",+ "references": "引用"}diff --git a/web/tests/clipboard.test.ts b/web/tests/clipboard.test.tsnew file mode 100644index 000000000..a2fd1b048--- /dev/null+++ b/web/tests/clipboard.test.ts@@ -0,0 +1,144 @@+import test from "node:test";+import assert from "node:assert/strict";++import { copyText } from "../lib/clipboard";++type GlobalName = "navigator" | "window" | "document";++/**+ * `globalThis.navigator` is an accessor on modern Node, so a plain assignment+ * throws. Define the property instead, and restore the original descriptor+ * afterwards so one case cannot leak into the next.+ */+function setGlobal(name: GlobalName, value: unknown): () => void {+ const previous = Object.getOwnPropertyDescriptor(globalThis, name);+ Object.defineProperty(globalThis, name, {+ value,+ configurable: true,+ writable: true,+ });+ return () => {+ if (previous) Object.defineProperty(globalThis, name, previous);+ else delete (globalThis as Record<string, unknown>)[name];+ };+}++/**+ * Stand in for the three browser objects `copyText` touches. Each field is+ * optional so a case can model an environment where one is simply absent —+ * which is the whole point: on a plain-http origin `navigator.clipboard` does+ * not exist.+ */+function withBrowser(+ parts: {+ clipboard?: { writeText: (text: string) => Promise<void> };+ isSecureContext?: boolean;+ execCommand?: (command: string) => boolean;+ },+ run: () => Promise<void>,+): Promise<void> {+ const appended: unknown[] = [];+ const restore = [+ setGlobal("navigator", parts.clipboard ? { clipboard: parts.clipboard } : {}),+ setGlobal("window", { isSecureContext: parts.isSecureContext ?? false }),+ setGlobal(+ "document",+ parts.execCommand+ ? {+ activeElement: null,+ body: { appendChild: (node: unknown) => void appended.push(node) },+ createElement: () => ({+ value: "",+ style: {},+ setAttribute: () => undefined,+ select: () => undefined,+ setSelectionRange: () => undefined,+ remove: () => undefined,+ }),+ execCommand: parts.execCommand,+ }+ : undefined,+ ),+ ];++ return run().finally(() => {+ for (const undo of restore.reverse()) undo();+ });+}++test("copyText rejects when there is nothing to copy", async () => {+ await assert.rejects(() => copyText(" "), /nothing to copy/i);+});++test("copyText uses the async Clipboard API in a secure context", async () => {+ const written: string[] = [];+ await withBrowser(+ {+ clipboard: {+ writeText: async (text: string) => void written.push(text),+ },+ isSecureContext: true,+ execCommand: () => {+ throw new Error("the selection fallback must not run here");+ },+ },+ async () => {+ await copyText("eigenvectors");+ },+ );+ assert.deepEqual(written, ["eigenvectors"]);+});++/**+ * The reported bug: reaching a DeepTutor instance over the LAN means a+ * plain-http origin, where `navigator.clipboard` is undefined. The old code+ * threw a TypeError here, swallowed it, and rendered 已复制 anyway.+ */+test("copyText falls back to the selection path on an insecure origin", async () => {+ const commands: string[] = [];+ await withBrowser(+ {+ isSecureContext: false,+ execCommand: (command: string) => {+ commands.push(command);+ return true;+ },+ },+ async () => {+ await copyText("eigenvectors");+ },+ );+ assert.deepEqual(commands, ["copy"]);+});++test("copyText rejects when neither path can write", async () => {+ await withBrowser(+ { isSecureContext: false, execCommand: () => false },+ async () => {+ await assert.rejects(() => copyText("eigenvectors"), /not available/i);+ },+ );+});++/** A rejected `writeText` (lost focus, denied permission) still gets one try. */+test("copyText falls back when the async API rejects", async () => {+ const commands: string[] = [];+ await withBrowser(+ {+ clipboard: {+ writeText: async () => {+ throw new Error("Document is not focused");+ },+ },+ isSecureContext: true,+ execCommand: (command: string) => {+ commands.push(command);+ return true;+ },+ },+ async () => {+ await copyText("eigenvectors");+ },+ );+ assert.deepEqual(commands, ["copy"]);+});diff --git a/web/tests/integration/chat-messages.spec.tsx b/web/tests/integration/chat-messages.spec.tsxindex af751ac6b..f992297a4 100644--- a/web/tests/integration/chat-messages.spec.tsx+++ b/web/tests/integration/chat-messages.spec.tsx@@ -8,7 +8,7 @@ initI18n("en");describe("chat message feature", () => {it("renders a user row with keyboard-accessible message actions", async () => {- const copy = vi.fn();+ const copy = vi.fn(async () => undefined);const user = userEvent.setup();render(<ChatMessageList@@ -28,5 +28,65 @@ describe("chat message feature", () => {expect(screen.getByText("Explain eigenvectors")).toBeVisible();await user.click(screen.getByRole("button", { name: "Copy" }));expect(copy).toHaveBeenCalledWith("Explain eigenvectors");+ expect(await screen.findByRole("button", { name: "Copied" })).toBeVisible();+ });++ // The button used to infer success from the handler's promise *resolving*,+ // so a swallowed clipboard error rendered 已复制 — and, because the label is+ // the aria-label on an aria-live element, announced it to screen readers.+ it("reports a failed copy instead of claiming success", async () => {+ const copy = vi.fn(async () => {+ throw new Error("clipboard unavailable");+ });+ const user = userEvent.setup();+ render(+ <ChatMessageList+ messages={[+ {+ id: 1,+ role: "user",+ content: "Explain eigenvectors",+ parentMessageId: null,+ },+ ]}+ isStreaming={false}+ onCopyAssistantMessage={copy}+ onRegenerateMessage={() => undefined}+ />,+ );+ await user.click(screen.getByRole("button", { name: "Copy" }));+ expect(+ await screen.findByRole("button", { name: "Could not copy" }),+ ).toBeVisible();+ expect(screen.queryByRole("button", { name: "Copied" })).toBeNull();+ });++ // A synchronous throw is what reading `navigator.clipboard.writeText` does+ // on an insecure origin, and `Promise.resolve(onCopy(content))` ran the+ // handler outside the chain, so that throw escaped the button entirely.+ it("catches a handler that throws synchronously", async () => {+ const copy = vi.fn(() => {+ throw new Error("navigator.clipboard is undefined");+ }) as unknown as (content: string) => Promise<void>;+ const user = userEvent.setup();+ render(+ <ChatMessageList+ messages={[+ {+ id: 1,+ role: "user",+ content: "Explain eigenvectors",+ parentMessageId: null,+ },+ ]}+ isStreaming={false}+ onCopyAssistantMessage={copy}+ onRegenerateMessage={() => undefined}+ />,+ );+ await user.click(screen.getByRole("button", { name: "Copy" }));+ expect(+ await screen.findByRole("button", { name: "Could not copy" }),+ ).toBeVisible();});});