Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(attachments): refresh image access when opening the viewer (#10854)

Danila Katalshov9c2277a830fb
diff --git a/packages/views/attachments/attachment-preview-page.test.tsx b/packages/views/attachments/attachment-preview-page.test.tsx
index 14e8220650..c5b46e6e8c 100644
--- a/packages/views/attachments/attachment-preview-page.test.tsx
+++ b/packages/views/attachments/attachment-preview-page.test.tsx
@@ -172,6 +172,7 @@ describe("AttachmentPreviewPage", () => {
renderPage(<AttachmentPreviewPage attachmentId="att-1" />);
const img = await screen.findByAltText("shot.png");
expect(img.getAttribute("src")).toBe("https://cdn.example.test/att-1?Signature=s");
+ expect(getAttachmentMock).toHaveBeenCalledTimes(1);
});
it("shows a CSV as a table", async () => {
@@ -204,3 +205,47 @@ describe("AttachmentPreviewPage", () => {
);
});
});
+
+
+it("refreshes an image once when reopening the actual page from cache", async () => {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ const image = makeAttachment({
+ filename: "shot.png",
+ content_type: "image/png",
+ });
+ getAttachmentMock.mockResolvedValueOnce(image);
+ const first = renderWithI18n(
+ <QueryClientProvider client={client}>
+ <AttachmentPreviewPage attachmentId="att-1" />
+ </QueryClientProvider>,
+ );
+ await screen.findByAltText("shot.png");
+ first.unmount();
+ getAttachmentMock.mockReset();
+ let finish!: (value: Attachment) => void;
+ getAttachmentMock.mockImplementationOnce(
+ () =>
+ new Promise<Attachment>((resolve) => {
+ finish = resolve;
+ }),
+ );
+ renderWithI18n(
+ <QueryClientProvider client={client}>
+ <AttachmentPreviewPage attachmentId="att-1" />
+ </QueryClientProvider>,
+ );
+ expect(screen.queryByAltText("shot.png")).toBeNull();
+ await waitFor(() => expect(getAttachmentMock).toHaveBeenCalledTimes(1));
+ finish({
+ ...image,
+ download_url: "https://cdn.example.test/new.png?Signature=current",
+ });
+ await waitFor(() =>
+ expect(screen.getByAltText("shot.png").getAttribute("src")).toContain(
+ "new.png",
+ ),
+ );
+ expect(getAttachmentMock).toHaveBeenCalledTimes(1);
+});
diff --git a/packages/views/attachments/attachment-preview-page.tsx b/packages/views/attachments/attachment-preview-page.tsx
index 45c63e0ddb..74c11b74ad 100644
--- a/packages/views/attachments/attachment-preview-page.tsx
+++ b/packages/views/attachments/attachment-preview-page.tsx
@@ -31,6 +31,7 @@ import { useCallback, useEffect } from "react";
import { useQuery } from "@tanstack/react-query";
import { Loader2 } from "@multica/ui/icons";
import { api } from "@multica/core/api";
+import { getPreviewKind } from "../editor/utils/preview";
import { useT } from "../i18n";
import { useRestoredViewState, useViewStateWriter } from "../platform";
import {
@@ -61,14 +62,19 @@ export function AttachmentPreviewPage({
const query = useQuery({
queryKey: ["attachment-preview-page", attachmentId] as const,
queryFn: () => api.getAttachment(attachmentId),
- // The record carries signed media URLs. Refetching would re-sign them and
- // reload a playing video or an open PDF under the reader; one fetch per
- // page view is enough.
+ // Images authenticate once per page open; loaded streams stay stable.
staleTime: Infinity,
+ refetchOnMount: (query) =>
+ query.state.data && getPreviewKind(
+ query.state.data.content_type, query.state.data.filename,
+ ) === "image" ? "always" : false,
refetchOnWindowFocus: false,
retry: false,
});
- const attachment = query.data?.id ? query.data : null;
+ const attachment = query.data?.id === attachmentId ? query.data : null;
+ const isImage = attachment &&
+ getPreviewKind(attachment.content_type, attachment.filename) === "image";
+ const imagePending = isImage && query.fetchStatus !== "idle";
// Set document.title so desktop's MutationObserver-based tab title picks
// up the filename. Web shows the same string in the browser tab.
@@ -84,10 +90,11 @@ export function AttachmentPreviewPage({
[writeViewState],
);
- if (attachment) {
+ if (attachment && !(isImage && (imagePending || query.isError))) {
return (
<AttachmentPreviewStandalone
attachment={attachment}
+ currentImageMetadata={isImage ? attachment : undefined}
renderHtmlFrame={renderPageHtmlFrame}
initialHtmlAddress={normalizeHtmlPreviewAddress(
restoredAddress ?? initialAddress ?? "",
@@ -99,7 +106,7 @@ export function AttachmentPreviewPage({
return (
<div className="dark flex h-full w-full items-center justify-center gap-2 bg-black/95 px-4 text-body text-muted-foreground">
- {query.isLoading ? (
+ {query.isPending || imagePending ? (
<>
<Loader2 className="size-4 animate-spin" />
{t(($) => $.attachment.preview_loading)}
diff --git a/packages/views/editor/attachment-preview-modal.test.tsx b/packages/views/editor/attachment-preview-modal.test.tsx
index 2289a68ee0..82a56aec36 100644
--- a/packages/views/editor/attachment-preview-modal.test.tsx
+++ b/packages/views/editor/attachment-preview-modal.test.tsx
@@ -4,6 +4,7 @@ import { focusManager, QueryClient, QueryClientProvider } from "@tanstack/react-
import { useState, type ReactElement } from "react";
import type { Attachment } from "@multica/core/types";
import { ApiError } from "@multica/core/api/client";
+import { configStore } from "@multica/core/config";
const { openExternalMock, isDesktopShellMock, copyImageMock, copyTextMock, toastMock } =
vi.hoisted(() => ({
@@ -37,6 +38,8 @@ vi.mock("sonner", () => ({ toast: toastMock }));
const {
getAttachmentTextContentMock,
getAttachmentMock,
+ getAttachmentForDownloadMock,
+ getAttachmentBlobMock,
downloadMock,
getBaseUrlMock,
FakePreviewTooLargeError,
@@ -58,7 +61,9 @@ const {
getAttachmentTextContentMock: vi.fn(),
// Re-sign metadata. Rejects by default: a deployment with nothing to
// upgrade to, so the picked URL stands.
- getAttachmentMock: vi.fn((): Promise<Attachment> => Promise.reject(new Error("no re-sign"))),
+ getAttachmentMock: vi.fn<(id: string) => Promise<Attachment>>(() => Promise.reject(new Error("no re-sign"))),
+ getAttachmentBlobMock: vi.fn(),
+ getAttachmentForDownloadMock: vi.fn(),
downloadMock: vi.fn(),
// Default to the web shape (empty base, same-origin). Tests covering
// the desktop-renderer / standalone-shell case override per-test.
@@ -72,6 +77,8 @@ vi.mock("@multica/core/api", () => ({
api: {
getAttachmentTextContent: getAttachmentTextContentMock,
getAttachment: getAttachmentMock,
+ getAttachmentForDownload: getAttachmentForDownloadMock,
+ getAttachmentBlob: getAttachmentBlobMock,
getBaseUrl: getBaseUrlMock,
},
PreviewTooLargeError: FakePreviewTooLargeError,
@@ -181,6 +188,7 @@ vi.mock("../i18n", () => ({
import {
AttachmentPreviewModal,
AttachmentPreviewStandalone,
+ PreviewImagePrefetch,
useAttachmentPreview,
} from "./attachment-preview-modal";
import { withFragmentNavShim } from "./utils/iframe-fragment-nav";
@@ -232,6 +240,8 @@ function ClosablePreview({ attachment }: { attachment: Attachment }) {
beforeEach(() => {
vi.clearAllMocks();
getAttachmentMock.mockReset().mockRejectedValue(new ApiError("no re-sign", 404, "Not Found"));
+ getAttachmentBlobMock.mockReset();
+ getAttachmentForDownloadMock.mockReset();
downloadMock.mockReset();
// Drops any body a test queued but never consumed (a media kind skips the
// text fetch), so it cannot answer the next test's request.
@@ -247,27 +257,29 @@ beforeEach(() => {
});
afterEach(() => {
+ vi.unstubAllGlobals();
vi.restoreAllMocks();
});
describe("AttachmentPreviewModal — dispatch", () => {
- it("renders an <img> centered in the modal for image content types", () => {
+ it("renders an <img> centered in the modal for image content types", async () => {
const att = makeAttachment({ filename: "shot.png", content_type: "image/png" });
+ getAttachmentMock.mockResolvedValueOnce(att);
render(<AttachmentPreviewModal source={{ kind: "full", attachment: att }} open onClose={() => {}} />);
- const img = document.querySelector("img");
+ const img = await screen.findByRole("img", { name: att.filename });
expect(img).toBeTruthy();
expect(img?.getAttribute("src")).toBe(att.download_url);
expect(img?.getAttribute("alt")).toBe(att.filename);
});
- it("falls back to durable media URLs when a full attachment has no download_url", () => {
+ it("resolves an image whose cached record has no download URL from current metadata", async () => {
const att = makeAttachment({
filename: "shot.png",
content_type: "image/png",
download_url: "",
- markdown_url: "https://api.example.test/api/attachments/att-1/download",
- url: "https://cdn.example.test/att-1.png?Signature=old",
});
+ const fresh = "https://cdn.example.test/shot.png?Signature=current";
+ getAttachmentMock.mockResolvedValueOnce({ ...att, download_url: fresh });
render(
<AttachmentPreviewModal
source={{ kind: "full", attachment: att }}
@@ -275,9 +287,8 @@ describe("AttachmentPreviewModal — dispatch", () => {
onClose={() => {}}
/>,
);
- const img = document.querySelector("img");
- expect(img?.getAttribute("src")).toBe(att.markdown_url);
- expect(img?.getAttribute("src")).not.toContain("Signature=");
+ expect(
+ (await screen.findByRole("img", { name: att.filename })).getAttribute("src")).toBe(fresh);
});
it("renders an <img> from a URL-only source for image filenames", () => {
@@ -450,13 +461,26 @@ describe("AttachmentPreviewModal — server-relative download_url resolution (MU
// is loaded from `app://` / file: / dev-server origin and needs the
// absolute URL — otherwise `<img src>`, `<iframe src>`, `<video src>`
// hit the shell origin and fail.
- it("prefixes the configured API base for image previews when download_url is server-relative", async () => {
- getBaseUrlMock.mockReturnValue("https://api.example.test");
+ it.each(["https://api.example.test", "", "https://api.example.test/"])(
+ "loads authenticated image bytes with API base '%s'",
+ async (base) => {
+ getBaseUrlMock.mockReturnValue(base);
const att = makeAttachment({
filename: "shot.png",
content_type: "image/png",
download_url: "/api/attachments/att-1/download",
- });
+ });
+ getAttachmentMock.mockResolvedValueOnce(att);
+ getAttachmentBlobMock.mockResolvedValueOnce(
+ new Blob(["image"], { type: "image/png" }),
+ );
+ const create = vi.fn(() => "blob:authenticated-image");
+ vi.stubGlobal(
+ "URL",
+ class extends URL {
+ static createObjectURL = create;
+ static revokeObjectURL = vi.fn();
+ });
render(
<AttachmentPreviewModal
source={{ kind: "full", attachment: att }}
@@ -464,18 +488,14 @@ describe("AttachmentPreviewModal — server-relative download_url resolution (MU
onClose={() => {}}
/>,
);
- // The auth-gated endpoint is only handed to <img> once the re-sign has
- // settled (here: nothing better on offer).
- await waitFor(() => {
- expect(document.querySelector("img")?.getAttribute("src")).toBe(
- "https://api.example.test/api/attachments/att-1/download",
+ await waitFor(() =>
+ expect(document.querySelector("img")?.getAttribute("src")).toBe(
+ "blob:authenticated-image",
+ ),
);
+ expect(getAttachmentBlobMock).toHaveBeenCalledWith(att.id);
});
- });
- // A client that cannot load the auth-gated endpoint natively (desktop,
- // split-origin web) would fail on it, and a sequence reads that failure as
- // a broken image and skips it. Nothing reaches <img> until the upgrade lands.
it("waits for the re-sign before loading an auth-gated image", async () => {
getBaseUrlMock.mockReturnValue("https://api.example.test");
let resolveMeta: (value: Attachment) => void = () => {};
@@ -536,52 +556,14 @@ describe("AttachmentPreviewModal — server-relative download_url resolution (MU
});
});
- it("keeps a same-origin relative URL untouched when the configured base is empty (web)", () => {
- // Default web shape — empty base. Browser resolves the relative path
- // against the document origin, no prefix needed.
- const att = makeAttachment({
- filename: "shot.png",
- content_type: "image/png",
- download_url: "/api/attachments/att-1/download",
- });
- render(
- <AttachmentPreviewModal
- source={{ kind: "full", attachment: att }}
- open
- onClose={() => {}}
- />,
- );
- const img = document.querySelector("img");
- expect(img?.getAttribute("src")).toBe("/api/attachments/att-1/download");
- });
-
- it("trims a trailing slash on the configured base when joining a relative URL", () => {
- getBaseUrlMock.mockReturnValue("https://api.example.test/");
- const att = makeAttachment({
- filename: "shot.png",
- content_type: "image/png",
- download_url: "/api/attachments/att-1/download",
- });
- render(
- <AttachmentPreviewModal
- source={{ kind: "full", attachment: att }}
- open
- onClose={() => {}}
- />,
- );
- const img = document.querySelector("img");
- expect(img?.getAttribute("src")).toBe(
- "https://api.example.test/api/attachments/att-1/download",
- );
- });
-
- it("passes an already-absolute CloudFront/presigned download_url through unchanged", () => {
+ it("passes an already-absolute CloudFront/presigned download_url through unchanged", async () => {
getBaseUrlMock.mockReturnValue("https://api.example.test");
const att = makeAttachment({
filename: "shot.png",
content_type: "image/png",
download_url: "https://cdn.example.test/att-1.png?Signature=s",
});
+ getAttachmentMock.mockResolvedValueOnce(att);
render(
<AttachmentPreviewModal
source={{ kind: "full", attachment: att }}
@@ -589,7 +571,7 @@ describe("AttachmentPreviewModal — server-relative download_url resolution (MU
onClose={() => {}}
/>,
);
- const img = document.querySelector("img");
+ const img = await screen.findByRole("img", { name: att.filename });
expect(img?.getAttribute("src")).toBe(
"https://cdn.example.test/att-1.png?Signature=s",
);
@@ -944,7 +926,13 @@ describe("AttachmentPreviewModal — copy image (MUL-7759)", () => {
it("copies the image on screen from the desktop shell", async () => {
isDesktopShellMock.mockReturnValue(true);
- render(<AttachmentPreviewModal source={{ kind: "full", attachment: image() }} open onClose={() => {}} />);
+ getAttachmentMock.mockResolvedValue(image());
+ render(<AttachmentPreviewModal source={{ kind: "full", attachment: image() }} open onClose={() => {}} />,
+ );
+
+ await waitFor(() =>
+ expect(screen.getByRole("button", { name: "Copy image" })).toBeEnabled(),
+ );
fireEvent.click(screen.getByRole("button", { name: "Copy image" }));
@@ -957,7 +945,13 @@ describe("AttachmentPreviewModal — copy image (MUL-7759)", () => {
it("says so when the copy fails", async () => {
isDesktopShellMock.mockReturnValue(true);
copyImageMock.mockResolvedValue(false);
- render(<AttachmentPreviewModal source={{ kind: "full", attachment: image() }} open onClose={() => {}} />);
+ getAttachmentMock.mockResolvedValue(image());
+ render(<AttachmentPreviewModal source={{ kind: "full", attachment: image() }} open onClose={() => {}} />,
+ );
+
+ await waitFor(() =>
+ expect(screen.getByRole("button", { name: "Copy image" })).toBeEnabled(),
+ );
fireEvent.click(screen.getByRole("button", { name: "Copy image" }));
@@ -966,6 +960,7 @@ describe("AttachmentPreviewModal — copy image (MUL-7759)", () => {
});
it("offers no copy button on web, where the storage CDN can't be read from script", () => {
+ getAttachmentMock.mockResolvedValue(image());
render(<AttachmentPreviewModal source={{ kind: "full", attachment: image() }} open onClose={() => {}} />);
expect(screen.queryByRole("button", { name: "Copy image" })).toBeNull();
});
@@ -1465,52 +1460,55 @@ function currentScale(): number {
return Number.parseFloat(match![1]!);
}
-function renderImagePreview(attachment: Attachment = imageAttachment()) {
- return render(
+async function renderImagePreview(attachment: Attachment = imageAttachment()) {
+ getAttachmentMock.mockResolvedValue(attachment);
+ const view = render(
<AttachmentPreviewModal
source={{ kind: "full", attachment }}
open
onClose={() => {}}
/>,
);
+ await screen.findByRole("img", { name: attachment.filename });
+ return view;
}
-describe("AttachmentPreviewModal — image zoom", () => {
+describe("AttachmentPreviewModal — image zoom", async () => {
beforeEach(() => {
stubCanvasViewport();
});
- it("fits an oversized image to the canvas on open", () => {
+ it("fits an oversized image to the canvas on open", async () => {
stubNaturalSize({ width: 1600, height: 800 });
- renderImagePreview();
+ await renderImagePreview();
// 1600x800 in an 800x400 canvas fits at exactly 50%.
expect(currentScale()).toBeCloseTo(0.5, 5);
expect(screen.getByText("50%")).toBeInTheDocument();
});
- it("opens a small image at 100% instead of magnifying it", () => {
+ it("opens a small image at 100% instead of magnifying it", async () => {
stubNaturalSize({ width: 200, height: 100 });
- renderImagePreview();
+ await renderImagePreview();
expect(currentScale()).toBe(1);
});
- it("shows a long screenshot in full, below the 25% floor", () => {
+ it("shows a long screenshot in full, below the 25% floor", async () => {
// The regression this pins: with a hard MIN_SCALE floor the fit snapped
// back up to 25% and a full-page screenshot opened cropped, with no zoom
// level that showed all of it.
stubNaturalSize({ width: 1600, height: 8000 });
- renderImagePreview();
+ await renderImagePreview();
const scale = currentScale();
expect(scale).toBeLessThan(0.25);
expect(8000 * scale).toBeLessThanOrEqual(CANVAS_VIEWPORT.height + 0.001);
});
- it("zooms in and out from the toolbar", () => {
+ it("zooms in and out from the toolbar", async () => {
stubNaturalSize({ width: 1600, height: 800 });
- renderImagePreview();
+ await renderImagePreview();
fireEvent.click(screen.getByRole("button", { name: "Zoom in" }));
expect(currentScale()).toBeCloseTo(0.5 * 1.2, 5);
@@ -1519,9 +1517,9 @@ describe("AttachmentPreviewModal — image zoom", () => {
expect(currentScale()).toBeCloseTo(0.5, 5);
});
- it("jumps to natural size and back to fit", () => {
+ it("jumps to natural size and back to fit", async () => {
stubNaturalSize({ width: 1600, height: 800 });
- renderImagePreview();
+ await renderImagePreview();
fireEvent.click(screen.getByRole("button", { name: "Actual size" }));
expect(currentScale()).toBe(1);
@@ -1530,9 +1528,9 @@ describe("AttachmentPreviewModal — image zoom", () => {
expect(currentScale()).toBeCloseTo(0.5, 5);
});
- it("zooms on wheel without scrolling the page behind the modal", () => {
+ it("zooms on wheel without scrolling the page behind the modal", async () => {
stubNaturalSize({ width: 1600, height: 800 });
- renderImagePreview();
+ await renderImagePreview();
const wheel = new WheelEvent("wheel", {
deltaY: -100,
@@ -1551,9 +1549,9 @@ describe("AttachmentPreviewModal — image zoom", () => {
expect(wheel.defaultPrevented).toBe(true);
});
- it("pans on drag", () => {
+ it("pans on drag", async () => {
stubNaturalSize({ width: 1600, height: 800 });
- renderImagePreview();
+ await renderImagePreview();
const before = canvasContent().style.transform;
fireEvent.pointerDown(zoomCanvas(), { pointerId: 1, clientX: 400, clientY: 200 });
@@ -1563,9 +1561,9 @@ describe("AttachmentPreviewModal — image zoom", () => {
expect(canvasContent().style.transform).not.toBe(before);
});
- it("toggles between fit and 100% on double-click", () => {
+ it("toggles between fit and 100% on double-click", async () => {
stubNaturalSize({ width: 1600, height: 800 });
- renderImagePreview();
+ await renderImagePreview();
fireEvent.doubleClick(zoomCanvas(), { clientX: 400, clientY: 200 });
expect(currentScale()).toBe(1);
@@ -1574,9 +1572,9 @@ describe("AttachmentPreviewModal — image zoom", () => {
expect(currentScale()).toBeCloseTo(0.5, 5);
});
- it("focuses the canvas on open so the keyboard controls work without a click first", () => {
+ it("focuses the canvas on open so the keyboard controls work without a click first", async () => {
stubNaturalSize({ width: 1600, height: 800 });
- renderImagePreview();
+ await renderImagePreview();
expect(document.activeElement).toBe(zoomCanvas());
@@ -1587,9 +1585,9 @@ describe("AttachmentPreviewModal — image zoom", () => {
// The focus placed on open is for the keyboard controls; drawn as a ring it
// framed the whole full-window stage. It stays marked (CSS drops the ring)
// until focus leaves, so a reader tabbing back in still sees one.
- it("keeps the focus ring off for the focus it places itself", () => {
+ it("keeps the focus ring off for the focus it places itself", async () => {
stubNaturalSize({ width: 1600, height: 800 });
- renderImagePreview();
+ await renderImagePreview();
expect(zoomCanvas()).toHaveAttribute("data-autofocused");
fireEvent.blur(zoomCanvas());
@@ -1599,7 +1597,9 @@ describe("AttachmentPreviewModal — image zoom", () => {
it("re-fits on reopen instead of restoring the previous zoom", async () => {
stubNaturalSize({ width: 1600, height: 800 });
const att = imageAttachment();
+ getAttachmentMock.mockResolvedValue(att);
render(<ClosablePreview attachment={att} />);
+ await screen.findByRole("img", { name: att.filename });
fireEvent.click(screen.getByRole("button", { name: "Actual size" }));
expect(currentScale()).toBe(1);
@@ -1609,15 +1609,15 @@ describe("AttachmentPreviewModal — image zoom", () => {
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
});
- renderImagePreview(att);
+ await renderImagePreview(att);
expect(currentScale()).toBeCloseTo(0.5, 5);
});
- it("letterboxes an image with no intrinsic size and hides the zoom controls", () => {
+ it("letterboxes an image with no intrinsic size and hides the zoom controls", async () => {
// An SVG that declares only a viewBox has no intrinsic size in Chromium,
// so there is nothing to build a transform against. It must still render.
stubNaturalSize({ width: 0, height: 0 });
- renderImagePreview(
+ await renderImagePreview(
makeAttachment({ filename: "chart.svg", content_type: "image/svg+xml" }),
);
@@ -1627,17 +1627,21 @@ describe("AttachmentPreviewModal — image zoom", () => {
expect(screen.queryByRole("button", { name: "Zoom in" })).toBeNull();
});
- it("keeps a pan that ends over the backdrop from closing the modal", () => {
+ it("keeps a pan that ends over the backdrop from closing the modal", async () => {
stubNaturalSize({ width: 1600, height: 800 });
const onClose = vi.fn();
+ const att = imageAttachment();
+ getAttachmentMock.mockResolvedValueOnce(att);
render(
<AttachmentPreviewModal
- source={{ kind: "full", attachment: imageAttachment() }}
+ source={{ kind: "full", attachment: att }}
open
onClose={onClose}
/>,
);
+ await screen.findByRole("img", { name: att.filename });
+
// A drag released outside the panel bubbles its click to the backdrop.
fireEvent.click(zoomCanvas());
expect(onClose).not.toHaveBeenCalled();
@@ -1646,7 +1650,7 @@ describe("AttachmentPreviewModal — image zoom", () => {
expect(onClose).toHaveBeenCalledTimes(1);
});
- it("shows no zoom controls for non-image kinds", () => {
+ it("shows no zoom controls for non-image kinds", async () => {
render(
<AttachmentPreviewModal
source={{
@@ -1814,3 +1818,257 @@ describe("AttachmentPreviewModal — tables", () => {
expect(table.querySelector("th[data-column-id='c1']")?.textContent).toBe("count");
});
});
+
+describe("AttachmentPreviewModal — expired cached image access", () => {
+ it("refreshes a cached signed image before decoding it", async () => {
+ const att = makeAttachment({
+ filename: "old-design.png",
+ content_type: "image/png",
+ download_url: "https://cdn.example.test/design.png?Signature=expired",
+ });
+ let resolveMetadata!: (value: Attachment) => void;
+ getAttachmentMock.mockImplementationOnce(
+ () =>
+ new Promise<Attachment>((resolve) => {
+ resolveMetadata = resolve;
+ }),
+ );
+ const onImageError = vi.fn();
+ render(
+ <AttachmentPreviewModal
+ source={{ kind: "full", attachment: att }}
+ open
+ onClose={() => {}}
+ onImageError={onImageError}
+ />,
+ );
+ expect(getAttachmentMock).toHaveBeenCalledWith(att.id);
+ expect(document.querySelector('img[src*="Signature=expired"]')).toBeNull();
+ expect(screen.getByText("Loading preview…")).toBeInTheDocument();
+ expect(onImageError).not.toHaveBeenCalled();
+ await act(async () => {
+ resolveMetadata({
+ ...att,
+ download_url: "https://cdn.example.test/design.png?Signature=fresh",
+ });
+ });
+ await waitFor(() =>
+ expect(document.querySelector("img")?.getAttribute("src")).toBe(
+ "https://cdn.example.test/design.png?Signature=fresh",
+ ),
+ );
+ expect(onImageError).not.toHaveBeenCalled();
+ });
+});
+
+describe("AttachmentPreviewModal — current image access failures", () => {
+ it.each([403, 404])(
+ "shows a failure and reports the current image once after metadata returns %s",
+ async (status) => {
+ const att = makeAttachment({
+ filename: "private.png",
+ content_type: "image/png",
+ });
+ getAttachmentMock.mockRejectedValueOnce(
+ new ApiError("not available", status, "Denied"),
+ );
+ const onImageError = vi.fn();
+ render(
+ <AttachmentPreviewModal
+ source={{ kind: "full", attachment: att }}
+ open
+ onClose={() => {}}
+ onImageError={onImageError}
+ />,
+ );
+ await waitFor(() => expect(onImageError).toHaveBeenCalledTimes(1));
+ expect(screen.getByText("Couldn't load preview")).toBeInTheDocument();
+ expect(document.querySelector("img")).toBeNull();
+ expect(getAttachmentBlobMock).not.toHaveBeenCalled();
+ },
+ );
+});
+
+it.each(["pending", "denied"])(
+ "does not expose the current attachment's held frame when access is %s",
+ async (phase) => {
+ isDesktopShellMock.mockReturnValue(true);
+ const a = makeAttachment({
+ id: "att-a",
+ filename: "a.png",
+ content_type: "image/png",
+ download_url: "https://cdn.example.test/a.png?Signature=old",
+ });
+ const b = makeAttachment({
+ id: "att-b",
+ filename: "b.png",
+ content_type: "image/png",
+ download_url: "https://cdn.example.test/b.png?Signature=new",
+ });
+ let aCalls = 0;
+ let deny!: (error: Error) => void;
+ getAttachmentMock.mockImplementation((id: string) =>
+ id === a.id
+ ? ++aCalls === 1
+ ? Promise.resolve(a)
+ : new Promise<Attachment>((_resolve, reject) => {
+ deny = reject;
+ })
+ : Promise.resolve(b),
+ );
+ Object.defineProperty(HTMLImageElement.prototype, "decode", {
+ configurable: true,
+ value: function (this: HTMLImageElement) {
+ return this.src === a.download_url
+ ? Promise.resolve()
+ : new Promise<void>(() => {});
+ },
+ });
+ function Harness() {
+ const [selected, setSelected] = useState(a);
+ return (
+ <>
+ <button onClick={() => setSelected(a)}>Select A</button>
+ <button onClick={() => setSelected(b)}>Select B</button>
+ <AttachmentPreviewModal
+ source={{ kind: "full", attachment: selected }}
+ open
+ onClose={() => {}}
+ />
+ </>
+ );
+ }
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ try {
+ rtlRender(<QueryClientProvider client={client}><Harness /></QueryClientProvider>);
+ await screen.findByRole("img", { name: a.filename });
+ fireEvent.click(screen.getByText("Select B"));
+ await waitFor(() => expect(getAttachmentMock).toHaveBeenCalledWith(b.id));
+ client.setQueryData(["attachment-inline-resign", a.id], a, {
+ updatedAt: Date.now() - 6 * 60 * 1000,
+ });
+ fireEvent.click(screen.getByText("Select A"));
+ await waitFor(() => expect(aCalls).toBe(2));
+ if (phase === "pending") {
+ expect(screen.queryByRole("img", { name: a.filename })).toBeNull();
+ } else {
+ await act(async () => {
+ deny(new ApiError("revoked", 403, "Forbidden"));
+ });
+ await screen.findByText("Couldn't load preview");
+ expect(
+ screen.getByRole("button", { name: "Copy image" }),
+ ).toBeDisabled();
+ fireEvent.click(screen.getByRole("button", { name: "Copy image" }));
+ expect(copyImageMock).not.toHaveBeenCalled();
+ }
+ } finally {
+ client.clear();
+ delete (HTMLImageElement.prototype as { decode?: unknown }).decode;
+ }
+ },
+);
+
+it.each([
+ "/api/attachments/11111111-2222-3333-4444-555555555555/download",
+ "/uploads/workspaces/aaaaaaaa-2222-3333-4444-555555555555/11111111-2222-3333-4444-555555555555.png",
+ "https://api.example.test/uploads/workspaces/aaaaaaaa-2222-3333-4444-555555555555/11111111-2222-3333-4444-555555555555.png",
+])("refreshes a pasted protected image against its owning workspace: %s", async (url) => {
+ const id = "11111111-2222-3333-4444-555555555555";
+ const fresh = makeAttachment({
+ id,
+ workspace_id: "other-workspace",
+ filename: "pasted.png",
+ content_type: "image/png",
+ });
+ getAttachmentForDownloadMock.mockResolvedValueOnce(fresh);
+ render(
+ <AttachmentPreviewModal
+ source={{
+ kind: "url",
+ url,
+ filename: fresh.filename,
+ }}
+ open
+ onClose={() => {}}
+ />,
+ );
+ expect(
+ (await screen.findByRole("img", { name: fresh.filename })).getAttribute(
+ "src",
+ ),
+ ).toBe(fresh.download_url);
+ expect(getAttachmentForDownloadMock).toHaveBeenCalledWith(id);
+ expect(getAttachmentMock).not.toHaveBeenCalled();
+});
+
+describe("image viewer prefetch reuse", () => {
+ it.each(["full", "url", "legacy-url", "absolute-legacy-url"] as const)(
+ "uses the prefetched signature without another metadata request for a %s source",
+ async (kind) => {
+ const att = makeAttachment({
+ id: "11111111-2222-3333-4444-555555555555",
+ filename: "neighbor.png",
+ content_type: "image/png",
+ download_url: "https://cdn.example.test/neighbor.png?Signature=expired",
+ });
+ const fresh = { ...att, download_url: "https://cdn.example.test/neighbor.png?Signature=prefetched" };
+ if (kind === "full") getAttachmentMock.mockResolvedValue(fresh);
+ getAttachmentForDownloadMock.mockResolvedValue(fresh);
+ const legacyUrl = `/uploads/workspaces/aaaaaaaa-2222-3333-4444-555555555555/${att.id}.png`;
+ const source = kind === "full"
+ ? { kind, attachment: att }
+ : {
+ kind: "url" as const,
+ url: kind === "url"
+ ? `/api/attachments/${att.id}/download`
+ : kind === "legacy-url" ? legacyUrl : `https://api.example.test${legacyUrl}`,
+ filename: att.filename,
+ };
+ const src = vi.spyOn(HTMLImageElement.prototype, "src", "set");
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const view = rtlRender(
+ <QueryClientProvider client={client}>
+ <PreviewImagePrefetch source={source} />
+ </QueryClientProvider>,
+ );
+ await waitFor(() => expect(src).toHaveBeenCalledWith(fresh.download_url));
+ expect(src).not.toHaveBeenCalledWith(att.download_url);
+ view.rerender(
+ <QueryClientProvider client={client}>
+ <AttachmentPreviewModal source={source} open onClose={() => {}} />
+ </QueryClientProvider>,
+ );
+ expect((await screen.findByRole("img", { name: att.filename })).getAttribute("src"))
+ .toBe(fresh.download_url);
+ expect(kind === "full" ? getAttachmentMock : getAttachmentForDownloadMock).toHaveBeenCalledTimes(1);
+ expect(kind === "full" ? getAttachmentForDownloadMock : getAttachmentMock).not.toHaveBeenCalled();
+ view.unmount();
+ client.clear();
+ },
+ );
+});
+
+it("keeps a bare CDN image from another workspace loadable without workspace metadata", async () => {
+ const cdnDomain = configStore.getState().cdnDomain;
+ configStore.setState({ cdnDomain: "cdn.example.test" });
+ const url = "https://cdn.example.test/workspaces/aaaaaaaa-2222-3333-4444-555555555555/11111111-2222-3333-4444-555555555555.png";
+ const onImageError = vi.fn();
+ try {
+ render(
+ <AttachmentPreviewModal
+ source={{ kind: "url", url, filename: "cross-workspace.png" }}
+ open
+ onClose={() => {}}
+ onImageError={onImageError}
+ />,
+ );
+ expect((await screen.findByRole("img", { name: "cross-workspace.png" })).getAttribute("src")).toBe(url);
+ expect(getAttachmentMock).not.toHaveBeenCalled();
+ expect(getAttachmentForDownloadMock).not.toHaveBeenCalled();
+ expect(getAttachmentBlobMock).not.toHaveBeenCalled();
+ expect(onImageError).not.toHaveBeenCalled();
+ } finally {
+ configStore.setState({ cdnDomain });
+ }
+});
diff --git a/packages/views/editor/attachment-preview-modal.tsx b/packages/views/editor/attachment-preview-modal.tsx
index 76a5d22ca7..9424d61d99 100644
--- a/packages/views/editor/attachment-preview-modal.tsx
+++ b/packages/views/editor/attachment-preview-modal.tsx
@@ -365,8 +365,10 @@ function useSettledImageURL(
targetUrl: string,
enabled: boolean,
onLoadError?: () => void,
+ identity = targetUrl,
+ pending = false,
): string {
- const [settled, setSettled] = useState<string | null>(null);
+ const [settled, setSettled] = useState<{ url: string; identity: string } | null>(null);
const onErrorRef = useRef(onLoadError);
onErrorRef.current = onLoadError;
@@ -381,13 +383,13 @@ function useSettledImageURL(
let cancelled = false;
const probe = new window.Image();
if (typeof probe.decode !== "function") {
- setSettled(targetUrl);
+ setSettled({ url: targetUrl, identity });
return;
}
probe.src = targetUrl;
probe.decode().then(
() => {
- if (!cancelled) setSettled(targetUrl);
+ if (!cancelled) setSettled({ url: targetUrl, identity });
},
() => {
// Rejection covers both load failure and undecodable bytes.
@@ -397,9 +399,11 @@ function useSettledImageURL(
return () => {
cancelled = true;
};
- }, [targetUrl, enabled]);
+ }, [targetUrl, enabled, identity]);
- return enabled && settled !== null ? settled : targetUrl;
+ return enabled && settled !== null && !(pending && settled.identity === identity)
+ ? settled.url
+ : targetUrl;
}
// Warms the browser cache for a sequence neighbour so paging to it swaps
@@ -411,6 +415,12 @@ export function PreviewImagePrefetch({ source }: { source: PreviewSource }) {
state.attachmentId ?? undefined,
state.mediaUrl,
true,
+ {
+ refreshOnMount: true,
+ metadataSource: source.kind === "url" && state.attachmentId
+ ? "markdown-link"
+ : "workspace",
+ },
);
useEffect(() => {
@@ -733,7 +743,9 @@ function PreviewPanel({
renderHtmlFrame = renderViewerHtmlFrame,
initialHtmlAddress = "",
onHtmlAddressChange,
+ currentImageMetadata,
}: {
+ currentImageMetadata?: Attachment;
surface: "viewer" | "page";
kind: PreviewKind | null;
source: PreviewSource;
@@ -798,15 +810,25 @@ function PreviewPanel({
htmlLocation,
};
- // Gallery navigation hands this panel an attachment the reader never
- // clicked, so — unlike the click-through path, where <Attachment> had
- // already upgraded the URL — the viewer has to run the re-sign itself. A
- // no-op for URLs that are already loadable (signed CDN, public storage).
+ // Cached attachment records can outlive their signed URLs. Reuse recent
+ // prefetch metadata and revalidate stale entries when opening the viewer.
+ // Bare CDN links keep their native URL and cookie-based access.
+ const cdnDomain = useConfigStore((s) => s.cdnDomain);
const resigned = useResignedInlineMedia(
- state.attachmentId ?? undefined,
+ kind === "image" ? state.attachmentId ?? undefined : undefined,
state.mediaUrl,
kind === "image",
+ {
+ refreshOnMount: kind === "image",
+ metadataSource: source.kind === "url" && state.attachmentId
+ ? "markdown-link"
+ : "workspace",
+ currentMetadata: kind === "image" ? currentImageMetadata : undefined,
+ },
);
+ useEffect(() => {
+ if (kind === "image" && resigned.failed) onImageError?.();
+ }, [kind, resigned.failed, onImageError]);
// Until that upgrade lands the picked URL may be one this client cannot
// load natively (desktop, split-origin web); handed to <img> it would fail
// and, in a sequence, read as a broken image to skip. Hold the previous
@@ -815,7 +837,10 @@ function PreviewPanel({
// The previous image stays on the canvas until this one has decoded — the
// swap itself is what used to flash. Also absorbs the re-sign URL upgrade
// (raw -> signed) without a second visible load.
- const mediaUrl = useSettledImageURL(targetUrl, kind === "image", onImageError);
+ const mediaUrl = useSettledImageURL(
+ targetUrl, kind === "image", onImageError,
+ state.attachmentId ?? state.mediaUrl, resigned.pending,
+ );
// A load error from the <img> belongs to the file being opened only when
// that is what it shows — a frame held from the previous image never
// reports against the next one.
@@ -824,7 +849,6 @@ function PreviewPanel({
// Video, audio and PDF stream straight from a URL the reader has never
// loaded, so they get a freshly signed one rather than the record's.
- const cdnDomain = useConfigStore((s) => s.cdnDomain);
const streamed = useFreshStreamedMediaURL(
state.attachmentId ??
attachmentIdFromLocalUploadURL(state.mediaUrl) ??
@@ -851,8 +875,12 @@ function PreviewPanel({
toast.error(t(($) => $.attachment.copy_failed));
}
};
+ const copyableImageUrl = !resigned.pending && !resigned.failed && !imageFailed
+ ? mediaUrl
+ : "";
const handleCopyImage = async () => {
- if (await copyImage(mediaUrl)) {
+ if (!copyableImageUrl) return;
+ if (await copyImage(copyableImageUrl)) {
toast.success(t(($) => $.image.image_copied));
} else {
toast.error(t(($) => $.image.copy_image_failed));
@@ -1081,7 +1109,7 @@ function PreviewPanel({
{canCopyImage && (
<ChromeButton
label={t(($) => $.image.copy_image)}
- disabled={!mediaUrl}
+ disabled={!copyableImageUrl}
onClick={() => void handleCopyImage()}
>
<Copy className="size-4" />
@@ -1277,7 +1305,7 @@ function PreviewPanel({
},
}}
>
- {kind === "image" && imageFailed ? (
+ {kind === "image" && (imageFailed || resigned.failed) ? (
<UnsupportedFallback
message={t(($) => $.attachment.preview_failed)}
onDownload={handleDownload}
@@ -2010,11 +2038,14 @@ function UnsupportedFallback({
*/
export function AttachmentPreviewStandalone({
attachment,
+ currentImageMetadata,
renderHtmlFrame,
initialHtmlAddress,
onHtmlAddressChange,
}: {
attachment: Attachment;
+ /** Metadata authenticated by the page request for this open. */
+ currentImageMetadata?: Attachment;
renderHtmlFrame?: HtmlFrameRenderer;
/** Query and fragment an HTML file opens at. */
initialHtmlAddress?: string;
@@ -2034,6 +2065,7 @@ export function AttachmentPreviewStandalone({
return (
<div className="flex h-full w-full flex-col bg-black/95">
<PreviewPanel
+ currentImageMetadata={currentImageMetadata}
surface="page"
kind={state.kind}
source={source}
diff --git a/packages/views/editor/attachment.test.tsx b/packages/views/editor/attachment.test.tsx
index 7a18c54f27..187012a951 100644
--- a/packages/views/editor/attachment.test.tsx
+++ b/packages/views/editor/attachment.test.tsx
@@ -344,6 +344,10 @@ describe("Attachment — image dispatch", () => {
fireEvent.click(screen.getByRole("button", { name: "View" }));
+ await waitFor(() =>
+ expect(document.querySelectorAll("img")).toHaveLength(2),
+ );
+
const imageSrcs = [...document.querySelectorAll("img")].map((img) =>
img.getAttribute("src"),
);
@@ -363,7 +367,7 @@ describe("Attachment — image dispatch", () => {
expect(getAttachmentBlobMock).toHaveBeenCalledWith(id);
});
- it("opens preview with the same resolved media URL when a reopened draft record has no download_url", () => {
+ it("opens preview with the same resolved media URL when a reopened draft record has no download_url", async () => {
configStore.setState({ cdnDomain: "cdn.example.test" });
const id = "11111111-2222-3333-4444-555555555555";
const markdownUrl = `https://multica-api.copilothub.ai/api/attachments/${id}/download`;
@@ -375,6 +379,7 @@ describe("Attachment — image dispatch", () => {
download_url: "",
});
resolverState.attachments = [att];
+ getAttachmentMock.mockResolvedValue({ ...att, download_url: mediaUrl });
renderWithQuery(
<Attachment
@@ -389,6 +394,9 @@ describe("Attachment — image dispatch", () => {
fireEvent.click(screen.getByRole("button", { name: "View" }));
+ await waitFor(() =>
+ expect(document.querySelectorAll("img")).toHaveLength(2));
+
const imageSrcs = [...document.querySelectorAll("img")].map((img) =>
img.getAttribute("src"),
);
diff --git a/packages/views/editor/hooks/use-inline-media-url.test.tsx b/packages/views/editor/hooks/use-inline-media-url.test.tsx
index 72bc031521..5d0d1beca6 100644
--- a/packages/views/editor/hooks/use-inline-media-url.test.tsx
+++ b/packages/views/editor/hooks/use-inline-media-url.test.tsx
@@ -1,14 +1,18 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
-import { focusManager, QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { focusManager, onlineManager, QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ApiError } from "@multica/core/api/client";
import type { ReactNode } from "react";
-import { useFreshStreamedMediaURL } from "./use-inline-media-url";
+import {
+ useFreshStreamedMediaURL,
+ useResignedInlineMedia,
+ __resetInlineMediaBlobCacheForTests,
+} from "./use-inline-media-url";
-const { getAttachment, getAttachmentBlob, getBaseUrl } = vi.hoisted(() => ({
- getAttachment: vi.fn(), getAttachmentBlob: vi.fn(), getBaseUrl: vi.fn(() => "https://api.example.test"),
+const { getAttachment, getAttachmentForDownload, getAttachmentBlob, getBaseUrl } = vi.hoisted(() => ({
+ getAttachment: vi.fn(), getAttachmentForDownload: vi.fn(), getAttachmentBlob: vi.fn(), getBaseUrl: vi.fn(() => "https://api.example.test"),
}));
-vi.mock("@multica/core/api", () => ({ api: { getAttachment, getAttachmentBlob, getBaseUrl } }));
+vi.mock("@multica/core/api", () => ({ api: { getAttachment, getAttachmentForDownload, getAttachmentBlob, 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}`;
@@ -19,8 +23,11 @@ function setup() {
return { client, wrapper };
}
afterEach(() => {
- cleanup(); vi.useRealTimers(); vi.clearAllMocks(); vi.unstubAllGlobals();
+ cleanup();
+ __resetInlineMediaBlobCacheForTests();
+ vi.useRealTimers(); vi.clearAllMocks(); vi.unstubAllGlobals();
focusManager.setFocused(undefined);
+ onlineManager.setOnline(true);
getBaseUrl.mockReturnValue("https://api.example.test");
});
@@ -131,3 +138,340 @@ describe("short-lived streamed attachment capabilities", () => {
expect(signal.aborted).toBe(true);
});
});
+
+describe("registered image viewer access", () => {
+ const cached = "https://cdn.example.test/design.png?Signature=expired";
+ const useOpenedImage = () =>
+ useResignedInlineMedia(id, cached, true, { refreshOnMount: true });
+ it("renews a cached signed image before handing it to the viewer", async () => {
+ getAttachment.mockResolvedValue({
+ id,
+ download_url: "https://cdn.example.test/design.png?Signature=fresh",
+ });
+ const { wrapper } = setup();
+ const h = renderHook(useOpenedImage, { wrapper });
+ expect(h.result.current.pending).toBe(true);
+ expect(h.result.current.url).toBe("");
+ await waitFor(() =>
+ expect(h.result.current.url).toContain("Signature=fresh"),
+ );
+ expect(getAttachment).toHaveBeenCalledWith(id);
+ expect(getAttachmentBlob).not.toHaveBeenCalled();
+ });
+ it("reuses a recent signature on reopen and refreshes after the short cache window or signature expiry", async () => {
+ vi.useFakeTimers();
+ getAttachment.mockImplementation(async () => ({
+ id,
+ download_url: `https://cdn.example.test/design.png?Signature=${getAttachment.mock.calls.length}`,
+ }));
+ const { client, wrapper } = setup();
+ const first = renderHook(useOpenedImage, { wrapper });
+ await act(async () => { await vi.advanceTimersByTimeAsync(10); });
+ expect(first.result.current.url).toContain("Signature=1");
+ first.unmount();
+ await act(async () => { await vi.advanceTimersByTimeAsync(60 * 1000); });
+ const recent = renderHook(useOpenedImage, { wrapper });
+ expect(recent.result.current.pending).toBe(false);
+ expect(recent.result.current.url).toContain("Signature=1");
+ expect(getAttachment).toHaveBeenCalledTimes(1);
+ recent.unmount();
+ await act(async () => { await vi.advanceTimersByTimeAsync(5 * 60 * 1000); });
+ const stale = renderHook(useOpenedImage, { wrapper });
+ expect(stale.result.current.pending).toBe(true);
+ expect(stale.result.current.url).toBe("");
+ await act(async () => { await vi.advanceTimersByTimeAsync(10); });
+ expect(stale.result.current.url).toContain("Signature=2");
+ expect(getAttachment).toHaveBeenCalledTimes(2);
+ // Keep the cached entry alive beyond the default 30-minute signature TTL.
+ await act(async () => { await vi.advanceTimersByTimeAsync(31 * 60 * 1000); });
+ stale.unmount();
+ const expired = renderHook(useOpenedImage, { wrapper });
+ expect(expired.result.current.url).toBe("");
+ expect(expired.result.current.pending).toBe(true);
+ await act(async () => { await vi.advanceTimersByTimeAsync(10); });
+ expect(expired.result.current.url).toContain("Signature=3");
+ expect(getAttachment).toHaveBeenCalledTimes(3);
+ expired.unmount();
+ client.clear();
+ });
+ it("waits for current authentication when metadata from an earlier open is stale", async () => {
+ getAttachment.mockResolvedValueOnce({
+ id,
+ download_url: "https://cdn.example.test/first.png?Signature=first",
+ });
+ const { client, wrapper } = setup();
+ const first = renderHook(useOpenedImage, { wrapper });
+ await waitFor(() =>
+ expect(first.result.current.url).toContain("Signature=first"),
+ );
+ first.unmount();
+ client.setQueryData(["attachment-inline-resign", id], {
+ id,
+ download_url: "https://cdn.example.test/first.png?Signature=first",
+ }, { updatedAt: Date.now() - 6 * 60 * 1000 });
+ let finish!: (value: { id: string; download_url: string }) => void;
+ getAttachment.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const second = renderHook(useOpenedImage, { wrapper });
+ expect(second.result.current.pending).toBe(true);
+ expect(second.result.current.url).toBe("");
+ await act(async () => {
+ finish({
+ id,
+ download_url: "https://cdn.example.test/second.png?Signature=second",
+ });
+ });
+ await waitFor(() =>
+ expect(second.result.current.url).toContain("Signature=second"),
+ );
+ expect(getAttachment).toHaveBeenCalledTimes(2);
+ client.clear();
+ });
+ it.each([403, 404])(
+ "does not use a cached private image after metadata returns %s",
+ async (status) => {
+ const { client, wrapper } = setup();
+ client.setQueryData(["attachment-inline-resign", id], {
+ id,
+ download_url: "https://cdn.example.test/previous.png?Signature=private",
+ }, { updatedAt: Date.now() - 6 * 60 * 1000 });
+ getAttachment.mockRejectedValue(
+ new ApiError("not available", status, "Denied"),
+ );
+ const h = renderHook(useOpenedImage, { wrapper });
+ await waitFor(() => expect(h.result.current.failed).toBe(true));
+ expect(h.result.current.url).toBe("");
+ expect(h.result.current.pending).toBe(false);
+ expect(getAttachment).toHaveBeenCalledTimes(1);
+ expect(getAttachmentBlob).not.toHaveBeenCalled();
+ },
+ );
+ it("keeps an inline thumbnail lazy when fresh-on-open is not requested", () => {
+ const { wrapper } = setup();
+ const h = renderHook(() => useResignedInlineMedia(id, cached, true), {
+ wrapper,
+ });
+ expect(h.result.current.url).toBe(cached);
+ expect(getAttachment).not.toHaveBeenCalled();
+ });
+ it("leaves an external image without an attachment identity unchanged", () => {
+ const { wrapper } = setup();
+ const h = renderHook(
+ () =>
+ useResignedInlineMedia(undefined, cached, true, {
+ refreshOnMount: true,
+ }),
+ { wrapper },
+ );
+ expect(h.result.current.url).toBe(cached);
+ expect(h.result.current.pending).toBe(false);
+ expect(getAttachment).not.toHaveBeenCalled();
+ });
+});
+
+describe("fresh image access on proxy storage", () => {
+ const cached = "https://cdn.example.test/design.png?Signature=expired";
+ const useOpenedImage = () =>
+ useResignedInlineMedia(id, cached, true, { refreshOnMount: true });
+ it("keeps the authenticated byte fallback when metadata has no native signed URL", async () => {
+ getAttachment.mockResolvedValue({ id, download_url: stable });
+ getAttachmentBlob.mockResolvedValue(
+ new Blob(["png"], { type: "image/png" }),
+ );
+ const create = vi.fn(() => "blob:fresh-image");
+ vi.stubGlobal(
+ "URL",
+ class extends URL {
+ static createObjectURL = create;
+ static revokeObjectURL = vi.fn();
+ },
+ );
+ const { wrapper } = setup();
+ const h = renderHook(useOpenedImage, { wrapper });
+ await waitFor(() => expect(h.result.current.url).toBe("blob:fresh-image"));
+ expect(h.result.current.pending).toBe(false);
+ expect(h.result.current.failed).toBe(false);
+ expect(getAttachment).toHaveBeenCalledTimes(1);
+ expect(getAttachmentBlob).toHaveBeenCalledWith(id);
+ });
+ it("does not show a blob from an earlier QueryClient before current authentication succeeds", async () => {
+ getAttachment.mockResolvedValueOnce({ id, download_url: stable });
+ getAttachmentBlob.mockResolvedValue(
+ new Blob(["private png"], { type: "image/png" }),
+ );
+ vi.stubGlobal(
+ "URL",
+ class extends URL {
+ static createObjectURL = vi.fn(() => "blob:previous-account");
+ static revokeObjectURL = vi.fn();
+ },
+ );
+ const first = renderHook(useOpenedImage, { wrapper: setup().wrapper });
+ await waitFor(() =>
+ expect(first.result.current.url).toBe("blob:previous-account"),
+ );
+ first.unmount();
+ getAttachment.mockRejectedValueOnce(
+ new ApiError("membership revoked", 403, "Forbidden"),
+ );
+ const second = renderHook(useOpenedImage, { wrapper: setup().wrapper });
+ expect(second.result.current.url).toBe("");
+ await waitFor(() => expect(second.result.current.failed).toBe(true));
+ expect(second.result.current.url).toBe("");
+ expect(getAttachmentBlob).toHaveBeenCalledTimes(1);
+ });
+ it("fails instead of rendering the old URL when authenticated image bytes are denied", async () => {
+ getAttachment.mockResolvedValue({ id, download_url: stable });
+ getAttachmentBlob.mockRejectedValue(
+ new ApiError("denied", 403, "Forbidden"),
+ );
+ const h = renderHook(useOpenedImage, { wrapper: setup().wrapper });
+ await waitFor(() => expect(h.result.current.failed).toBe(true));
+ expect(h.result.current.url).toBe("");
+ expect(getAttachmentBlob).toHaveBeenCalledTimes(1);
+ });
+ it("refreshes metadata when navigating to an image already cached by an inline thumbnail", async () => {
+ const other = "aaaaaaaa-2222-3333-4444-555555555555";
+ const { client, wrapper } = setup();
+ client.setQueryData(["attachment-inline-resign", other], {
+ id: other,
+ download_url: "https://cdn.example.test/other.png?Signature=old",
+ }, { updatedAt: Date.now() - 6 * 60 * 1000 });
+ let finish!: (value: { id: string; download_url: string }) => void;
+ getAttachment.mockImplementation((selected: string) =>
+ selected === id
+ ? Promise.resolve({
+ id,
+ download_url: "https://cdn.example.test/first.png?Signature=fresh",
+ })
+ : new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
+ const h = renderHook(
+ ({ selected }) =>
+ useResignedInlineMedia(selected, cached, true, {
+ refreshOnMount: true,
+ }),
+ { wrapper, initialProps: { selected: id } },
+ );
+ await waitFor(() => expect(h.result.current.url).toContain("first.png"));
+ h.rerender({ selected: other });
+ expect(h.result.current.pending).toBe(true);
+ expect(h.result.current.url).toBe("");
+ await act(async () => {
+ finish({
+ id: other,
+ download_url: "https://cdn.example.test/other.png?Signature=fresh",
+ });
+ });
+ await waitFor(() =>
+ expect(h.result.current.url).toContain("other.png?Signature=fresh"),
+ );
+ expect(getAttachment).toHaveBeenCalledWith(other);
+ });
+});
+
+describe("image viewer current authorization regressions", () => {
+ it("waits for an offline stale refresh and continues after reconnecting", async () => {
+ onlineManager.setOnline(false);
+ getAttachment.mockResolvedValueOnce({
+ id,
+ download_url: "https://cdn.example.test/private.png?Signature=reconnected",
+ });
+ const { client, wrapper } = setup();
+ client.setQueryData(["attachment-inline-resign", id], {
+ id,
+ download_url: "https://cdn.example.test/private.png?Signature=old",
+ }, { updatedAt: Date.now() - 6 * 60 * 1000 });
+ const hook = renderHook(
+ () => useResignedInlineMedia(id, stable, true, { refreshOnMount: true }),
+ { wrapper },
+ );
+ expect(hook.result.current.url).toBe("");
+ expect(hook.result.current.pending).toBe(true);
+ expect(getAttachment).not.toHaveBeenCalled();
+ await act(async () => { onlineManager.setOnline(true); });
+ await waitFor(() => expect(hook.result.current.url).toContain("Signature=reconnected"));
+ expect(hook.result.current.pending).toBe(false);
+ expect(getAttachment).toHaveBeenCalledTimes(1);
+ });
+
+ it("uses the owning-workspace metadata endpoint for a pasted download link", async () => {
+ getAttachment.mockRejectedValue(
+ new ApiError("wrong workspace", 404, "Not Found"),
+ );
+ getAttachmentForDownload.mockResolvedValue({
+ id,
+ download_url: "https://cdn.example.test/pasted.png?Signature=new",
+ });
+ const hook = renderHook(
+ () =>
+ useResignedInlineMedia(id, stable, true, {
+ refreshOnMount: true,
+ metadataSource: "markdown-link",
+ }),
+ { wrapper: setup().wrapper },
+ );
+ await waitFor(() =>
+ expect(hook.result.current.url).toContain("pasted.png"),
+ );
+ expect(getAttachmentForDownload).toHaveBeenCalledWith(id);
+ expect(getAttachment).not.toHaveBeenCalled();
+ });
+
+ it("rejects malformed metadata instead of unlocking a previous private blob", async () => {
+ getAttachment.mockResolvedValueOnce({ id, download_url: stable });
+ getAttachmentBlob.mockResolvedValue(new Blob(["private"]));
+ vi.stubGlobal(
+ "URL",
+ class extends URL {
+ static createObjectURL = vi.fn(() => "blob:private");
+ static revokeObjectURL = vi.fn();
+ },
+ );
+ const first = renderHook(
+ () => useResignedInlineMedia(id, stable, true, { refreshOnMount: true }),
+ { wrapper: setup().wrapper },
+ );
+ await waitFor(() => expect(first.result.current.url).toBe("blob:private"));
+ first.unmount();
+ getAttachment.mockResolvedValueOnce({ id: "", download_url: "" });
+ const second = renderHook(
+ () => useResignedInlineMedia(id, stable, true, { refreshOnMount: true }),
+ { wrapper: setup().wrapper },
+ );
+ await waitFor(() => expect(second.result.current.failed).toBe(true));
+ expect(second.result.current.url).toBe("");
+ expect(getAttachmentBlob).toHaveBeenCalledTimes(1);
+ });
+});
+
+it("uses a new signed URL despite an earlier failure of the inactive byte path", async () => {
+ const { client, wrapper } = setup();
+ await client
+ .fetchQuery({
+ queryKey: ["attachment-inline-blob", id],
+ queryFn: () =>
+ Promise.reject(new ApiError("old failure", 403, "Forbidden")),
+ retry: false,
+ })
+ .catch(() => {});
+ getAttachment.mockResolvedValueOnce({
+ id,
+ download_url: "https://cdn.example.test/recovered.png?Signature=new",
+ });
+ const hook = renderHook(
+ () => useResignedInlineMedia(id, stable, true, { refreshOnMount: true }),
+ { wrapper },
+ );
+ await waitFor(() =>
+ expect(hook.result.current.url).toContain("recovered.png"),
+ );
+ expect(hook.result.current.failed).toBe(false);
+ expect(getAttachmentBlob).not.toHaveBeenCalled();
+});
diff --git a/packages/views/editor/hooks/use-inline-media-url.ts b/packages/views/editor/hooks/use-inline-media-url.ts
index d92ad868fc..e02f90835c 100644
--- a/packages/views/editor/hooks/use-inline-media-url.ts
+++ b/packages/views/editor/hooks/use-inline-media-url.ts
@@ -13,6 +13,7 @@ import { useEffect, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { api } from "@multica/core/api";
import { ApiError } from "@multica/core/api/client";
+import type { Attachment } from "@multica/core/types";
import {
attachmentDownloadPath,
attachmentIdFromDownloadURL,
@@ -23,6 +24,9 @@ import {
// server/internal/handler/file.go) so a re-render never serves an expired
// signature from the query cache.
const RESIGN_STALE_MS = 20 * 60 * 1000;
+// Neighbour prefetch and the viewer must use the same signature to reuse
+// browser-cached bytes, while refreshing well before the default 30-min TTL.
+const PREVIEW_RESIGN_STALE_MS = 5 * 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
@@ -79,11 +83,22 @@ export function __resetInlineMediaBlobCacheForTests(): void {
// picked URL, which this client may be unable to load. A caller that treats a
// load failure as meaningful (the viewer skips broken images) waits it out
// instead of rendering it.
+// Viewers and neighbour prefetch reauthenticate stale metadata on mount;
+// inline thumbnails stay lazy.
export function useResignedInlineMedia(
attachmentId: string | undefined,
rawPickedUrl: string,
blobFallback: boolean,
-): { url: string; pending: boolean } {
+ {
+ refreshOnMount = false,
+ metadataSource = "workspace",
+ currentMetadata,
+ }: {
+ refreshOnMount?: boolean;
+ metadataSource?: "workspace" | "markdown-link";
+ currentMetadata?: Attachment;
+ } = {},
+): { url: string; pending: boolean; failed: boolean } {
const pickedUrl = resolveLegacyLocalMediaURL(rawPickedUrl);
const idFromPickedUrl = attachmentIdFromDownloadURL(pickedUrl);
const resignAttachmentId = attachmentId ?? idFromPickedUrl;
@@ -101,17 +116,35 @@ export function useResignedInlineMedia(
const needsResign =
!!resignAttachmentId &&
!!pickedUrl &&
- idFromPickedUrl !== undefined &&
- ((api.getBaseUrl?.() ?? "") !== "" || isCrossOriginWebURL);
+ (refreshOnMount ||
+ (idFromPickedUrl !== undefined &&
+ ((api.getBaseUrl?.() ?? "") !== "" || isCrossOriginWebURL)));
- const { data: fresh, isError: freshFailed } = useQuery({
- queryKey: ["attachment-inline-resign", resignAttachmentId],
- queryFn: () => api.getAttachment(resignAttachmentId as string),
- enabled: needsResign,
- staleTime: RESIGN_STALE_MS,
+ const metadataQuery = useQuery({
+ queryKey: metadataSource === "markdown-link"
+ ? ["attachment-inline-resign", resignAttachmentId, "markdown-link"]
+ : ["attachment-inline-resign", resignAttachmentId],
+ queryFn: () => metadataSource === "markdown-link"
+ ? api.getAttachmentForDownload(resignAttachmentId as string)
+ : api.getAttachment(resignAttachmentId as string),
+ enabled: needsResign && !currentMetadata,
+ staleTime: refreshOnMount ? PREVIEW_RESIGN_STALE_MS : RESIGN_STALE_MS,
gcTime: RESIGN_STALE_MS,
+ ...(refreshOnMount
+ ? {
+ retry: retryAttachmentPreview,
+ refetchOnMount: true,
+ refetchOnWindowFocus: recoverFailedPreview,
+ refetchOnReconnect: recoverFailedPreview,
+ }
+ : {}),
});
+ const fresh = currentMetadata ?? metadataQuery.data;
+ const freshFailed = !currentMetadata && metadataQuery.isError;
+ // Offline refreshes are paused, not fetching, and still need authorization.
+ const metadataPending = !currentMetadata && metadataQuery.fetchStatus !== "idle";
+ const invalidMetadata = refreshOnMount && !!fresh && fresh.id !== resignAttachmentId;
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
@@ -124,18 +157,30 @@ export function useResignedInlineMedia(
// 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 isAuthenticated =
+ !!fresh && !(refreshOnMount && (metadataPending || freshFailed || invalidMetadata));
const { data: blob, isError: blobFailed } = useQuery({
queryKey: ["attachment-inline-blob", resignAttachmentId],
queryFn: () => api.getAttachmentBlob(resignAttachmentId as string),
- enabled: needsResign && blobFallback && !!fresh && signedUrl === "",
+ enabled: needsResign && blobFallback && isAuthenticated && signedUrl === "",
staleTime: Infinity,
gcTime: INLINE_BLOB_GC_MS,
+ ...(refreshOnMount
+ ? {
+ retry: retryAttachmentPreview,
+ refetchOnWindowFocus: recoverFailedPreview,
+ refetchOnReconnect: recoverFailedPreview,
+ }
+ : {}),
});
- const isAuthenticated = !!fresh;
const blobUrl = useObjectURL(resignAttachmentId, blob, isAuthenticated);
- if (!needsResign) return { url: pickedUrl, pending: false };
- if (signedUrl) return { url: signedUrl, pending: false };
+ if (!needsResign) return { url: pickedUrl, pending: false, failed: false };
+ if (refreshOnMount && metadataPending)
+ return { url: "", pending: true, failed: false };
+ if (refreshOnMount && (freshFailed || invalidMetadata || (signedUrl === "" && blobFailed)))
+ return { url: "", pending: false, failed: true };
+ if (signedUrl) return { url: signedUrl, pending: false, failed: false };
// Only return the cached blob URL when it belongs to the current id and
// the current QueryClient has authenticated metadata for it. This keeps
// the 5-min re-entry cache for the same session but prevents a logged-out
@@ -147,16 +192,20 @@ export function useResignedInlineMedia(
isAuthenticated &&
blobUrlCache.get(resignAttachmentId) === blobUrl
) {
- return { url: blobUrl, pending: false };
+ return { url: blobUrl, pending: false, failed: false };
}
if (blobUrl && !resignAttachmentId && isAuthenticated) {
- return { url: blobUrl, pending: false };
+ return { url: blobUrl, pending: false, failed: false };
}
// Still upgrading while the metadata is in flight, and — for a caller that
// renders the bytes — while they are. A failure at either step ends the
// wait on the picked URL.
const pending = !freshFailed && (!fresh || (blobFallback && !blobFailed));
- return { url: pickedUrl, pending };
+ return {
+ url: refreshOnMount ? "" : pickedUrl,
+ pending,
+ failed: freshFailed || blobFailed,
+ };
}
// useFreshStreamedMediaURL resolves the URL the viewer streams a video, audio
diff --git a/packages/views/editor/preview-sequence-context.test.tsx b/packages/views/editor/preview-sequence-context.test.tsx
index 56c18e6f23..97eb5a0287 100644
--- a/packages/views/editor/preview-sequence-context.test.tsx
+++ b/packages/views/editor/preview-sequence-context.test.tsx
@@ -320,7 +320,7 @@ describe("PreviewSequenceProvider", () => {
expectCounter("3 / 3");
});
- it("skips a broken image and says so", () => {
+ it("skips a broken image and says so", async () => {
render(
<PreviewSequenceProvider items={sequenceOf(THREE)}>
<Opener openKey={THREE[0]!.id} />
@@ -334,8 +334,13 @@ describe("PreviewSequenceProvider", () => {
});
expectCounter("2 / 3");
+ const image = await waitFor(() => {
+ const image = screen.getByRole("dialog").querySelector("img");
+ expect(image).not.toBeNull();
+ return image!;
+ });
act(() => {
- fireEvent.error(screen.getByRole("dialog").querySelector("img")!);
+ fireEvent.error(image);
});
// Kept moving the way the reader was going, and the dead frame is now out
@@ -348,7 +353,7 @@ describe("PreviewSequenceProvider", () => {
expectCounter("1 / 3");
});
- it("stays on a file opened by name when it fails, and says so on the stage", () => {
+ it("stays on a file opened by name when it fails, and says so on the stage", async () => {
function PinnedOpener() {
const sequence = usePreviewSequence();
return (
@@ -367,6 +372,12 @@ describe("PreviewSequenceProvider", () => {
});
expectCounter("2 / 3");
+ await waitFor(() =>
+ expect(
+ screen.getByRole("dialog").querySelector("img")?.getAttribute("src"),
+ ).toBe(THREE[1]!.download_url),
+ );
+
act(() => {
fireEvent.error(screen.getByRole("dialog").querySelector("img")!);
});
@@ -386,6 +397,11 @@ describe("PreviewSequenceProvider", () => {
fireEvent.click(nextButton());
});
expectCounter("3 / 3");
+ await waitFor(() =>
+ expect(
+ screen.getByRole("dialog").querySelector("img")?.getAttribute("src"),
+ ).toBe(THREE[2]!.download_url),
+ );
act(() => {
fireEvent.error(screen.getByRole("dialog").querySelector("img")!);
});
@@ -418,7 +434,9 @@ describe("PreviewSequenceProvider", () => {
fireEvent.click(nextButton());
});
expectCounter("3 / 3");
- expect(screen.getByRole("dialog").querySelector("img")).not.toBeNull();
+ await waitFor(() =>
+ expect(screen.getByRole("dialog").querySelector("img")).not.toBeNull(),
+ );
});
it("leaves the arrow keys to a focused video", async () => {
@@ -454,7 +472,7 @@ describe("PreviewSequenceProvider", () => {
// Review of #8763: the panel is reused across kinds, so the frame it held
// for a PDF must never reach the image canvas while the next image decodes.
- it("shows the image itself, not the previous file, while it decodes", () => {
+ it("shows the image itself, not the previous file, while it decodes", async () => {
const restoreDecode = stubDecode(() => new Promise<void>(() => {}));
try {
const mixed = [
@@ -474,8 +492,10 @@ describe("PreviewSequenceProvider", () => {
fireEvent.click(nextButton());
});
- const image = screen.getByRole("dialog").querySelector("img")!;
- expect(image.getAttribute("src")).toBe(mixed[1]!.download_url);
+ await waitFor(() =>
+ expect(
+ screen.getByRole("dialog").querySelector("img")?.getAttribute("src")).toBe(mixed[1]!.download_url),
+ );
expectCounter("2 / 3");
expect(nextButton()).not.toBeDisabled();
expect(toastErrorMock).not.toHaveBeenCalled();
@@ -500,7 +520,11 @@ describe("PreviewSequenceProvider", () => {
act(() => {
fireEvent.click(screen.getByText("open"));
});
- await act(async () => {});
+ await waitFor(() =>
+ expect(
+ screen.getByRole("dialog").querySelector("img")?.getAttribute("src"),
+ ).toBe(first.download_url),
+ );
act(() => {
fireEvent.click(nextButton());
});