Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(editor): render proxy-mode inline images from an authenticated byte fetch (MUL-5445) (#6091)
Bohan Jiang06a100d612d3
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 1a2e42722d..6d40e83366 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -2360,6 +2360,29 @@ export class ApiClient {};}+ // Fetches the raw bytes of an attachment through the unified download+ // endpoint.+ //+ // This is the last-resort inline-media path for deployments where the+ // server has no natively-loadable URL to offer. `GET /api/attachments/{id}`+ // only upgrades `download_url` to a signed storage URL under CloudFront+ // signing or presign mode; in **proxy** mode (self-hosted MinIO or any+ // storage endpoint on an internal host, which the default `auto` mode+ // classifies as proxy) it returns the auth-gated API path again. Clients+ // that cannot ride the session cookie on a native `<img>` resource fetch —+ // Desktop's file:// renderer, the mobile webview, split-origin web — get+ // the bytes here and render them from an object URL instead.+ //+ // Routes through `fetchRaw` so it inherits the standard auth headers,+ // 401 → handleUnauthorized recovery, request-id logging and ApiError shape.+ // Callers must only reach for this once the metadata refresh has shown+ // there is no signed URL: in the other modes the endpoint 302s to storage,+ // where CORS is not configured for a JS fetch.+ async getAttachmentBlob(id: string): Promise<Blob> {+ const res = await this.fetchRaw(`/api/attachments/${id}/download`);+ return res.blob();+ }+// Projectsasync listProjects(params?: { status?: string }): Promise<ListProjectsResponse> {const search = new URLSearchParams();diff --git a/packages/views/editor/attachment.test.tsx b/packages/views/editor/attachment.test.tsxindex d18beff574..eb672b819c 100644--- a/packages/views/editor/attachment.test.tsx+++ b/packages/views/editor/attachment.test.tsx@@ -7,6 +7,7 @@ import type { Attachment as AttachmentRecord } from "@multica/core/types";const {getAttachmentTextContentMock,getAttachmentMock,+ getAttachmentBlobMock,getBaseUrlMock,downloadMock,openExternalMock,@@ -14,6 +15,7 @@ const {} = vi.hoisted(() => ({getAttachmentTextContentMock: vi.fn(),getAttachmentMock: vi.fn(),+ getAttachmentBlobMock: vi.fn(),// Default: empty base URL so existing tests render site-relative URLs// through the proxy (i.e. exactly the way the web app behaves). The// absolutize-specific suite below overrides this to simulate Desktop /@@ -28,6 +30,7 @@ vi.mock("@multica/core/api", () => ({api: {getAttachmentTextContent: getAttachmentTextContentMock,getAttachment: getAttachmentMock,+ getAttachmentBlob: getAttachmentBlobMock,getBaseUrl: getBaseUrlMock,},PreviewTooLargeError: class extends Error {},@@ -154,6 +157,15 @@ function renderWithQuery(ui: ReactElement) {return render(<QueryClientProvider client={qc}>{ui}</QueryClientProvider>);}+// jsdom implements neither half of the object-URL API, and the proxy-mode+// byte fallback depends on both. Stub them per-test so the created/revoked+// calls are assertable, and restore afterwards.+const OBJECT_URL = "blob:https://app.example/att-1";+let originalCreateObjectURL: typeof URL.createObjectURL | undefined;+let originalRevokeObjectURL: typeof URL.revokeObjectURL | undefined;+let createObjectURLMock: ReturnType<typeof vi.fn>;+let revokeObjectURLMock: ReturnType<typeof vi.fn>;+beforeEach(() => {vi.clearAllMocks();resolverState.attachments = [];@@ -162,12 +174,38 @@ beforeEach(() => {// the web app's same-origin proxy. Tests that simulate Desktop / mobile// webview override per-case via getBaseUrlMock.mockReturnValue(...).getBaseUrlMock.mockReturnValue("");++ originalCreateObjectURL = URL.createObjectURL;+ originalRevokeObjectURL = URL.revokeObjectURL;+ createObjectURLMock = vi.fn(() => OBJECT_URL);+ revokeObjectURLMock = vi.fn();+ Object.defineProperty(URL, "createObjectURL", {+ configurable: true,+ value: createObjectURLMock,+ });+ Object.defineProperty(URL, "revokeObjectURL", {+ configurable: true,+ value: revokeObjectURLMock,+ });});afterEach(() => {+ restoreObjectURL("createObjectURL", originalCreateObjectURL);+ restoreObjectURL("revokeObjectURL", originalRevokeObjectURL);vi.restoreAllMocks();});+function restoreObjectURL(+ prop: "createObjectURL" | "revokeObjectURL",+ original: unknown,+): void {+ if (original) {+ Object.defineProperty(URL, prop, { configurable: true, value: original });+ } else {+ delete (URL as Partial<typeof URL>)[prop];+ }+}+describe("Attachment — image dispatch", () => {it("record image renders <img> with hover toolbar (View/Download/Copy)", () => {const att = makeRecord();@@ -468,15 +506,19 @@ describe("Attachment — image dispatch", () => {expect(getAttachmentMock).toHaveBeenCalledWith(id);});- it("keeps the picked URL when fresh metadata has no signed download_url (MUL-3254)", async () => {- // Non-CloudFront deployments return the API path again as download_url —- // swapping to it gains nothing, so the original pick must stay.+ it("falls back to an authenticated byte fetch when the deployment has no signed URL (MUL-5445)", async () => {+ // Proxy download mode — the default `auto` classification for a storage+ // endpoint on an internal host (docker-compose MinIO). GET+ // /api/attachments/{id} hands back the auth-gated API path again, so+ // there is nothing to swap in: the renderer must pull the bytes through+ // the authenticated client and paint them from an object URL instead of+ // keeping a src it already knows 401s.getBaseUrlMock.mockReturnValue("https://multica-api.copilothub.ai");const id = "11111111-2222-3333-4444-555555555555";const markdownUrl = `https://multica-api.copilothub.ai/api/attachments/${id}/download`;const att = makeRecord({id,- url: "https://cdn.example.test/uploads/ws/shot.png",+ url: "https://minio:9000/multica/uploads/ws/shot.png",markdown_url: markdownUrl,download_url: "",});@@ -485,6 +527,56 @@ describe("Attachment — image dispatch", () => {getAttachmentMock.mockResolvedValue(makeRecord({ id, download_url: `/api/attachments/${id}/download` }),);+ const blob = new Blob(["png-bytes"], { type: "image/png" });+ getAttachmentBlobMock.mockResolvedValue(blob);++ const { unmount } = renderWithQuery(+ <Attachment+ attachment={{+ kind: "url",+ url: markdownUrl,+ filename: "shot.png",+ forceKind: "image",+ }}+ />,+ );++ await waitFor(() => {+ expect(document.querySelector("img")?.getAttribute("src")).toBe(OBJECT_URL);+ });+ expect(getAttachmentBlobMock).toHaveBeenCalledWith(id);+ expect(createObjectURLMock).toHaveBeenCalledWith(blob);++ // The bytes are released once nothing renders them.+ unmount();+ expect(revokeObjectURLMock).toHaveBeenCalledWith(OBJECT_URL);+ });++ it("copies the durable URL, not the session-local object URL (MUL-5445)", async () => {+ // A `blob:` URL resolves only inside this renderer session, so Copy Link+ // must keep handing out the persisted attachment URL.+ getBaseUrlMock.mockReturnValue("https://multica-api.copilothub.ai");+ const id = "11111111-2222-3333-4444-555555555555";+ const markdownUrl = `https://multica-api.copilothub.ai/api/attachments/${id}/download`;+ resolverState.attachments = [+ makeRecord({+ id,+ url: "https://minio:9000/multica/uploads/ws/shot.png",+ markdown_url: markdownUrl,+ download_url: "",+ }),+ ];+ getAttachmentMock.mockResolvedValue(+ makeRecord({ id, download_url: `/api/attachments/${id}/download` }),+ );+ getAttachmentBlobMock.mockResolvedValue(+ new Blob(["png-bytes"], { type: "image/png" }),+ );+ const writeText = vi.fn().mockResolvedValue(undefined);+ Object.defineProperty(navigator, "clipboard", {+ configurable: true,+ value: { writeText },+ });renderWithQuery(<Attachment@@ -497,8 +589,79 @@ describe("Attachment — image dispatch", () => {/>,);+ await waitFor(() => {+ expect(document.querySelector("img")?.getAttribute("src")).toBe(OBJECT_URL);+ });+ fireEvent.click(screen.getByTitle("Copy link"));+ await waitFor(() => expect(writeText).toHaveBeenCalledWith(markdownUrl));+ });++ it("does not pull bytes for non-image attachments (MUL-5445)", async () => {+ // A file card only needs a link. Downloading a large archive into+ // renderer memory to draw a chip would be a bad trade, so the byte+ // fallback stays image-only.+ getBaseUrlMock.mockReturnValue("https://multica-api.copilothub.ai");+ const id = "11111111-2222-3333-4444-555555555555";+ const markdownUrl = `https://multica-api.copilothub.ai/api/attachments/${id}/download`;+ resolverState.attachments = [+ makeRecord({+ id,+ filename: "archive.zip",+ content_type: "application/zip",+ url: "https://minio:9000/multica/uploads/ws/archive.zip",+ markdown_url: markdownUrl,+ download_url: "",+ }),+ ];+ getAttachmentMock.mockResolvedValue(+ makeRecord({+ id,+ filename: "archive.zip",+ content_type: "application/zip",+ download_url: `/api/attachments/${id}/download`,+ }),+ );++ renderWithQuery(+ <Attachment+ attachment={{+ kind: "url",+ url: markdownUrl,+ filename: "archive.zip",+ }}+ />,+ );+await waitFor(() => expect(getAttachmentMock).toHaveBeenCalledWith(id));- expect(document.querySelector("img")?.getAttribute("src")).toBe(markdownUrl);+ expect(getAttachmentBlobMock).not.toHaveBeenCalled();+ });++ it("prefers the signed URL over a byte fetch when the server can presign (MUL-5445)", async () => {+ // Presign / CloudFront deployments already hand back a natively-loadable+ // URL. Pulling the bytes as well would double every image download.+ getBaseUrlMock.mockReturnValue("https://multica-api.copilothub.ai");+ configStore.setState({ cdnDomain: "cdn.example.test", cdnSigned: true });+ const id = "11111111-2222-3333-4444-555555555555";+ const markdownUrl = `https://multica-api.copilothub.ai/api/attachments/${id}/download`;+ const signed =+ "https://cdn.example.test/uploads/ws/shot.png?Signature=fresh&Key-Pair-Id=K";+ getAttachmentMock.mockResolvedValue(makeRecord({ id, download_url: signed }));++ renderWithQuery(+ <Attachment+ attachment={{+ kind: "url",+ url: markdownUrl,+ filename: "shot.png",+ forceKind: "image",+ }}+ />,+ );++ await waitFor(() => {+ expect(document.querySelector("img")?.getAttribute("src")).toBe(signed);+ });+ expect(getAttachmentBlobMock).not.toHaveBeenCalled();});it("forceKind=image renders as image even when filename is empty (markdown  regression)", () => {diff --git a/packages/views/editor/attachment.tsx b/packages/views/editor/attachment.tsxindex ceaeb537be..b43ccb1a0e 100644--- a/packages/views/editor/attachment.tsx+++ b/packages/views/editor/attachment.tsx@@ -23,6 +23,7 @@* hints (selected, editable, onDelete).*/+import { useEffect, useState } from "react";import {Download,Link as LinkIcon,@@ -313,6 +314,14 @@ function hasExpiringSignatureQuery(q: URLSearchParams): boolean {// signature from the query cache.const RESIGN_STALE_MS = 20 * 60 * 1000;+// How long fetched image bytes stay in the query cache after the last <img>+// using them unmounts. The bytes themselves never go stale (an attachment id+// maps to an immutable storage object), so the blob query uses+// `staleTime: Infinity`; this bound exists purely to keep a long scroll+// through an image-heavy thread from pinning every decoded screenshot in+// renderer memory forever.+const INLINE_BLOB_GC_MS = 5 * 60 * 1000;+// useResignedInlineMediaURL upgrades an auth-gated media URL to a freshly// signed one for clients that cannot load `/api/attachments/<id>/download`// natively.@@ -330,12 +339,24 @@ const RESIGN_STALE_MS = 20 * 60 * 1000;//// For them, fetch fresh attachment metadata through the authenticated API —// the same re-sign the click-time download path already does — and swap in-// the response's signed `download_url`. When the server has no signed URL to-// offer (non-CloudFront deployments return the API path again), keep the-// original URL rather than looping.+// the response's signed `download_url`.+//+// The server only has a signed URL to offer under CloudFront signing or+// presign mode. In **proxy** download mode `GetAttachmentByID` hands back the+// auth-gated API path again, and before MUL-5445 the renderer simply kept the+// original URL — the image stayed broken and the metadata request was pure+// overhead. Proxy is not an exotic setting: the default `auto` mode forces it+// whenever the storage URL points at an internal host, which is exactly the+// docker-compose MinIO (`http://minio:9000`) self-host shape. So when the+// refreshed metadata confirms there is no signed URL, fall back to pulling the+// bytes through the authenticated client and rendering them from an object+// URL. `blobFallback` gates that on the caller actually rendering a native+// `<img>`: a file card only needs a link, and downloading a 100 MB archive+// into renderer memory to draw a chip would be a bad trade.function useResignedInlineMediaURL(attachmentId: string | undefined,pickedUrl: string,+ blobFallback: boolean,): string {const idFromPickedUrl = attachmentIdFromDownloadURL(pickedUrl);const resignAttachmentId = attachmentId ?? idFromPickedUrl;@@ -363,15 +384,56 @@ function useResignedInlineMediaURL(gcTime: RESIGN_STALE_MS,});- if (!needsResign) return pickedUrl;const dl = fresh?.download_url ?? "";// Accept the fresh URL only when it is an actual upgrade — absolute and no// longer the auth-gated API shape (i.e. a signed storage URL the renderer// can load natively).- if (/^https?:\/\//i.test(dl) && attachmentIdFromDownloadURL(dl) === undefined) {- return dl;- }- return pickedUrl;+ const signedUrl =+ /^https?:\/\//i.test(dl) && attachmentIdFromDownloadURL(dl) === undefined+ ? dl+ : "";++ // Only after `fresh` has landed do we know this deployment has nothing+ // signed to give — firing the byte fetch earlier would double-download on+ // every CloudFront / presign client.+ const { data: blob } = useQuery({+ queryKey: ["attachment-inline-blob", resignAttachmentId],+ queryFn: () => api.getAttachmentBlob(resignAttachmentId as string),+ enabled: needsResign && blobFallback && !!fresh && signedUrl === "",+ staleTime: Infinity,+ gcTime: INLINE_BLOB_GC_MS,+ });+ const blobUrl = useObjectURL(blob);++ if (!needsResign) return pickedUrl;+ if (signedUrl) return signedUrl;+ return blobUrl || pickedUrl;+}++// useObjectURL turns a Blob into a `blob:` URL for the lifetime of the calling+// component, revoking it on unmount / replacement so the bytes are released+// once nothing renders them. Returns "" while there is no blob (and during+// SSR, where createObjectURL does not exist).+function useObjectURL(blob: Blob | undefined): string {+ const [url, setUrl] = useState("");+ useEffect(() => {+ if (!blob || typeof URL.createObjectURL !== "function") {+ setUrl("");+ return;+ }+ const next = URL.createObjectURL(blob);+ setUrl(next);+ return () => {+ URL.revokeObjectURL(next);+ };+ }, [blob]);+ return url;+}++// isObjectURL flags a src that only resolves inside this renderer session —+// safe to paint, wrong to expose through Copy Link or persist anywhere.+function isObjectURL(rawUrl: string): boolean {+ return /^blob:/i.test(rawUrl);}// ---------------------------------------------------------------------------@@ -392,10 +454,6 @@ export function Attachment({const preview = useAttachmentPreview();const state = normalize(attachment, resolveAttachment, cdnDomain, cdnSigned);- // 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.- const mediaUrl = useResignedInlineMediaURL(state.attachmentId, state.url);const forceKind =attachment.kind === "url" ? attachment.forceKind : undefined;const kind =@@ -403,6 +461,20 @@ export function Attachment({(state.filename || state.contentType? getPreviewKind(state.contentType, state.filename): null);+ // 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 —+ // on deployments that have no signed URL to give — to an object URL built+ // from the authenticated byte fetch. Only the image branch renders a native+ // resource load, so only it opts into that byte fetch.+ const mediaUrl = useResignedInlineMediaURL(+ state.attachmentId,+ state.url,+ kind === "image",+ );+ // 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;const openPreview = () => {if (state.record) {@@ -429,7 +501,7 @@ export function Attachment({download(state.attachmentId);return;}- if (mediaUrl) openByUrl(mediaUrl);+ if (shareUrl) openByUrl(shareUrl);};if (kind === "image") {@@ -437,6 +509,7 @@ export function Attachment({<><ImageAttachmentViewsrc={mediaUrl}+ linkUrl={shareUrl}alt={state.filename}uploading={state.uploading}width={state.width}@@ -474,7 +547,7 @@ export function Attachment({filename={state.filename}contentType={state.contentType}attachmentId={state.attachmentId}- href={mediaUrl || undefined}+ href={shareUrl || undefined}uploading={state.uploading}onPreview={openPreview}onDownload={handleDownload}@@ -497,6 +570,12 @@ export function Attachment({interface ImageAttachmentViewProps {src: string;+ /**+ * URL handed to the user by Copy Link. Splits from `src` only when `src` is+ * a session-local object URL (proxy-mode byte fallback) — pasting a `blob:`+ * URL anywhere outside this renderer resolves to nothing.+ */+ linkUrl: string;alt: string;uploading: boolean;width?: number;@@ -511,6 +590,7 @@ interface ImageAttachmentViewProps {function ImageAttachmentView({src,+ linkUrl,alt,uploading,width,@@ -525,7 +605,7 @@ function ImageAttachmentView({const { t } = useT("editor");const handleCopyLink = async () => {- if (await copyText(src)) {+ if (await copyText(linkUrl)) {toast.success(t(($) => $.image.link_copied));} else {toast.error(t(($) => $.image.copy_link_failed));