Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
perf(comments): load server thumbnails for comment images in thumbnails mode (MUL-9598) (#11114)
Jiayuan Zhang76188dade356
diff --git a/packages/views/common/row-actions-menu.tsx b/packages/views/common/row-actions-menu.tsxindex 19a409eaa2..f9eb56339c 100644--- a/packages/views/common/row-actions-menu.tsx+++ b/packages/views/common/row-actions-menu.tsx@@ -92,10 +92,15 @@ export function RowActionsPointMenu({menu,onOpenChange,groups,+ trailing,+ finalFocus,}: {menu: RowMenuState;onOpenChange: (open: boolean) => void;groups: RowActionItem[][];+ /** Rendered after the groups, e.g. the surrounding object's submenu. */+ trailing?: ReactNode;+ finalFocus?: () => boolean;}) {const anchor = usePointAnchor(menu.point);const filled = groups.filter((group) => group.length > 0);@@ -111,8 +116,9 @@ export function RowActionsPointMenu({onOpenChange(open);}}>- <DropdownMenuContent align="start" anchor={anchor} className="w-auto">+ <DropdownMenuContent align="start" anchor={anchor} finalFocus={finalFocus} className="w-auto"><RowActionGroups groups={filled} />+ {trailing}</DropdownMenuContent></DropdownMenu>);diff --git a/packages/views/editor/attachment-thumbnail.test.tsx b/packages/views/editor/attachment-thumbnail.test.tsxnew file mode 100644index 0000000000..2fff2d4670--- /dev/null+++ b/packages/views/editor/attachment-thumbnail.test.tsx@@ -0,0 +1,269 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { fireEvent, screen, waitFor } from "@testing-library/react";+import type { ReactNode } from "react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import type { Attachment as AttachmentRecord } from "@multica/core/types";+import { renderWithI18n } from "../test/i18n";++const {+ getAttachmentMock,+ getAttachmentBlobMock,+ thumbnailBlobMock,+ originalBlobMock,+ getBaseUrlMock,+ downloadMock,+ openAtMock,+ copyImageMock,+ copyTextMock,+} = vi.hoisted(() => ({+ getAttachmentMock: vi.fn(),+ getAttachmentBlobMock: vi.fn(),+ thumbnailBlobMock: vi.fn(async () => new Blob(["thumb"], { type: "image/jpeg" })),+ originalBlobMock: vi.fn(async () => new Blob(["original"], { type: "image/png" })),+ getBaseUrlMock: vi.fn(() => ""),+ downloadMock: vi.fn(),+ openAtMock: vi.fn((_key: string) => true),+ copyImageMock: vi.fn(async (_source: string | (() => Promise<Blob>)) => true),+ copyTextMock: vi.fn(async (_text: string) => true),+}));++vi.mock("@multica/core/api", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/api")>()),+ api: {+ getAttachment: getAttachmentMock,+ getAttachmentBlob: getAttachmentBlobMock,+ getAttachmentThumbnailBlob: thumbnailBlobMock,+ getAttachmentOriginalBlob: originalBlobMock,+ getBaseUrl: getBaseUrlMock,+ },+}));++vi.mock("@multica/ui/lib/clipboard", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/ui/lib/clipboard")>()),+ copyImage: copyImageMock,+ copyText: copyTextMock,+}));++vi.mock("./use-download-attachment", () => ({+ useDownloadAttachment: () => downloadMock,+}));++vi.mock("./preview-sequence-context", () => ({+ usePreviewSequence: () => ({ openAt: openAtMock }),+}));++import { MessageSquare } from "@multica/ui/icons";+import { Attachment } from "./attachment";+import { ImageThumbnailsProvider } from "./image-thumbnails-context";+import { AttachmentDownloadProvider } from "./attachment-download-context";+import { useContextMenuScope } from "../common/context-menu-scope";+import { __resetInlineMediaBlobCacheForTests } from "./hooks/use-inline-media-url";++const ID = "01a1fd7f-d98e-74a7-a9f3-650a6ca7bc15";+const THUMBNAIL = `/api/attachments/${ID}/thumbnail`;+const SIGNED = "https://cdn.example.test/shot.png?Signature=s";++function record(over: Partial<AttachmentRecord> = {}): AttachmentRecord {+ return {+ id: ID,+ workspace_id: "ws-1",+ issue_id: "issue-1",+ comment_id: "c-1",+ chat_session_id: null,+ chat_message_id: null,+ uploader_type: "agent",+ uploader_id: "lambda",+ filename: "shot.png",+ url: "https://cdn.example.test/shot.png",+ download_url: SIGNED,+ markdown_url: `https://cdn.example.test/api/attachments/${ID}/download`,+ content_type: "image/png",+ size_bytes: 6 * 1024 * 1024,+ width: 5472,+ height: 3072,+ thumbnail_url: THUMBNAIL,+ created_at: "2026-11-20T10:00:00Z",+ ...over,+ };+}++function CommentScope({ children }: { children: ReactNode }) {+ const ref = useContextMenuScope(() => ({+ label: "Comment actions",+ icon: <MessageSquare />,+ groups: [[{ key: "reply", icon: null, label: "Reply", onSelect: vi.fn() }]],+ }));+ return <div ref={ref}>{children}</div>;+}++function renderImage(+ attachment: AttachmentRecord,+ { thumbnails = true, editable = false }: { thumbnails?: boolean; editable?: boolean } = {},+) {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ return renderWithI18n(+ <QueryClientProvider client={qc}>+ <ImageThumbnailsProvider enabled={thumbnails}>+ <CommentScope>+ <Attachment attachment={{ kind: "record", attachment }} layout="card" editable={editable} />+ </CommentScope>+ </ImageThumbnailsProvider>+ </QueryClientProvider>,+ );+}++function sources() {+ return Array.from(document.querySelectorAll("img"), (img) => img.getAttribute("src"));+}++function image() {+ return document.querySelector<HTMLImageElement>("img")!;+}++beforeEach(() => {+ vi.clearAllMocks();+ getBaseUrlMock.mockReturnValue("");+ Object.defineProperty(URL, "createObjectURL", {+ configurable: true,+ value: vi.fn(() => "blob:thumbnail"),+ });+ Object.defineProperty(URL, "revokeObjectURL", { configurable: true, value: vi.fn() });+});++afterEach(() => {+ __resetInlineMediaBlobCacheForTests();+ Reflect.deleteProperty(navigator, "clipboard");+ vi.unstubAllGlobals();+});++describe("comment images under the thumbnails preference", () => {+ it("loads the server thumbnail, never the original", () => {+ renderImage(record());+ expect(sources()).toEqual([THUMBNAIL]);+ expect(getAttachmentBlobMock).not.toHaveBeenCalled();+ // The box keeps the original's size, so the layout is unchanged.+ expect(image()).toHaveAttribute("width", "5472");+ expect(image()).toHaveAttribute("height", "3072");+ });++ it("loads the original under Full size, in an editor, and without a thumbnail", () => {+ const { unmount } = renderImage(record(), { thumbnails: false });+ expect(sources()).toEqual([SIGNED]);+ unmount();++ const editing = renderImage(record(), { editable: true });+ expect(sources()).toEqual([SIGNED]);+ editing.unmount();++ renderImage(record({ thumbnail_url: undefined }));+ expect(sources()).toEqual([SIGNED]);+ });++ it("falls back to the original when the thumbnail fails to load", () => {+ renderImage(record());+ fireEvent.error(image());+ expect(sources()).toEqual([SIGNED]);+ });++ it("on desktop, fetches the thumbnail's bytes and nothing for the original", async () => {+ getBaseUrlMock.mockReturnValue("https://api.example.test");+ // Proxy storage: the original would be re-signed, then fetched as bytes.+ getAttachmentMock.mockResolvedValue(record({ download_url: "" }));+ renderImage(+ record({ download_url: "", markdown_url: `/api/attachments/${ID}/download`, url: "" }),+ );+ await waitFor(() => expect(sources()).toEqual(["blob:thumbnail"]));+ expect(thumbnailBlobMock).toHaveBeenCalledWith(ID, expect.anything());+ expect(getAttachmentMock).not.toHaveBeenCalled();+ expect(getAttachmentBlobMock).not.toHaveBeenCalled();+ });++ it("on desktop, re-signs the original once its thumbnail fails", async () => {+ getBaseUrlMock.mockReturnValue("https://api.example.test");+ thumbnailBlobMock.mockRejectedValueOnce(new Error("404"));+ getAttachmentMock.mockResolvedValue(record());+ renderImage(+ record({ download_url: "", markdown_url: `/api/attachments/${ID}/download`, url: "" }),+ );+ await waitFor(() => expect(sources()).toEqual([SIGNED]));+ expect(getAttachmentMock).toHaveBeenCalledTimes(1);+ });++ it("resolves a body image to its attachment and loads the thumbnail", () => {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ const attachment = record();+ renderWithI18n(+ <QueryClientProvider client={qc}>+ <ImageThumbnailsProvider enabled>+ <AttachmentDownloadProvider attachments={[attachment]}>+ <Attachment+ attachment={{ kind: "url", url: attachment.markdown_url!, filename: "", forceKind: "image" }}+ />+ </AttachmentDownloadProvider>+ </ImageThumbnailsProvider>+ </QueryClientProvider>,+ );+ expect(sources()).toEqual([THUMBNAIL]);+ });+});++describe("a comment thumbnail's right-click menu", () => {+ async function openMenu() {+ // Handled, so neither the browser's nor the desktop host's image menu,+ // which would act on the thumbnail, opens.+ expect(fireEvent.contextMenu(image())).toBe(false);+ return screen.findByRole("menu");+ }++ async function menuItems() {+ await openMenu();+ return (await screen.findAllByRole("menuitem")).map((item) => item.textContent);+ }++ it("acts on the original and keeps the comment's actions", async () => {+ Object.defineProperty(navigator, "clipboard", {+ configurable: true,+ value: { write: vi.fn() },+ });+ vi.stubGlobal("ClipboardItem", class {});+ renderImage(record());++ expect(await menuItems()).toEqual([+ "View image",+ "Copy image",+ "Download",+ "Copy link",+ "Comment actions",+ ]);++ fireEvent.click(screen.getByRole("menuitem", { name: "Copy image" }));+ const load = copyImageMock.mock.calls[0]![0] as () => Promise<Blob>;+ expect(await (await load()).text()).toBe("original");+ expect(originalBlobMock).toHaveBeenCalledWith(ID);++ await openMenu();+ fireEvent.click(await screen.findByRole("menuitem", { name: "Download" }));+ expect(downloadMock).toHaveBeenCalledWith(ID);++ await openMenu();+ fireEvent.click(await screen.findByRole("menuitem", { name: "View image" }));+ expect(openAtMock).toHaveBeenCalledWith(ID);++ await openMenu();+ fireEvent.click(await screen.findByRole("menuitem", { name: "Copy link" }));+ expect(copyTextMock).toHaveBeenCalledWith(SIGNED);+ });++ // Plain http:// self-hosting has no async Clipboard API.+ it("offers no Copy image without the async Clipboard API", async () => {+ expect(navigator.clipboard?.write).toBeUndefined();+ renderImage(record());+ expect(await menuItems()).toEqual(["View image", "Download", "Copy link", "Comment actions"]);+ });++ it("leaves an original's right-click to the host menu", () => {+ renderImage(record(), { thumbnails: false });+ expect(fireEvent.contextMenu(image())).toBe(true);+ expect(screen.queryByRole("menu")).toBeNull();+ });+});diff --git a/packages/views/editor/attachment.tsx b/packages/views/editor/attachment.tsxindex e1e3c5d8f8..4fc6dc3f71 100644--- a/packages/views/editor/attachment.tsx+++ b/packages/views/editor/attachment.tsx@@ -35,7 +35,15 @@ import {Maximize2,Trash2,} from "@multica/ui/icons";-import { useCallback, useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";+import {+ useCallback,+ useEffect,+ useRef,+ useState,+ type CSSProperties,+ type MouseEvent,+ type ReactNode,+} from "react";import { autoUpdate, computePosition, flip, hide, offset, shift } from "@floating-ui/dom";import { toast } from "sonner";import { cn } from "@multica/ui/lib/utils";@@ -51,12 +59,23 @@ import {} from "@multica/core/types/attachment-url";import { useT } from "../i18n";import { DeferredTooltip } from "../common/deferred-tooltip";-import { useContextMenuScope } from "../common/context-menu-scope";+import {+ ContextMenuScopeSubmenu,+ findContextMenuScope,+ useContextMenuScope,+ useScopeSubmenuFocus,+ type ResolvedContextMenuScope,+} from "../common/context-menu-scope";+import { dropdownPrimitives } from "../common/menu-primitives";+import { CLOSED_ROW_MENU, yieldsToTextMenu, type RowMenuState } from "../common/point-menu";import { useAttachmentDownloadResolver } from "./attachment-download-context";import { useAttachmentPreview } from "./attachment-preview-modal";import { usePreviewSequence } from "./preview-sequence-context";+import { useImageThumbnails } from "./image-thumbnails-context";+import { OriginalImageMenu } from "./original-image-menu";import {isObjectURL,+ useAttachmentThumbnailURL,useResignedInlineMedia,} from "./hooks/use-inline-media-url";import { useDownloadAttachment } from "./use-download-attachment";@@ -317,6 +336,26 @@ export function Attachment({(state.filename || state.contentType? getPreviewKind(state.contentType, state.filename): null);+ // Where the surface asks for thumbnails, a large image paints the server's+ // downscaled copy and never loads its original; a failed thumbnail falls+ // back to the original.+ const preferThumbnails = useImageThumbnails();+ const [failedThumbnail, setFailedThumbnail] = useState<string | null>(null);+ const thumbnailPath = state.record?.thumbnail_url ?? "";+ const wantsThumbnail =+ kind === "image" &&+ preferThumbnails &&+ !editable &&+ !state.uploading &&+ !!state.attachmentId &&+ !!thumbnailPath &&+ failedThumbnail !== thumbnailPath;+ const thumbnail = useAttachmentThumbnailURL(+ state.attachmentId ?? "",+ thumbnailPath,+ wantsThumbnail,+ );+ const showThumbnail = wantsThumbnail && !thumbnail.failed;// The picked URL may still be the auth-gated API endpoint (reopened drafts// whose persisted record has no signed download_url). Upgrade it to a// freshly signed URL on clients that can't load the endpoint natively, or —@@ -327,7 +366,11 @@ export function Attachment({state.attachmentId,state.url,kind === "image",+ { enabled: !showThumbnail },);+ const [imageMenu, setImageMenu] = useState<RowMenuState>(CLOSED_ROW_MENU);+ const [outerScope, setOuterScope] = useState<ResolvedContextMenuScope["submenu"]>(null);+ const outerScopeFocus = useScopeSubmenuFocus(outerScope);// Object URLs are session-local, so anything that hands a URL to the user or// to another surface keeps the durable pick instead.const shareUrl = isObjectURL(mediaUrl) ? state.url : mediaUrl;@@ -418,10 +461,17 @@ export function Attachment({}, { content: !editable });if (kind === "image") {+ const openImageMenu = (event: MouseEvent<HTMLElement>) => {+ if (yieldsToTextMenu(event.target as Element)) return;+ event.preventDefault();+ // The comment around the image, read when the menu opens.+ setOuterScope(findContextMenuScope(event.currentTarget.parentElement).submenu);+ setImageMenu({ open: true, point: { x: event.clientX, y: event.clientY } });+ };return (<><ImageAttachmentView- src={mediaUrl}+ src={showThumbnail ? thumbnail.url : mediaUrl}linkUrl={shareUrl}alt={state.filename}uploading={state.uploading}@@ -432,9 +482,28 @@ export function Attachment({onView={openPreview}onDownload={handleDownload}onDelete={onDelete}+ onError={showThumbnail ? () => setFailedThumbnail(thumbnailPath) : undefined}+ onContextMenu={showThumbnail ? openImageMenu : undefined}scopeRef={scopeRef}className={cn(layout === "card" && "image-standalone", className)}/>+ {showThumbnail && imageMenu.point && (+ <OriginalImageMenu+ attachmentId={state.attachmentId!}+ link={shareUrl}+ menu={imageMenu}+ onOpenChange={(open) => setImageMenu((current) => ({ ...current, open }))}+ onView={openPreview}+ onDownload={() => void handleDownload()}+ trailing={+ <ContextMenuScopeSubmenu+ submenu={outerScopeFocus.submenu}+ primitives={dropdownPrimitives}+ />+ }+ finalFocus={outerScopeFocus.finalFocus}+ />+ )}{preview.modal}</>);@@ -516,6 +585,10 @@ interface ImageAttachmentViewProps {onView: () => void;onDownload: () => void | Promise<unknown>;onDelete?: () => void;+ /** Called when `src` fails to load. */+ onError?: () => void;+ /** Replaces the host's right-click menu on the image. */+ onContextMenu?: (event: MouseEvent<HTMLElement>) => void;/** Registers the image with the right-click menu. */scopeRef?: (element: HTMLElement | null) => void;className?: string;@@ -533,6 +606,8 @@ function ImageAttachmentView({onView,onDownload,onDelete,+ onError,+ onContextMenu,scopeRef,className,}: ImageAttachmentViewProps) {@@ -641,7 +716,7 @@ function ImageAttachmentView({// the NodeViewWrapper still emits its own outer .image-node div around// this — the duplicate `image-node` class is harmless.return (- <span ref={scopeRef} className="image-node">+ <span ref={scopeRef} className="image-node" onContextMenu={onContextMenu}><spanref={figureRef}className={cn(@@ -679,7 +754,10 @@ function ImageAttachmentView({className={cn("image-content", uploading && "image-uploading")}draggable={false}onLoad={() => setLoadedSrc(src)}- onError={() => setLoadedSrc(src)}+ onError={() => {+ setLoadedSrc(src);+ onError?.();+ }}/>{hasToolbar && (<spandiff --git a/packages/views/editor/hooks/use-inline-media-url.ts b/packages/views/editor/hooks/use-inline-media-url.tsindex 1ffe8bf7b1..8954dcfe21 100644--- a/packages/views/editor/hooks/use-inline-media-url.ts+++ b/packages/views/editor/hooks/use-inline-media-url.ts@@ -84,17 +84,20 @@ export function __resetInlineMediaBlobCacheForTests(): void {// load failure as meaningful (the viewer skips broken images) waits it out// instead of rendering it.// Viewers and neighbour prefetch reauthenticate stale metadata on mount;-// inline thumbnails stay lazy.+// inline thumbnails stay lazy. A disabled call fetches nothing and returns+// the picked URL, for a caller that is not rendering the original.export function useResignedInlineMedia(attachmentId: string | undefined,rawPickedUrl: string,blobFallback: boolean,{+ enabled = true,refreshOnMount = false,metadataSource = "workspace",workspaceId,currentMetadata,}: {+ enabled?: boolean;refreshOnMount?: boolean;metadataSource?: "workspace" | "markdown-link";/** Workspace that owns the attachment, when it may not be the current one. */@@ -117,6 +120,7 @@ export function useResignedInlineMedia(}})();const needsResign =+ enabled &&!!resignAttachmentId &&!!pickedUrl &&(refreshOnMount ||@@ -218,24 +222,28 @@ export function useResignedInlineMedia(// cookie, so the browser can lazy-load and cache it. Clients that cannot ride// that cookie (see useResignedInlineMedia) fetch the bytes through the// authenticated client instead; a thumbnail is small enough to hold as a blob.-// `failed` tells the caller to fall back to the original.+// `failed` tells the caller to fall back to the original. A disabled call+// loads nothing and returns an empty url.export function useAttachmentThumbnailURL(attachmentId: string,thumbnailPath: string,+ enabled = true,): { url: string; pending: boolean; failed: boolean } {const native =(api.getBaseUrl?.() ?? "") === "" &&thumbnailPath.startsWith("/") &&!thumbnailPath.startsWith("//");+ const fetchBytes = enabled && !native;const { data: blob, isError } = useQuery({queryKey: ["attachment-thumbnail-blob", attachmentId],queryFn: ({ signal }) => api.getAttachmentThumbnailBlob(attachmentId, signal),- enabled: !native,+ enabled: fetchBytes,staleTime: Infinity,gcTime: INLINE_BLOB_GC_MS,retry: false,});- const blobUrl = useObjectURL(native ? undefined : `thumbnail:${attachmentId}`, blob, !!blob);+ const blobUrl = useObjectURL(fetchBytes ? `thumbnail:${attachmentId}` : undefined, blob, !!blob);+ if (!enabled) return { url: "", pending: false, failed: false };if (native) return { url: thumbnailPath, pending: false, failed: false };if (isError) return { url: "", pending: false, failed: true };return { url: blobUrl, pending: !blobUrl, failed: false };diff --git a/packages/views/editor/image-thumbnails-context.tsx b/packages/views/editor/image-thumbnails-context.tsxnew file mode 100644index 0000000000..b3da3f5009--- /dev/null+++ b/packages/views/editor/image-thumbnails-context.tsx@@ -0,0 +1,30 @@+"use client";++import { createContext, use, type ReactNode } from "react";++const ImageThumbnailsContext = createContext(false);++/**+ * Inside an enabled provider, a read-only image whose attachment has a server+ * thumbnail shows that instead of the original. For surfaces that draw images+ * smaller than they are — the issue timeline's comment thumbnails — so the+ * page does not download and decode every original to paint them. The viewer,+ * download and copy keep the original.+ */+export function ImageThumbnailsProvider({+ enabled,+ children,+}: {+ enabled: boolean;+ children: ReactNode;+}) {+ return (+ <ImageThumbnailsContext.Provider value={enabled}>+ {children}+ </ImageThumbnailsContext.Provider>+ );+}++export function useImageThumbnails(): boolean {+ return use(ImageThumbnailsContext);+}diff --git a/packages/views/editor/index.ts b/packages/views/editor/index.tsindex 37dab00cc3..d7af7d2d26 100644--- a/packages/views/editor/index.ts+++ b/packages/views/editor/index.ts@@ -23,6 +23,7 @@ export { useLazyEditor, type LazyEditorHandle, type LazyFocusTarget } from "./usexport { anchorFromPoint, type TextAnchor } from "./text-anchor";export { useDownloadAttachment } from "./use-download-attachment";export { AttachmentDownloadProvider } from "./attachment-download-context";+export { ImageThumbnailsProvider } from "./image-thumbnails-context";export {AttachmentPreviewModal,useAttachmentPreview,diff --git a/packages/views/editor/original-image-menu.tsx b/packages/views/editor/original-image-menu.tsxnew file mode 100644index 0000000000..7f992bb35a--- /dev/null+++ b/packages/views/editor/original-image-menu.tsx@@ -0,0 +1,100 @@+"use client";++import type { ReactNode } from "react";+import { toast } from "sonner";+import { api } from "@multica/core/api";+import { Download, Eye, ImageIcon, Link2 } from "@multica/ui/icons";+import { canCopyImage, copyImage, copyText } from "@multica/ui/lib/clipboard";+import { useT } from "../i18n";+import type { RowMenuState } from "../common/point-menu";+import { RowActionsPointMenu, type RowActionItem } from "../common/row-actions-menu";++/**+ * The right-click menu of an image showing the server's downscaled copy. The+ * browser's image menu, and the desktop's Copy image, would act on the copy on+ * screen, so the image brings this one, acting on the original. The caller+ * opens it from `onContextMenu` and calls `preventDefault`, which keeps either+ * of those from opening.+ */+export function OriginalImageMenu({+ attachmentId,+ link,+ menu,+ onOpenChange,+ onView,+ onDownload,+ trailing,+ finalFocus,+}: {+ attachmentId: string;+ /** What Copy link copies; no item without one. */+ link: string | null | undefined;+ menu: RowMenuState;+ onOpenChange: (open: boolean) => void;+ onView: () => void;+ onDownload: () => void;+ trailing?: ReactNode;+ finalFocus?: () => boolean;+}) {+ const { t } = useT("editor");+ const copyOriginal = async () => {+ if (await copyImage(() => api.getAttachmentOriginalBlob(attachmentId))) {+ toast.success(t(($) => $.image.image_copied));+ } else {+ toast.error(t(($) => $.image.copy_image_failed));+ }+ };+ const copyLink = async (url: string) => {+ // Same-origin web resolves the durable URL to a site-relative path.+ if (await copyText(new URL(url, window.location.href).href)) {+ toast.success(t(($) => $.image.link_copied));+ } else {+ toast.error(t(($) => $.image.copy_link_failed));+ }+ };+ const actions: RowActionItem[] = [+ // The viewer shows the original, where the browser's own Copy image works+ // even without the async Clipboard API that Copy image here needs.+ {+ key: "view",+ icon: <Eye />,+ label: t(($) => $.image.view),+ onSelect: onView,+ },+ ...(canCopyImage()+ ? [+ {+ key: "copy-image",+ icon: <ImageIcon />,+ label: t(($) => $.image.copy_image),+ onSelect: () => void copyOriginal(),+ },+ ]+ : []),+ {+ key: "download",+ icon: <Download />,+ label: t(($) => $.image.download),+ onSelect: onDownload,+ },+ ...(link+ ? [+ {+ key: "copy-link",+ icon: <Link2 />,+ label: t(($) => $.image.copy_link),+ onSelect: () => void copyLink(link),+ },+ ]+ : []),+ ];+ return (+ <RowActionsPointMenu+ menu={menu}+ onOpenChange={onOpenChange}+ groups={[actions]}+ trailing={trailing}+ finalFocus={finalFocus}+ />+ );+}diff --git a/packages/views/issues/components/deliverables/deliverable-thumbnail.tsx b/packages/views/issues/components/deliverables/deliverable-thumbnail.tsxindex 5fdb48ad75..2a5544d196 100644--- a/packages/views/issues/components/deliverables/deliverable-thumbnail.tsx+++ b/packages/views/issues/components/deliverables/deliverable-thumbnail.tsx@@ -1,21 +1,16 @@"use client";import { useEffect, useState, type MouseEvent } from "react";-import { toast } from "sonner";-import { api } from "@multica/core/api";import type { Attachment } from "@multica/core/types";import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";-import { Download, Eye, ImageIcon, Link2 } from "@multica/ui/icons";-import { canCopyImage, copyImage, copyText } from "@multica/ui/lib/clipboard";import { cn } from "@multica/ui/lib/utils";-import { useT } from "../../../i18n";import { CLOSED_ROW_MENU, type RowMenuState } from "../../../common/point-menu";-import { RowActionsPointMenu, type RowActionItem } from "../../../common/row-actions-menu";import { useDownloadAttachment } from "../../../editor";import {useAttachmentThumbnailURL,useResignedInlineMedia,} from "../../../editor/hooks/use-inline-media-url";+import { OriginalImageMenu } from "../../../editor/original-image-menu";import { useOpenAttachment } from "./use-open-attachment";import { fileTypeLabel, getPreviewKind } from "../../../editor/utils/preview";import { fileIcon } from "../../../editor/utils/file-icon";@@ -141,7 +136,7 @@ function ResizedImageThumbnail({)}</span>{menu.point && (- <OriginalImageMenu+ <TileImageMenuattachment={attachment}menu={menu}onOpenChange={(open) => setMenu((current) => ({ ...current, open }))}@@ -151,7 +146,7 @@ function ResizedImageThumbnail({);}-function OriginalImageMenu({+function TileImageMenu({attachment,menu,onOpenChange,@@ -160,64 +155,18 @@ function OriginalImageMenu({menu: RowMenuState;onOpenChange: (open: boolean) => void;}) {- const { t } = useT("editor");const { open, modal } = useOpenAttachment();const download = useDownloadAttachment();- const link = resolvePublicFileUrl(attachment.markdown_url);- const copyOriginal = async () => {- if (await copyImage(() => api.getAttachmentOriginalBlob(attachment.id))) {- toast.success(t(($) => $.image.image_copied));- } else {- toast.error(t(($) => $.image.copy_image_failed));- }- };- const copyLink = async (url: string) => {- // Same-origin web resolves the durable URL to a site-relative path.- if (await copyText(new URL(url, window.location.href).href)) {- toast.success(t(($) => $.image.link_copied));- } else {- toast.error(t(($) => $.image.copy_link_failed));- }- };- const actions: RowActionItem[] = [- // The viewer shows the original, where the browser's own Copy image works- // even without the async Clipboard API that Copy image here needs.- {- key: "view",- icon: <Eye />,- label: t(($) => $.image.view),- onSelect: () => open(attachment),- },- ...(canCopyImage()- ? [- {- key: "copy-image",- icon: <ImageIcon />,- label: t(($) => $.image.copy_image),- onSelect: () => void copyOriginal(),- },- ]- : []),- {- key: "download",- icon: <Download />,- label: t(($) => $.image.download),- onSelect: () => void download(attachment.id),- },- ...(link- ? [- {- key: "copy-link",- icon: <Link2 />,- label: t(($) => $.image.copy_link),- onSelect: () => void copyLink(link),- },- ]- : []),- ];return (<>- <RowActionsPointMenu menu={menu} onOpenChange={onOpenChange} groups={[actions]} />+ <OriginalImageMenu+ attachmentId={attachment.id}+ link={resolvePublicFileUrl(attachment.markdown_url)}+ menu={menu}+ onOpenChange={onOpenChange}+ onView={() => open(attachment)}+ onDownload={() => void download(attachment.id)}+ />{modal}</>);diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsxindex bab7ffdeb5..eff9acf4a0 100644--- a/packages/views/issues/components/issue-detail.test.tsx+++ b/packages/views/issues/components/issue-detail.test.tsx@@ -199,6 +199,10 @@ vi.mock("../../editor", async () => ({children,usePreviewSequence: () => ({ openAt: () => false }),collectPreviewSequence: () => [],+ // The real provider is plain context; attachment-thumbnail.test.tsx covers it.+ ...(await vi.importActual<typeof import("../../editor/image-thumbnails-context")>(+ "../../editor/image-thumbnails-context",+ )),// Comment attachments render as their filename — the viewer and file cards// have their own suites.AttachmentDownloadProvider: ({ children }: { children: React.ReactNode }) =>diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 43e048c933..cdf836bcfc 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -49,7 +49,7 @@ import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@multica/uimport { Sheet, SheetContent } from "@multica/ui/components/ui/sheet";import { useIsMobile } from "@multica/ui/hooks/use-mobile";import { StorageLimitNotice } from "../../billing/storage-limit-notice";-import { ContentEditor, ReadonlyContent, type ContentEditorRef, TitleEditor, type TitleEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useEditorUpload, PreviewSequenceProvider, collectPreviewSequence } from "../../editor";+import { ContentEditor, ReadonlyContent, type ContentEditorRef, TitleEditor, type TitleEditorRef, useFileDropZone, FileDropOverlay, useLazyEditor, useEditorUpload, PreviewSequenceProvider, collectPreviewSequence, ImageThumbnailsProvider } from "../../editor";import {WAKEUP_ACTIVITY_ACTIONS,WakeupActivityIcon,@@ -1753,7 +1753,8 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d// User preference: pin the bottom comment bar to the scroll viewport. Off// below `md` regardless of the preference — see the hook.const stickyComposer = useStickyComposer();- // Read by the image rules in editor/styles/attachment.css.+ // Read by the image rules in editor/styles/attachment.css; under+ // "thumbnails" the timeline's images also load the server's thumbnails.const commentImageLayout = useCommentComposerStore((s) => s.imageLayout);// Per-session: which resolved threads the user has temporarily expanded.@@ -4535,28 +4536,30 @@ export function IssueDetail({ issueId, onDelete, onDone, onUnsubscribeArchive, d// flash empty.<TimelineSkeleton />) : (- <div ref={virtualTimelineRef} className="mt-4">- <Virtuoso- key={`${wsId}:${id}`}- ref={virtuosoRef}- customScrollParent={scrollContainerEl}- data={items}- initialScrollTop={readingAnchor ? undefined : restoredScrollTop}- heightEstimates={timelineHeightEstimates}- increaseViewportBy={timelineOverscan}- totalListHeightChanged={handleTimelineHeightChange}- rangeChanged={handleTimelineRangeChanged}- computeItemKey={(_i, item) => `${item.kind}:${item.kind === "run" ? item.run.task.id : item.id}`}- // Also load-bearing for long threads: keepThreadRowAnchored- // corrects after Virtuoso's resize handling in the same frame.- skipAnimationFrameInResizeObserver- // followOutput intentionally NOT set. Virtuoso treats- // it as a sticky "is at bottom" flag and resets- // scrollTop to maxScrollTop on every height-change- // tick — issue-detail is document-shaped, not chat.- itemContent={renderItem}- />- </div>+ <ImageThumbnailsProvider enabled={commentImageLayout === "thumbnails"}>+ <div ref={virtualTimelineRef} className="mt-4">+ <Virtuoso+ key={`${wsId}:${id}`}+ ref={virtuosoRef}+ customScrollParent={scrollContainerEl}+ data={items}+ initialScrollTop={readingAnchor ? undefined : restoredScrollTop}+ heightEstimates={timelineHeightEstimates}+ increaseViewportBy={timelineOverscan}+ totalListHeightChanged={handleTimelineHeightChange}+ rangeChanged={handleTimelineRangeChanged}+ computeItemKey={(_i, item) => `${item.kind}:${item.kind === "run" ? item.run.task.id : item.id}`}+ // Also load-bearing for long threads: keepThreadRowAnchored+ // corrects after Virtuoso's resize handling in the same frame.+ skipAnimationFrameInResizeObserver+ // followOutput intentionally NOT set. Virtuoso treats+ // it as a sticky "is at bottom" flag and resets+ // scrollTop to maxScrollTop on every height-change+ // tick — issue-detail is document-shaped, not chat.+ itemContent={renderItem}+ />+ </div>+ </ImageThumbnailsProvider>))}