Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
perf(deliverables): load downscaled thumbnails in image tiles (MUL-9563) (#10892)
Jiayuan Zhang3212e49fb32c
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex 6d39bcd2a2..06aa71e2b2 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -1838,6 +1838,24 @@ describe("ApiClient", () => {expect(att.id).toBe("att-1");expect([att.width, att.height]).toEqual(expected);});++ it.each([+ [{ thumbnail_url: "/api/attachments/att-1/thumbnail" }, "/api/attachments/att-1/thumbnail"],+ [{ thumbnail_url: 42 }, undefined],+ [{ thumbnail_url: "" }, undefined],+ [{}, undefined],+ ])("keeps the attachment and drops an unusable thumbnail %j", async (metadata, expected) => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(+ JSON.stringify({+ id: "att-1", filename: "shot.png", url: "/uploads/shot.png",+ download_url: "/uploads/shot.png", ...metadata,+ }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ )));+ const att = await new ApiClient("https://api.example.test").getAttachment("att-1");+ expect(att.id).toBe("att-1");+ expect(att.thumbnail_url).toBe(expected);+ });});describe("getAttachmentTextContent", () => {diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex fddbe43500..990508c00f 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -4531,6 +4531,21 @@ export class ApiClient {return res.blob();}+ // Thumbnail bytes for clients that cannot load the auth-gated thumbnail+ // path as a native <img> src (see getAttachmentBlob). Always proxied by the+ // API, so unlike /download there is no storage redirect to worry about.+ async getAttachmentThumbnailBlob(id: string, signal?: AbortSignal): Promise<Blob> {+ const res = await this.fetchRaw(`/api/attachments/${id}/thumbnail`, { signal });+ return res.blob();+ }++ // The original bytes of an image that has a thumbnail, for copying it from+ // a tile. Proxied by the API in every storage mode, so script can read it.+ async getAttachmentOriginalBlob(id: string, signal?: AbortSignal): Promise<Blob> {+ const res = await this.fetchRaw(`/api/attachments/${id}/original`, { signal });+ return res.blob();+ }+// Projectsasync listProjects(params?: { status?: string; include_archived?: boolean }): Promise<ListProjectsResponse> {const search = new URLSearchParams();diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex d55589a550..9260c242b1 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -1125,6 +1125,7 @@ const ReactionSchema = z.object({const AttachmentImageFields = {width: z.number().int().positive().optional().catch(undefined),height: z.number().int().positive().optional().catch(undefined),+ thumbnail_url: z.string().min(1).optional().catch(undefined),};const AttachmentSchema = z.object({diff --git a/packages/core/types/attachment.ts b/packages/core/types/attachment.tsindex 0be4c44ac6..dd47b318a1 100644--- a/packages/core/types/attachment.ts+++ b/packages/core/types/attachment.ts@@ -60,4 +60,11 @@ export interface Attachment {*/width?: number;height?: number;+ /**+ * Stable, auth-gated path of a downscaled copy for grid tiles, like+ * `/api/attachments/<id>/thumbnail`. Set only for large raster images;+ * absent everywhere else and from servers older than this field, where+ * tiles load the original. Never use it for viewers or downloads.+ */+ thumbnail_url?: string;}diff --git a/packages/ui/lib/clipboard.test.ts b/packages/ui/lib/clipboard.test.tsindex f74ff5e50e..3cd167b848 100644--- a/packages/ui/lib/clipboard.test.ts+++ b/packages/ui/lib/clipboard.test.ts@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { copyText, copyTextAndHtml } from "./clipboard";+import { canCopyImage, copyImage, copyText, copyTextAndHtml } from "./clipboard";const clipboardDescriptor = Object.getOwnPropertyDescriptor(navigator, "clipboard");@@ -206,3 +206,55 @@ describe("copyTextAndHtml", () => {expect(navigator.clipboard.writeText).toHaveBeenCalledWith("plain");});});++describe("copyImage", () => {+ class FakeClipboardItem {+ constructor(readonly data: Record<string, Promise<Blob>>) {}+ }++ // Like the browser, the write settles only once the item's data has.+ function stubClipboard() {+ const written: Blob[] = [];+ const write = vi.fn(async (items: FakeClipboardItem[]) => {+ written.push(await items[0]!.data["image/png"]!);+ });+ Object.defineProperty(navigator, "clipboard", { value: { write }, configurable: true });+ vi.stubGlobal("ClipboardItem", FakeClipboardItem);+ return { write, written };+ }++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("copies the PNG a loader returns, starting the write before it settles", async () => {+ const { write, written } = stubClipboard();+ const png = new Blob(["png"], { type: "image/png" });+ let resolve!: (blob: Blob) => void;+ const loader = vi.fn(() => new Promise<Blob>((r) => (resolve = r)));++ const copied = copyImage(loader);+ expect(loader).toHaveBeenCalledTimes(1);+ expect(write).toHaveBeenCalledTimes(1);+ resolve(png);++ expect(await copied).toBe(true);+ expect(written).toEqual([png]);+ });++ it("is unavailable without the async Clipboard API, as on plain http://", async () => {+ vi.stubGlobal("ClipboardItem", FakeClipboardItem);+ const loader = vi.fn(async () => new Blob(["png"], { type: "image/png" }));+ expect(canCopyImage()).toBe(false);+ expect(await copyImage(loader)).toBe(false);+ expect(loader).not.toHaveBeenCalled();++ stubClipboard();+ expect(canCopyImage()).toBe(true);+ });++ it("fails when the loader does", async () => {+ stubClipboard();+ expect(await copyImage(() => Promise.reject(new Error("synthetic 404")))).toBe(false);+ });+});diff --git a/packages/ui/lib/clipboard.ts b/packages/ui/lib/clipboard.tsindex 48fc6c7005..06646726c3 100644--- a/packages/ui/lib/clipboard.ts+++ b/packages/ui/lib/clipboard.ts@@ -130,9 +130,23 @@ export async function copyTextAndHtml(}/**- * Copy the image at `url` to the clipboard as a PNG.+ * Whether `copyImage` can work here. Images need the async Clipboard API,+ * which has no legacy fallback and exists only in a secure context, so a+ * self-hosted deployment on plain http:// (not localhost) has none.+ */+export function canCopyImage(): boolean {+ return (+ typeof navigator !== "undefined" &&+ !!navigator.clipboard?.write &&+ typeof ClipboardItem !== "undefined"+ );+}++/**+ * Copy an image to the clipboard as a PNG: the one at a URL, or the bytes a+ * loader returns.*- * Reads the bytes with `fetch`, so the URL has to be readable from script:+ * A URL is read with `fetch`, so it 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@@ -141,20 +155,14 @@ export async function copyTextAndHtml(* @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;- }+export async function copyImage(source: string | (() => Promise<Blob>)): Promise<boolean> {+ if (!canCopyImage()) 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) }),+ new ClipboardItem({ "image/png": loadAsPng(source) }),]);return true;} catch {@@ -162,10 +170,8 @@ export async function copyImage(url: string): Promise<boolean> {}}-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();+async function loadAsPng(source: string | (() => Promise<Blob>)): Promise<Blob> {+ const blob = typeof source === "string" ? await fetchBlob(source) : await source();if (blob.type === "image/png") return blob;// Decoded through <img> rather than createImageBitmap so SVG works too, and@@ -194,3 +200,9 @@ async function fetchAsPng(url: string): Promise<Blob> {URL.revokeObjectURL(objectUrl);}}++async function fetchBlob(url: string): Promise<Blob> {+ const res = await fetch(url);+ if (!res.ok) throw new Error(`image fetch failed: ${res.status}`);+ return res.blob();+}diff --git a/packages/views/editor/hooks/use-inline-media-url.test.tsx b/packages/views/editor/hooks/use-inline-media-url.test.tsxindex 5d0d1beca6..2a15d32800 100644--- a/packages/views/editor/hooks/use-inline-media-url.test.tsx+++ b/packages/views/editor/hooks/use-inline-media-url.test.tsx@@ -4,15 +4,16 @@ import { focusManager, onlineManager, QueryClient, QueryClientProvider } from "@import { ApiError } from "@multica/core/api/client";import type { ReactNode } from "react";import {+ useAttachmentThumbnailURL,useFreshStreamedMediaURL,useResignedInlineMedia,__resetInlineMediaBlobCacheForTests,} from "./use-inline-media-url";-const { getAttachment, getAttachmentForDownload, getAttachmentBlob, getBaseUrl } = vi.hoisted(() => ({- getAttachment: vi.fn(), getAttachmentForDownload: vi.fn(), getAttachmentBlob: vi.fn(), getBaseUrl: vi.fn(() => "https://api.example.test"),+const { getAttachment, getAttachmentForDownload, getAttachmentBlob, getAttachmentThumbnailBlob, getBaseUrl } = vi.hoisted(() => ({+ getAttachment: vi.fn(), getAttachmentForDownload: vi.fn(), getAttachmentBlob: vi.fn(), getAttachmentThumbnailBlob: vi.fn(), getBaseUrl: vi.fn(() => "https://api.example.test"),}));-vi.mock("@multica/core/api", () => ({ api: { getAttachment, getAttachmentForDownload, getAttachmentBlob, getBaseUrl } }));+vi.mock("@multica/core/api", () => ({ api: { getAttachment, getAttachmentForDownload, getAttachmentBlob, getAttachmentThumbnailBlob, getBaseUrl } }));const id = "11111111-2222-3333-4444-555555555555";const stable = `/api/attachments/${id}/download`;const capability = (exp: number, sig = "fresh") => `/api/attachments/${id}/signed-download?exp=${exp}&sig=${sig}`;@@ -475,3 +476,41 @@ it("uses a new signed URL despite an earlier failure of the inactive byte path",expect(hook.result.current.failed).toBe(false);expect(getAttachmentBlob).not.toHaveBeenCalled();});++describe("attachment thumbnails", () => {+ const thumbnail = `/api/attachments/${id}/thumbnail`;++ it("loads the path natively on same-origin web", () => {+ getBaseUrl.mockReturnValue("");+ const { wrapper } = setup();+ const h = renderHook(() => useAttachmentThumbnailURL(id, thumbnail), { wrapper });+ expect(h.result.current).toEqual({ url: thumbnail, pending: false, failed: false });+ expect(getAttachmentThumbnailBlob).not.toHaveBeenCalled();+ });++ it("fetches authenticated bytes where a native load carries no credentials", async () => {+ getAttachmentThumbnailBlob.mockResolvedValue(new Blob(["jpg"], { type: "image/jpeg" }));+ vi.stubGlobal(+ "URL",+ class extends URL {+ static createObjectURL = vi.fn(() => "blob:thumbnail");+ static revokeObjectURL = vi.fn();+ },+ );+ const { wrapper } = setup();+ const h = renderHook(() => useAttachmentThumbnailURL(id, thumbnail), { wrapper });+ expect(h.result.current.pending).toBe(true);+ await waitFor(() => expect(h.result.current.url).toBe("blob:thumbnail"));+ expect(h.result.current.failed).toBe(false);+ expect(getAttachmentThumbnailBlob).toHaveBeenCalledWith(id, expect.anything());+ expect(getAttachmentBlob).not.toHaveBeenCalled();+ });++ it("reports a failed fetch so the tile can fall back to the original", async () => {+ getAttachmentThumbnailBlob.mockRejectedValue(new ApiError("not available", 404, "Not Found"));+ const { wrapper } = setup();+ const h = renderHook(() => useAttachmentThumbnailURL(id, thumbnail), { wrapper });+ await waitFor(() => expect(h.result.current.failed).toBe(true));+ expect(h.result.current.url).toBe("");+ });+});diff --git a/packages/views/editor/hooks/use-inline-media-url.ts b/packages/views/editor/hooks/use-inline-media-url.tsindex fb2b807d3f..1ffe8bf7b1 100644--- a/packages/views/editor/hooks/use-inline-media-url.ts+++ b/packages/views/editor/hooks/use-inline-media-url.ts@@ -213,6 +213,34 @@ export function useResignedInlineMedia(};}+// useAttachmentThumbnailURL resolves an attachment's `thumbnail_url` for a+// grid tile. Web on the API's origin loads the path natively, with the session+// 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.+export function useAttachmentThumbnailURL(+ attachmentId: string,+ thumbnailPath: string,+): { url: string; pending: boolean; failed: boolean } {+ const native =+ (api.getBaseUrl?.() ?? "") === "" &&+ thumbnailPath.startsWith("/") &&+ !thumbnailPath.startsWith("//");+ const { data: blob, isError } = useQuery({+ queryKey: ["attachment-thumbnail-blob", attachmentId],+ queryFn: ({ signal }) => api.getAttachmentThumbnailBlob(attachmentId, signal),+ enabled: !native,+ staleTime: Infinity,+ gcTime: INLINE_BLOB_GC_MS,+ retry: false,+ });+ const blobUrl = useObjectURL(native ? undefined : `thumbnail:${attachmentId}`, blob, !!blob);+ if (native) return { url: thumbnailPath, pending: false, failed: false };+ if (isError) return { url: "", pending: false, failed: true };+ return { url: blobUrl, pending: !blobUrl, failed: false };+}+// useFreshStreamedMediaURL resolves the URL the viewer streams a video, audio// file or PDF from. Unlike an inline image, these are never loaded before the// viewer opens, so whatever URL the attachment record carries is used for thediff --git a/packages/views/issues/components/deliverables/deliverable-thumbnail.tsx b/packages/views/issues/components/deliverables/deliverable-thumbnail.tsxindex 8beb245648..5fdb48ad75 100644--- a/packages/views/issues/components/deliverables/deliverable-thumbnail.tsx+++ b/packages/views/issues/components/deliverables/deliverable-thumbnail.tsx@@ -1,10 +1,22 @@"use client";-import { useState } from "react";+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 { useResignedInlineMedia } from "../../../editor/hooks/use-inline-media-url";+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 { useOpenAttachment } from "./use-open-attachment";import { fileTypeLabel, getPreviewKind } from "../../../editor/utils/preview";import { fileIcon } from "../../../editor/utils/file-icon";@@ -60,14 +72,165 @@ function FileFace({);}-// Loads the original — there is no thumbnail endpoint yet — so callers keep-// these few (the sidebar shows three) or lazy (the overview's grid).+// A large image shows the server's downscaled copy: decoding dozens of+// multi-megapixel originals into small tiles is what made the overview stutter.+// Small images, other formats, older servers and a failed thumbnail load the+// original.function ImageThumbnail({attachment,className,}: {attachment: Attachment;className?: string;+}) {+ const [failedThumbnail, setFailedThumbnail] = useState<string | null>(null);+ const thumbnailPath = attachment.thumbnail_url;+ if (thumbnailPath && failedThumbnail !== thumbnailPath) {+ return (+ <ResizedImageThumbnail+ attachment={attachment}+ thumbnailPath={thumbnailPath}+ onFail={() => setFailedThumbnail(thumbnailPath)}+ className={className}+ />+ );+ }+ return <OriginalImageThumbnail attachment={attachment} className={className} />;+}++// The browser's image menu, and the desktop's Copy image, would act on the+// thumbnail the tile shows, so the tile brings its own menu, acting on the+// original. Handling the right-click keeps either from opening.+function ResizedImageThumbnail({+ attachment,+ thumbnailPath,+ onFail,+ className,+}: {+ attachment: Attachment;+ thumbnailPath: string;+ onFail: () => void;+ className?: string;+}) {+ const { url, pending, failed } = useAttachmentThumbnailURL(attachment.id, thumbnailPath);+ const [menu, setMenu] = useState<RowMenuState>(CLOSED_ROW_MENU);+ useEffect(() => {+ if (failed) onFail();+ }, [failed, onFail]);++ const openMenu = (event: MouseEvent) => {+ event.preventDefault();+ setMenu({ open: true, point: { x: event.clientX, y: event.clientY } });+ };++ return (+ <>+ <span className="contents" onContextMenu={openMenu}>+ {pending || failed || !url ? (+ <FileFace attachment={attachment} showTypeLabel={false} className={className} />+ ) : (+ <img+ src={url}+ alt=""+ loading="lazy"+ decoding="async"+ draggable={false}+ onError={onFail}+ className={cn("bg-muted object-cover", className)}+ />+ )}+ </span>+ {menu.point && (+ <OriginalImageMenu+ attachment={attachment}+ menu={menu}+ onOpenChange={(open) => setMenu((current) => ({ ...current, open }))}+ />+ )}+ </>+ );+}++function OriginalImageMenu({+ attachment,+ menu,+ onOpenChange,+}: {+ attachment: Attachment;+ 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]} />+ {modal}+ </>+ );+}++// Loads the original, so callers keep these few (the sidebar shows three) or+// lazy (the overview's grid).+function OriginalImageThumbnail({+ attachment,+ className,+}: {+ attachment: Attachment;+ className?: string;}) {const picked =attachment.download_url || attachment.markdown_url || attachment.url;diff --git a/packages/views/issues/components/deliverables/deliverables.test.tsx b/packages/views/issues/components/deliverables/deliverables.test.tsxindex 013dea8b6e..57b37c495d 100644--- a/packages/views/issues/components/deliverables/deliverables.test.tsx+++ b/packages/views/issues/components/deliverables/deliverables.test.tsx@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";import { act, fireEvent, screen, waitFor, within } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { useState, type ReactNode } from "react";@@ -9,10 +9,33 @@ import {import type { Attachment, TimelineEntry } from "@multica/core/types";import { renderWithI18n } from "../../../test/i18n";-const { openAtMock, tryOpenMock, downloadMock } = vi.hoisted(() => ({+const {+ openAtMock,+ tryOpenMock,+ downloadMock,+ resignedMediaMock,+ copyImageMock,+ copyTextMock,+ originalBlobMock,+} = vi.hoisted(() => ({openAtMock: vi.fn((_key: string) => true),tryOpenMock: vi.fn(() => false),downloadMock: vi.fn(),+ resignedMediaMock: vi.fn((_id: string | undefined, url: string) => ({ url, pending: false })),+ copyImageMock: vi.fn(async (_source: string | (() => Promise<Blob>)) => true),+ copyTextMock: vi.fn(async (_text: string) => true),+ originalBlobMock: vi.fn(async (_id: string) => new Blob(["original"], { type: "image/jpeg" })),+}));++vi.mock("@multica/core/api", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/core/api")>()),+ api: { getBaseUrl: () => "", getAttachmentOriginalBlob: originalBlobMock },+}));++vi.mock("@multica/ui/lib/clipboard", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@multica/ui/lib/clipboard")>()),+ copyImage: copyImageMock,+ copyText: copyTextMock,}));vi.mock("@multica/core/workspace/hooks", () => ({@@ -30,7 +53,8 @@ vi.mock("../../../editor", () => ({}));vi.mock("../../../editor/hooks/use-inline-media-url", () => ({- useResignedInlineMedia: (_id: string | undefined, url: string) => ({ url, pending: false }),+ useResignedInlineMedia: resignedMediaMock,+ useAttachmentThumbnailURL: (_id: string, path: string) => ({ url: path, pending: false, failed: false }),}));vi.mock("@multica/core/workspace/avatar-url", () => ({@@ -181,6 +205,24 @@ describe("DeliverablesSection", () => {expect(screen.queryByRole("button", { name: "Copy link to latest version" })).toBeNull();});+ it("tiles a large image with its thumbnail and falls back to the original if it fails", () => {+ const render = attachment({+ id: "render",+ filename: "render.jpg",+ content_type: "image/jpeg",+ size_bytes: 6 * 1024 * 1024,+ thumbnail_url: "/api/attachments/render/thumbnail",+ });+ const { container } = renderSection(collectDeliverableFiles([comment("c-9", [render, SHOT])]));+ const sources = () =>+ Array.from(container.querySelectorAll("img"), (img) => img.getAttribute("src")).sort();+ // A small image without a thumbnail keeps loading its original.+ expect(sources()).toEqual(["/api/attachments/render/thumbnail", SHOT.download_url].sort());++ fireEvent.error(container.querySelector('img[src="/api/attachments/render/thumbnail"]')!);+ expect(sources()).toEqual([render.download_url, SHOT.download_url].sort());+ });+it("opens the overview from view all", () => {const onOpenOverview = vi.fn();renderSection(FILES, onOpenOverview);@@ -396,3 +438,146 @@ describe("useDeliverableDetails", () => {expect(copyLink).toBeUndefined();});});++describe("a thumbnail tile's right-click menu", () => {+ const RENDER = attachment({+ id: "render",+ filename: "render.jpg",+ content_type: "image/jpeg",+ size_bytes: 6 * 1024 * 1024,+ thumbnail_url: "/api/attachments/render/thumbnail",+ });+ const SKETCH = attachment({+ id: "sketch",+ filename: "sketch.jpg",+ content_type: "image/jpeg",+ size_bytes: 5 * 1024 * 1024,+ thumbnail_url: "/api/attachments/sketch/thumbnail",+ created_at: "2026-09-20T10:00:02Z",+ });+ const IMAGES = [RENDER, SKETCH];+ const IMAGE_TIMELINE = [comment("c-9", IMAGES)];+ const IMAGE_FILES = collectDeliverableFiles(IMAGE_TIMELINE);++ function DetailsSiblings() {+ const describe = useDeliverableDetails({+ files: IMAGE_FILES,+ commentById: new Map(IMAGE_TIMELINE.map((entry) => [entry.id, entry])),+ onLocate: vi.fn(),+ });+ const items = IMAGES.map((a) => ({+ key: a.id,+ url: a.url,+ filename: a.filename,+ attachment: a,+ imageByConstruction: false,+ blockId: "c-9",+ }));+ return <>{describe(items[1]!, { items, goTo: () => true, close: vi.fn() }).info}</>;+ }++ const surfaces: [string, () => ReactNode][] = [+ ["sidebar", () => <DeliverablesSection files={IMAGE_FILES} onOpenOverview={vi.fn()} />],+ [+ "overview",+ () => (+ <DeliverablesOverview+ open+ onClose={vi.fn()}+ identifier="MUL-9563"+ files={IMAGE_FILES}+ commentById={new Map()}+ onLocate={vi.fn()}+ returnKey={null}+ />+ ),+ ],+ ["viewer details", () => <DetailsSiblings />],+ ];++ function tileOf() {+ return document.querySelector<HTMLImageElement>('img[src="/api/attachments/render/thumbnail"]')!;+ }++ async function pick(name: string) {+ fireEvent.contextMenu(tileOf());+ fireEvent.click(await screen.findByRole("menuitem", { name }));+ }++ async function menuItems() {+ fireEvent.contextMenu(tileOf());+ const items = (await screen.findAllByRole("menuitem")).map((item) => item.textContent);+ fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" });+ return items;+ }++ describe("with the async Clipboard API", () => {+ beforeEach(() => {+ Object.defineProperty(navigator, "clipboard", {+ configurable: true,+ value: { write: vi.fn() },+ });+ vi.stubGlobal("ClipboardItem", class {});+ });++ afterEach(() => {+ Reflect.deleteProperty(navigator, "clipboard");+ vi.unstubAllGlobals();+ });++ it.each(surfaces)(+ "%s: browsing loads only thumbnails, the menu acts on the original",+ async (_surface, renderSurface) => {+ renderWithI18n(withQuery(renderSurface()));++ // Every tile shows its thumbnail; no original is requested.+ expect(tileOf()).toBeInTheDocument();+ const sources = Array.from(document.querySelectorAll("img"), (img) => img.getAttribute("src"));+ expect(sources.every((src) => src?.endsWith("/thumbnail"))).toBe(true);+ expect(resignedMediaMock).not.toHaveBeenCalled();+ expect(await menuItems()).toEqual(["View image", "Copy image", "Download", "Copy link"]);++ await pick("Copy image");+ expect(copyImageMock).toHaveBeenCalledTimes(1);+ expect(originalBlobMock).not.toHaveBeenCalled();+ const load = copyImageMock.mock.calls[0]![0] as () => Promise<Blob>;+ expect(await (await load()).text()).toBe("original");+ expect(originalBlobMock).toHaveBeenCalledWith("render");++ await pick("Download");+ expect(downloadMock).toHaveBeenCalledWith("render");++ await pick("Copy link");+ expect(copyTextMock).toHaveBeenCalledWith(RENDER.markdown_url);++ // Picking an item does not also open the file under it.+ expect(openAtMock).not.toHaveBeenCalled();+ expect(tryOpenMock).not.toHaveBeenCalled();+ },+ );+ });++ // Plain http:// self-hosting (not localhost) has no async Clipboard API, and+ // nothing can copy an image there but the browser's own menu.+ it.each(surfaces)(+ "%s: without the async Clipboard API, offers the original in the viewer instead of a copy that fails",+ async (_surface, renderSurface) => {+ const actual = await vi.importActual<typeof import("@multica/ui/lib/clipboard")>(+ "@multica/ui/lib/clipboard",+ );+ copyImageMock.mockImplementation(actual.copyImage);+ onTestFinished(() => {+ copyImageMock.mockReset();+ });+ expect(navigator.clipboard?.write).toBeUndefined();+ renderWithI18n(withQuery(renderSurface()));++ expect(await menuItems()).toEqual(["View image", "Download", "Copy link"]);+ await pick("View image");+ expect(openAtMock).toHaveBeenCalledWith("render");+ expect(copyImageMock).not.toHaveBeenCalled();+ expect(originalBlobMock).not.toHaveBeenCalled();+ expect(resignedMediaMock).not.toHaveBeenCalled();+ },+ );+});diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 3b618cd36d..a22f814d1d 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1820,6 +1820,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// because they are JSON-API consumers that always have// workspace context.r.Get("/api/attachments/{id}/download", h.DownloadAttachment)+ // Same access shape as /download, for grid tiles' native <img> src.+ r.Get("/api/attachments/{id}/thumbnail", h.GetAttachmentThumbnail)+ // The original of a thumbnailed image, for copying it from a tile.+ r.Get("/api/attachments/{id}/original", h.GetAttachmentOriginal)// Markdown links may point to an attachment in a different workspace.// Resolve that workspace from the row and check membership before minting// a fresh URL; the workspace-scoped metadata route stays unchanged.diff --git a/server/go.mod b/server/go.modindex 199b6289de..1274c16941 100644--- a/server/go.mod+++ b/server/go.mod@@ -32,6 +32,7 @@ require (github.com/spf13/pflag v1.0.10github.com/tdewolff/parse/v2 v2.8.16github.com/yuin/goldmark v1.8.6+ golang.org/x/image v0.47.0golang.org/x/net v0.62.0golang.org/x/sync v0.24.0golang.org/x/sys v0.49.0diff --git a/server/go.sum b/server/go.sumindex 3c6ba13629..0a607060a1 100644--- a/server/go.sum+++ b/server/go.sum@@ -168,6 +168,8 @@ go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=+golang.org/x/image v0.47.0 h1:za/8gVz++PPZqmZJBNSISICN5Rrj5zixP/8K++fgmqo=+golang.org/x/image v0.47.0/go.mod h1:IkN5o4A7vq55vXN8FWjjnhg9Rs2GOtffqsSi9mWAKYE=golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=diff --git a/server/internal/handler/attachment_thumbnail.go b/server/internal/handler/attachment_thumbnail.gonew file mode 100644index 0000000000..59f9d26df0--- /dev/null+++ b/server/internal/handler/attachment_thumbnail.go@@ -0,0 +1,233 @@+package handler++import (+ "context"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "net/http"+ "strconv"+ "time"++ "github.com/multica-ai/multica/server/internal/storage"+ "github.com/multica-ai/multica/server/internal/thumbnail"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "golang.org/x/sync/singleflight"+)++const (+ // Below both bounds the original is already cheap for a tile to load.+ thumbnailMinSourceBytes = 512 << 10+ thumbnailMinSourcePixels = 4_000_000+ thumbnailMaxSourceBytes = 64 << 20+ thumbnailMaxStoredBytes = 8 << 20++ thumbnailGenerateTimeout = 2 * time.Minute+ // The bytes behind an attachment id never change, so a browser may reuse a+ // thumbnail for as long as a signed original URL stays valid.+ thumbnailCacheControl = "private, max-age=1800"+)++var (+ // Decoding a 16 MP original holds ~110 MB, so generations are capped.+ thumbnailSlots = make(chan struct{}, 2)+ thumbnailFlight singleflight.Group+)++var errThumbnailUnavailable = errors.New("thumbnail not available")++// hasThumbnail reports whether a gets a thumbnail: a large raster image, so+// clients keep loading small images and every other file type as before.+func hasThumbnail(store storage.Storage, a db.Attachment) bool {+ if store == nil || !thumbnail.SupportedContentType(a.ContentType) || a.SizeBytes > thumbnailMaxSourceBytes {+ return false+ }+ if _, ok := thumbnail.StorageKey(store.KeyFromURL(a.Url)); !ok {+ return false+ }+ return a.SizeBytes >= thumbnailMinSourceBytes ||+ (a.Width.Valid && a.Height.Valid && int64(a.Width.Int32)*int64(a.Height.Int32) >= thumbnailMinSourcePixels)+}++func (h *Handler) attachmentThumbnailURL(a db.Attachment, id string) string {+ if !hasThumbnail(h.Storage, a) {+ return ""+ }+ return "/api/attachments/" + id + "/thumbnail"+}++// GetAttachmentThumbnail — GET /api/attachments/{id}/thumbnail+//+// Serves a downscaled copy of a large image attachment for grid tiles. Upload+// renders it in the background; a request that finds none (older uploads, a+// render still running or one that failed) renders it then. It is stored next+// to the original. Access mirrors /api/attachments/{id}/download, so it loads+// as a native <img> src. Clients fall back to the original on any error.+func (h *Handler) GetAttachmentThumbnail(w http.ResponseWriter, r *http.Request) {+ att, ok := h.loadAttachmentForDownload(w, r)+ if !ok {+ return+ }+ store := h.Storage+ if store == nil {+ writeFeatureDisabled(w, "storage_not_configured", "storage not configured")+ return+ }+ if !hasThumbnail(store, att) {+ writeError(w, http.StatusNotFound, "thumbnail not available")+ return+ }++ thumb, err := loadAttachmentThumbnail(r.Context(), store, att)+ if err != nil {+ if writeRequestCancellation(w, r, err) {+ return+ }+ if errors.Is(err, errThumbnailUnavailable) {+ writeError(w, http.StatusNotFound, "thumbnail not available")+ return+ }+ slog.Warn("failed to build attachment thumbnail", "id", uuidToString(att.ID), "error", err)+ writeError(w, http.StatusBadGateway, "failed to build thumbnail")+ return+ }++ w.Header().Set("Content-Type", thumb.ContentType)+ w.Header().Set("Content-Length", strconv.Itoa(len(thumb.Data)))+ w.Header().Set("Cache-Control", thumbnailCacheControl)+ w.Header().Set("X-Content-Type-Options", "nosniff")+ h.setAttachmentPreviewSecurityHeaders(w)+ if _, err := w.Write(thumb.Data); err != nil && !isRequestCancellation(r, err) {+ slog.Warn("failed to write attachment thumbnail", "id", uuidToString(att.ID), "error", err)+ }+}++// GetAttachmentOriginal — GET /api/attachments/{id}/original+//+// Serves the original bytes of an image that has a thumbnail, always through+// the API. A tile shows the thumbnail, so copying the image from it reads the+// original from script, and web script can't read the storage CDN, which+// sends no CORS headers. /download redirects there in CDN and presign modes.+func (h *Handler) GetAttachmentOriginal(w http.ResponseWriter, r *http.Request) {+ att, ok := h.loadAttachmentForDownload(w, r)+ if !ok {+ return+ }+ store := h.Storage+ if store == nil {+ writeFeatureDisabled(w, "storage_not_configured", "storage not configured")+ return+ }+ if !hasThumbnail(store, att) {+ writeError(w, http.StatusNotFound, "original not available")+ return+ }+ h.proxyAttachmentDownload(w, r, att, store.KeyFromURL(att.Url), false)+}++// prewarmAttachmentThumbnail renders a new upload's thumbnail in the+// background, so the first grid that shows it does not wait for the render.+func (h *Handler) prewarmAttachmentThumbnail(att db.Attachment) {+ store := h.Storage+ if !hasThumbnail(store, att) {+ return+ }+ go func() {+ ctx, cancel := context.WithTimeout(context.Background(), thumbnailGenerateTimeout)+ defer cancel()+ if _, err := loadAttachmentThumbnail(ctx, store, att); err != nil && !errors.Is(err, errThumbnailUnavailable) {+ slog.Warn("failed to prewarm attachment thumbnail", "id", uuidToString(att.ID), "error", err)+ }+ }()+}++func loadAttachmentThumbnail(ctx context.Context, store storage.Storage, att db.Attachment) (thumbnail.Thumbnail, error) {+ objectKey := store.KeyFromURL(att.Url)+ key, ok := thumbnail.StorageKey(objectKey)+ if !ok {+ return thumbnail.Thumbnail{}, errThumbnailUnavailable+ }+ if thumb, ok := readStoredThumbnail(ctx, store, key); ok {+ return thumb, nil+ }++ // One generation per object, shared by every concurrent request for it and+ // detached from any single request so one cancelled tile does not fail the+ // others waiting on the same result.+ ch := thumbnailFlight.DoChan(key, func() (any, error) {+ genCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), thumbnailGenerateTimeout)+ defer cancel()+ return generateAttachmentThumbnail(genCtx, store, objectKey, key)+ })+ select {+ case res := <-ch:+ if res.Err != nil {+ return thumbnail.Thumbnail{}, res.Err+ }+ return res.Val.(thumbnail.Thumbnail), nil+ case <-ctx.Done():+ return thumbnail.Thumbnail{}, ctx.Err()+ }+}++func readStoredThumbnail(ctx context.Context, store storage.Storage, key string) (thumbnail.Thumbnail, bool) {+ reader, err := store.GetReader(ctx, key)+ if err != nil {+ return thumbnail.Thumbnail{}, false+ }+ defer reader.Close()+ data, err := io.ReadAll(io.LimitReader(reader, thumbnailMaxStoredBytes+1))+ if err != nil || len(data) == 0 || len(data) > thumbnailMaxStoredBytes {+ return thumbnail.Thumbnail{}, false+ }+ switch contentType := http.DetectContentType(data); contentType {+ case "image/jpeg", "image/png":+ return thumbnail.Thumbnail{Data: data, ContentType: contentType}, true+ }+ return thumbnail.Thumbnail{}, false+}++func generateAttachmentThumbnail(ctx context.Context, store storage.Storage, objectKey, key string) (thumbnail.Thumbnail, error) {+ select {+ case thumbnailSlots <- struct{}{}:+ defer func() { <-thumbnailSlots }()+ case <-ctx.Done():+ return thumbnail.Thumbnail{}, ctx.Err()+ }+ // A render this caller missed, such as the upload prewarm, may have stored+ // it while this one waited for a slot.+ if thumb, ok := readStoredThumbnail(ctx, store, key); ok {+ return thumb, nil+ }++ reader, err := store.GetReader(ctx, objectKey)+ if err != nil {+ return thumbnail.Thumbnail{}, fmt.Errorf("open original: %w", err)+ }+ defer reader.Close()+ data, err := io.ReadAll(io.LimitReader(reader, thumbnailMaxSourceBytes+1))+ if err != nil {+ return thumbnail.Thumbnail{}, fmt.Errorf("read original: %w", err)+ }+ if len(data) > thumbnailMaxSourceBytes {+ return thumbnail.Thumbnail{}, errThumbnailUnavailable+ }++ thumb, err := thumbnail.Generate(data)+ if errors.Is(err, thumbnail.ErrUnsupported) {+ return thumbnail.Thumbnail{}, fmt.Errorf("%w: %v", errThumbnailUnavailable, err)+ }+ if err != nil {+ return thumbnail.Thumbnail{}, err+ }+ filename := "thumbnail.jpg"+ if thumb.ContentType == "image/png" {+ filename = "thumbnail.png"+ }+ if _, err := store.Upload(ctx, key, thumb.Data, thumb.ContentType, filename); err != nil {+ // Still serve it; the next request renders it again.+ slog.Warn("failed to store attachment thumbnail", "key", key, "error", err)+ }+ return thumb, nil+}diff --git a/server/internal/handler/attachment_thumbnail_test.go b/server/internal/handler/attachment_thumbnail_test.gonew file mode 100644index 0000000000..deffb0f01a--- /dev/null+++ b/server/internal/handler/attachment_thumbnail_test.go@@ -0,0 +1,296 @@+package handler++import (+ "bytes"+ "context"+ "encoding/json"+ "image"+ "image/jpeg"+ "mime/multipart"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/go-chi/chi/v5"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func useThumbnailTestStorage(t *testing.T) *mockStorage {+ t.Helper()+ store := &mockStorage{}+ origStorage := testHandler.Storage+ testHandler.Storage = store+ t.Cleanup(func() { testHandler.Storage = origStorage })+ return store+}++func thumbnailRequest(t *testing.T, attachmentID string) *httptest.ResponseRecorder {+ t.Helper()+ r := chi.NewRouter()+ r.Get("/api/attachments/{id}/thumbnail", testHandler.GetAttachmentThumbnail)+ req := httptest.NewRequest("GET", "/api/attachments/"+attachmentID+"/thumbnail", nil)+ req.Header.Set("X-User-ID", testUserID)+ w := httptest.NewRecorder()+ r.ServeHTTP(w, req)+ return w+}++func testJPEG(t *testing.T, w, h int) []byte {+ t.Helper()+ var b bytes.Buffer+ if err := jpeg.Encode(&b, image.NewRGBA(image.Rect(0, 0, w, h)), nil); err != nil {+ t.Fatal(err)+ }+ return b.Bytes()+}++func TestAttachmentThumbnail_GeneratesStoresAndReuses(t *testing.T) {+ if testPool == nil {+ t.Skip("test database not available")+ }+ store := useThumbnailTestStorage(t)+ key := "thumbs/generated.jpg"+ store.put(key, testJPEG(t, 2000, 1500))+ id := seedAttachmentURL(t, "https://s3.example.com/test-bucket/"+key, "render.jpg", "image/jpeg", 600<<10)++ w := thumbnailRequest(t, id)+ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, body=%s", w.Code, w.Body.String())+ }+ if got := w.Header().Get("Content-Type"); got != "image/jpeg" {+ t.Fatalf("Content-Type = %q", got)+ }+ if got := w.Header().Get("Cache-Control"); got != thumbnailCacheControl {+ t.Fatalf("Cache-Control = %q", got)+ }+ cfg, err := jpeg.DecodeConfig(bytes.NewReader(w.Body.Bytes()))+ if err != nil {+ t.Fatal(err)+ }+ if cfg.Width != 640 || cfg.Height != 480 {+ t.Fatalf("thumbnail = %dx%d, want 640x480", cfg.Width, cfg.Height)+ }+ stored := store.files[key+".thumb"]+ if !bytes.Equal(stored, w.Body.Bytes()) {+ t.Fatal("generated thumbnail was not stored next to the original")+ }++ // A stored thumbnail is served without reading the original again.+ store.Delete(context.Background(), key)+ w = thumbnailRequest(t, id)+ if w.Code != http.StatusOK || !bytes.Equal(w.Body.Bytes(), stored) {+ t.Fatalf("second request: status = %d", w.Code)+ }+}++func TestUploadFile_PrewarmsThumbnail(t *testing.T) {+ if testPool == nil {+ t.Skip("test database not available")+ }+ store := useThumbnailTestStorage(t)+ var body bytes.Buffer+ writer := multipart.NewWriter(&body)+ part, err := writer.CreateFormFile("file", "render.jpg")+ if err != nil {+ t.Fatal(err)+ }+ part.Write(testJPEG(t, 2400, 1800))+ writer.Close()+ req := httptest.NewRequest("POST", "/api/upload-file", &body)+ req.Header.Set("Content-Type", writer.FormDataContentType())+ req.Header.Set("X-User-ID", testUserID)+ req.Header.Set("X-Workspace-ID", testWorkspaceID)+ w := httptest.NewRecorder()+ testHandler.UploadFile(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("upload: status = %d, body=%s", w.Code, w.Body.String())+ }+ var resp AttachmentResponse+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM attachment WHERE id = $1`, resp.ID) })+ if resp.ThumbnailURL != "/api/attachments/"+resp.ID+"/thumbnail" {+ t.Fatalf("thumbnail_url = %q", resp.ThumbnailURL)+ }++ thumbKey := "workspaces/" + testWorkspaceID + "/" + resp.ID + ".jpg.thumb"+ deadline := time.Now().Add(10 * time.Second)+ for {+ store.mu.Lock()+ _, ok := store.files[thumbKey]+ store.mu.Unlock()+ if ok {+ return+ }+ if time.Now().After(deadline) {+ t.Fatal("upload did not store a thumbnail")+ }+ time.Sleep(20 * time.Millisecond)+ }+}++func TestAttachmentThumbnail_OnlyLargeRasterImagesGetOne(t *testing.T) {+ if testPool == nil {+ t.Skip("test database not available")+ }+ store := useThumbnailTestStorage(t)+ for _, tc := range []struct {+ name, key, contentType string+ size int64+ want bool+ }{+ {"large jpeg", "thumbs/large.jpg", "image/jpeg", 600 << 10, true},+ {"large webp", "thumbs/large.webp", "image/webp", 2 << 20, true},+ {"small jpeg", "thumbs/small.jpg", "image/jpeg", 100 << 10, false},+ {"gif", "thumbs/anim.gif", "image/gif", 4 << 20, false},+ {"svg", "thumbs/vector.svg", "image/svg+xml", 4 << 20, false},+ {"pdf", "thumbs/doc.pdf", "application/pdf", 4 << 20, false},+ {"jpeg without image extension", "thumbs/blob.bin", "image/jpeg", 4 << 20, false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ id := seedAttachmentURL(t, "https://s3.example.com/test-bucket/"+tc.key, "f", tc.contentType, tc.size)+ resp := testHandler.attachmentToResponse(db.Attachment{+ ID: parseUUID(id), Url: "https://s3.example.com/test-bucket/" + tc.key,+ ContentType: tc.contentType, SizeBytes: tc.size,+ }, attachmentURLModeSigned)+ if got := resp.ThumbnailURL != ""; got != tc.want {+ t.Fatalf("thumbnail_url = %q, want present=%v", resp.ThumbnailURL, tc.want)+ }+ if tc.want {+ if resp.ThumbnailURL != "/api/attachments/"+id+"/thumbnail" {+ t.Fatalf("thumbnail_url = %q", resp.ThumbnailURL)+ }+ return+ }+ if w := thumbnailRequest(t, id); w.Code != http.StatusNotFound {+ t.Fatalf("status = %d, want 404", w.Code)+ }+ })+ }+ if len(store.files) != 0 {+ t.Fatalf("ineligible attachments wrote objects: %v", store.files)+ }+}++func TestAttachmentThumbnail_UndecodableImageIsNotAvailable(t *testing.T) {+ if testPool == nil {+ t.Skip("test database not available")+ }+ store := useThumbnailTestStorage(t)+ key := "thumbs/corrupt.png"+ store.put(key, []byte("not really a png"))+ id := seedAttachmentURL(t, "https://s3.example.com/test-bucket/"+key, "corrupt.png", "image/png", 1<<20)++ if w := thumbnailRequest(t, id); w.Code != http.StatusNotFound {+ t.Fatalf("status = %d, want 404; body=%s", w.Code, w.Body.String())+ }+ if _, ok := store.files[key+".thumb"]; ok {+ t.Fatal("stored a thumbnail for an undecodable image")+ }+}++func TestAttachmentThumbnail_NonMemberGets404(t *testing.T) {+ if testPool == nil {+ t.Skip("test database not available")+ }+ store := useThumbnailTestStorage(t)+ ctx := context.Background()+ var foreignWorkspaceID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO workspace (name, slug, description, issue_prefix)+ VALUES ('Thumb Foreign', 'thumb-foreign', '', 'THF')+ RETURNING id::text+ `).Scan(&foreignWorkspaceID); err != nil {+ t.Fatalf("seed foreign workspace: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM workspace WHERE id = $1`, foreignWorkspaceID) })++ key := "thumbs/foreign.jpg"+ store.put(key, testJPEG(t, 2000, 1500))+ var id string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO attachment (workspace_id, uploader_type, uploader_id, filename, url, content_type, size_bytes)+ VALUES ($1, 'member', $2, 'foreign.jpg', $3, 'image/jpeg', $4)+ RETURNING id::text+ `, foreignWorkspaceID, testUserID, "https://s3.example.com/test-bucket/"+key, 600<<10).Scan(&id); err != nil {+ t.Fatalf("seed foreign attachment: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM attachment WHERE id = $1`, id) })++ if w := thumbnailRequest(t, id); w.Code != http.StatusNotFound {+ t.Fatalf("status = %d, want 404 for non-member", w.Code)+ }+ if _, ok := store.files[key+".thumb"]; ok {+ t.Fatal("non-member request generated a thumbnail")+ }+ if w := originalRequest(t, id); w.Code != http.StatusNotFound {+ t.Fatalf("original: status = %d, want 404 for non-member", w.Code)+ }+}++func originalRequest(t *testing.T, attachmentID string) *httptest.ResponseRecorder {+ t.Helper()+ r := chi.NewRouter()+ r.Get("/api/attachments/{id}/original", testHandler.GetAttachmentOriginal)+ req := httptest.NewRequest("GET", "/api/attachments/"+attachmentID+"/original", nil)+ req.Header.Set("X-User-ID", testUserID)+ w := httptest.NewRecorder()+ r.ServeHTTP(w, req)+ return w+}++func TestAttachmentOriginal_StreamsThroughTheAPI(t *testing.T) {+ if testPool == nil {+ t.Skip("test database not available")+ }+ store := useThumbnailTestStorage(t)+ origMode := testHandler.cfg.AttachmentDownloadMode+ // /download redirects to storage in this mode; /original never does.+ testHandler.cfg.AttachmentDownloadMode = "presign"+ t.Cleanup(func() { testHandler.cfg.AttachmentDownloadMode = origMode })++ key := "thumbs/original.jpg"+ original := testJPEG(t, 2000, 1500)+ store.put(key, original)+ id := seedAttachmentURL(t, "https://s3.example.com/test-bucket/"+key, "render.jpg", "image/jpeg", 600<<10)++ w := originalRequest(t, id)+ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, body=%s", w.Code, w.Body.String())+ }+ if got := w.Header().Get("Content-Type"); got != "image/jpeg" {+ t.Fatalf("Content-Type = %q", got)+ }+ if got := w.Header().Get("X-Content-Type-Options"); got != "nosniff" {+ t.Fatalf("X-Content-Type-Options = %q", got)+ }+ if !bytes.Equal(w.Body.Bytes(), original) {+ t.Fatal("body is not the original")+ }++ // Only images that have a thumbnail are served: anything else keeps+ // /download as its one route.+ smallKey := "thumbs/original-small.jpg"+ store.put(smallKey, testJPEG(t, 100, 100))+ smallID := seedAttachmentURL(t, "https://s3.example.com/test-bucket/"+smallKey, "small.jpg", "image/jpeg", 10<<10)+ if w := originalRequest(t, smallID); w.Code != http.StatusNotFound {+ t.Fatalf("small image: status = %d, want 404", w.Code)+ }+}++func TestDeleteS3ObjectsRemovesThumbnails(t *testing.T) {+ store := useThumbnailTestStorage(t)+ for _, key := range []string{"a.png", "a.png.thumb", "b.pdf", "c.JPG", "c.JPG.thumb"} {+ store.put(key, []byte("x"))+ }+ testHandler.deleteS3Objects(context.Background(), []string{+ "https://cdn.example.com/a.png",+ "https://cdn.example.com/b.pdf",+ })+ testHandler.deleteS3Object(context.Background(), "https://cdn.example.com/c.JPG")+ if len(store.files) != 0 {+ t.Fatalf("left behind: %v", store.files)+ }+}diff --git a/server/internal/handler/file.go b/server/internal/handler/file.goindex 1279f68b6f..91e9a2d351 100644--- a/server/internal/handler/file.go+++ b/server/internal/handler/file.go@@ -22,6 +22,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/imagemetadata""github.com/multica-ai/multica/server/internal/storage"+ "github.com/multica-ai/multica/server/internal/thumbnail""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol"@@ -109,6 +110,11 @@ type AttachmentResponse struct {// Displayed image dimensions, absent for non-images and older uploads.Width *int32 `json:"width,omitempty"`Height *int32 `json:"height,omitempty"`+ // ThumbnailURL is the stable, auth-gated path of a downscaled copy for+ // grid tiles, set only for large raster images. Durable like the stable+ // download path; never a substitute for the original in viewers or+ // downloads.+ ThumbnailURL string `json:"thumbnail_url,omitempty"`}// attachmentURLMode selects how DownloadURL is rendered on a response.@@ -171,6 +177,7 @@ func (h *Handler) attachmentToResponse(a db.Attachment, mode attachmentURLMode)URL: a.Url,DownloadURL: util.AttachmentDownloadPath(id),MarkdownURL: h.buildMarkdownURL(a, id),+ ThumbnailURL: h.attachmentThumbnailURL(a, id),ContentType: a.ContentType,SizeBytes: a.SizeBytes,CreatedAt: a.CreatedAt.Time.Format("2006-01-02T15:04:05Z07:00"),@@ -623,6 +630,7 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {// S3 upload succeeded but DB record failed — still return the link// so the file is usable. Log the error for investigation.} else {+ h.prewarmAttachmentThumbnail(att.Attachment())if att.IssueRevision > 0 && att.IssueID.Valid {h.publish(protocol.EventIssueAttachmentsChanged, workspaceID, uploaderType, uploaderID, map[string]any{"issue_id": uuidToString(att.IssueID),@@ -1638,22 +1646,27 @@ func (h *Handler) attachmentOwnerLockAttempt(ctx context.Context, att db.Attachmreturn fresh, tx.Commit(ctx)}-// deleteS3Object removes a single file from S3 by its CDN URL.+// deleteS3Object removes a single file, and its thumbnail, from S3 by its CDN URL.func (h *Handler) deleteS3Object(ctx context.Context, url string) {if h.Storage == nil || url == "" {return}- h.Storage.Delete(ctx, h.Storage.KeyFromURL(url))+ h.deleteS3Objects(ctx, []string{url})}-// deleteS3Objects removes multiple files from S3 by their CDN URLs.+// deleteS3Objects removes multiple files, and their thumbnails, from S3 by+// their CDN URLs.func (h *Handler) deleteS3Objects(ctx context.Context, urls []string) {if h.Storage == nil || len(urls) == 0 {return}- keys := make([]string, len(urls))- for i, u := range urls {- keys[i] = h.Storage.KeyFromURL(u)+ keys := make([]string, 0, len(urls))+ for _, u := range urls {+ key := h.Storage.KeyFromURL(u)+ keys = append(keys, key)+ if thumbKey, ok := thumbnail.StorageKey(key); ok {+ keys = append(keys, thumbKey)+ }}h.Storage.DeleteKeys(ctx, keys)}diff --git a/server/internal/handler/file_test.go b/server/internal/handler/file_test.goindex d6c58b1e88..0c1abfad43 100644--- a/server/internal/handler/file_test.go+++ b/server/internal/handler/file_test.go@@ -93,7 +93,11 @@ func (m *mockStorage) DeleteObject(ctx context.Context, key string) error {m.Delete(ctx, key)return nil}-func (m *mockStorage) DeleteKeys(_ context.Context, _ []string) {}+func (m *mockStorage) DeleteKeys(ctx context.Context, keys []string) {+ for _, key := range keys {+ m.Delete(ctx, key)+ }+}func (m *mockStorage) ObjectURL(key string) string {return "https://cdn.example.com/" + key}diff --git a/server/internal/imagemetadata/dimensions.go b/server/internal/imagemetadata/dimensions.goindex 022aa2b816..ec5484742c 100644--- a/server/internal/imagemetadata/dimensions.go+++ b/server/internal/imagemetadata/dimensions.go@@ -24,13 +24,15 @@ func Dimensions(data []byte) (Size, bool) {return Size{}, false}width, height := int32(cfg.Width), int32(cfg.Height)- if format == "jpeg" && jpegOrientation(data) >= 5 {+ if format == "jpeg" && JPEGOrientation(data) >= 5 {width, height = height, width}return Size{Width: width, Height: height}, true}-func jpegOrientation(data []byte) int {+// JPEGOrientation returns the EXIF orientation (1-8) of a JPEG, or 1 when the+// data is not a JPEG or carries no valid orientation tag.+func JPEGOrientation(data []byte) int {if len(data) < 2 || data[0] != 0xff || data[1] != 0xd8 {return 1}diff --git a/server/internal/service/source_context.go b/server/internal/service/source_context.goindex c49379906c..beb1c23950 100644--- a/server/internal/service/source_context.go+++ b/server/internal/service/source_context.go@@ -14,6 +14,7 @@ import ("github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/thumbnail""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/dbid"@@ -778,6 +779,9 @@ func (s *TaskService) CleanupAbandonedSourceContexts(ctx context.Context, limitkey := s.SourceContextStorage.KeyFromURL(attachment.Url)deleteCtx, cancel := context.WithTimeout(ctx, sourceContextObjectDeleteTimeout)err := s.SourceContextStorage.DeleteObject(deleteCtx, key)+ if thumbKey, ok := thumbnail.StorageKey(key); ok && err == nil {+ err = s.SourceContextStorage.DeleteObject(deleteCtx, thumbKey)+ }cancel()if err != nil {deleteFailed = truediff --git a/server/internal/thumbnail/thumbnail.go b/server/internal/thumbnail/thumbnail.gonew file mode 100644index 0000000000..395b869136--- /dev/null+++ b/server/internal/thumbnail/thumbnail.go@@ -0,0 +1,163 @@+// Package thumbnail renders small display copies of large images, so a grid of+// tiles does not have to download and decode multi-megapixel originals.+package thumbnail++import (+ "bytes"+ "errors"+ "fmt"+ "image"+ "image/jpeg"+ "image/png"+ "math"+ "path"+ "strings"++ "github.com/multica-ai/multica/server/internal/imagemetadata"+ "golang.org/x/image/draw"+ _ "golang.org/x/image/webp"+)++const (+ // ShortSide covers a ~240 CSS px tile edge at 2x density.+ ShortSide = 480+ // MaxLongSide bounds panoramas and tall screenshots.+ MaxLongSide = 1280+ // MaxSourcePixels bounds decode memory: a 40 MP RGBA bitmap is 160 MB.+ MaxSourcePixels = 40_000_000++ jpegQuality = 82+)++// ErrUnsupported reports a source this package will not decode: an unknown or+// excluded format, a malformed header, or an image above MaxSourcePixels.+var ErrUnsupported = errors.New("thumbnail: unsupported image")++// Thumbnail is an encoded thumbnail. Opaque images are JPEG; images with any+// transparency stay PNG so their alpha survives.+type Thumbnail struct {+ Data []byte+ ContentType string+}++// StorageKey names the stored thumbnail of a storage object. Only keys with a+// raster image extension get one, so a delete path that knows just the object+// URL can remove the thumbnail without a lookup.+func StorageKey(objectKey string) (string, bool) {+ switch strings.ToLower(path.Ext(objectKey)) {+ case ".jpg", ".jpeg", ".png", ".webp":+ return objectKey + ".thumb", true+ }+ return "", false+}++// SupportedContentType reports whether Generate accepts images of this type.+// GIF (animation), SVG (vector) and HEIC (no decoder) are left to the original.+func SupportedContentType(contentType string) bool {+ switch contentType {+ case "image/jpeg", "image/png", "image/webp":+ return true+ }+ return false+}++// Generate decodes a JPEG, PNG or WebP and returns a copy scaled to Size,+// with JPEG EXIF orientation applied so it displays like the original.+func Generate(data []byte) (Thumbnail, error) {+ cfg, format, err := image.DecodeConfig(bytes.NewReader(data))+ if err != nil {+ return Thumbnail{}, fmt.Errorf("%w: %v", ErrUnsupported, err)+ }+ switch format {+ case "jpeg", "png", "webp":+ default:+ return Thumbnail{}, fmt.Errorf("%w: format %s", ErrUnsupported, format)+ }+ if cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width)*int64(cfg.Height) > MaxSourcePixels {+ return Thumbnail{}, fmt.Errorf("%w: %dx%d", ErrUnsupported, cfg.Width, cfg.Height)+ }++ src, _, err := image.Decode(bytes.NewReader(data))+ if err != nil {+ return Thumbnail{}, fmt.Errorf("thumbnail: decode %s: %w", format, err)+ }+ orientation := 1+ if format == "jpeg" {+ orientation = imagemetadata.JPEGOrientation(data)+ }++ srcW, srcH := src.Bounds().Dx(), src.Bounds().Dy()+ transposed := orientation >= 5+ displayW, displayH := srcW, srcH+ if transposed {+ displayW, displayH = srcH, srcW+ }+ outW, outH := Size(displayW, displayH)+ scaledW, scaledH := outW, outH+ if transposed {+ scaledW, scaledH = outH, outW+ }++ scaled := image.NewRGBA(image.Rect(0, 0, scaledW, scaledH))+ draw.CatmullRom.Scale(scaled, scaled.Bounds(), src, src.Bounds(), draw.Src, nil)+ out := orient(scaled, orientation)++ var buf bytes.Buffer+ if out.Opaque() {+ if err := jpeg.Encode(&buf, out, &jpeg.Options{Quality: jpegQuality}); err != nil {+ return Thumbnail{}, fmt.Errorf("thumbnail: encode jpeg: %w", err)+ }+ return Thumbnail{Data: buf.Bytes(), ContentType: "image/jpeg"}, nil+ }+ if err := png.Encode(&buf, out); err != nil {+ return Thumbnail{}, fmt.Errorf("thumbnail: encode png: %w", err)+ }+ return Thumbnail{Data: buf.Bytes(), ContentType: "image/png"}, nil+}++// Size returns the thumbnail dimensions for a w x h image: the short side+// shrinks to ShortSide and the long side to at most MaxLongSide, keeping the+// aspect ratio. Images already within both bounds keep their size.+func Size(w, h int) (int, int) {+ short, long := min(w, h), max(w, h)+ scale := min(1, float64(ShortSide)/float64(short), float64(MaxLongSide)/float64(long))+ return max(1, int(math.Round(float64(w)*scale))), max(1, int(math.Round(float64(h)*scale)))+}++// orient applies an EXIF orientation (1-8) to src. Orientations 5-8 swap the+// image's width and height.+func orient(src *image.RGBA, orientation int) *image.RGBA {+ if orientation < 2 || orientation > 8 {+ return src+ }+ w, h := src.Bounds().Dx(), src.Bounds().Dy()+ dstW, dstH := w, h+ if orientation >= 5 {+ dstW, dstH = h, w+ }+ dst := image.NewRGBA(image.Rect(0, 0, dstW, dstH))+ for y := 0; y < dstH; y++ {+ for x := 0; x < dstW; x++ {+ var sx, sy int+ switch orientation {+ case 2:+ sx, sy = w-1-x, y+ case 3:+ sx, sy = w-1-x, h-1-y+ case 4:+ sx, sy = x, h-1-y+ case 5:+ sx, sy = y, x+ case 6:+ sx, sy = y, h-1-x+ case 7:+ sx, sy = w-1-y, h-1-x+ case 8:+ sx, sy = w-1-y, x+ }+ si, di := src.PixOffset(sx, sy), dst.PixOffset(x, y)+ copy(dst.Pix[di:di+4], src.Pix[si:si+4])+ }+ }+ return dst+}diff --git a/server/internal/thumbnail/thumbnail_test.go b/server/internal/thumbnail/thumbnail_test.gonew file mode 100644index 0000000000..b67251e1e1--- /dev/null+++ b/server/internal/thumbnail/thumbnail_test.go@@ -0,0 +1,218 @@+package thumbnail++import (+ "bytes"+ "encoding/binary"+ "errors"+ "hash/crc32"+ "image"+ "image/color"+ "image/gif"+ "image/jpeg"+ "image/png"+ "testing"+)++func TestSize(t *testing.T) {+ for _, tc := range []struct{ w, h, wantW, wantH int }{+ {5472, 3072, 855, 480},+ {3072, 5472, 480, 855},+ {4000, 4000, 480, 480},+ {10000, 1000, 1280, 128},+ {400, 300, 400, 300},+ {1, 1, 1, 1},+ } {+ if w, h := Size(tc.w, tc.h); w != tc.wantW || h != tc.wantH {+ t.Errorf("Size(%d, %d) = %dx%d, want %dx%d", tc.w, tc.h, w, h, tc.wantW, tc.wantH)+ }+ }+}++func TestGenerateScalesLargeJPEG(t *testing.T) {+ src := encodeJPEG(t, image.NewRGBA(image.Rect(0, 0, 5472, 3072)))+ got, err := Generate(src)+ if err != nil {+ t.Fatal(err)+ }+ if got.ContentType != "image/jpeg" {+ t.Fatalf("content type = %q", got.ContentType)+ }+ cfg, err := jpeg.DecodeConfig(bytes.NewReader(got.Data))+ if err != nil {+ t.Fatal(err)+ }+ if cfg.Width != 855 || cfg.Height != 480 {+ t.Fatalf("thumbnail = %dx%d", cfg.Width, cfg.Height)+ }+ if len(got.Data) > 100<<10 {+ t.Fatalf("thumbnail is %d bytes", len(got.Data))+ }+}++func TestGenerateKeepsTransparencyAsPNG(t *testing.T) {+ img := image.NewNRGBA(image.Rect(0, 0, 1200, 900))+ for i := range img.Pix {+ img.Pix[i] = 0x80+ }+ got, err := Generate(encodePNG(t, img))+ if err != nil {+ t.Fatal(err)+ }+ if got.ContentType != "image/png" {+ t.Fatalf("content type = %q", got.ContentType)+ }+ decoded, err := png.Decode(bytes.NewReader(got.Data))+ if err != nil {+ t.Fatal(err)+ }+ if _, _, _, a := decoded.At(0, 0).RGBA(); a == 0xffff {+ t.Fatal("alpha was flattened")+ }+}++func TestGenerateEncodesOpaquePNGAsJPEG(t *testing.T) {+ img := image.NewRGBA(image.Rect(0, 0, 1200, 900))+ for i := range img.Pix {+ img.Pix[i] = 0xff+ }+ got, err := Generate(encodePNG(t, img))+ if err != nil {+ t.Fatal(err)+ }+ if got.ContentType != "image/jpeg" {+ t.Fatalf("content type = %q", got.ContentType)+ }+}++func TestGenerateAppliesJPEGOrientation(t *testing.T) {+ // The left half is red. EXIF orientation 6 rotates the image 90° clockwise+ // for display, which moves that half to the top.+ img := image.NewRGBA(image.Rect(0, 0, 1600, 1000))+ for y := 0; y < 1000; y++ {+ for x := 0; x < 1600; x++ {+ c := color.RGBA{0, 0, 255, 255}+ if x < 800 {+ c = color.RGBA{255, 0, 0, 255}+ }+ img.SetRGBA(x, y, c)+ }+ }+ got, err := Generate(withJPEGOrientation(encodeJPEG(t, img), 6))+ if err != nil {+ t.Fatal(err)+ }+ decoded, err := jpeg.Decode(bytes.NewReader(got.Data))+ if err != nil {+ t.Fatal(err)+ }+ b := decoded.Bounds()+ if b.Dx() != 480 || b.Dy() != 768 {+ t.Fatalf("rotated thumbnail = %dx%d", b.Dx(), b.Dy())+ }+ if r, _, bl, _ := decoded.At(b.Dx()/2, b.Dy()/8).RGBA(); r < bl {+ t.Fatal("top of the rotated thumbnail is not the original's left half")+ }+ if r, _, bl, _ := decoded.At(b.Dx()/2, b.Dy()*7/8).RGBA(); r > bl {+ t.Fatal("bottom of the rotated thumbnail is not the original's right half")+ }+}++func TestOrientMapsEveryOrientation(t *testing.T) {+ // A 2x1 source: left pixel A, right pixel B. Each EXIF orientation places A+ // at a known spot of the displayed image.+ a, b := color.RGBA{1, 0, 0, 255}, color.RGBA{2, 0, 0, 255}+ src := image.NewRGBA(image.Rect(0, 0, 2, 1))+ src.SetRGBA(0, 0, a)+ src.SetRGBA(1, 0, b)+ for orientation, wantA := range map[int]image.Point{+ 1: {0, 0}, 2: {1, 0}, 3: {1, 0}, 4: {0, 0},+ 5: {0, 0}, 6: {0, 0}, 7: {0, 1}, 8: {0, 1},+ } {+ got := orient(src, orientation)+ if got.RGBAAt(wantA.X, wantA.Y) != a {+ t.Errorf("orientation %d: A not at %v", orientation, wantA)+ }+ }+}++func TestGenerateRejectsUnsupportedSources(t *testing.T) {+ var gifData bytes.Buffer+ if err := gif.Encode(&gifData, image.NewPaletted(image.Rect(0, 0, 10, 10), color.Palette{color.White}), nil); err != nil {+ t.Fatal(err)+ }+ for name, data := range map[string][]byte{+ "empty": nil,+ "not image": []byte("hello"),+ "gif": gifData.Bytes(),+ "too large": pngHeaderOnly(10000, 5000),+ } {+ if _, err := Generate(data); !errors.Is(err, ErrUnsupported) {+ t.Errorf("%s: err = %v, want ErrUnsupported", name, err)+ }+ }+}++func BenchmarkGenerate5472x3072JPEG(b *testing.B) {+ img := image.NewRGBA(image.Rect(0, 0, 5472, 3072))+ for i := range img.Pix {+ img.Pix[i] = byte(i * 31)+ }+ var buf bytes.Buffer+ if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 90}); err != nil {+ b.Fatal(err)+ }+ b.ResetTimer()+ for b.Loop() {+ if _, err := Generate(buf.Bytes()); err != nil {+ b.Fatal(err)+ }+ }+}++func encodeJPEG(t *testing.T, img image.Image) []byte {+ t.Helper()+ var b bytes.Buffer+ if err := jpeg.Encode(&b, img, nil); err != nil {+ t.Fatal(err)+ }+ return b.Bytes()+}++func encodePNG(t *testing.T, img image.Image) []byte {+ t.Helper()+ var b bytes.Buffer+ if err := png.Encode(&b, img); err != nil {+ t.Fatal(err)+ }+ return b.Bytes()+}++// withJPEGOrientation inserts an EXIF APP1 segment carrying orientation right+// after the JPEG's SOI marker.+func withJPEGOrientation(data []byte, orientation uint16) []byte {+ tiff := make([]byte, 26)+ copy(tiff, "MM")+ binary.BigEndian.PutUint16(tiff[2:], 42)+ binary.BigEndian.PutUint32(tiff[4:], 8)+ binary.BigEndian.PutUint16(tiff[8:], 1)+ binary.BigEndian.PutUint16(tiff[10:], 0x0112)+ binary.BigEndian.PutUint16(tiff[12:], 3)+ binary.BigEndian.PutUint32(tiff[14:], 1)+ binary.BigEndian.PutUint16(tiff[18:], orientation)+ payload := append([]byte("Exif\x00\x00"), tiff...)+ out := append([]byte{0xff, 0xd8, 0xff, 0xe1}, byte((len(payload)+2)>>8), byte(len(payload)+2))+ out = append(out, payload...)+ return append(out, data[2:]...)+}++// pngHeaderOnly is a PNG whose IHDR declares w x h with no pixel data.+func pngHeaderOnly(w, h uint32) []byte {+ header := make([]byte, 13)+ binary.BigEndian.PutUint32(header, w)+ binary.BigEndian.PutUint32(header[4:], h)+ header[8], header[9] = 8, 2+ chunk := append([]byte("IHDR"), header...)+ data := append([]byte("\x89PNG\r\n\x1a\n"), 0, 0, 0, 13)+ data = append(data, chunk...)+ return binary.BigEndian.AppendUint32(data, crc32.ChecksumIEEE(chunk))+}