Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7759: copy image from the desktop attachment viewer (#8888)
Jiayuan Zhang0a51a6cc433a
diff --git a/apps/desktop/src/main/context-menu.test.ts b/apps/desktop/src/main/context-menu.test.tsindex 8cc1e80160..fcd5dadcde 100644--- a/apps/desktop/src/main/context-menu.test.ts+++ b/apps/desktop/src/main/context-menu.test.ts@@ -61,6 +61,10 @@ type ContextMenuParams = {selectionText: string;isEditable: boolean;linkURL: string;+ mediaType: string;+ hasImageContents: boolean;+ x: number;+ y: number;editFlags: {canCut: boolean;canCopy: boolean;@@ -78,6 +82,7 @@ type Listener = (event: unknown, params: ContextMenuParams) => void;function makeWebContents() {const handlers: Listener[] = [];return {+ copyImageAt: vi.fn(),on(event: string, fn: Listener) {if (event === "context-menu") handlers.push(fn);},@@ -148,12 +153,12 @@ describe("installContextMenu — link items", () => {it("does NOT add link items when there is no link under the cursor", () => {const wc = makeWebContents();installContextMenu(wc as never);- wc.fire({- selectionText: "hello",- isEditable: false,- linkURL: "",- editFlags: { ...baseEditFlags, canCopy: true },- });+ wc.fire(+ baseSelection({+ selectionText: "hello",+ editFlags: { ...baseEditFlags, canCopy: true },+ }),+ );const labels = lastMenuLabelsOrEmpty();expect(labels).not.toContain("Open Link in Browser");// Selection-only context still surfaces copy as before — guards@@ -184,6 +189,63 @@ describe("installContextMenu — link items", () => {});});+describe("installContextMenu — image items", () => {+ beforeEach(() => {+ ctx.capturedItems.length = 0;+ ctx.popupSpy.mockClear();+ ctx.preferredLanguagesRef.current = ["en-US"];+ });++ it("adds 'Copy Image' on a loaded image and copies the pixels under the cursor", () => {+ // MUL-7759: the attachment viewer and inline images had no way to+ // copy the picture itself — Electron shows no menu at all by default.+ const wc = makeWebContents();+ installContextMenu(wc as never);+ wc.fire(+ baseSelection({ mediaType: "image", hasImageContents: true, x: 120, y: 48 }),+ );++ expect(lastMenuLabels()).toEqual(["Copy Image"]);+ invokeByLabel("Copy Image");+ expect(wc.copyImageAt).toHaveBeenCalledWith(120, 48);+ expect(ctx.popupSpy).toHaveBeenCalledTimes(1);+ });++ it("does NOT add 'Copy Image' before the image has loaded", () => {+ const wc = makeWebContents();+ installContextMenu(wc as never);+ wc.fire(baseSelection({ mediaType: "image", hasImageContents: false }));+ expect(lastMenuLabelsOrEmpty()).not.toContain("Copy Image");+ expect(ctx.popupSpy).not.toHaveBeenCalled();+ });++ it("lists the image items after the link items for an image inside a link", () => {+ const wc = makeWebContents();+ installContextMenu(wc as never);+ wc.fire(+ baseSelection({+ linkURL: "https://multica.ai",+ mediaType: "image",+ hasImageContents: true,+ }),+ );+ expect(lastMenu().map((i) => i.label ?? i.type)).toEqual([+ "Open Link in Browser",+ "Copy Link Address",+ "separator",+ "Copy Image",+ ]);+ });++ it("uses zh-Hans labels when the OS preferred language is Chinese", () => {+ ctx.preferredLanguagesRef.current = ["zh-CN"];+ const wc = makeWebContents();+ installContextMenu(wc as never);+ wc.fire(baseSelection({ mediaType: "image", hasImageContents: true }));+ expect(lastMenuLabels()).toContain("复制图片");+ });+});+// --- helpers ---function baseSelection(over: Partial<ContextMenuParams>): ContextMenuParams {@@ -191,6 +253,10 @@ function baseSelection(over: Partial<ContextMenuParams>): ContextMenuParams {selectionText: "",isEditable: false,linkURL: "",+ mediaType: "none",+ hasImageContents: false,+ x: 0,+ y: 0,editFlags: { ...baseEditFlags },...over,};diff --git a/apps/desktop/src/main/context-menu.ts b/apps/desktop/src/main/context-menu.tsindex 93610cd7d5..32a847edf9 100644--- a/apps/desktop/src/main/context-menu.ts+++ b/apps/desktop/src/main/context-menu.ts@@ -12,16 +12,23 @@ import { isSafeExternalHttpUrl, openExternalSafely } from "./external-url";// in the renderer has no way to copy it. Mirror Chrome's minimal clipboard// menu using `roles`, which keeps i18n + accelerator handling native.//-// Custom (non-role) link items below are NOT auto-localized by Electron —-// roles like "copy" pull labels from the OS, but a custom MenuItem only-// shows the `label` you give it. We translate by OS-preferred language so-// the link items at least track Chinese / Japanese / Korean speakers+// Custom (non-role) link and image items below are NOT auto-localized by+// Electron — roles like "copy" pull labels from the OS, but a custom+// MenuItem only shows the `label` you give it. We translate by OS-preferred+// language so those items at least track Chinese / Japanese / Korean speakers// alongside the English default; everything else falls through to English,// which matches Chrome's behavior on those locales without app-level// translation files.export function installContextMenu(webContents: WebContents): void {webContents.on("context-menu", (_event, params) => {- const { editFlags, selectionText, isEditable, linkURL } = params;+ const {+ editFlags,+ selectionText,+ isEditable,+ linkURL,+ mediaType,+ hasImageContents,+ } = params;const hasSelection = selectionText.trim().length > 0;// params.linkURL is the resolved absolute URL of the anchor under the// cursor; Electron normalizes relative hrefs against the page URL for@@ -83,38 +90,60 @@ export function installContextMenu(webContents: WebContents): void {);}+ // Image items — only for an <img> whose pixels have loaded. Copies the+ // decoded bitmap Chromium already holds, so it works for any format and+ // any origin (signed CDN URLs, blob: URLs) without refetching.+ if (mediaType === "image" && hasImageContents) {+ if (menu.items.length > 0) {+ menu.append(new MenuItem({ type: "separator" }));+ }+ menu.append(+ new MenuItem({+ label: labels.copyImage,+ click: () => {+ webContents.copyImageAt(params.x, params.y);+ },+ }),+ );+ }+if (menu.items.length === 0) return;const window = BrowserWindow.fromWebContents(webContents) ?? undefined;menu.popup({ window });});}-// Labels for the two link-related menu items in the user's OS-preferred-// language, with English as the fallback. Kept inline because the main-// process has no shared i18n loader (the renderer's i18next is per-window-// and not reachable from here), and pulling one in for two strings would-// be more rope than payload. Matches the four locales the renderer ships.+// Labels for the custom menu items in the user's OS-preferred language,+// with English as the fallback. Kept inline because the main process has+// no shared i18n loader (the renderer's i18next is per-window and not+// reachable from here), and pulling one in for three strings would be+// more rope than payload. Matches the four locales the renderer ships.type ContextMenuLabels = {openLink: string;copyLinkAddress: string;+ copyImage: string;};const labelsByLocale: Record<string, ContextMenuLabels> = {en: {openLink: "Open Link in Browser",copyLinkAddress: "Copy Link Address",+ copyImage: "Copy Image",},"zh-Hans": {openLink: "在浏览器中打开链接",copyLinkAddress: "复制链接地址",+ copyImage: "复制图片",},ja: {openLink: "ブラウザでリンクを開く",copyLinkAddress: "リンクのアドレスをコピー",+ copyImage: "画像をコピー",},ko: {openLink: "브라우저에서 링크 열기",copyLinkAddress: "링크 주소 복사",+ copyImage: "이미지 복사",},};diff --git a/packages/ui/lib/clipboard.ts b/packages/ui/lib/clipboard.tsindex dce3366889..4b8ba079aa 100644--- a/packages/ui/lib/clipboard.ts+++ b/packages/ui/lib/clipboard.ts@@ -58,3 +58,69 @@ export async function copyText(text: string): Promise<boolean> {previouslyFocused?.focus();}}++/**+ * Copy the image at `url` to the clipboard as a PNG.+ *+ * Reads the bytes with `fetch`, so the URL has to be readable from script:+ * same-origin, `blob:` / `data:`, or a CORS-enabled host (the desktop shell+ * reads any origin). The async Clipboard API only takes `image/png` for+ * images, so anything else — JPEG, WebP, GIF (first frame) — is re-encoded+ * through a canvas first.+ *+ * @returns `true` on success, `false` on failure (unreadable URL, bytes that+ * don't decode as an image, no async Clipboard API, permission denied).+ */+export async function copyImage(url: string): Promise<boolean> {+ if (+ typeof navigator === "undefined" ||+ !navigator.clipboard?.write ||+ typeof ClipboardItem === "undefined"+ ) {+ return false;+ }+ try {+ // The item takes the pending PNG rather than the finished one so the+ // write starts inside the click that asked for it; Safari rejects a+ // clipboard write that happens after an await.+ await navigator.clipboard.write([+ new ClipboardItem({ "image/png": fetchAsPng(url) }),+ ]);+ return true;+ } catch {+ return false;+ }+}++async function fetchAsPng(url: string): Promise<Blob> {+ const res = await fetch(url);+ if (!res.ok) throw new Error(`image fetch failed: ${res.status}`);+ const blob = await res.blob();+ if (blob.type === "image/png") return blob;++ // Decoded through <img> rather than createImageBitmap so SVG works too, and+ // so a storage host that serves `application/octet-stream` still sniffs as+ // the image it is.+ const objectUrl = URL.createObjectURL(blob);+ try {+ const image = new Image();+ image.src = objectUrl;+ await image.decode();+ const canvas = document.createElement("canvas");+ canvas.width = image.naturalWidth;+ canvas.height = image.naturalHeight;+ const context = canvas.getContext("2d");+ if (!context || canvas.width === 0 || canvas.height === 0) {+ throw new Error("image has no drawable size");+ }+ context.drawImage(image, 0, 0);+ return await new Promise<Blob>((resolve, reject) => {+ canvas.toBlob(+ (png) => (png ? resolve(png) : reject(new Error("PNG encode failed"))),+ "image/png",+ );+ });+ } finally {+ URL.revokeObjectURL(objectUrl);+ }+}diff --git a/packages/views/editor/attachment-preview-modal.test.tsx b/packages/views/editor/attachment-preview-modal.test.tsxindex c828856d0e..3d097ee149 100644--- a/packages/views/editor/attachment-preview-modal.test.tsx+++ b/packages/views/editor/attachment-preview-modal.test.tsx@@ -4,12 +4,29 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { useState, type ReactElement } from "react";import type { Attachment } from "@multica/core/types";-const openExternalMock = vi.hoisted(() => vi.fn());+const { openExternalMock, isDesktopShellMock, copyImageMock, toastMock } =+ vi.hoisted(() => ({+ openExternalMock: vi.fn(),+ // Web by default; the copy-image tests flip it to the desktop shell.+ isDesktopShellMock: vi.fn(() => false),+ copyImageMock: vi.fn(async (_url: string) => true),+ toastMock: { success: vi.fn(), error: vi.fn() },+ }));vi.mock("../platform", () => ({openExternal: openExternalMock,}));+vi.mock("../platform/local-directory", () => ({+ isDesktopShell: isDesktopShellMock,+}));++vi.mock("@multica/ui/lib/clipboard", () => ({+ copyImage: copyImageMock,+}));++vi.mock("sonner", () => ({ toast: toastMock }));+// vi.hoisted: factories run before module evaluation, letting us name mocks// referenced from inside vi.mock factories below. The Error classes must be// hoisted too because vi.mock is itself hoisted above the top-level `class`@@ -108,6 +125,9 @@ vi.mock("../i18n", () => ({sel({image: {download: "Download",+ copy_image: "Copy image",+ image_copied: "Image copied",+ copy_image_failed: "Couldn't copy image",canvas_label: "Image canvas",},canvas: {@@ -207,6 +227,8 @@ beforeEach(() => {getAttachmentTextContentMock.mockReset();navState.hasOpenInNewTab = true;slugState.value = "acme";+ isDesktopShellMock.mockReturnValue(false);+ copyImageMock.mockResolvedValue(true);// Default to web's same-origin empty base so existing absolute-URL tests// remain unaffected by the relative-URL resolution added in normalize().getBaseUrlMock.mockReturnValue("");@@ -662,6 +684,50 @@ describe("AttachmentPreviewModal — controls", () => {});});+describe("AttachmentPreviewModal — copy image (MUL-7759)", () => {+ const image = () =>+ makeAttachment({+ filename: "screenshot.png",+ content_type: "image/png",+ download_url: "https://cdn.example.test/screenshot.png?Signature=s",+ });++ it("copies the image on screen from the desktop shell", async () => {+ isDesktopShellMock.mockReturnValue(true);+ render(<AttachmentPreviewModal source={{ kind: "full", attachment: image() }} open onClose={() => {}} />);++ fireEvent.click(screen.getByRole("button", { name: "Copy image" }));++ expect(copyImageMock).toHaveBeenCalledWith(+ "https://cdn.example.test/screenshot.png?Signature=s",+ );+ await waitFor(() => expect(toastMock.success).toHaveBeenCalledWith("Image copied"));+ });++ it("says so when the copy fails", async () => {+ isDesktopShellMock.mockReturnValue(true);+ copyImageMock.mockResolvedValue(false);+ render(<AttachmentPreviewModal source={{ kind: "full", attachment: image() }} open onClose={() => {}} />);++ fireEvent.click(screen.getByRole("button", { name: "Copy image" }));++ await waitFor(() => expect(toastMock.error).toHaveBeenCalledWith("Couldn't copy image"));+ expect(toastMock.success).not.toHaveBeenCalled();+ });++ it("offers no copy button on web, where the storage CDN can't be read from script", () => {+ render(<AttachmentPreviewModal source={{ kind: "full", attachment: image() }} open onClose={() => {}} />);+ expect(screen.queryByRole("button", { name: "Copy image" })).toBeNull();+ });++ it("offers no copy button for files that aren't images", () => {+ isDesktopShellMock.mockReturnValue(true);+ const pdf = makeAttachment({ filename: "manual.pdf", content_type: "application/pdf" });+ render(<AttachmentPreviewModal source={{ kind: "full", attachment: pdf }} open onClose={() => {}} />);+ expect(screen.queryByRole("button", { name: "Copy image" })).toBeNull();+ });+});+describe("AttachmentPreviewModal — URL-only source", () => {it("renders a PDF iframe from the URL when no attachment record is available", () => {const url = "https://cdn.example.test/orphan.pdf?Signature=s";diff --git a/packages/views/editor/attachment-preview-modal.tsx b/packages/views/editor/attachment-preview-modal.tsxindex cfb0359302..1595816ec0 100644--- a/packages/views/editor/attachment-preview-modal.tsx+++ b/packages/views/editor/attachment-preview-modal.tsx@@ -58,6 +58,7 @@ import {} from "react";import { createPortal } from "react-dom";import { AnimatePresence, motion, useReducedMotion } from "motion/react";+import { toast } from "sonner";import {PreviewTooLargeError,PreviewUnsupportedError,@@ -66,6 +67,7 @@ import {ChevronLeft,ChevronRight,Code,+ Copy,Download,ExternalLink,File,@@ -92,6 +94,7 @@ import {import type { Attachment } from "@multica/core/types";import { paths, useWorkspaceSlug } from "@multica/core/paths";import { cn } from "@multica/ui/lib/utils";+import { copyImage } from "@multica/ui/lib/clipboard";import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";import {UI_EASE_OUT,@@ -100,6 +103,7 @@ import {import { useT } from "../i18n";import { useNavigation } from "../navigation";import { openExternal } from "../platform";+import { isDesktopShell } from "../platform/local-directory";import { useImmersiveMode } from "../platform/use-immersive-mode";import { ReadonlyContent } from "./readonly-content";import {@@ -802,6 +806,19 @@ function PreviewPanel({const imageLoadError =mediaUrl !== "" && mediaUrl === targetUrl ? onImageError : undefined;+ // Copying reads the image's bytes from script. The desktop renderer can+ // read any origin; web script can't read the storage CDN (it sends no CORS+ // headers), and there the browser's own context menu has Copy image. Copies+ // the frame on screen, which during a sequence swap is still the last one.+ const canCopyImage = kind === "image" && isDesktopShell();+ const handleCopyImage = async () => {+ if (await copyImage(mediaUrl)) {+ toast.success(t(($) => $.image.image_copied));+ } else {+ toast.error(t(($) => $.image.copy_image_failed));+ }+ };+// Natural size is carried with the URL it was measured from, so a panel// reused for a different attachment can never fit the new image against the// old one's dimensions.@@ -999,6 +1016,15 @@ function PreviewPanel({<ExternalLink className="size-4" /></ChromeButton>)}+ {canCopyImage && (+ <ChromeButton+ label={t(($) => $.image.copy_image)}+ disabled={!mediaUrl}+ onClick={() => void handleCopyImage()}+ >+ <Copy className="size-4" />+ </ChromeButton>+ )}<ChromeButton label={t(($) => $.image.download)} onClick={onDownload}><Download className="size-4" /></ChromeButton>diff --git a/packages/views/locales/en/editor.json b/packages/views/locales/en/editor.jsonindex 5cb37a6e41..b6c0792b3b 100644--- a/packages/views/locales/en/editor.json+++ b/packages/views/locales/en/editor.json@@ -40,6 +40,9 @@"delete": "Delete","link_copied": "Link copied","copy_link_failed": "Failed to copy link",+ "copy_image": "Copy image",+ "image_copied": "Image copied",+ "copy_image_failed": "Couldn't copy image","canvas_label": "Image canvas. Drag to pan, scroll to zoom, double-click to toggle actual size.","unavailable": "That image is no longer available — skipped it."},diff --git a/packages/views/locales/fr/editor.json b/packages/views/locales/fr/editor.jsonindex 6eb9c50ff8..35dbc80375 100644--- a/packages/views/locales/fr/editor.json+++ b/packages/views/locales/fr/editor.json@@ -40,6 +40,9 @@"delete": "Supprimer","link_copied": "Lien copié","copy_link_failed": "Échec de la copie du lien",+ "copy_image": "Copier l'image",+ "image_copied": "Image copiée",+ "copy_image_failed": "Impossible de copier l'image","canvas_label": "Zone d'image. Faites glisser pour déplacer, faites défiler pour zoomer, double-cliquez pour basculer en taille réelle.","unavailable": "Cette image n'est plus disponible — elle a été ignorée."},diff --git a/packages/views/locales/ja/editor.json b/packages/views/locales/ja/editor.jsonindex bef07f24a8..3b7ac510f0 100644--- a/packages/views/locales/ja/editor.json+++ b/packages/views/locales/ja/editor.json@@ -40,6 +40,9 @@"delete": "削除","link_copied": "リンクをコピーしました","copy_link_failed": "リンクをコピーできませんでした",+ "copy_image": "画像をコピー",+ "image_copied": "画像をコピーしました",+ "copy_image_failed": "画像をコピーできませんでした","canvas_label": "画像キャンバス。ドラッグで移動、スクロールで拡大縮小、ダブルクリックで実際のサイズに切り替えできます。","unavailable": "この画像は表示できないためスキップしました。"},diff --git a/packages/views/locales/ko/editor.json b/packages/views/locales/ko/editor.jsonindex 4738313fbc..e33ece2917 100644--- a/packages/views/locales/ko/editor.json+++ b/packages/views/locales/ko/editor.json@@ -40,6 +40,9 @@"delete": "삭제","link_copied": "링크를 복사했습니다","copy_link_failed": "링크를 복사하지 못했습니다",+ "copy_image": "이미지 복사",+ "image_copied": "이미지를 복사했습니다",+ "copy_image_failed": "이미지를 복사하지 못했습니다","canvas_label": "이미지 캔버스. 드래그하여 이동, 스크롤하여 확대/축소, 두 번 클릭하여 실제 크기로 전환할 수 있습니다.","unavailable": "이 이미지를 불러올 수 없어 건너뛰었습니다."},diff --git a/packages/views/locales/zh-Hans/editor.json b/packages/views/locales/zh-Hans/editor.jsonindex ff6da59cf2..2953271426 100644--- a/packages/views/locales/zh-Hans/editor.json+++ b/packages/views/locales/zh-Hans/editor.json@@ -40,6 +40,9 @@"delete": "删除","link_copied": "已复制链接","copy_link_failed": "复制链接失败",+ "copy_image": "复制图片",+ "image_copied": "已复制图片",+ "copy_image_failed": "无法复制图片","canvas_label": "图片画布,拖动可平移,滚动可缩放,双击可切换实际大小。","unavailable": "这张图片已失效,已跳过。"},