From 4693bba81fe21cbca6a51f1e0420236b61bdc4d6 Mon Sep 17 00:00:00 2001 From: Xubin Ren <52506698+Re-bin@users.noreply.github.com> Date: Thu, 24 Sep 2026 02:37:46 +0800 Subject: [PATCH] fix(webui): preserve native touch menus with message link actions --- docs/webui.md | 13 +- webui/src/components/MessageBubble.tsx | 7 ++ webui/src/components/MessageLinksMenu.tsx | 91 ++++++++++++++ webui/src/components/WebLink.tsx | 40 ++----- .../src/components/thread/ThreadMessages.tsx | 16 ++- webui/src/i18n/locales/en/common.json | 2 + webui/src/i18n/locales/es/common.json | 2 + webui/src/i18n/locales/fr/common.json | 2 + webui/src/i18n/locales/id/common.json | 2 + webui/src/i18n/locales/ja/common.json | 2 + webui/src/i18n/locales/ko/common.json | 2 + webui/src/i18n/locales/pt-BR/common.json | 2 + webui/src/i18n/locales/vi/common.json | 2 + webui/src/i18n/locales/zh-CN/common.json | 2 + webui/src/i18n/locales/zh-TW/common.json | 2 + webui/src/tests/message-links-menu.test.tsx | 111 ++++++++++++++++++ .../tests/temporary-chat-navigation.test.tsx | 9 +- webui/src/tests/web-preview.test.tsx | 49 ++++---- 18 files changed, 291 insertions(+), 65 deletions(-) create mode 100644 webui/src/components/MessageLinksMenu.tsx create mode 100644 webui/src/tests/message-links-menu.test.tsx diff --git a/docs/webui.md b/docs/webui.md index 89f905caa..043629b07 100644 --- a/docs/webui.md +++ b/docs/webui.md @@ -457,11 +457,14 @@ private, trusted network. ### Links and website previews -HTTP(S) links in replies have a **Link actions** menu: right-click the link, -press Shift+F10 while it is focused, or touch and hold it. There is no persistent -action button beside the link. Scrolling or a short tap does not open the menu. -You can copy the link, open it in a browser tab, or preview it beside the current -conversation. +HTTP(S) links in replies have a **Link actions** menu: right-click the link or +press Shift+F10 while it is focused. Touch and hold keeps the browser's native +link menu. For in-app actions on touch devices, open the message's existing +**Message actions → View links** entry. It lists only the web links rendered in +that message, not URLs inside code blocks or file references. Choose a link to +copy it, open it externally, or preview it beside the current conversation. +There is no persistent action button beside each link and no custom long-press +gesture to interfere with scrolling or text selection. Ordinary clicks still open links in a browser tab. File and session links keep their own behavior. diff --git a/webui/src/components/MessageBubble.tsx b/webui/src/components/MessageBubble.tsx index 0697cf464..5b9e5d1f5 100644 --- a/webui/src/components/MessageBubble.tsx +++ b/webui/src/components/MessageBubble.tsx @@ -14,6 +14,7 @@ import { CircleAlert, Clock3, Copy, + Link2, Quote, Wrench, } from "lucide-react"; @@ -131,6 +132,7 @@ interface MessageBlockMenuActionsProps { isTurnStreaming?: boolean; onForkFromHere?: () => void; activity?: MessageBlockMenuActivity; + onViewLinks?: () => void; } /** Actions and metadata shown after opening a visual message block's context panel. */ @@ -139,6 +141,7 @@ export function MessageBlockMenuActions({ isTurnStreaming = false, onForkFromHere, activity, + onViewLinks, }: MessageBlockMenuActionsProps) { const { t } = useTranslation(); const content = message.role === "assistant" @@ -274,6 +277,10 @@ export function MessageBlockMenuActions({ ) : null} ) : null} + {onViewLinks ? : null} , open: boolean) { + const [links, setLinks] = useState([]); + useLayoutEffect(() => { + const element = root.current; + if (!open || !element) return; + const collect = () => { + const unique = new Map(); + element.querySelectorAll("[data-assistant-selectable] a[data-web-link]").forEach((anchor) => { + const href = anchor.getAttribute("href") ?? ""; + const url = parseWebLink(href); + if (url && !unique.has(url.href)) { + unique.set(url.href, { href, title: anchor.textContent?.trim() || href }); + } + }); + setLinks(Array.from(unique.values())); + }; + collect(); + // Markdown is lazy-loaded; collect again when its real links appear/change. + const observer = new MutationObserver(collect); + observer.observe(element, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ["href"] }); + return () => observer.disconnect(); + }, [root, open]); + return links; +} + +const itemClassName = `${floatingItemClassName} ${floatingItemFocusClassName} w-full min-h-11 text-start hover:bg-muted/70`; + +/** A drill-in inside the existing message popover, not another floating layer. */ +export function MessageLinksMenu({ links, onBack, onClose }: { + links: MessageWebLink[]; + onBack: () => void; + onClose: () => void; +}) { + const { t } = useTranslation(); + const openPreview = useContext(WebPreviewContext); + const [selected, setSelected] = useState(links.length === 1 ? links[0].href : null); + const active = links.find((link) => link.href === selected); + const backRef = useRef(null); + useLayoutEffect(() => { backRef.current?.focus({ preventScroll: true }); }, [selected]); + return
+ + {active ? { onClose(); openPreview(active.href); } : undefined} /> + :
+ {links.map((link) => )} +
} +
; +} + +function MessageLinkActions({ link, onClose, onPreview }: { + link: MessageWebLink; + onClose: () => void; + onPreview?: () => void; +}) { + const { t } = useTranslation(); + const [feedback, setFeedback] = useState<"copied" | "copyFailed" | null>(null); + const mounted = useRef(false); + useLayoutEffect(() => { + mounted.current = true; + return () => { mounted.current = false; }; + }, []); + const copy = async () => { + const success = await copyTextToClipboard(link.href); + if (mounted.current) setFeedback(success ? "copied" : "copyFailed"); + }; + return
+

{link.href}

+ {onPreview ? : null} + {t("webPreview.external")} + + {feedback ?

{t(`webPreview.${feedback}`)}

: null} +
; +} diff --git a/webui/src/components/WebLink.tsx b/webui/src/components/WebLink.tsx index deac6453a..d66fddb4b 100644 --- a/webui/src/components/WebLink.tsx +++ b/webui/src/components/WebLink.tsx @@ -34,20 +34,13 @@ function WebsiteLink({ href, children, className, ...props }: ComponentPropsWith const anchor = useRef({ getBoundingClientRect: () => new DOMRect(point.current.x, point.current.y, 0, 0) }); const interactedOutside = useRef(false); const generation = useRef(0); - const press = useRef<{ id: number; x: number; y: number; timer: number } | null>(null); - const suppressClick = useRef(false); + const pointerType = useRef(""); - const cancelPress = () => { - if (press.current) window.clearTimeout(press.current.timer); - press.current = null; - }; useEffect(() => () => { - cancelPress(); generation.current += 1; }, []); const changeOpen = (next: boolean) => { - cancelPress(); generation.current += 1; setOpen(next); }; @@ -70,38 +63,25 @@ function WebsiteLink({ href, children, className, ...props }: ComponentPropsWith { - event.preventDefault(); event.stopPropagation(); + event.stopPropagation(); + // Touch keeps the browser's native link preview/copy/share menu. Older + // WebKit exposes contextmenu as a MouseEvent, so remember the last pointer. + const type = (event.nativeEvent as PointerEvent).pointerType || pointerType.current; + if (type === "touch" || (!type && window.matchMedia("(pointer: coarse)").matches)) return; + event.preventDefault(); openAt(event.clientX, event.clientY); }} onKeyDown={(event) => { - suppressClick.current = false; if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return; event.preventDefault(); event.stopPropagation(); const bounds = link.current!.getBoundingClientRect(); openAt(bounds.left, bounds.bottom); }} onPointerDown={(event) => { - suppressClick.current = false; - cancelPress(); - if (event.pointerType !== "touch" || !event.isPrimary || event.button !== 0) return; - const { pointerId: id, clientX: x, clientY: y } = event; - press.current = { id, x, y, timer: window.setTimeout(() => { - suppressClick.current = true; - openAt(x, y); - }, 600) }; - }} - onPointerMove={(event) => { - const current = press.current; - if (current && (event.pointerId !== current.id || Math.hypot(event.clientX - current.x, event.clientY - current.y) > 10)) cancelPress(); - }} - onPointerUp={cancelPress} onPointerCancel={cancelPress} onPointerLeave={cancelPress} - onClickCapture={(event) => { - if (!suppressClick.current) return; - suppressClick.current = false; - event.preventDefault(); event.stopPropagation(); + pointerType.current = event.pointerType; }}> - {children} + {children} {feedback === "copied" ? {t("webPreview.copied")} : null} diff --git a/webui/src/components/thread/ThreadMessages.tsx b/webui/src/components/thread/ThreadMessages.tsx index 1023d12f3..82ec8bcdb 100644 --- a/webui/src/components/thread/ThreadMessages.tsx +++ b/webui/src/components/thread/ThreadMessages.tsx @@ -1,7 +1,8 @@ -import { memo, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react"; +import { memo, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type RefObject } from "react"; import { MoreHorizontal } from "lucide-react"; import { useTranslation } from "react-i18next"; import { MessageBlockMenuActions, MessageBubble } from "@/components/MessageBubble"; +import { MessageLinksMenu, useMessageWebLinks } from "@/components/MessageLinksMenu"; import { FallbackResponseSources } from "@/components/ResponseSourceBadge"; import { AgentActivityCluster, @@ -355,6 +356,7 @@ interface ThreadDisplayUnitProps { } interface MessageBlockMenuProps { + messageRoot: RefObject; message: UIMessage; isTurnStreaming: boolean; contextBlockKey: string; @@ -372,6 +374,7 @@ interface MessageBlockMenuProps { } function MessageBlockMenu({ + messageRoot, message, isTurnStreaming, contextBlockKey, @@ -385,6 +388,9 @@ function MessageBlockMenu({ const { t } = useTranslation(); const contentRef = useRef(null); const triggerRef = useRef(null); + const links = useMessageWebLinks(messageRoot, open); + const [linksShown, setLinksShown] = useState(false); + useEffect(() => { if (!open) setLinksShown(false); }, [open]); const [triggerHeight, setTriggerHeight] = useState(28); useLayoutEffect(() => { const trigger = triggerRef.current; @@ -466,12 +472,15 @@ function MessageBlockMenu({ "shadow-[0_2px_10px_rgba(0,0,0,0.08)] dark:shadow-[0_2px_10px_rgba(0,0,0,0.24)]", )} > - 0 ? { setLinksShown(false); contentRef.current?.focus({ preventScroll: true }); }} + onClose={() => onOpenChange(false)} /> : + onViewLinks={links.length > 0 ? () => setLinksShown(true) : undefined} + />} ); @@ -570,6 +579,7 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({ ]); const blockMenu = unit.type === "message" && contextBlockKey !== undefined ? ( ({ copyTextToClipboard: vi.fn(async () => true) })); +afterEach(() => { cleanup(); vi.mocked(copyTextToClipboard).mockReset().mockResolvedValue(true); }); + +function view(content: string, openPreview?: (url: string) => void) { + return + + ; +} + +async function openLinks() { + fireEvent.click(screen.getByRole("button", { name: "Message actions" })); + fireEvent.click(await screen.findByRole("button", { name: "View links" })); + return screen.getByRole("dialog", { name: "Message actions" }); +} + +describe("message link actions", () => { + it("collects rendered links, deduplicates destinations and ignores code, images and file references", async () => { + render(view("[First](https://example.com/) and [Again](https://example.com).\n\n[Second](https://example.org/demo)\n\nhttps://example.net/plain\n\n`https://code.invalid/inline`\n\n```text\nhttps://code.invalid/block\n```\n\n![Image](https://image.invalid/pic.png)\n\n[notes.txt](notes.txt)")); + await screen.findByRole("link", { name: "First" }); + const menu = await openLinks(); + expect(within(menu).getAllByRole("button").map(button => button.textContent)).toEqual(["View links", "First", "Second", "https://example.net/plain"]); + expect(within(menu).queryByRole("button", { name: "Again" })).not.toBeInTheDocument(); + expect(within(menu).getByRole("button", { name: "Second" })).toBeVisible(); + expect(within(menu).getByRole("button", { name: "https://example.net/plain" })).toBeVisible(); + fireEvent.click(within(menu).getByRole("button", { name: "First" })); + expect(within(menu).getByRole("link", { name: "Open in browser" })).toHaveAttribute("href", "https://example.com/"); + expect(within(menu).getByRole("link", { name: "Open in browser" })).toHaveAttribute("rel", "noreferrer noopener"); + expect(within(menu).queryByRole("button", { name: "Preview website" })).not.toBeInTheDocument(); + fireEvent.click(within(menu).getByRole("button", { name: "Back" })); + expect(within(menu).getByRole("button", { name: "Second" })).toBeVisible(); + fireEvent.click(within(menu).getByRole("button", { name: "Back" })); + expect(within(menu).getByRole("button", { name: "View links" })).toBeVisible(); + }); + + it("does not show an entry for a message without a rendered web link", async () => { + render(view("No links here. `https://example.com/code` [Mail](mailto:test@example.com) [Unsafe](javascript:alert)")); + await screen.findByText(/No links here/); + fireEvent.click(screen.getByRole("button", { name: "Message actions" })); + expect(screen.queryByRole("button", { name: "View links" })).not.toBeInTheDocument(); + }); + + it("opens the single link's actions directly and closes the message menu on preview", async () => { + const preview = vi.fn(); + render(view("[Website](https://example.com/demo?q=one#two)", preview)); + await screen.findByRole("link", { name: /Website/ }); + const menu = await openLinks(); + expect(screen.getAllByRole("dialog")).toHaveLength(1); + fireEvent.click(within(menu).getByRole("button", { name: "Preview website" })); + expect(preview).toHaveBeenCalledWith("https://example.com/demo?q=one#two"); + await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()); + fireEvent.click(screen.getByRole("button", { name: "Message actions" })); + expect(screen.getByRole("button", { name: "View links" })).toBeVisible(); + }); + + it("provides copy feedback and retry without losing the selected link", async () => { + vi.mocked(copyTextToClipboard).mockResolvedValueOnce(false).mockResolvedValueOnce(true); + render(view("[Website](https://example.com/demo)")); + await screen.findByRole("link", { name: /Website/ }); + const menu = await openLinks(); + fireEvent.click(within(menu).getByRole("button", { name: "Copy link" })); + expect(await screen.findByRole("status")).toHaveTextContent("Could not copy link"); + fireEvent.click(within(menu).getByRole("button", { name: "Copy link" })); + await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("Link copied")); + expect(copyTextToClipboard).toHaveBeenLastCalledWith("https://example.com/demo"); + fireEvent.keyDown(menu, { key: "Escape" }); + await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()); + expect(screen.getByRole("button", { name: "Message actions" })).toHaveFocus(); + }); + + it("ignores late copy feedback after going back", async () => { + let finish!: (result: boolean) => void; + vi.mocked(copyTextToClipboard).mockImplementationOnce(() => new Promise(resolve => { finish = resolve; })); + render(view("[Old](https://example.com/old)")); + await screen.findByRole("link", { name: /Old/ }); + const menu = await openLinks(); + fireEvent.click(within(menu).getByRole("button", { name: "Copy link" })); + fireEvent.click(within(menu).getByRole("button", { name: "Back" })); + await act(async () => finish(true)); + expect(screen.queryByRole("status")).not.toBeInTheDocument(); + expect(within(menu).getByRole("button", { name: "View links" })).toBeVisible(); + }); + + it("tracks newly rendered or changed links only within the owning message", async () => { + function LiveMessage({ href }: { href: string | null }) { + const root = useRef(null); + const links = useMessageWebLinks(root, true); + return <>Another message +
+ An activity link, not part of the reply +
{href ? Current link : null}
+
+ {links.map(link => link.href).join(",")}; + } + const { rerender } = render(); + expect(screen.getByRole("status")).toBeEmptyDOMElement(); + rerender(); + await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent(/^https:\/\/example.com\/old$/)); + rerender(); + await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent(/^https:\/\/example.com\/new$/)); + rerender(); + await waitFor(() => expect(screen.getByRole("status")).toBeEmptyDOMElement()); + }); +}); diff --git a/webui/src/tests/temporary-chat-navigation.test.tsx b/webui/src/tests/temporary-chat-navigation.test.tsx index 80a999f4d..0f733b096 100644 --- a/webui/src/tests/temporary-chat-navigation.test.tsx +++ b/webui/src/tests/temporary-chat-navigation.test.tsx @@ -283,8 +283,13 @@ describe("temporary chat navigation", () => { await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument()); fireEvent.keyDown(window, { key: "Escape" }); await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument()); - fireEvent.contextMenu(screen.getByRole("link", { name: "Website" })); - fireEvent.click(await screen.findByRole("menuitem", { name: "Preview website" })); + // The same pane is reachable with taps only, without intercepting a native + // touch context menu or adding a button next to every rendered link. + fireEvent.click(screen.getByRole("button", { name: "Message actions" })); + fireEvent.click(await screen.findByRole("button", { name: "View links" })); + fireEvent.click(await screen.findByRole("button", { name: "Preview website" })); + await screen.findByTestId("web-preview-panel"); + expect(screen.queryByRole("dialog", { name: "Message actions" })).not.toBeInTheDocument(); fireEvent.click(screen.getByRole("button", { name: "notes.txt" })); await waitFor(() => expect(screen.queryByTestId("web-preview-panel")).not.toBeInTheDocument()); await screen.findByText("Preview of notes.txt"); diff --git a/webui/src/tests/web-preview.test.tsx b/webui/src/tests/web-preview.test.tsx index 93d5a0244..fd0dd38d9 100644 --- a/webui/src/tests/web-preview.test.tsx +++ b/webui/src/tests/web-preview.test.tsx @@ -145,45 +145,44 @@ describe("web link actions", () => { await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument()); expect(link).not.toHaveFocus(); }); - it("opens on a touch hold and suppresses the following ghost click, but keeps the next tap usable", async () => { + it("leaves touch holds, native context menus and subsequent taps to the browser", async () => { vi.useFakeTimers(); const onClick = vi.fn(); render(Example); const link = screen.getByRole("link", { name: "Example" }); fireEvent.pointerDown(link, { pointerId: 1, pointerType: "touch", isPrimary: true, button: 0, clientX: 100, clientY: 150 }); - await act(async () => { await vi.advanceTimersByTimeAsync(600); }); - expect(screen.getByRole("menu")).toBeInTheDocument(); + await act(async () => { await vi.advanceTimersByTimeAsync(1000); }); + expect(screen.queryByRole("menu")).not.toBeInTheDocument(); + expect(fireEvent.contextMenu(link)).toBe(true); + expect(screen.queryByRole("menu")).not.toBeInTheDocument(); + expect(link.className).not.toContain("touch-callout"); fireEvent.pointerUp(link, { pointerId: 1, pointerType: "touch" }); - expect(fireEvent.click(link)).toBe(false); - expect(onClick).not.toHaveBeenCalled(); - fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" }); - await act(async () => { await vi.advanceTimersByTimeAsync(300); }); - fireEvent.pointerDown(link, { pointerId: 2, pointerType: "touch", isPrimary: true, button: 0 }); - fireEvent.pointerUp(link, { pointerId: 2, pointerType: "touch" }); expect(fireEvent.click(link)).toBe(true); expect(onClick).toHaveBeenCalledTimes(1); }); - it.each(["move", "cancel", "leave", "short tap", "second finger"])("cancels touch hold on %s", async (reason) => { - vi.useFakeTimers(); + it("still supports a mouse and keyboard after touch on a hybrid device", () => { render(Example); const link = screen.getByRole("link", { name: "Example" }); - fireEvent.pointerDown(link, { pointerId: 1, pointerType: "touch", isPrimary: true, button: 0, clientX: 100, clientY: 100 }); - if (reason === "move") fireEvent.pointerMove(link, { pointerId: 1, clientX: 100, clientY: 125 }); - else if (reason === "cancel") fireEvent.pointerCancel(link); - else if (reason === "leave") fireEvent.pointerLeave(link); - else if (reason === "short tap") fireEvent.pointerUp(link); - else fireEvent.pointerDown(link, { pointerId: 2, pointerType: "touch", isPrimary: false, button: 0 }); - await act(async () => { await vi.advanceTimersByTimeAsync(700); }); - expect(screen.queryByRole("menu")).not.toBeInTheDocument(); + fireEvent.pointerDown(link, { pointerType: "touch" }); + fireEvent.pointerDown(link, { pointerType: "mouse", button: 2 }); + expect(fireEvent.contextMenu(link)).toBe(false); + expect(screen.getByRole("menu")).toBeInTheDocument(); + fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" }); + fireEvent.pointerDown(link, { pointerType: "touch" }); + fireEvent.keyDown(link, { key: "F10", shiftKey: true }); + expect(screen.getByRole("menu")).toBeInTheDocument(); }); - it("cancels pending holds and discards an open menu when its URL changes", async () => { - vi.useFakeTimers(); + it("leaves a coarse-pointer context menu native even without a preceding pointer event", () => { + const original = window.matchMedia; + const media = vi.spyOn(window, "matchMedia").mockImplementation(query => ({ ...original(query), matches: query === "(pointer: coarse)" })); + render(Example); + expect(fireEvent.contextMenu(screen.getByRole("link", { name: "Example" }))).toBe(true); + expect(screen.queryByRole("menu")).not.toBeInTheDocument(); + media.mockRestore(); + }); + it("discards an open menu when its URL changes", () => { const view = (href: string) => Example; const { rerender } = render(view("https://example.com/old")); - fireEvent.pointerDown(screen.getByRole("link", { name: "Example" }), { pointerId: 1, pointerType: "touch", isPrimary: true, button: 0 }); - rerender(view("https://example.com/new")); - await act(async () => { await vi.advanceTimersByTimeAsync(700); }); - expect(screen.queryByRole("menu")).not.toBeInTheDocument(); fireEvent.contextMenu(screen.getByRole("link", { name: "Example" })); expect(screen.getByRole("menu")).toBeInTheDocument(); rerender(view("https://example.com/third"));