Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(chat): checkpoint the transcript context menu surface
vastsaa5565e69e6aa
diff --git a/apps/desktop/src/components/ContextMenu.tsx b/apps/desktop/src/components/ContextMenu.tsxnew file mode 100644index 000000000..7362e2ca1--- /dev/null+++ b/apps/desktop/src/components/ContextMenu.tsx@@ -0,0 +1,293 @@+/**+ * A pointer-anchored context menu for renderer surfaces.+ *+ * `AnchoredMenu` places a surface against a control's rect, which a right-click+ * cannot provide, so this is the pointer-anchored member of the same family. It+ * follows the same rules every other renderer-owned dropdown follows: it+ * portals to `document.body` as a viewport-fixed layer (a transformed or+ * `overflow: hidden` ancestor cannot trap it), it is measured before it is+ * revealed so it never flashes at the viewport origin, it clamps inside the+ * viewport, and it closes on an outside press, Escape, or a scroll of anything+ * behind it. `is-open` gates visibility because a `visibility: hidden` surface+ * cannot take focus.+ *+ * Menus are data, not children: `useContextMenu` owns the open request, call+ * sites hand it a label plus items, and one mounted `<ContextMenu>` renders it.+ * That keeps exactly one such surface on screen and lets a row build its items+ * where the actions already live.+ */+import {+ Fragment,+ useCallback,+ useEffect,+ useLayoutEffect,+ useRef,+ useState,+ type KeyboardEvent as ReactKeyboardEvent,+ type MouseEvent as ReactMouseEvent,+ type ReactNode,+} from "react";+import { createPortal } from "react-dom";+import {+ placeContextMenu,+ type ContextMenuPlacement,+ type ContextMenuPoint,+} from "../lib/context-menu";++export type ContextMenuItem = {+ /** Stable identity for React keys and for tests naming a row. */+ id: string;+ label: string;+ icon?: ReactNode;+ disabled?: boolean;+ /** Destructive item: error ink, and never adjacent to what it undoes. */+ danger?: boolean;+ /** Hairline above this item, splitting the menu into groups. */+ separatorBefore?: boolean;+ onSelect: () => void;+};++export type ContextMenuRequest = {+ /**+ * Accessible name for the surface, e.g. "Message actions". Optional because a+ * menu whose items already name their target (a link's own actions) reads+ * correctly unnamed; an unnamed *and* ambiguous menu is the caller's bug.+ */+ label?: string;+ items: ContextMenuItem[];+};++export type ContextMenuState = ContextMenuRequest & {+ /** Where the pointer asked for the surface. */+ point: ContextMenuPoint;+};++/**+ * Keyboard-opened menus (Shift+F10, the context-menu key) report no pointer+ * coordinates, so they anchor near the focused node instead of the origin.+ */+function pointForEvent(event: ReactMouseEvent<HTMLElement>): ContextMenuPoint {+ if (event.clientX !== 0 || event.clientY !== 0) {+ return { x: event.clientX, y: event.clientY };+ }+ const rect = event.currentTarget.getBoundingClientRect();+ return {+ x: rect.left + Math.min(24, rect.width / 2),+ y: rect.top + Math.min(24, rect.height / 2),+ };+}++export function useContextMenu() {+ const [state, setState] = useState<ContextMenuState | null>(null);+ const closeContextMenu = useCallback(() => setState(null), []);+ /*+ Every caller wants the same two effects: the platform's own menu must not+ also appear, and an ancestor surface must not react to the same right-click.+ Both are applied here so no call site can forget one.+ */+ const openContextMenu = useCallback(+ (event: ReactMouseEvent<HTMLElement>, request: ContextMenuRequest) => {+ if (!request.items.length) return;+ event.preventDefault();+ event.stopPropagation();+ setState({ ...request, point: pointForEvent(event) });+ },+ [],+ );+ return { contextMenu: state, openContextMenu, closeContextMenu };+}++export function ContextMenu({+ state,+ onClose,+}: {+ state: ContextMenuState | null;+ onClose: () => void;+}) {+ const menuRef = useRef<HTMLDivElement>(null);+ const [placement, setPlacement] = useState<ContextMenuPlacement | null>(null);++ const measure = useCallback(+ (request: ContextMenuState) => {+ const menu = menuRef.current;+ if (!menu) return;+ const rect = menu.getBoundingClientRect();+ const next = placeContextMenu(+ request.point,+ { width: rect.width, height: rect.height },+ { width: window.innerWidth, height: window.innerHeight },+ );+ setPlacement((previous) =>+ previous && previous.top === next.top && previous.left === next.left+ ? previous+ : next,+ );+ },+ [],+ );++ // A menu that is not on screen owns no placement; the closed surface is+ // unmounted, so the next one starts over from its own measurement.+ useEffect(() => {+ if (!state) setPlacement(null);+ }, [state]);++ /*+ Measured in a layout effect so the reveal and the final position land in the+ same paint: a deferred measurement would show the surface at the viewport+ origin for one frame.+ */+ useLayoutEffect(() => {+ if (state) measure(state);+ }, [measure, state]);++ // Content that resizes after reveal (a longer label, a late font) is+ // re-clamped rather than left hanging past the edge.+ useEffect(() => {+ if (!state || typeof ResizeObserver === "undefined") return;+ const menu = menuRef.current;+ if (!menu) return;+ const observer = new ResizeObserver(() => measure(state));+ observer.observe(menu);+ return () => observer.disconnect();+ }, [measure, state]);++ /*+ Focus leaves the transcript while a menu is up and returns to whatever the+ right-click interrupted, so closing never strands focus on `<body>`.+ */+ useEffect(() => {+ if (!state) return;+ const interrupted =+ document.activeElement instanceof HTMLElement+ ? document.activeElement+ : null;+ return () => {+ if (interrupted?.isConnected) interrupted.focus();+ };+ }, [state]);++ useEffect(() => {+ if (!state) return;+ const menu = menuRef.current;+ /*+ Capture phase on purpose: a nested surface that stops propagation on its+ own press would otherwise leave this menu open behind it.+ */+ const onOutside = (event: Event) => {+ const target = event.target as Node | null;+ if (target && menu?.contains(target)) return;+ onClose();+ };+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key !== "Escape") return;+ // Stop so a surrounding overlay does not also close on this Escape.+ event.preventDefault();+ event.stopPropagation();+ onClose();+ };+ window.addEventListener("pointerdown", onOutside, true);+ window.addEventListener("contextmenu", onOutside, true);+ window.addEventListener("scroll", onOutside, true);+ window.addEventListener("resize", onClose);+ window.addEventListener("blur", onClose);+ window.addEventListener("keydown", onKeyDown, true);+ return () => {+ window.removeEventListener("pointerdown", onOutside, true);+ window.removeEventListener("contextmenu", onOutside, true);+ window.removeEventListener("scroll", onOutside, true);+ window.removeEventListener("resize", onClose);+ window.removeEventListener("blur", onClose);+ window.removeEventListener("keydown", onKeyDown, true);+ };+ }, [onClose, state]);++ // Keyboard users land on the first item; Enter then runs it instead of+ // re-opening the menu.+ useEffect(() => {+ if (!state || !placement) return;+ const frame = requestAnimationFrame(() => {+ menuRef.current+ ?.querySelector<HTMLButtonElement>(+ '[role="menuitem"]:not(:disabled)',+ )+ ?.focus();+ });+ return () => cancelAnimationFrame(frame);+ }, [placement, state]);++ const onMenuKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {+ // Tab leaves the menu rather than walking its items.+ if (event.key === "Tab") {+ onClose();+ return;+ }+ if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;+ const items = Array.from(+ event.currentTarget.querySelectorAll<HTMLButtonElement>(+ '[role="menuitem"]:not(:disabled)',+ ),+ );+ if (!items.length) return;+ event.preventDefault();+ const current = items.indexOf(document.activeElement as HTMLButtonElement);+ const next =+ event.key === "Home"+ ? 0+ : event.key === "End"+ ? items.length - 1+ : (current + (event.key === "ArrowDown" ? 1 : -1) + items.length) %+ items.length;+ items[next]?.focus();+ };++ if (!state || typeof document === "undefined") return null;++ return createPortal(+ <div+ ref={menuRef}+ className={`context-menu${placement ? " is-open" : ""}`}+ role="menu"+ aria-label={state.label}+ onKeyDown={onMenuKeyDown}+ onContextMenu={(event) => {+ event.preventDefault();+ event.stopPropagation();+ }}+ style={+ placement+ ? { top: `${placement.top}px`, left: `${placement.left}px` }+ : undefined+ }+ >+ {state.items.map((item, index) => (+ <Fragment key={item.id}>+ {item.separatorBefore && index > 0 ? (+ <div className="context-menu-separator" role="separator" />+ ) : null}+ <button+ type="button"+ role="menuitem"+ className={`context-menu-item${item.danger ? " danger" : ""}`}+ data-context-menu-item={item.id}+ disabled={item.disabled}+ onClick={() => {+ // Close first: an item that opens a dialog must not leave a menu+ // layered over it.+ onClose();+ item.onSelect();+ }}+ >+ {item.icon ? (+ <span className="context-menu-icon" aria-hidden>+ {item.icon}+ </span>+ ) : null}+ <span className="context-menu-label">{item.label}</span>+ </button>+ </Fragment>+ ))}+ </div>,+ document.body,+ );+}diff --git a/apps/desktop/src/components/Markdown.tsx b/apps/desktop/src/components/Markdown.tsxindex e295d9d40..9a03b7799 100644--- a/apps/desktop/src/components/Markdown.tsx+++ b/apps/desktop/src/components/Markdown.tsx@@ -37,7 +37,7 @@ import {IconWorkflow,} from "./icons";import { TooltipButton } from "./ui";-import { createPortal } from "react-dom";+import { ContextMenu, useContextMenu } from "./ContextMenu";import { api } from "../lib/api";import { openHttpUrl } from "../lib/open-http-url";import {@@ -501,73 +501,15 @@ function Anchor({const openUrl = useAppStore((s) => s.openUrlInWorkPanel);const showToast = useAppStore((s) => s.showToast);- const [menuPosition, setMenuPosition] = useState<{ top: number; left: number } | null>(null);- const menuRef = useRef<HTMLDivElement | null>(null);- const anchorRef = useRef<HTMLAnchorElement | null>(null);+ const { contextMenu, openContextMenu, closeContextMenu } = useContextMenu();- useEffect(() => {- if (!menuPosition) return;- const close = () => setMenuPosition(null);- const onPointerDown = (event: PointerEvent) => {- if (menuRef.current?.contains(event.target as Node)) return;- close();- };- const onKeyDown = (event: KeyboardEvent) => {- if (event.key !== "Escape") return;- event.preventDefault();- close();- requestAnimationFrame(() => anchorRef.current?.focus());- };- window.addEventListener("pointerdown", onPointerDown);- window.addEventListener("scroll", close, true);- window.addEventListener("keydown", onKeyDown);- const focusFrame = requestAnimationFrame(() => {- menuRef.current- ?.querySelector<HTMLButtonElement>('[role="menuitem"]')- ?.focus();- });- return () => {- cancelAnimationFrame(focusFrame);- window.removeEventListener("pointerdown", onPointerDown);- window.removeEventListener("scroll", close, true);- window.removeEventListener("keydown", onKeyDown);- };- }, [menuPosition]);-- const onContextMenu = (e: React.MouseEvent<HTMLAnchorElement>) => {- if (!href || !/^https?:\/\//i.test(href)) return;- e.preventDefault();- e.stopPropagation();- const x = Math.min(e.clientX, window.innerWidth - 200);- const y = Math.min(e.clientY + 4, window.innerHeight - 150);- setMenuPosition({ top: y, left: x });- };-- const onMenuKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {- if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;- const items = Array.from(- event.currentTarget.querySelectorAll<HTMLButtonElement>(- '[role="menuitem"]:not(:disabled)',- ),- );- if (!items.length) return;- event.preventDefault();- const current = items.indexOf(document.activeElement as HTMLButtonElement);- const next =- event.key === "Home"- ? 0- : event.key === "End"- ? items.length - 1- : (current + (event.key === "ArrowDown" ? 1 : -1) + items.length) %- items.length;- items[next]?.focus();- };-- const copyLink = async () => {- setMenuPosition(null);- if (!href) return;+ /*+ Copying reports through the toast host: the menu closes the moment the item+ runs, so there is no button left to carry its own copied state.+ */+ const copyLink = async (target: string) => {try {- await navigator.clipboard.writeText(href);+ await navigator.clipboard.writeText(target);showToast(t("settings.linkCopied", { defaultValue: "Link copied to clipboard" }), {variant: "success",});@@ -579,6 +521,47 @@ function Anchor({}};+ /*+ A link keeps the renderer's own menu instead of the platform's so both+ destinations the app can send it to stay one press away. The surface is the+ shared pointer-anchored menu, which measures before it reveals, clamps inside+ the viewport, and owns dismissal and arrow-key navigation; only the items are+ link-specific.+ */+ const onContextMenu = (event: React.MouseEvent<HTMLAnchorElement>) => {+ if (!href || !/^https?:\/\//i.test(href)) return;+ const target = href;+ openContextMenu(event, {+ items: [+ {+ id: "open-external",+ label: t("settings.linkContextMenuOpenExternal", {+ defaultValue: "Open in default browser",+ }),+ icon: <IconExternal size={14} />,+ onSelect: () => void api.browserOpenExternal(target),+ },+ {+ id: "open-workpanel",+ label: t("settings.linkContextMenuOpenWorkpanel", {+ defaultValue: "Open in work panel",+ }),+ icon: <IconGlobe size={14} />,+ onSelect: () => openUrl(target),+ },+ {+ id: "copy-address",+ label: t("settings.linkContextMenuCopy", {+ defaultValue: "Copy link address",+ }),+ icon: <IconCopy size={14} />,+ separatorBefore: true,+ onSelect: () => void copyLink(target),+ },+ ],+ });+ };+// Plain click follows Link open destination. Modifier clicks fall through// to _blank, which main routes to shell.openExternal.@@ -599,7 +582,6 @@ function Anchor({return (<><a- ref={anchorRef}{...rest}href={href}onClick={onClick}@@ -609,52 +591,7 @@ function Anchor({>{children}</a>- {menuPosition &&- createPortal(- <div- ref={menuRef}- className="sidebar-row-menu sidebar-floating-menu"- role="menu"- onKeyDown={onMenuKeyDown}- style={{- top: menuPosition.top,- left: menuPosition.left,- }}- onClick={(e) => e.stopPropagation()}- >- <button- type="button"- role="menuitem"- onClick={() => {- setMenuPosition(null);- if (href) void api.browserOpenExternal(href);- }}- >- <IconExternal size={14} />- {t("settings.linkContextMenuOpenExternal", { defaultValue: "Open in default browser" })}- </button>- <button- type="button"- role="menuitem"- onClick={() => {- setMenuPosition(null);- if (href) openUrl(href);- }}- >- <IconGlobe size={14} />- {t("settings.linkContextMenuOpenWorkpanel", { defaultValue: "Open in work panel" })}- </button>- <button- type="button"- role="menuitem"- onClick={() => void copyLink()}- >- <IconCopy size={14} />- {t("settings.linkContextMenuCopy", { defaultValue: "Copy link address" })}- </button>- </div>,- document.body,- )}+ <ContextMenu state={contextMenu} onClose={closeContextMenu} /></>);}diff --git a/apps/desktop/src/components/icons.tsx b/apps/desktop/src/components/icons.tsxindex 9426062f1..934b999e3 100644--- a/apps/desktop/src/components/icons.tsx+++ b/apps/desktop/src/components/icons.tsx@@ -86,6 +86,7 @@ import {Sun,Target,Terminal,+ TextSelect,Trash2,TriangleAlert,UserRound,@@ -179,6 +180,8 @@ export const IconSidebar = icon(PanelLeft);export const IconArrowUp = icon(ArrowUp);export const IconArrowDown = icon(ArrowDown);export const IconCopy = icon(Copy);+/* Chat context menus: hand a message's rendered text to the platform selection. */+export const IconTextSelect = icon(TextSelect);export const IconCode = icon(Code2);export const IconDatabase = icon(Database);export const IconCheck = icon(Check);diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsxindex d93e28def..970e36784 100644--- a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx+++ b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx@@ -2,6 +2,7 @@ import {memo,useMemo,useRef,+ type MouseEvent as ReactMouseEvent,} from "react";import { useTranslation } from "react-i18next";import type {@@ -41,6 +42,11 @@ import {} from "./shared";import { activityItemsEqual, ActivityGroup } from "./ActivityGroup";import { MessageRow } from "./MessageRow";+import { assistantTurnMenuItems } from "./menu-items";+import {+ useChatTextActions,+ useTranscriptMenu,+} from "./TranscriptMenu";import { TurnProcess } from "./TurnProcess";type AssistantTurnProps = {@@ -218,6 +224,8 @@ export const AssistantTurn = memo(function AssistantTurn({runtimeActivity,}: AssistantTurnProps) {const { t } = useTranslation();+ const openTranscriptMenu = useTranscriptMenu();+ const { copyText, selectText } = useChatTextActions();const retryAssistantMessage = useAppStore((s) => s.retryAssistantMessage);const forkAssistantMessage = useAppStore((s) => s.forkAssistantMessage);const messages = assistantTurnMessages(entry);@@ -246,6 +254,34 @@ export const AssistantTurn = memo(function AssistantTurn({!isActive && !hasError && Boolean(content) && Boolean(actionMessage);const streaming =isActive && messages.some((message) => message.status === "streaming");+ /*+ The turn owns the menu for its whole subtree, the answer rows it renders+ included: Regenerate and Branch act on the turn's answer message, so a menu+ owned by a single message part could not offer them honestly.+ */+ const onContextMenu = (event: ReactMouseEvent<HTMLDivElement>) => {+ openTranscriptMenu(event, {+ label: t("chat.messageMenu"),+ items: assistantTurnMenuItems({+ t,+ answer: content,+ selectTarget:+ [+ ...event.currentTarget.querySelectorAll<HTMLElement>(+ ".message-bubble",+ ),+ ].at(-1) ?? null,+ complete: complete && Boolean(actionMessage),+ actions: { copyText, selectText },+ onRegenerate: () => {+ if (actionMessage) void retryAssistantMessage(actionMessage.id);+ },+ onBranch: () => {+ if (actionMessage) void forkAssistantMessage(actionMessage.id);+ },+ }),+ });+ };// Collect delegation statuses across ALL activity parts of this turn so that// a TaskWait in one part can inform the Task cards in a different part.@@ -325,6 +361,7 @@ export const AssistantTurn = memo(function AssistantTurn({className={`message-row assistant assistant-turn${streaming ? " streaming" : ""}`}data-minimap-id={entry.anchorId}data-row-role="assistant"+ onContextMenu={onContextMenu}role="article"aria-label={t("chat.assistantMessage")}>diff --git a/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx b/apps/desktop/src/features/chat/transcript/ChatTranscript.tsxindex 5af204ca3..54bb02f88 100644--- a/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx+++ b/apps/desktop/src/features/chat/transcript/ChatTranscript.tsx@@ -1,4 +1,4 @@-import { memo } from "react";+import { memo, type MouseEvent as ReactMouseEvent } from "react";import { useTranslation } from "react-i18next";import type { PlanningState, UiMessage } from "@pi-desktop/shared";import { proposalKindForMode } from "@pi-desktop/shared";@@ -20,25 +20,15 @@ import { useTranscriptScroll } from "./hooks/useTranscriptScroll";import type { TranscriptSearchTarget } from "../../../lib/transcript-reading";import { TranscriptSearchContext } from "../../../lib/transcript-search-context";import { DisclosureAnchorContext } from "../../../lib/disclosure-anchor-context";+import { conversationPlainText } from "../../../lib/chat-transcript-text";+import {+ TranscriptMenuProvider,+ useChatTextActions,+ useTranscriptMenu,+} from "./TranscriptMenu";+import { conversationMenuItems } from "./menu-items";-export const ChatTranscript = memo(function ChatTranscript({- sessionId,- messages,- hasMoreBefore = false,- onLoadOlder,- isRunning,- pendingPermission,- queuedPermissions = 0,- askPending = false,- planningState,- paneVisible = true,- searchTarget = null,- readingWindow = false,- hasMoreAfter = false,- onLoadNewer,- onReturnToLatest,- navigationLoading = false,-}: {+type ChatTranscriptProps = {sessionId: string | undefined;messages: UiMessage[];hasMoreBefore?: boolean;@@ -61,8 +51,44 @@ export const ChatTranscript = memo(function ChatTranscript({onLoadNewer?: () => Promise<void>;onReturnToLatest?: () => void;navigationLoading?: boolean;-}) {+};++/**+ * The transcript facade only mounts the right-click menu provider: the+ * scroller's own background menu has to consume that context, and a component+ * cannot read a provider it renders itself.+ */+export const ChatTranscript = memo(function ChatTranscript(+ props: ChatTranscriptProps,+) {+ return (+ <TranscriptMenuProvider>+ <TranscriptBody {...props} />+ </TranscriptMenuProvider>+ );+});++function TranscriptBody({+ sessionId,+ messages,+ hasMoreBefore = false,+ onLoadOlder,+ isRunning,+ pendingPermission,+ queuedPermissions = 0,+ askPending = false,+ planningState,+ paneVisible = true,+ searchTarget = null,+ readingWindow = false,+ hasMoreAfter = false,+ onLoadNewer,+ onReturnToLatest,+ navigationLoading = false,+}: ChatTranscriptProps) {const { t } = useTranslation();+ const openTranscriptMenu = useTranscriptMenu();+ const { copyText, selectText } = useChatTextActions();const transcriptRunning = isRunning && !readingWindow;const latestTurnResult = useAppStore((state) =>sessionId ? state.latestTurnResults[sessionId] : undefined,@@ -169,6 +195,32 @@ export const ChatTranscript = memo(function ChatTranscript({// lane at all, so a finished transcript keeps its exact layout.const runtimeStatusLane = transcriptRunning;+ /*+ The background menu answers the right-clicks no row claimed: the space below+ the last turn, a system row, a permission or outcome card. It reads the+ conversation rather than one message, so it is the only surface that can+ copy the whole thread.+ */+ const onContextMenu = (event: ReactMouseEvent<HTMLDivElement>) => {+ openTranscriptMenu(event, {+ label: t("chat.conversationMenu"),+ items: conversationMenuItems({+ t,+ conversation: conversationPlainText(messages, {+ user: t("chat.speakerYou"),+ assistant: t("chat.speakerAssistant"),+ }),+ scrollRef,+ contentRef,+ actions: { copyText, selectText },+ onReturnToLatest: () => {+ onReturnToLatest?.();+ jumpToLatest();+ },+ }),+ });+ };+return (<TranscriptSearchContext.Provider value={searchTarget}><DisclosureAnchorContext.Provider value={disclosureAnchorNotifier}>@@ -196,6 +248,7 @@ export const ChatTranscript = memo(function ChatTranscript({className="thread-scroll"ref={scrollRef}data-scroll-owner="transcript"+ onContextMenu={onContextMenu}onScroll={handleScroll}role="log"aria-live="polite"@@ -310,4 +363,4 @@ export const ChatTranscript = memo(function ChatTranscript({</DisclosureAnchorContext.Provider></TranscriptSearchContext.Provider>);-});+}diff --git a/apps/desktop/src/features/chat/transcript/MessageRow.tsx b/apps/desktop/src/features/chat/transcript/MessageRow.tsxindex 69fe4f46f..135ca525b 100644--- a/apps/desktop/src/features/chat/transcript/MessageRow.tsx+++ b/apps/desktop/src/features/chat/transcript/MessageRow.tsx@@ -2,6 +2,7 @@ import {memo,useMemo,useState,+ type MouseEvent as ReactMouseEvent,} from "react";import { useTranslation } from "react-i18next";import type { UiMessage } from "@pi-desktop/shared";@@ -16,6 +17,7 @@ import {IconTrash,} from "../../../components/icons";import { TooltipButton } from "../../../components/ui";+import { userMessageMenuItems } from "./menu-items";import { SessionMessageOrigin } from "./SessionMessageOrigin";import {CopyButton,@@ -23,6 +25,10 @@ import {LinkifiedText,MessageAttachmentImage,} from "./shared";+import {+ useChatTextActions,+ useTranscriptMenu,+} from "./TranscriptMenu";export const MessageRow = memo(function MessageRow({message,@@ -32,6 +38,8 @@ export const MessageRow = memo(function MessageRow({isRunning: boolean;}) {const { t } = useTranslation();+ const openTranscriptMenu = useTranscriptMenu();+ const { copyText, selectText } = useChatTextActions();const editUserMessage = useAppStore((s) => s.editUserMessage);const activateMessageRevision = useAppStore((s) => s.activateMessageRevision);const deleteMessage = useAppStore((s) => s.deleteMessage);@@ -79,12 +87,44 @@ export const MessageRow = memo(function MessageRow({setRetryingEdit(false);if (saved) setEditing(false);};+ /*+ The pointer path to the actions the hover row already offers. Only a human+ turn is owned here: an assistant answer belongs to its turn, so this row+ must not answer for one — it would offer Copy without the Regenerate and+ Branch items that live on the turn.+ */+ const onContextMenu = (event: ReactMouseEvent<HTMLDivElement>) => {+ if (!isUser) return;+ openTranscriptMenu(event, {+ label: t("chat.messageMenu"),+ items: userMessageMenuItems({+ t,+ text: message.content || "",+ selectTarget:+ event.currentTarget.querySelector<HTMLElement>(".message-bubble"),+ editable: editableUserMessage,+ running: isRunning,+ revision: showRevisionPager+ ? { count: revisionCount, active: activeRevision }+ : null,+ actions: { copyText, selectText },+ onEdit: () => {+ setEditValue(editSeed);+ setEditing(true);+ },+ onDelete: () => void deleteMessage(message.id),+ onActivateRevision: (index) =>+ void activateMessageRevision(message.id, index),+ }),+ });+ };return (<divclassName={`message-row ${isSessionMessage ? "session-message" : isUser ? "user" : message.role}`}data-minimap-id={message.id}data-message-id={message.id}data-row-role={isSessionMessage ? undefined : "user"}+ onContextMenu={onContextMenu}role="article"aria-label={isSessionMessage ? t("sessionCollaboration.agentMessage") : isUser ? t("chat.userMessage") : t("chat.assistantMessage")}>diff --git a/apps/desktop/src/features/chat/transcript/TranscriptMenu.tsx b/apps/desktop/src/features/chat/transcript/TranscriptMenu.tsxnew file mode 100644index 000000000..5297cab3d--- /dev/null+++ b/apps/desktop/src/features/chat/transcript/TranscriptMenu.tsx@@ -0,0 +1,94 @@+/**+ * The transcript's right-click menu: one surface per conversation, fed by+ * whichever row the pointer asked from.+ *+ * The menu lives at the transcript level because a row cannot own a floating+ * layer that has to outlive it — deleting a message removes its row, and the+ * transcript scroller measures every row for the minimap. Rows therefore+ * publish a request through context (the same shape `TranscriptSearchContext`+ * and `DisclosureAnchorContext` use) and the provider renders exactly one+ * `<ContextMenu>`.+ *+ * The item vocabulary is the one the hover action rows already ship — Copy,+ * Edit, Delete, Regenerate, Branch, versions — now also reachable from the+ * keyboard-visible pointer path instead of hover only.+ */+import {+ createContext,+ useCallback,+ useContext,+ type MouseEvent as ReactMouseEvent,+ type ReactNode,+} from "react";+import { useTranslation } from "react-i18next";+import {+ ContextMenu,+ useContextMenu,+ type ContextMenuRequest,+} from "../../../components/ContextMenu";+import { useAppStore } from "../../../stores/app-store";++export type OpenTranscriptMenu = (+ event: ReactMouseEvent<HTMLElement>,+ request: ContextMenuRequest,+) => void;++/**+ * A row rendered outside the provider (tests, a focused single-row view) keeps+ * a working handler that opens nothing rather than throwing mid-render.+ */+export const TranscriptMenuContext = createContext<OpenTranscriptMenu>(() => {});++export function useTranscriptMenu(): OpenTranscriptMenu {+ return useContext(TranscriptMenuContext);+}++export function TranscriptMenuProvider({ children }: { children: ReactNode }) {+ const { contextMenu, openContextMenu, closeContextMenu } = useContextMenu();+ return (+ <TranscriptMenuContext.Provider value={openContextMenu}>+ {children}+ <ContextMenu state={contextMenu} onClose={closeContextMenu} />+ </TranscriptMenuContext.Provider>+ );+}++/**+ * The clipboard and selection half of a menu item.+ *+ * A menu disappears the moment an item runs, so an item cannot report its+ * outcome through its own state the way the hover copy chips do (see `useCopy`);+ * the toast host carries the outcome instead.+ */+export function useChatTextActions() {+ const { t } = useTranslation();+ const showToast = useAppStore((state) => state.showToast);++ const copyText = useCallback(+ async (text: string) => {+ try {+ await navigator.clipboard.writeText(text);+ showToast(t("chat.copied"), { variant: "success" });+ } catch {+ showToast(t("chat.copyFailed"), { variant: "error" });+ }+ },+ [showToast, t],+ );++ /*+ Selecting the row's rendered text hands a partial copy back to the platform:+ dragging across a long answer is the only way to take a sentence out of it,+ and the row is already on screen, so nothing needs measuring.+ */+ const selectText = useCallback((element: HTMLElement | null) => {+ const selection = window.getSelection();+ if (!element || !selection) return;+ const range = document.createRange();+ range.selectNodeContents(element);+ selection.removeAllRanges();+ selection.addRange(range);+ }, []);++ return { copyText, selectText };+}diff --git a/apps/desktop/src/features/chat/transcript/menu-items.tsx b/apps/desktop/src/features/chat/transcript/menu-items.tsxnew file mode 100644index 000000000..89b440c3e--- /dev/null+++ b/apps/desktop/src/features/chat/transcript/menu-items.tsx@@ -0,0 +1,280 @@+/**+ * The transcript's context-menu vocabulary, as pure functions of the state a+ * row already knows.+ *+ * Three surfaces build menus over the same actions — a user row, an assistant+ * turn, the conversation background — and they must not each decide for+ * themselves which item is available when. Keeping the decision here means the+ * item set for a state is a plain value that a test can assert, while the+ * components stay wiring.+ *+ * Each builder mirrors the hover action row it belongs to. `separatorBefore`+ * marks the transition from "read this" to "act on this", so a menu with only+ * one group never paints a leading rule.+ */+import type { TFunction } from "i18next";+import {+ IconArrowDown,+ IconArrowUp,+ IconBranch,+ IconChevronLeft,+ IconChevronRight,+ IconCopy,+ IconPencil,+ IconReview,+ IconTextSelect,+ IconTrash,+} from "../../../components/icons";+import type { ContextMenuItem } from "../../../components/ContextMenu";++/** Actions the builders call; the components own their real implementations. */+export type MenuItemActions = {+ copyText: (text: string) => void;+ selectText: (element: HTMLElement | null) => void;+};++/**+ * A human turn: read it, or change it.+ *+ * Delete is separated from Edit rather than placed beside it: it is the only+ * item that destroys durable history, and Edit's undo is a revision the user can+ * walk back to.+ */+export function userMessageMenuItems({+ t,+ text,+ selectTarget,+ editable,+ running,+ revision,+ actions,+ onEdit,+ onDelete,+ onActivateRevision,+}: {+ t: TFunction;+ text: string;+ selectTarget: HTMLElement | null;+ /** Session-relayed turns are not human input, so they cannot be edited. */+ editable: boolean;+ running: boolean;+ /** Present only while a regenerate left more than one version behind. */+ revision: { count: number; active: number } | null;+ actions: MenuItemActions;+ onEdit: () => void;+ onDelete: () => void;+ onActivateRevision: (index: number) => void;+}): ContextMenuItem[] {+ const items: ContextMenuItem[] = [];+ if (text.trim()) {+ items.push({+ id: "copy",+ label: t("chat.copy"),+ icon: copyIcon(),+ onSelect: () => actions.copyText(text),+ });+ items.push({+ id: "select-text",+ label: t("chat.selectMessageText"),+ icon: selectIcon(),+ onSelect: () => actions.selectText(selectTarget),+ });+ }+ if (editable) {+ items.push({+ id: "edit",+ label: t("chat.editMessage"),+ icon: pencilIcon(),+ disabled: running,+ separatorBefore: items.length > 0,+ onSelect: onEdit,+ });+ }+ if (revision) {+ items.push({+ id: "revision-previous",+ label: t("chat.revisionPrev"),+ icon: previousIcon(),+ disabled: running || revision.active <= 1,+ separatorBefore: items.length > 0,+ onSelect: () => onActivateRevision(Math.max(1, revision.active - 1)),+ });+ items.push({+ id: "revision-next",+ label: t("chat.revisionNext"),+ icon: nextIcon(),+ disabled: running || revision.active >= revision.count,+ onSelect: () =>+ onActivateRevision(Math.min(revision.count, revision.active + 1)),+ });+ }+ if (editable) {+ items.push({+ id: "delete",+ label: t("chat.deleteMessage"),+ icon: trashIcon(),+ danger: true,+ disabled: running,+ separatorBefore: true,+ onSelect: onDelete,+ });+ }+ return items;+}++/**+ * An assistant turn: read the answer, or re-run it.+ *+ * Copy/Select need answer text, and Regenerate/Branch need a settled turn, so a+ * streaming or failed turn legitimately yields an empty list — the caller then+ * opens no menu at all rather than an empty one.+ */+export function assistantTurnMenuItems({+ t,+ answer,+ selectTarget,+ complete,+ actions,+ onRegenerate,+ onBranch,+}: {+ t: TFunction;+ answer: string;+ selectTarget: HTMLElement | null;+ /** Idle, error-free, and backed by an answer message. */+ complete: boolean;+ actions: MenuItemActions;+ onRegenerate: () => void;+ onBranch: () => void;+}): ContextMenuItem[] {+ const items: ContextMenuItem[] = [];+ if (answer.trim()) {+ items.push({+ id: "copy",+ label: t("chat.copy"),+ icon: copyIcon(),+ onSelect: () => actions.copyText(answer),+ });+ items.push({+ id: "select-text",+ label: t("chat.selectMessageText"),+ icon: selectIcon(),+ onSelect: () => actions.selectText(selectTarget),+ });+ }+ if (complete) {+ items.push({+ id: "regenerate",+ label: t("chat.retry"),+ icon: regenerateIcon(),+ separatorBefore: items.length > 0,+ onSelect: onRegenerate,+ });+ items.push({+ id: "branch",+ label: t("chat.forkResponse"),+ icon: branchIcon(),+ onSelect: onBranch,+ });+ }+ return items;+}++/**+ * The conversation background: the actions that need the whole thread, which no+ * single row can offer.+ */+export function conversationMenuItems({+ t,+ conversation,+ scrollRef,+ contentRef,+ actions,+ onReturnToLatest,+}: {+ t: TFunction;+ /** Labelled dialogue text; empty means nothing worth copying. */+ conversation: string;+ scrollRef: { current: HTMLElement | null };+ contentRef: { current: HTMLElement | null };+ actions: MenuItemActions;+ onReturnToLatest: () => void;+}): ContextMenuItem[] {+ const scrollTo = (top: number) => () => scrollRef.current?.scrollTo({ top });+ return [+ {+ id: "copy-conversation",+ label: t("chat.copyConversation"),+ icon: copyIcon(),+ disabled: !conversation,+ onSelect: () => actions.copyText(conversation),+ },+ {+ id: "select-conversation",+ label: t("chat.selectConversationText"),+ icon: selectIcon(),+ separatorBefore: true,+ onSelect: () => actions.selectText(contentRef.current),+ },+ {+ id: "scroll-top",+ label: t("chat.scrollToTop"),+ icon: upIcon(),+ separatorBefore: true,+ onSelect: scrollTo(0),+ },+ {+ id: "scroll-bottom",+ label: t("chat.scrollToBottom"),+ icon: downIcon(),+ // Re-entering follow mode is part of jumping to the end: without it the+ // scroller would scroll once and then stay pinned where it landed.+ onSelect: onReturnToLatest,+ },+ ];+}++/*+ Icons arrive as elements rather than components so a builder stays a plain+ function of data. They are created per call, which React reconciles by+ position inside the menu — the same shape the hover toolbar already uses.+*/+function copyIcon() {+ return <IconCopy size={14} />;+}++function selectIcon() {+ return <IconTextSelect size={14} />;+}++function pencilIcon() {+ return <IconPencil size={14} />;+}++function trashIcon() {+ return <IconTrash size={14} />;+}++function previousIcon() {+ return <IconChevronLeft size={14} />;+}++function nextIcon() {+ return <IconChevronRight size={14} />;+}++function regenerateIcon() {+ return <IconReview size={14} />;+}++function branchIcon() {+ return <IconBranch size={14} />;+}++function upIcon() {+ return <IconArrowUp size={14} />;+}++function downIcon() {+ return <IconArrowDown size={14} />;+}diff --git a/apps/desktop/src/lib/chat-transcript-text.ts b/apps/desktop/src/lib/chat-transcript-text.tsnew file mode 100644index 000000000..75d881411--- /dev/null+++ b/apps/desktop/src/lib/chat-transcript-text.ts@@ -0,0 +1,42 @@+/**+ * Text readings of a transcript, for the right-click menu's clipboard actions.+ *+ * A conversation is not one string: the transcript holds user turns, assistant+ * turns, and the tool/system rows that carry their own state. "Copy+ * conversation" means what a user would paste into a document — the readable+ * dialogue — so tool and system rows are skipped rather than dumped as raw+ * payloads. Each block keeps its turn text exactly as stored, so code fences and+ * quoting survive the copy.+ */++/** The part of a transcript message this module reads. */+export type TranscriptTextMessage = {+ role: string;+ content?: string;+};++export type TranscriptSpeakerLabels = {+ user: string;+ assistant: string;+};++/**+ * One labelled block per speaking turn, separated by a blank line. Returns an+ * empty string when the conversation holds no user or assistant text, which+ * callers use to disable the action instead of copying nothing.+ */+export function conversationPlainText(+ messages: readonly TranscriptTextMessage[],+ labels: TranscriptSpeakerLabels,+): string {+ const blocks: string[] = [];+ for (const message of messages) {+ if (message.role !== "user" && message.role !== "assistant") continue;+ const text = (message.content ?? "").trim();+ if (!text) continue;+ const speaker =+ message.role === "user" ? labels.user : labels.assistant;+ blocks.push(`${speaker}:\n${text}`);+ }+ return blocks.join("\n\n");+}diff --git a/apps/desktop/src/lib/context-menu.ts b/apps/desktop/src/lib/context-menu.tsnew file mode 100644index 000000000..44feb9d98--- /dev/null+++ b/apps/desktop/src/lib/context-menu.ts@@ -0,0 +1,44 @@+/**+ * Placement math for a pointer-anchored context menu.+ *+ * A right-click menu has no trigger edge to align to: the pointer names where+ * it should appear. A menu that does not fit is therefore clamped inside the+ * viewport instead of flipped to the anchor's other side, which is the same+ * fallback the sidebar's body-level menus use for the same reason.+ *+ * The caller measures the rendered surface first and passes its size in, so the+ * first paint is already the final position and the menu can never flash at the+ * viewport origin.+ */++/** Keeps a floating surface off the window edge it would otherwise touch. */+export const CONTEXT_MENU_MARGIN = 8;++export type ContextMenuPoint = { x: number; y: number };+export type ContextMenuSize = { width: number; height: number };+export type ContextMenuPlacement = { top: number; left: number };++/**+ * A surface larger than the viewport cannot satisfy both margins. `min` is+ * returned in that case so the menu's top-left stays reachable and its own+ * `max-height`/`overflow` scrolls the remainder.+ */+function clamp(value: number, minimum: number, maximum: number) {+ return Math.max(minimum, Math.min(value, maximum));+}++export function placeContextMenu(+ point: ContextMenuPoint,+ surface: ContextMenuSize,+ viewport: ContextMenuSize,+ margin: number = CONTEXT_MENU_MARGIN,+): ContextMenuPlacement {+ const maxLeft = viewport.width - surface.width - margin;+ const maxTop = viewport.height - surface.height - margin;+ return {+ // Rounded so the surface lands on a whole pixel: a half-pixel offset makes+ // every item's hairline separator blur.+ left: Math.round(clamp(point.x, margin, maxLeft)),+ top: Math.round(clamp(point.y, margin, maxTop)),+ };+}diff --git a/apps/desktop/src/styles/ui-kit.css b/apps/desktop/src/styles/ui-kit.cssindex ab41eca78..954ca4247 100644--- a/apps/desktop/src/styles/ui-kit.css+++ b/apps/desktop/src/styles/ui-kit.css@@ -211,3 +211,92 @@padding: 18px;animation: surface-in var(--motion-duration-normal) var(--motion-ease-out) both;}+/* Pointer-anchored right-click menu (see components/ContextMenu.tsx). It is+ measured before it is revealed, so `is-open` gates a surface that would+ otherwise paint at the viewport origin. It shares the sidebar menus' surface+ grammar so one floating-layer grammar covers the whole renderer. */+.context-menu {+ position: fixed;+ top: 0;+ left: 0;+ z-index: 60; /* body-level menu layer, above pane stacking */+ min-width: 184px;+ width: max-content;+ max-width: calc(100vw - 16px);+ max-height: calc(100vh - 16px);+ overflow-y: auto;+ padding: 5px;+ border: 1px solid var(--ds-border-subtle);+ border-radius: var(--radius-md-plus);+ background: var(--ds-bg-elevated-opaque, var(--ds-bg-primary));+ box-shadow: var(--ds-shadow-dialog);+ color: var(--ds-text-primary);+ opacity: 0;+ pointer-events: none;+ visibility: hidden;+}++.context-menu.is-open {+ opacity: 1;+ pointer-events: auto;+ visibility: visible;+}++.context-menu-item {+ display: flex;+ width: 100%;+ align-items: center;+ gap: 8px;+ border-radius: var(--radius-sm);+ padding: 7px 8px;+ color: var(--ds-text-primary);+ font-size: var(--text-sm-plus);+ text-align: left;+ white-space: nowrap;+}++/* Keyboard arrow navigation moves focus, so the hover fill has to follow it or+ the active row is invisible. */+.context-menu-item:hover,+.context-menu-item:focus-visible {+ background: var(--ds-bg-hover);+}++.context-menu-item:disabled {+ background: transparent;+ color: var(--ds-text-muted);+ cursor: not-allowed;+ opacity: 0.55;+}++.context-menu-item.danger {+ color: var(--ds-error);+}++.context-menu-item.danger:hover,+.context-menu-item.danger:focus-visible {+ background: color-mix(in oklab, var(--ds-error) 10%, transparent);+}++.context-menu-icon {+ display: inline-flex;+ flex: 0 0 auto;+ color: var(--ds-text-muted);+}++/* A destructive row carries one signal (its ink), not two. */+.context-menu-item.danger .context-menu-icon {+ color: inherit;+}++.context-menu-label {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+}++.context-menu-separator {+ height: 1px;+ margin: 5px 6px;+ background: var(--ds-border-subtle);+}diff --git a/apps/desktop/test/chat-context-menu-items.test.mjs b/apps/desktop/test/chat-context-menu-items.test.mjsnew file mode 100644index 000000000..606494f1a--- /dev/null+++ b/apps/desktop/test/chat-context-menu-items.test.mjs@@ -0,0 +1,161 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import * as React from "react";+import * as jsxRuntime from "react/jsx-runtime";+import ts from "typescript";++const t = (key) => key;+const noop = () => {};+const actions = { copyText: noop, selectText: noop };++function loadMenuItems() {+ const file = new URL("../src/features/chat/transcript/menu-items.tsx", import.meta.url);+ const { outputText } = ts.transpileModule(readFileSync(file, "utf8"), {+ compilerOptions: { module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX },+ fileName: file.pathname,+ });+ const imports = {+ react: React,+ "react/jsx-runtime": jsxRuntime,+ "i18next": {},+ "../../../components/ContextMenu": {},+ "../../../components/icons": new Proxy({}, { get: () => () => null }),+ };+ const module = { exports: {} };+ new Function("require", "exports", "module", outputText)(+ (id) => {+ assert.ok(Object.hasOwn(imports, id), `unmocked menu-item dependency: ${id}`);+ return imports[id];+ },+ module.exports,+ module,+ );+ return module.exports;+}++const {+ userMessageMenuItems,+ assistantTurnMenuItems,+ conversationMenuItems,+} = loadMenuItems();++const ids = (items) => items.map((item) => item.id);++test("a user message menu offers copy, select, edit, and a separated delete", () => {+ const items = userMessageMenuItems({+ t,+ text: "Fix the crash",+ selectTarget: null,+ editable: true,+ running: false,+ revision: null,+ actions,+ onEdit: noop,+ onDelete: noop,+ onActivateRevision: noop,+ });+ assert.deepEqual(ids(items), ["copy", "select-text", "edit", "delete"]);+ assert.equal(items.find((item) => item.id === "edit").separatorBefore, true);+ assert.equal(items.find((item) => item.id === "delete").danger, true);+ assert.equal(items.find((item) => item.id === "delete").separatorBefore, true);+});++test("a session-relayed user message cannot be edited or deleted", () => {+ const items = userMessageMenuItems({+ t,+ text: "Review the changes",+ selectTarget: null,+ editable: false,+ running: false,+ revision: null,+ actions,+ onEdit: noop,+ onDelete: noop,+ onActivateRevision: noop,+ });+ assert.deepEqual(ids(items), ["copy", "select-text"]);+});++test("a running turn disables edit, delete, and revision navigation", () => {+ const items = userMessageMenuItems({+ t,+ text: "Try again",+ selectTarget: null,+ editable: true,+ running: true,+ revision: { count: 3, active: 2 },+ actions,+ onEdit: noop,+ onDelete: noop,+ onActivateRevision: noop,+ });+ assert.deepEqual(ids(items), [+ "copy",+ "select-text",+ "edit",+ "revision-previous",+ "revision-next",+ "delete",+ ]);+ for (const id of ["edit", "delete", "revision-previous", "revision-next"]) {+ assert.equal(items.find((item) => item.id === id).disabled, true, id);+ }+});++test("a completed assistant turn offers copy, select, regenerate, and branch", () => {+ const items = assistantTurnMenuItems({+ t,+ answer: "Patched main.ts.",+ selectTarget: null,+ complete: true,+ actions,+ onRegenerate: noop,+ onBranch: noop,+ });+ assert.deepEqual(ids(items), ["copy", "select-text", "regenerate", "branch"]);+ assert.equal(items.find((item) => item.id === "regenerate").separatorBefore, true);+});++test("a streaming assistant turn without a settled answer offers no items", () => {+ const items = assistantTurnMenuItems({+ t,+ answer: "",+ selectTarget: null,+ complete: false,+ actions,+ onRegenerate: noop,+ onBranch: noop,+ });+ assert.deepEqual(ids(items), []);+});++test("the conversation menu copies the thread and keeps scroll actions", () => {+ const items = conversationMenuItems({+ t,+ conversation: "You:\nHi",+ scrollRef: { current: null },+ contentRef: { current: null },+ actions,+ onReturnToLatest: noop,+ });+ assert.deepEqual(ids(items), [+ "copy-conversation",+ "select-conversation",+ "scroll-top",+ "scroll-bottom",+ ]);+ assert.equal(items.find((item) => item.id === "copy-conversation").disabled, false);+});++test("an empty conversation disables copy instead of writing a blank clipboard", () => {+ const items = conversationMenuItems({+ t,+ conversation: "",+ scrollRef: { current: null },+ contentRef: { current: null },+ actions,+ onReturnToLatest: noop,+ });+ assert.equal(items.find((item) => item.id === "copy-conversation").disabled, true);+});diff --git a/apps/desktop/test/chat-context-menu-surface.test.mjs b/apps/desktop/test/chat-context-menu-surface.test.mjsnew file mode 100644index 000000000..2296e2ee6--- /dev/null+++ b/apps/desktop/test/chat-context-menu-surface.test.mjs@@ -0,0 +1,52 @@+import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";+import test from "node:test";+import { loadStyles } from "./helpers/styles.mjs";++const styles = await loadStyles();+const menuSource = await readFile(+ new URL("../src/components/ContextMenu.tsx", import.meta.url),+ "utf8",+);+const transcriptSource = await readFile(+ new URL("../src/features/chat/transcript/ChatTranscript.tsx", import.meta.url),+ "utf8",+);+const messageRowSource = await readFile(+ new URL("../src/features/chat/transcript/MessageRow.tsx", import.meta.url),+ "utf8",+);+const assistantTurnSource = await readFile(+ new URL("../src/features/chat/transcript/AssistantTurn.tsx", import.meta.url),+ "utf8",+);++test("the pointer-anchored menu portals, measures, and closes without trapping focus", () => {+ assert.match(menuSource, /createPortal\(/);+ assert.match(menuSource, /document\.body/);+ assert.match(menuSource, /placeContextMenu\(/);+ assert.match(menuSource, /className=\{`context-menu\$\{placement \? " is-open" : ""\}`\}/);+ assert.match(menuSource, /window\.addEventListener\("pointerdown", onOutside, true\)/);+ assert.match(menuSource, /window\.addEventListener\("keydown", onKeyDown, true\)/);+ assert.match(menuSource, /if \(event\.key === "Tab"\)/);+ assert.match(menuSource, /onContextMenu=\{/);+ assert.match(menuSource, /if \(!request\.items\.length\) return;/);+});++test("the transcript owns one menu and each speaking row can open it", () => {+ assert.match(transcriptSource, /<TranscriptMenuProvider>/);+ assert.match(transcriptSource, /onContextMenu=\{onContextMenu\}/);+ assert.match(transcriptSource, /conversationMenuItems\(/);+ assert.match(messageRowSource, /onContextMenu=\{onContextMenu\}/);+ assert.match(messageRowSource, /userMessageMenuItems\(/);+ assert.match(assistantTurnSource, /onContextMenu=\{onContextMenu\}/);+ assert.match(assistantTurnSource, /assistantTurnMenuItems\(/);+});++test("the context-menu surface is a measured fixed layer", () => {+ const rule = styles.match(/\.context-menu\s*\{[\s\S]*?\}/)?.[0] ?? "";+ assert.match(rule, /position:\s*fixed/);+ assert.match(rule, /z-index:\s*60/);+ assert.match(rule, /visibility:\s*hidden/);+ assert.match(styles, /\.context-menu\.is-open\s*\{[\s\S]*?visibility:\s*visible/);+});diff --git a/apps/desktop/test/chat-context-menu.test.mjs b/apps/desktop/test/chat-context-menu.test.mjsnew file mode 100644index 000000000..91e16f7cb--- /dev/null+++ b/apps/desktop/test/chat-context-menu.test.mjs@@ -0,0 +1,49 @@+import assert from "node:assert/strict";+import test from "node:test";+import { placeContextMenu } from "../src/lib/context-menu.ts";+import { conversationPlainText } from "../src/lib/chat-transcript-text.ts";++test("a menu that fits the viewport stays at the pointer", () => {+ assert.deepEqual(+ placeContextMenu({ x: 120, y: 80 }, { width: 184, height: 160 }, { width: 800, height: 600 }),+ { left: 120, top: 80 },+ );+});++test("a menu near the far edge clamps inside the viewport margin", () => {+ assert.deepEqual(+ placeContextMenu({ x: 790, y: 590 }, { width: 184, height: 160 }, { width: 800, height: 600 }),+ { left: 608, top: 432 },+ );+});++test("a surface larger than the viewport still stays reachable at the margin", () => {+ assert.deepEqual(+ placeContextMenu({ x: 400, y: 300 }, { width: 900, height: 700 }, { width: 800, height: 600 }),+ { left: 8, top: 8 },+ );+});++test("copy conversation keeps speaking turns and skips tool rows", () => {+ const text = conversationPlainText(+ [+ { role: "user", content: "Fix the crash" },+ { role: "tool", content: "{\"ok\":true}" },+ { role: "assistant", content: "Patched `main.ts`." },+ { role: "system", content: "session started" },+ { role: "user", content: " " },+ ],+ { user: "You", assistant: "Assistant" },+ );+ assert.equal(text, "You:\nFix the crash\n\nAssistant:\nPatched `main.ts`.");+});++test("an empty conversation copies nothing so the action can stay disabled", () => {+ assert.equal(+ conversationPlainText(+ [{ role: "tool", content: "noise" }, { role: "assistant", content: "" }],+ { user: "You", assistant: "Assistant" },+ ),+ "",+ );+});diff --git a/apps/desktop/test/fixed-dropdown-surfaces.test.mjs b/apps/desktop/test/fixed-dropdown-surfaces.test.mjsindex a30528e58..21f019ea3 100644--- a/apps/desktop/test/fixed-dropdown-surfaces.test.mjs+++ b/apps/desktop/test/fixed-dropdown-surfaces.test.mjs@@ -48,6 +48,7 @@ const dropdownSurfaces = ["composer-autocomplete","context-inspector-popover","home-project-switcher-menu",+ "context-menu",];function findSurfaceRule(className) {diff --git a/apps/desktop/test/markdown-link-menu.test.mjs b/apps/desktop/test/markdown-link-menu.test.mjsindex 18727482c..932e727ac 100644--- a/apps/desktop/test/markdown-link-menu.test.mjs+++ b/apps/desktop/test/markdown-link-menu.test.mjs@@ -11,26 +11,22 @@ const koreanCatalog = await readFile("utf8",);-test("chat link menus keep inside clicks and keyboard navigation", () => {- assert.match(- markdownSource,- /if \(menuRef\.current\?\.contains\(event\.target as Node\)\) return;/,- );- assert.match(markdownSource, /ref=\{menuRef\}/);- assert.match(markdownSource, /onKeyDown=\{onMenuKeyDown\}/);- assert.match(- markdownSource,- /querySelector<HTMLButtonElement>\('\[role="menuitem"\]'\)/,- );+test("chat links use the shared pointer-anchored menu", () => {+ assert.match(markdownSource, /useContextMenu\(\)/);+ assert.match(markdownSource, /<ContextMenu state=\{contextMenu\} onClose=\{closeContextMenu\} \/>/);+ assert.match(markdownSource, /openContextMenu\(event, \{/);+ assert.match(markdownSource, /id: "open-external"/);+ assert.match(markdownSource, /id: "open-workpanel"/);+ assert.match(markdownSource, /id: "copy-address"/);});test("copy link feedback follows the clipboard result", () => {- assert.match(markdownSource, /await navigator\.clipboard\.writeText\(href\)/);+ assert.match(markdownSource, /await navigator\.clipboard\.writeText\(target\)/);assert.match(markdownSource, /t\("settings\.linkCopied"/);assert.match(markdownSource, /t\("settings\.linkCopyFailed"/);assert.doesNotMatch(markdownSource,- /void navigator\.clipboard\.writeText\(href\);\s*showToast\(/,+ /void navigator\.clipboard\.writeText\([^)]+\);\s*showToast\(/,);});diff --git a/apps/desktop/test/session-message-presentation.test.mjs b/apps/desktop/test/session-message-presentation.test.mjsindex 812928f6e..a16da2936 100644--- a/apps/desktop/test/session-message-presentation.test.mjs+++ b/apps/desktop/test/session-message-presentation.test.mjs@@ -43,6 +43,11 @@ function loadComponent(name, extras = {}) {"../../../components/icons": new Proxy({}, { get: () => Icon }),"../../../components/ui": { TooltipButton },"./shared": shared,+ "./menu-items": { userMessageMenuItems: () => [] },+ "./TranscriptMenu": {+ useTranscriptMenu: () => () => {},+ useChatTextActions: () => ({ copyText: () => {}, selectText: () => {} }),+ },...extras,};const module = { exports: {} };diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 19b20e881..b03ee69fc 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -1659,7 +1659,16 @@ Single message render — either user (plaintext) or assistant (markdown streamiand owns the pager whenever `revisionCount > 1`; replacing the assistant/tooltail must not move or detach that pager from the user bubble. The pager ispart of the message action toolbar: hidden by default and revealed together- with Copy on row hover or keyboard focus.+ with Copy on row hover or keyboard focus. Right-clicking a user message or+ an assistant turn opens the same action vocabulary as a body-level+ pointer-anchored menu (Copy, Select text, and the row's own Edit / Delete /+ Regenerate / Branch / revision items). Right-clicking empty transcript+ space, a system row, or a permission/outcome card opens a conversation+ menu: Copy conversation, Select conversation text, Scroll to top, Jump to+ latest. Quote, Annotate, and Open side chat stay retired (ADR 0268). A+ streaming or empty assistant turn that would produce no items opens+ nothing. Copying from the menu reports through the toast host because the+ surface closes as soon as the item runs.Fork creates and activates an independent session whose snapshot ends at theselected assistant response, requires an idle source, and leaves thatsource's transcript, live runtime, and provider cache state untouched (D134).@@ -1783,6 +1792,11 @@ message its checkpoint covers.whatever its z-index. When the pane is narrower than the panel, the popovernarrows with the pane instead of crossing that edge.- Timestamps: `aria-label` with full time string, visual shows relative time+- Right-click menus are `role="menu"` with `role="menuitem"` rows, arrow /+ Home / End navigation, Escape / Tab / outside-press / scroll-behind+ dismissal, and an accessible name (`chat.messageMenu` or+ `chat.conversationMenu`). Focus returns to whatever the right-click+ interrupted.### 8.6 MVP constraintsdiff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.mdindex a628b811b..a78de2cf8 100644--- a/docs/spec/04-ux/09-interaction-patterns.md+++ b/docs/spec/04-ux/09-interaction-patterns.md@@ -398,6 +398,13 @@ may be retained while exactly one workspace supplies the visible shell context.trigger unless the pattern explicitly retains input focus.- Native `<select>` popups remain platform-owned; this rule covers customrenderer surfaces only.+- Pointer-anchored context menus (transcript rows, conversation+ background, markdown links) are the same family: they portal to+ `document.body` as a viewport-fixed layer, measure before reveal so+ they never flash at the origin, clamp inside the viewport instead of+ flipping, and close on outside press, Escape, Tab, window blur, or a+ scroll of anything behind them. An empty item list never opens a+ surface.### 1.6 Local profile footerdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex a11aa502d..1463d4fe0 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -3422,6 +3422,33 @@ identify the platform validation still needed.- **Milestone**: M5- **Status**: Unit-covered (`transcript-style.test.mjs`); full visual scenario Draft+#### E2E-CHAT-transcript-context-menu: Right-click a message or the transcript++- **Preconditions**: A session contains a completed user prompt and a+ completed assistant answer; the conversation pane is focused.+- **Steps**: 1) Right-click the user plate. 2) Choose Copy, then Select+ message text. 3) Right-click the assistant turn and choose Copy.+ 4) Right-click empty space below the last turn and choose Copy+ conversation. 5) Press Escape on an open menu, then Tab. 6) Right-click+ a markdown link in the answer.+- **Expected**: The user menu lists Copy, Select message text, Edit, and+ a separated Delete; the assistant menu lists Copy, Select message text,+ Regenerate, and Branch. Copy writes the message or the labelled+ conversation to the clipboard and shows a toast. Select text highlights+ the bubble. Escape and Tab dismiss the menu without running an item.+ A link still offers Open in default browser, Open in work panel, and+ Copy link address. Quote, Annotate, and Open side chat are absent+ (ADR 0268). The surface is a viewport-fixed body-level layer and does+ not resize the transcript.+- **Specs linked**: `04-ux/08-component-spec.md` §8.3 / §8.5,+ `04-ux/09-interaction-patterns.md` (floating dropdown surfaces),+ ADR 0268+- **Acceptance**: C (chat stream), Quality+- **Milestone**: M5+- **Status**: Unit-covered (`chat-context-menu.test.mjs`,+ `chat-context-menu-items.test.mjs`, `chat-context-menu-surface.test.mjs`);+ full UI scenario Draft+#### E2E-060b: Neutral gray accent across chrome- **Preconditions**: App running in dark and light themes; plugins page and adiff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex 5baffe007..63d00cc49 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -1190,10 +1190,9 @@ row 而不是在转录本中添加树镶边。存在变体,root 用户上有一个 ChatGPT 风格的 `current / total` 寻呼机切换归档分支而不丢失历史记录(D109)。之后Retry/Regenerate 启动,root 用户轮流保留在实时记录中- 并在 `revisionCount > 1` 时拥有寻呼机;更换 assistant/tool-tail 不得将该寻呼机从用户气泡中移动或分离。寻呼机是- 消息操作工具栏的一部分:默认隐藏并一起显示- 在行悬停或键盘焦点上复制。+ tail 不得将该寻呼机从用户气泡中移动或分离。寻呼机是+ 消息操作工具栏的一部分:默认隐藏,并与复制一起在行悬停或键盘聚焦时显示。+ 右键用户消息或助手回合会打开与悬停操作相同的词汇(复制、选中文本,以及该行自己的编辑 / 删除 / 重新生成 / 分叉 / 版本项),作为文档级、指针锚定的菜单。右键空白记录、系统行、权限卡或结果卡会打开对话菜单:复制整个对话、选中对话文本、滚动到顶部、跳到最新。引用、批注、打开侧边聊天仍按 ADR 0268 退役。流式或空助手回合若没有可提供的项则不打开菜单。菜单项的复制结果走 toast,因为表面在项执行时就会关闭。Fork 创建并激活一个独立的会话,其快照结束于选择辅助响应,需要一个空闲源,然后留下源的转录本、实时运行时和提供程序缓存状态保持不变 (D134)。@@ -1289,6 +1288,7 @@ tail 不得将该寻呼机从用户气泡中移动或分离。寻呼机是因此一旦弹框伸入面板列就会被覆盖,与其 z-index 无关。当会话面板比弹框窄时,弹框随面板收窄,而不是越过该边界。- 时间戳:`aria-label` 带有完整时间字符串,视觉显示相对时间+- 右键菜单为 `role="menu"`、行项为 `role="menuitem"`,支持方向键 / Home / End,Escape / Tab / 外部按下 / 背后滚动关闭,并带有可访问名称(`chat.messageMenu` 或 `chat.conversationMenu`)。焦点回到被右键打断的控件。### 8.6 MVP 约束diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 74844bae7..05f51af37 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -2192,6 +2192,20 @@ MainChat 弥补了缺口。 Maximized/fullscreen 调用保留最新的- **里程碑**:M5- **状态**:单位覆盖(`transcript-style.test.mjs`);全视觉场景草稿+#### E2E-CHAT-transcript-context-menu:右键消息或记录++- **前提条件**:会话中有一条完成的用户提示和一条完成的助手回答;对话面板已聚焦。+- **步骤**:1)右键用户板。2)选择复制,再选择选中消息文本。3)右键助手回合并选择复制。4)右键最后一回合下方空白处,选择复制整个对话。5)在打开的菜单上按 Escape,再按 Tab。6)右键回答里的 markdown 链接。+- **预期**:用户菜单列出复制、选中消息文本、编辑,以及分隔后的删除;助手菜单列出复制、选中消息文本、重新生成和分叉。复制把该消息或带说话人标签的整段对话写入剪贴板并显示 toast。选中文本会高亮气泡。Escape 和 Tab 关闭菜单且不执行项。链接仍提供在默认浏览器打开、在工作面板打开、复制链接地址。引用、批注、打开侧边聊天不出现(ADR 0268)。表面是视口固定的文档级层,不会改变记录高度。+- **链接规格**:`04-ux/08-component-spec.md` §8.3 / §8.5,+ `04-ux/09-interaction-patterns.md`(浮动下拉表面),+ ADR 0268+- **验收**:C(聊天流),质量+- **里程碑**:M5+- **状态**:单位覆盖(`chat-context-menu.test.mjs`、+ `chat-context-menu-items.test.mjs`、`chat-context-menu-surface.test.mjs`);+ 完整 UI 场景草稿+#### E2E-060b:镀铬中性灰色调- **先决条件**:应用程序在深色和浅色主题中运行;插件页面和diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 2611112ee..dc6aac89e 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -269,6 +269,15 @@ export const de = {"showEarlierMessages": "Frühere Nachrichten anzeigen","copy": "Kopieren","copied": "Kopiert",+ "copyFailed": "Kopieren in die Zwischenablage fehlgeschlagen",+ "messageMenu": "Nachrichtenaktionen",+ "conversationMenu": "Gesprächsaktionen",+ "selectMessageText": "Nachrichtentext auswählen",+ "copyConversation": "Gespräch kopieren",+ "selectConversationText": "Gesprächstext auswählen",+ "scrollToTop": "Nach oben scrollen",+ "speakerYou": "Du",+ "speakerAssistant": "Assistent","copyDiagramSource": "Diagrammquelle kopieren","showDiagram": "Diagramm anzeigen","showDiagramSource": "Diagrammquelle anzeigen",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 89b4b65c6..d64b659c4 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -276,6 +276,15 @@ export const en = {showEarlierMessages: "Show earlier messages",copy: "Copy",copied: "Copied",+ copyFailed: "Couldn't copy to the clipboard",+ messageMenu: "Message actions",+ conversationMenu: "Conversation actions",+ selectMessageText: "Select message text",+ copyConversation: "Copy conversation",+ selectConversationText: "Select conversation text",+ scrollToTop: "Scroll to top",+ speakerYou: "You",+ speakerAssistant: "Assistant",copyDiagramSource: "Copy diagram source",showDiagram: "Show diagram",showDiagramSource: "Show diagram source",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 8042ce4ad..0bbb24306 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -269,6 +269,15 @@ export const es = {"showEarlierMessages": "Mostrar mensajes anteriores","copy": "Copiar","copied": "Copiado",+ "copyFailed": "No se pudo copiar al portapapeles",+ "messageMenu": "Acciones del mensaje",+ "conversationMenu": "Acciones de la conversación",+ "selectMessageText": "Seleccionar el texto del mensaje",+ "copyConversation": "Copiar la conversación",+ "selectConversationText": "Seleccionar el texto de la conversación",+ "scrollToTop": "Ir al principio",+ "speakerYou": "Tú",+ "speakerAssistant": "Asistente","copyDiagramSource": "Copiar fuente del diagrama","showDiagram": "Mostrar diagrama","showDiagramSource": "Mostrar fuente del diagrama",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 70d7dcb83..4d0c5cda2 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -269,6 +269,15 @@ export const fr = {"showEarlierMessages": "Afficher les messages précédents","copy": "Copier","copied": "Copié",+ "copyFailed": "Impossible de copier dans le presse-papiers",+ "messageMenu": "Actions du message",+ "conversationMenu": "Actions de la conversation",+ "selectMessageText": "Sélectionner le texte du message",+ "copyConversation": "Copier la conversation",+ "selectConversationText": "Sélectionner le texte de la conversation",+ "scrollToTop": "Aller en haut",+ "speakerYou": "Vous",+ "speakerAssistant": "Assistant","copyDiagramSource": "Copier la source du diagramme","showDiagram": "Afficher le diagramme","showDiagramSource": "Afficher la source du diagramme",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 623e8c002..d33d2c763 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -278,6 +278,15 @@ export const ko = {showEarlierMessages: "이전 메시지 표시",copy: "복사",copied: "복사됨",+ copyFailed: "클립보드에 복사하지 못했습니다",+ messageMenu: "메시지 작업",+ conversationMenu: "대화 작업",+ selectMessageText: "메시지 텍스트 선택",+ copyConversation: "대화 복사",+ selectConversationText: "대화 텍스트 선택",+ scrollToTop: "맨 위로 이동",+ speakerYou: "나",+ speakerAssistant: "어시스턴트",copyDiagramSource: "다이어그램 소스 복사",showDiagram: "다이어그램 표시",showDiagramSource: "다이어그램 소스 표시",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex ee743beb8..32511d861 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -278,6 +278,15 @@ export const tr = {showEarlierMessages: "Önceki iletileri göster",copy: "Kopyala",copied: "Kopyalandı",+ copyFailed: "Panoya kopyalanamadı",+ messageMenu: "Mesaj işlemleri",+ conversationMenu: "Konuşma işlemleri",+ selectMessageText: "Mesaj metnini seç",+ copyConversation: "Konuşmayı kopyala",+ selectConversationText: "Konuşma metnini seç",+ scrollToTop: "Başa kaydır",+ speakerYou: "Sen",+ speakerAssistant: "Asistan",copyDiagramSource: "Diyagram kaynağını kopyala",showDiagram: "Diyagramı göster",showDiagramSource: "Diyagram kaynağını göster",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 3def702ce..0b68aca7a 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -270,6 +270,15 @@ export const zhCN = {showEarlierMessages: "显示更早的消息",copy: "复制",copied: "已复制",+ copyFailed: "复制到剪贴板失败",+ messageMenu: "消息操作",+ conversationMenu: "对话操作",+ selectMessageText: "选中消息文本",+ copyConversation: "复制整个对话",+ selectConversationText: "选中对话文本",+ scrollToTop: "滚动到顶部",+ speakerYou: "你",+ speakerAssistant: "助手",copyDiagramSource: "复制图表源码",showDiagram: "显示图表",showDiagramSource: "显示图表源码",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 2d4d956de..9c8a1f820 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -270,6 +270,15 @@ export const zhTW = {showEarlierMessages: "顯示更早的訊息",copy: "複製",copied: "已複製",+ copyFailed: "複製到剪貼簿失敗",+ messageMenu: "訊息操作",+ conversationMenu: "對話操作",+ selectMessageText: "選取訊息文字",+ copyConversation: "複製整段對話",+ selectConversationText: "選取對話文字",+ scrollToTop: "捲動到頂端",+ speakerYou: "你",+ speakerAssistant: "助手",copyDiagramSource: "複製圖表原始碼",showDiagram: "顯示圖表",showDiagramSource: "顯示圖表原始碼",diff --git a/packages/i18n/test/user-facing-copy.test.mjs b/packages/i18n/test/user-facing-copy.test.mjsindex 792700b7f..963af8248 100644--- a/packages/i18n/test/user-facing-copy.test.mjs+++ b/packages/i18n/test/user-facing-copy.test.mjs@@ -155,3 +155,12 @@ test("font size presets use Starbucks-style cup names", () => {assert.equal(chinese["settings.fontSizeLarge"], "超大杯");assert.equal(chinese["settings.fontSizeXl"], "超超大杯");});++test("chat context-menu copy stays user-facing", () => {+ assert.equal(english["chat.copyFailed"], "Couldn't copy to the clipboard");+ assert.equal(english["chat.messageMenu"], "Message actions");+ assert.equal(english["chat.copyConversation"], "Copy conversation");+ assert.equal(chinese["chat.copyFailed"], "复制到剪贴板失败");+ assert.equal(chinese["chat.copyConversation"], "复制整个对话");+ assert.equal(chinese["chat.selectMessageText"], "选中消息文本");+});