Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(editor): sign streamed video, audio and PDF previews afresh (MUL-8892) (#10232)
Jiayuan Zhangb5ac15690dcd
diff --git a/packages/views/editor/attachment-preview-modal.test.tsx b/packages/views/editor/attachment-preview-modal.test.tsxindex b1c77715fa..82a54a9def 100644--- a/packages/views/editor/attachment-preview-modal.test.tsx+++ b/packages/views/editor/attachment-preview-modal.test.tsx@@ -284,27 +284,28 @@ describe("AttachmentPreviewModal — dispatch", () => {expect(img?.getAttribute("src")).toBe(url);});- it("renders a PDF iframe pointing at the signed download URL", () => {+ it("renders a PDF iframe pointing at the signed download URL", async () => {const att = makeAttachment({ filename: "manual.pdf", content_type: "application/pdf" });render(<AttachmentPreviewModal source={{ kind: "full", attachment: att }} open onClose={() => {}} />);- const iframe = document.querySelector("iframe");- expect(iframe).toBeTruthy();- expect(iframe?.getAttribute("src")).toBe(att.download_url);+ await waitFor(() => {+ expect(document.querySelector("iframe")?.getAttribute("src")).toBe(att.download_url);+ });});- it("renders a <video> for video/* content types", () => {+ it("renders a <video> for video/* content types", async () => {const att = makeAttachment({ filename: "clip.mp4", content_type: "video/mp4" });render(<AttachmentPreviewModal source={{ kind: "full", attachment: att }} open onClose={() => {}} />);- const video = document.querySelector("video");- expect(video).toBeTruthy();- expect(video?.getAttribute("src")).toBe(att.download_url);+ await waitFor(() => {+ expect(document.querySelector("video")?.getAttribute("src")).toBe(att.download_url);+ });});- it("renders an <audio> for audio/* content types", () => {+ it("renders an <audio> for audio/* content types", async () => {const att = makeAttachment({ filename: "note.mp3", content_type: "audio/mpeg" });render(<AttachmentPreviewModal source={{ kind: "full", attachment: att }} open onClose={() => {}} />);- const audio = document.querySelector("audio");- expect(audio).toBeTruthy();+ await waitFor(() => {+ expect(document.querySelector("audio")).toBeTruthy();+ });});it("fetches text and hands it to ReadonlyContent for Markdown", async () => {@@ -504,7 +505,7 @@ describe("AttachmentPreviewModal — server-relative download_url resolution (MUexpect(onImageError).not.toHaveBeenCalled();});- it("prefixes the configured API base for PDF previews when download_url is server-relative", () => {+ it("prefixes the configured API base for PDF previews when download_url is server-relative", async () => {getBaseUrlMock.mockReturnValue("https://api.example.test");const att = makeAttachment({filename: "manual.pdf",@@ -518,10 +519,11 @@ describe("AttachmentPreviewModal — server-relative download_url resolution (MUonClose={() => {}}/>,);- const iframe = document.querySelector("iframe");- expect(iframe?.getAttribute("src")).toBe(- "https://api.example.test/api/attachments/att-1/download",- );+ await waitFor(() => {+ expect(document.querySelector("iframe")?.getAttribute("src")).toBe(+ "https://api.example.test/api/attachments/att-1/download",+ );+ });});it("keeps a same-origin relative URL untouched when the configured base is empty (web)", () => {@@ -613,6 +615,91 @@ describe("AttachmentPreviewModal — error states", () => {});});+describe("AttachmentPreviewModal — streamed media (MUL-8892)", () => {+ // The record comes from a cache that never goes stale; its signed+ // download_url may have expired long before the reader clicks play.+ const staleVideo = () =>+ makeAttachment({+ filename: "clip.mp4",+ content_type: "video/mp4",+ download_url: "https://cdn.example.test/clip.mp4?Signature=expired",+ });++ it("plays a video from a freshly signed URL, not the one cached on the record", async () => {+ let resolveMeta: (value: Attachment) => void = () => {};+ getAttachmentMock.mockImplementationOnce(+ () => new Promise<Attachment>((resolve) => { resolveMeta = resolve; }),+ );+ const att = staleVideo();+ render(<AttachmentPreviewModal source={{ kind: "full", attachment: att }} open onClose={() => {}} />);++ expect(getAttachmentMock).toHaveBeenCalledWith("att-1");+ expect(document.querySelector("video")).toBeNull();+ expect(screen.getByText("Loading preview…")).toBeInTheDocument();++ await act(async () => {+ resolveMeta({ ...att, download_url: "https://cdn.example.test/clip.mp4?Signature=fresh" });+ });+ await waitFor(() => {+ expect(document.querySelector("video")?.getAttribute("src")).toBe(+ "https://cdn.example.test/clip.mp4?Signature=fresh",+ );+ });+ });++ it("signs a PDF afresh too", async () => {+ getAttachmentMock.mockResolvedValueOnce(+ makeAttachment({ download_url: "https://cdn.example.test/manual.pdf?Signature=fresh" }),+ );+ const att = makeAttachment({+ filename: "manual.pdf",+ content_type: "application/pdf",+ download_url: "https://cdn.example.test/manual.pdf?Signature=expired",+ });+ render(<AttachmentPreviewModal source={{ kind: "full", attachment: att }} open onClose={() => {}} />);+ await waitFor(() => {+ expect(document.querySelector("iframe")?.getAttribute("src")).toBe(+ "https://cdn.example.test/manual.pdf?Signature=fresh",+ );+ });+ });++ it("keeps the record's URL when the server has no storage URL to sign (proxy mode)", async () => {+ getAttachmentMock.mockResolvedValueOnce(+ makeAttachment({ download_url: "/api/attachments/att-1/capability?token=t" }),+ );+ const att = makeAttachment({+ filename: "clip.mp4",+ content_type: "video/mp4",+ download_url: "/api/attachments/att-1/download",+ });+ render(<AttachmentPreviewModal source={{ kind: "full", attachment: att }} open onClose={() => {}} />);+ await waitFor(() => {+ expect(document.querySelector("video")?.getAttribute("src")).toBe(+ "/api/attachments/att-1/download",+ );+ });+ });++ it("says so, with a download, when the video cannot be played", async () => {+ const att = staleVideo();+ render(<AttachmentPreviewModal source={{ kind: "full", attachment: att }} open onClose={() => {}} />);+ const video = await waitFor(() => {+ const el = document.querySelector("video");+ expect(el).toBeTruthy();+ return el!;+ });++ fireEvent.error(video);++ expect(document.querySelector("video")).toBeNull();+ expect(screen.getByText("Couldn't load preview")).toBeInTheDocument();+ const downloads = screen.getAllByRole("button", { name: "Download" });+ fireEvent.click(downloads[downloads.length - 1]!);+ expect(downloadMock).toHaveBeenCalledWith("att-1");+ });+});+describe("AttachmentPreviewModal — controls", () => {it("ESC closes the modal", () => {const onClose = vi.fn();diff --git a/packages/views/editor/attachment-preview-modal.tsx b/packages/views/editor/attachment-preview-modal.tsxindex 762a2ce6ad..8d6194de28 100644--- a/packages/views/editor/attachment-preview-modal.tsx+++ b/packages/views/editor/attachment-preview-modal.tsx@@ -89,7 +89,10 @@ import { ShortcutKeycaps } from "../common/shortcut-keycaps";import { useDownloadAttachment } from "./use-download-attachment";import { useAttachmentDownloadState } from "./hooks/use-attachment-download-state";import { useAttachmentHtmlText } from "./hooks/use-attachment-html-text";-import { useResignedInlineMedia } from "./hooks/use-inline-media-url";+import {+ useFreshStreamedMediaURL,+ useResignedInlineMedia,+} from "./hooks/use-inline-media-url";import { useZoomCanvas, type ZoomCanvasApi } from "./hooks/use-zoom-canvas";import { ZoomCanvas, ZoomControls } from "./zoom-canvas";import type { Size } from "./utils/zoom-transform";@@ -773,6 +776,16 @@ function PreviewPanel({const imageLoadError =mediaUrl !== "" && mediaUrl === targetUrl ? onImageError : undefined;+ // 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 ?? attachmentIdFromStorageURL(state.mediaUrl, cdnDomain),+ state.mediaUrl,+ kind === "video" || kind === "audio" || kind === "pdf",+ );+ const streamUrl = streamed.pending ? "" : streamed.url;+// Copying reads the image's bytes from script. The desktop renderer can// read any origin; web script can't read the storage CDN (it sends no CORS// headers), and there the browser's own context menu has Copy image. Copies@@ -1049,6 +1062,7 @@ function PreviewPanel({kind={kind}source={source}state={state}+ streamUrl={streamUrl}view={view}onDownload={handleDownload}downloading={downloading}@@ -1354,6 +1368,7 @@ function PreviewContent({kind,source,state,+ streamUrl,view,onDownload,downloading,@@ -1362,6 +1377,8 @@ function PreviewContent({kind: Exclude<PreviewKind, "image"> | null;source: PreviewSource;state: PreviewState;+ /** Where video, audio and PDF load from; empty while it is being signed. */+ streamUrl: string;view: StageView;onDownload: () => void;downloading: boolean;@@ -1406,32 +1423,33 @@ function PreviewContent({</DocumentSheet>);+ if ((kind === "pdf" || kind === "video" || kind === "audio") && !streamUrl) {+ return <PreviewLoading />;+ }+switch (kind) {case "pdf":return (<div className="h-full pb-4"><iframe- src={state.mediaUrl}+ src={streamUrl}className="h-full w-full rounded-lg bg-background"title={state.filename}/></div>);case "video":- return (- <div className="flex h-full w-full items-center justify-center pb-4">- <video- src={state.mediaUrl}- controls- className="h-full w-full object-contain"- />- </div>- );case "audio":return (- <div className="dark flex h-full w-full items-center justify-center p-8">- <audio src={state.mediaUrl} controls className="w-full max-w-xl" />- </div>+ // Keyed on the URL: a failure belongs to the file that failed, not+ // to the next one the sequence pages to.+ <MediaPlayer+ key={streamUrl}+ kind={kind}+ src={streamUrl}+ onDownload={onDownload}+ downloading={downloading}+ />);case "markdown":return (@@ -1582,14 +1600,7 @@ function TextBackedPreview({const { t } = useT("editor");const query = useAttachmentHtmlText(attachmentId);- if (query.isLoading) {- return (- <div className="dark flex h-full items-center justify-center gap-2 text-body text-muted-foreground">- <Loader2 className="size-4 animate-spin" />- {t(($) => $.attachment.preview_loading)}- </div>- );- }+ if (query.isLoading) return <PreviewLoading />;if (query.error) {if (query.error instanceof PreviewTooLargeError) {return (@@ -1621,6 +1632,66 @@ function TextBackedPreview({return <>{render(query.data.text)}</>;}+function PreviewLoading() {+ const { t } = useT("editor");+ return (+ <div className="dark flex h-full items-center justify-center gap-2 text-body text-muted-foreground">+ <Loader2 className="size-4 animate-spin" />+ {t(($) => $.attachment.preview_loading)}+ </div>+ );+}++// Video and audio — the browser's own player. A file it cannot play (an+// unsupported container or codec, a URL that stopped working) would otherwise+// leave an empty player with no explanation.+function MediaPlayer({+ kind,+ src,+ onDownload,+ downloading,+}: {+ kind: "video" | "audio";+ src: string;+ onDownload: () => void;+ downloading: boolean;+}) {+ const { t } = useT("editor");+ const [failed, setFailed] = useState(false);++ if (failed) {+ return (+ <UnsupportedFallback+ message={t(($) => $.attachment.preview_failed)}+ onDownload={onDownload}+ downloading={downloading}+ />+ );+ }+ if (kind === "audio") {+ return (+ <div className="dark flex h-full w-full items-center justify-center p-8">+ <audio+ src={src}+ controls+ className="w-full max-w-xl"+ onError={() => setFailed(true)}+ />+ </div>+ );+ }+ return (+ <div className="flex h-full w-full items-center justify-center pb-4">+ <video+ src={src}+ controls+ className="h-full w-full object-contain"+ onError={() => setFailed(true)}+ />+ </div>+ );+}+// Fallback — used for 413 / 415 / unknown kinds. Sits on the stage, so dark.function UnsupportedFallback({diff --git a/packages/views/editor/hooks/use-inline-media-url.ts b/packages/views/editor/hooks/use-inline-media-url.tsindex 5de84856ae..f622b89fa2 100644--- a/packages/views/editor/hooks/use-inline-media-url.ts+++ b/packages/views/editor/hooks/use-inline-media-url.ts@@ -157,6 +157,45 @@ export function useResignedInlineMedia(return { url: pickedUrl, pending };}+// 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 the+// first time here — and records live in caches that never go stale, while the+// signed `download_url` in them expires after 30 minutes. Handing that to+// `<video>` on a page that has been open a while plays nothing (MUL-8892).+//+// So for these kinds the viewer always asks the authenticated metadata+// endpoint for a fresh signature, the same exchange the Download button makes.+// It shares the re-sign query above, so an attachment is fetched once per TTL.+// Proxy mode has no storage URL to sign; the picked URL stands there, as it+// does when the request fails.+export function useFreshStreamedMediaURL(+ attachmentId: string | undefined,+ pickedUrl: string,+ enabled: boolean,+): { url: string; pending: boolean } {+ const active = enabled && !!attachmentId && !!pickedUrl;+ const { data: fresh, isError, isStale, isFetching } = useQuery({+ queryKey: ["attachment-inline-resign", attachmentId],+ queryFn: () => api.getAttachment(attachmentId as string),+ enabled: active,+ staleTime: RESIGN_STALE_MS,+ gcTime: RESIGN_STALE_MS,+ });++ if (!active) return { url: pickedUrl, pending: false };+ // A cached answer past its stale time may hold a signature that has+ // already expired: wait for the refetch it triggers rather than start a+ // stream on it and restart once the new URL lands.+ if (fresh && !(isStale && isFetching)) {+ const dl = fresh.download_url ?? "";+ const signed =+ /^https?:\/\//i.test(dl) && attachmentIdFromDownloadURL(dl) === undefined;+ return { url: signed ? dl : pickedUrl, pending: false };+ }+ return { url: pickedUrl, pending: !isError };+}+// useObjectURL turns a Blob into a `blob:` URL. The module cache keeps the// URL stable across remounts so a re-entry with a cached blob does not flash// the fallback pickedUrl for one frame (see #7741). Refcount + delayed GCdiff --git a/packages/views/editor/preview-sequence-context.test.tsx b/packages/views/editor/preview-sequence-context.test.tsxindex 455b9d7022..3ea65abd4f 100644--- a/packages/views/editor/preview-sequence-context.test.tsx+++ b/packages/views/editor/preview-sequence-context.test.tsx@@ -19,7 +19,12 @@ const { downloadMock, getBaseUrlMock, toastErrorMock } = vi.hoisted(() => ({vi.mock("../platform", () => ({ openExternal: vi.fn() }));vi.mock("@multica/core/api", () => ({- api: { getBaseUrl: getBaseUrlMock, getAttachmentTextContent: vi.fn() },+ api: {+ getBaseUrl: getBaseUrlMock,+ getAttachmentTextContent: vi.fn(),+ // Nothing fresher to sign: streamed media keeps the record's URL.+ getAttachment: vi.fn(() => Promise.reject(new Error("no re-sign"))),+ },PreviewTooLargeError: class extends Error {},PreviewUnsupportedError: class extends Error {},}));@@ -340,7 +345,7 @@ describe("PreviewSequenceProvider", () => {expectCounter("1 / 3");});- it("pages onto files that are not images", () => {+ it("pages onto files that are not images", async () => {const mixed = [imageAttachment(1),fileAttachment(2, "spec.pdf", "application/pdf"),@@ -359,7 +364,7 @@ describe("PreviewSequenceProvider", () => {fireEvent.click(nextButton());});expectCounter("2 / 3");- expect(screen.getByTitle("spec.pdf").tagName).toBe("IFRAME");+ expect((await screen.findByTitle("spec.pdf")).tagName).toBe("IFRAME");act(() => {fireEvent.click(nextButton());@@ -368,7 +373,7 @@ describe("PreviewSequenceProvider", () => {expect(screen.getByRole("dialog").querySelector("img")).not.toBeNull();});- it("leaves the arrow keys to a focused video", () => {+ it("leaves the arrow keys to a focused video", async () => {const mixed = [fileAttachment(1, "demo.mp4", "video/mp4"),imageAttachment(2),@@ -382,7 +387,11 @@ describe("PreviewSequenceProvider", () => {fireEvent.click(screen.getByText("open"));});- const video = screen.getByRole("dialog").querySelector("video")!;+ const video = await waitFor(() => {+ const el = screen.getByRole("dialog").querySelector("video");+ expect(el).not.toBeNull();+ return el!;+ });act(() => {fireEvent.keyDown(video, { key: "ArrowRight" });});