Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(attachments): restore authenticated local previews (MUL-8859) (#10263)
Multica Evec6c279495bc3
diff --git a/e2e/local-attachment-compat.spec.ts b/e2e/local-attachment-compat.spec.tsnew file mode 100644index 0000000000..4d3fbfee4f--- /dev/null+++ b/e2e/local-attachment-compat.spec.ts@@ -0,0 +1,33 @@+import { test, expect } from "@playwright/test";+import { readFile } from "node:fs/promises";+import { createTestApi, loginAsDefault } from "./helpers";++const apiBase = process.env.NEXT_PUBLIC_API_URL || `http://localhost:${process.env.PORT || "8080"}`;++test("local attachment historical image", async ({ page, baseURL }, testInfo) => {+ test.setTimeout(120000);+ const local = (url: string) => ["localhost", "127.0.0.1", "[::1]"].includes(new URL(url).hostname);+ test.skip(!local(baseURL!) || !local(apiBase) || !!process.env.S3_BUCKET, "Isolated LocalStorage fixtures only");+ const api = await createTestApi();+ try {+ const slug = await loginAsDefault(page);+ const issue = await api.createIssue("Local attachment compatibility");+ const form = new FormData();+ form.append("file", new Blob([await readFile("apps/web/public/images/landing-hero.webp")], { type: "image/webp" }), "workspace-preview.webp");+ form.append("issue_id", issue.id);+ const headers = { Authorization: `Bearer ${api.getToken()}`, "X-Workspace-Slug": slug };+ const uploaded = await fetch(`${apiBase}/api/upload-file`, { method: "POST", headers, body: form });+ expect(uploaded.status).toBe(200);+ const att = await uploaded.json();+ expect(att.url).toContain(`/api/attachments/${att.id}/download`);+ const ws = (await api.getWorkspaces()).find((w) => w.slug === slug)!;+ const raw = `/uploads/workspaces/${ws.id}/${att.id}.webp`;+ await api.updateIssue(issue.id, { description: `An image saved by an earlier client.\n\n` });+ await page.goto(`/${slug}/issues/${issue.identifier}`);+ await expect(page.getByText("An image saved by an earlier client.")).toBeVisible();+ const image = page.locator('img[alt="Workspace preview"]');+ await expect.poll(() => image.evaluate((el: HTMLImageElement) => el.naturalWidth)).toBeGreaterThan(0);+ expect(await image.getAttribute("src")).toMatch(/^(blob:|.*\/api\/attachments\/)/);+ await testInfo.attach("historical-image-restored", { body: await page.screenshot(), contentType: "image/png" });+ } finally { await api.cleanup(); }+});diff --git a/e2e/local-pdf-compat.spec.ts b/e2e/local-pdf-compat.spec.tsnew file mode 100644index 0000000000..019a05995c--- /dev/null+++ b/e2e/local-pdf-compat.spec.ts@@ -0,0 +1,138 @@+import { test, expect, type Frame } from "@playwright/test";+import { createTestApi, loginAsDefault } from "./helpers";++const apiBase = process.env.NEXT_PUBLIC_API_URL || `http://localhost:${process.env.PORT || "8080"}`;+// The full browser includes the native PDF viewer; headless-shell does not.+test.use({ channel: "chromium" });++function twoPagePDF(): Buffer {+ const stream = (text: string) => {+ const body = `BT /F1 24 Tf 72 700 Td (${text}) Tj ET`;+ return `<< /Length ${body.length} >>\nstream\n${body}\nendstream`;+ };+ const objects = [+ "<< /Type /Catalog /Pages 2 0 R >>",+ "<< /Type /Pages /Kids [3 0 R 5 0 R] /Count 2 >>",+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> /Contents 4 0 R >>",+ stream("Attachment preview - page one"),+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 7 0 R >> >> /Contents 6 0 R >>",+ stream("Keep reading - page two"),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",+ ];+ let pdf = "%PDF-1.4\n";+ const offsets = [0];+ objects.forEach((object, index) => {+ offsets.push(Buffer.byteLength(pdf));+ pdf += `${index + 1} 0 obj\n${object}\nendobj\n`;+ });+ const xref = Buffer.byteLength(pdf);+ pdf += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;+ pdf += offsets.slice(1).map((offset) => `${String(offset).padStart(10, "0")} 00000 n \n`).join("");+ pdf += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`;+ return Buffer.from(pdf);+}++test("cross-origin local PDF keeps its reading position past capability TTL", async ({ page, baseURL }, testInfo) => {+ test.setTimeout(120000);+ const local = (url: string) => ["localhost", "127.0.0.1", "[::1]"].includes(new URL(url).hostname);+ test.skip(!local(baseURL!) || !local(apiBase) || !!process.env.S3_BUCKET, "Isolated LocalStorage fixtures only");+ test.skip(new URL(baseURL!).origin === new URL(apiBase).origin, "Cross-origin PDF path only");+ const api = await createTestApi();+ try {+ const slug = await loginAsDefault(page);+ const issue = await api.createIssue("Local PDF reading position");+ const form = new FormData();+ form.append("file", new Blob([twoPagePDF()], { type: "application/pdf" }), "reading.pdf");+ form.append("issue_id", issue.id);+ const uploaded = await fetch(`${apiBase}/api/upload-file`, {+ method: "POST", headers: { Authorization: `Bearer ${api.getToken()}`, "X-Workspace-Slug": slug }, body: form,+ });+ expect(uploaded.status).toBe(200);+ const att = await uploaded.json();+ await page.goto(`/${slug}/attachments/${att.id}/preview`);+ const frame = page.locator('iframe[title="reading.pdf"]');+ await expect(frame).toHaveAttribute("src", /^blob:/);+ let viewerFrame: Frame | undefined;+ await expect.poll(async () => {+ for (const child of page.frames()) {+ if (await child.locator("pdf-viewer").count()) { viewerFrame = child; return true; }+ }+ return false;+ }).toBe(true);+ const pageNumber = viewerFrame!.getByRole("textbox", { name: "Page number" });+ await pageNumber.fill("2");+ await pageNumber.press("Enter");+ await expect(pageNumber).toHaveValue("2");+ const source = await frame.getAttribute("src");+ const timeOrigin = await viewerFrame!.evaluate(() => performance.timeOrigin);+ const before = await page.screenshot({ path: testInfo.outputPath("pdf-page-two-before.png") });+ await testInfo.attach("pdf-page-two-before", { body: before, contentType: "image/png" });+ const openedAt = Date.now();+ await expect.poll(() => Date.now(), { timeout: 70000 }).toBeGreaterThan(openedAt + 65000);+ await page.evaluate(() => document.dispatchEvent(new Event("visibilitychange")));+ expect(await frame.getAttribute("src")).toBe(source);+ await expect(pageNumber).toHaveValue("2");+ expect(await viewerFrame!.evaluate(() => performance.timeOrigin)).toBe(timeOrigin);+ const after = await page.screenshot({ path: testInfo.outputPath("pdf-page-two-after.png") });+ await testInfo.attach("pdf-page-two-after-65s", { body: after, contentType: "image/png" });+ } finally { await api.cleanup(); }+});++for (const [mode, inlineURL] of [+ ["presign", "https://storage.example.test/reading.pdf?X-Amz-Signature=fresh"],+ ["CloudFront", "https://cdn.example.test/reading.pdf?Signature=fresh&Key-Pair-Id=test"],+] as const) {+ test(`same-origin ${mode} PDF opens inline instead of downloading`, async ({ page, baseURL }, testInfo) => {+ const local = (url: string) => ["localhost", "127.0.0.1", "[::1]"].includes(new URL(url).hostname);+ test.skip(!local(baseURL!) || !local(apiBase) || !!process.env.S3_BUCKET, "Isolated LocalStorage fixtures only");+ test.skip(new URL(baseURL!).origin !== new URL(apiBase).origin, "Run with a same-origin Web API base");+ const api = await createTestApi();+ try {+ const slug = await loginAsDefault(page);+ const issue = await api.createIssue(`Same-origin ${mode} PDF preview`);+ const pdf = twoPagePDF();+ const form = new FormData();+ form.append("file", new Blob([pdf], { type: "application/pdf" }), "reading.pdf");+ form.append("issue_id", issue.id);+ const uploaded = await fetch(`${apiBase}/api/upload-file`, {+ method: "POST", headers: { Authorization: `Bearer ${api.getToken()}`, "X-Workspace-Slug": slug }, body: form,+ });+ expect(uploaded.status).toBe(200);+ const att = await uploaded.json();+ let forcedDownloads = 0;+ const downloads: string[] = [];+ page.on("download", (download) => downloads.push(download.suggestedFilename()));+ // Model the production storage contracts without AWS credentials: metadata+ // offers an inline signature, while the durable download route forces save.+ await page.route(`${apiBase}/api/attachments/${att.id}`, (route) => route.fulfill({+ json: { ...att, download_url: inlineURL, attachment_download_url: `${inlineURL}&response-content-disposition=attachment` },+ }));+ await page.route(`${apiBase}/api/attachments/${att.id}/download`, (route) => {+ forcedDownloads++;+ return route.fulfill({ status: 302, headers: { Location: `${inlineURL}&response-content-disposition=attachment` } });+ });+ await page.route(`${inlineURL}&response-content-disposition=attachment`, (route) => route.fulfill({+ contentType: "application/pdf", headers: { "Content-Disposition": "attachment; filename=reading.pdf" }, body: pdf,+ }));+ await page.route(inlineURL, (route) => route.fulfill({+ contentType: "application/pdf", headers: { "Content-Disposition": "inline; filename=reading.pdf" }, body: pdf,+ }));+ await page.goto(`/${slug}/attachments/${att.id}/preview`);+ await expect(page.locator('iframe[title="reading.pdf"]')).toHaveAttribute("src", inlineURL);+ let viewerFrame: Frame | undefined;+ await expect.poll(async () => {+ for (const child of page.frames()) {+ if (await child.locator("pdf-viewer").count()) { viewerFrame = child; return true; }+ }+ return false;+ }).toBe(true);+ const pageNumber = viewerFrame!.getByRole("textbox", { name: "Page number" });+ await pageNumber.fill("2");+ await pageNumber.press("Enter");+ await expect(pageNumber).toHaveValue("2");+ expect(forcedDownloads).toBe(0);+ expect(downloads).toEqual([]);+ await page.screenshot({ path: testInfo.outputPath(`same-origin-${mode}-pdf.png`) });+ } finally { await api.cleanup(); }+ });+}diff --git a/e2e/local-stream-compat.spec.ts b/e2e/local-stream-compat.spec.tsnew file mode 100644index 0000000000..0b2825d319--- /dev/null+++ b/e2e/local-stream-compat.spec.ts@@ -0,0 +1,59 @@+import { test, expect } from "@playwright/test";+import { createTestApi, loginAsDefault } from "./helpers";++const apiBase = process.env.NEXT_PUBLIC_API_URL || `http://localhost:${process.env.PORT || "8080"}`;++test("native local audio survives capability renewal", async ({ page, baseURL }, testInfo) => {+ test.setTimeout(120000);+ const local = (url: string) => ["localhost", "127.0.0.1", "[::1]"].includes(new URL(url).hostname);+ test.skip(!local(baseURL!) || !local(apiBase) || !!process.env.S3_BUCKET, "Isolated LocalStorage fixtures only");+ const api = await createTestApi();+ try {+ const slug = await loginAsDefault(page);+ const issue = await api.createIssue("Local streamed attachment");+ const bytes = Buffer.alloc(44 + 8000 * 2 * 120);+ bytes.write("RIFF", 0); bytes.writeUInt32LE(bytes.length - 8, 4);+ bytes.write("WAVEfmt ", 8); bytes.writeUInt32LE(16, 16);+ bytes.writeUInt16LE(1, 20); bytes.writeUInt16LE(1, 22);+ bytes.writeUInt32LE(8000, 24); bytes.writeUInt32LE(16000, 28);+ bytes.writeUInt16LE(2, 32); bytes.writeUInt16LE(16, 34);+ bytes.write("data", 36); bytes.writeUInt32LE(bytes.length - 44, 40);+ const form = new FormData();+ form.append("file", new Blob([bytes], { type: "audio/wav" }), "renewal.wav");+ form.append("issue_id", issue.id);+ const headers = { Authorization: `Bearer ${api.getToken()}`, "X-Workspace-Slug": slug };+ const uploaded = await fetch(`${apiBase}/api/upload-file`, { method: "POST", headers, body: form });+ expect(uploaded.status).toBe(200);+ const att = await uploaded.json();+ await page.goto(`/${slug}/attachments/${att.id}/preview`);+ const audio = page.locator("audio");+ await expect(audio).toBeVisible();+ await expect.poll(() => audio.evaluate((el: HTMLAudioElement) => el.readyState)).toBeGreaterThan(0);+ const first = (await audio.getAttribute("src"))!;+ expect(first).toContain("/signed-download?");+ const expires = Number(new URL(first).searchParams.get("exp"));+ expect(expires * 1000 - Date.now()).toBeLessThanOrEqual(60000);+ await page.locator("body").click({ position: { x: 10, y: 100 } });+ await audio.evaluate(async (el: HTMLAudioElement) => { el.currentTime = 12; await el.play(); });+ // A loaded stream must not be replaced just because its capability expires.+ await expect.poll(() => Date.now(), { timeout: 70000 }).toBeGreaterThan((expires + 2) * 1000);+ await page.evaluate(() => document.dispatchEvent(new Event("visibilitychange")));+ expect(await audio.getAttribute("src")).toBe(first);+ expect(await audio.evaluate((el: HTMLAudioElement) => el.currentTime)).toBeGreaterThan(60);+ expect((await fetch(first)).status).toBe(403);+ // A late native error renews on demand. The first metadata request fails+ // to cover bounded recovery from a transient network outage as well.+ let outage = true;+ await page.route(`**/api/attachments/${att.id}`, async (route) => {+ if (outage) { outage = false; await route.abort("failed"); }+ else await route.continue();+ });+ const position = await audio.evaluate((el: HTMLAudioElement) => el.currentTime);+ await audio.dispatchEvent("error");+ await expect.poll(() => audio.getAttribute("src"), { timeout: 10000 }).not.toBe(first);+ await expect.poll(() => audio.evaluate((el: HTMLAudioElement) => el.readyState)).toBeGreaterThan(0);+ expect(await audio.evaluate((el: HTMLAudioElement) => el.currentTime)).toBeGreaterThanOrEqual(position - 1);+ expect(await audio.evaluate((el: HTMLAudioElement) => el.paused)).toBe(false);+ await testInfo.attach("stream-after-renewal", { body: await page.screenshot(), contentType: "image/png" });+ } finally { await api.cleanup(); }+});diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex ed68e35289..ae6ea8951f 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -4279,8 +4279,8 @@ export class ApiClient {// 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`);+ async getAttachmentBlob(id: string, signal?: AbortSignal): Promise<Blob> {+ const res = await this.fetchRaw(`/api/attachments/${id}/download`, { signal });return res.blob();}diff --git a/packages/core/attachments/image-sequence.test.ts b/packages/core/attachments/image-sequence.test.tsindex 9512b9ee33..75af261531 100644--- a/packages/core/attachments/image-sequence.test.ts+++ b/packages/core/attachments/image-sequence.test.ts@@ -54,6 +54,14 @@ describe("isImageAttachment", () => {describe("matchAttachmentByURL", () => {const a = attachment({ id: UUID_A });+ it("matches historical local URLs after the backend aliases the storage URL", () => {+ const local = attachment({ id: UUID_A, url: `/api/attachments/${UUID_A}/download` });+ const url = `/uploads/workspaces/${UUID_B}/${UUID_A}.png`;+ expect(matchAttachmentByURL(url, [local])).toBe(local);+ expect(selectStandaloneAttachments(``, [local])).toEqual([]);+ expect(collectImageSequence([{ content: ``, attachments: [local] }])).toHaveLength(1);+ });+it("matches the stable download path regardless of host and query", () => {expect(matchAttachmentByURL(diff --git a/packages/core/attachments/image-sequence.ts b/packages/core/attachments/image-sequence.tsindex 0e0d340110..7dfc34b97a 100644--- a/packages/core/attachments/image-sequence.ts+++ b/packages/core/attachments/image-sequence.ts@@ -23,6 +23,7 @@ import { normalizeUri } from "micromark-util-sanitize-uri";import type { Attachment } from "../types/attachment";import {attachmentIdFromDownloadURL,+ attachmentIdFromLocalUploadURL,contentReferencesAttachment,} from "../types/attachment-url";@@ -109,7 +110,7 @@ export function matchAttachmentByURL(attachments: ReadonlyArray<Attachment> | null | undefined,): Attachment | undefined {if (!url || !attachments?.length) return undefined;- const idFromUrl = attachmentIdFromDownloadURL(url);+ const idFromUrl = attachmentIdFromDownloadURL(url) ?? attachmentIdFromLocalUploadURL(url);if (idFromUrl) {const byId = attachments.find((a) => a.id === idFromUrl);if (byId) return byId;diff --git a/packages/core/types/attachment-url.test.ts b/packages/core/types/attachment-url.test.tsindex b002cbfaa6..254104611e 100644--- a/packages/core/types/attachment-url.test.ts+++ b/packages/core/types/attachment-url.test.ts@@ -1,13 +1,34 @@+// @vitest-environment nodeimport { describe, expect, it } from "vitest";import {attachmentDownloadPath,attachmentIdFromDownloadURL,+ attachmentIdFromLocalUploadURL,attachmentIdFromStorageURL,contentReferencesAttachment,stripChannelMediaMarkers,} from "./attachment-url";const ID = "11111111-2222-3333-4444-555555555555";+const LOCAL_URL = `/uploads/workspaces/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee/${ID}.png`;++describe("legacy local attachment URLs", () => {+ it.each([LOCAL_URL, `${LOCAL_URL}?exp=1&sig=old#image`, `https://old.example${LOCAL_URL}`])(+ "extracts the attachment identity from %s",+ (url) => expect(attachmentIdFromLocalUploadURL(url)).toBe(ID),+ );++ it.each(["/uploads/users/user/avatar.png", `${LOCAL_URL}.meta.json`, "/uploads/workspaces/ws/file.png", `//other.example${LOCAL_URL}`])(+ "does not treat %s as an attachment",+ (url) => expect(attachmentIdFromLocalUploadURL(url)).toBeUndefined(),+ );++ it("deduplicates historical body references after the response URL changes", () => {+ expect(contentReferencesAttachment(``, {+ id: ID, url: attachmentDownloadPath(ID),+ })).toBe(true);+ });+});describe("attachmentDownloadPath", () => {it("returns the stable per-attachment download path", () => {diff --git a/packages/core/types/attachment-url.ts b/packages/core/types/attachment-url.tsindex 0d8ebfd74c..944edac2c6 100644--- a/packages/core/types/attachment-url.ts+++ b/packages/core/types/attachment-url.ts@@ -91,6 +91,24 @@ const WORKSPACE_STORAGE_PATH_RE = new RegExp(`^/workspaces/${UUID_PATTERN}/(${UUID_PATTERN})(?:\\.[A-Za-z0-9]+)?$`,"i",);+const LOCAL_UPLOAD_PATH_RE = new RegExp(+ `^/uploads/workspaces/${UUID_PATTERN}/(${UUID_PATTERN})(?:\\.[A-Za-z0-9]+)?$`,+ "i",+);++/** Recover the id in historical local-storage Markdown. This is only an+ * identity hint: the API still authorizes access before returning any bytes. */+export function attachmentIdFromLocalUploadURL(rawURL: string): string | undefined {+ let path = rawURL.split(/[?#]/, 1)[0] ?? "";+ if (/^https?:\/\//i.test(rawURL)) {+ try {+ path = new URL(rawURL).pathname;+ } catch {+ return undefined;+ }+ }+ return LOCAL_UPLOAD_PATH_RE.exec(path)?.[1];+}/*** Extract the attachment id from a raw storage URL on the configured CDN@@ -159,6 +177,11 @@ export function contentReferencesAttachment(): boolean {if (!content) return false;if (content.includes(attachmentDownloadPath(attachment.id))) return true;+ // Bound LocalStorage responses now alias `url` to the authenticated API;+ // historical bodies still contain the original storage object path.+ for (const match of content.matchAll(/\/uploads\/workspaces\/[^\s)"'<>]+/g)) {+ if (attachmentIdFromLocalUploadURL(match[0]) === attachment.id) return true;+ }if (contentReferencesURL(content, attachment.url)) return true;if (contentReferencesURL(content, attachment.download_url)) return true;if (contentReferencesURL(content, attachment.markdown_url)) return true;diff --git a/packages/views/editor/attachment-preview-modal.test.tsx b/packages/views/editor/attachment-preview-modal.test.tsxindex 82a54a9def..b662f24486 100644--- a/packages/views/editor/attachment-preview-modal.test.tsx+++ b/packages/views/editor/attachment-preview-modal.test.tsx@@ -1,8 +1,9 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { act, fireEvent, render as rtlRender, screen, waitFor } from "@testing-library/react";-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { focusManager, QueryClient, QueryClientProvider } from "@tanstack/react-query";import { useState, type ReactElement } from "react";import type { Attachment } from "@multica/core/types";+import { ApiError } from "@multica/core/api/client";const { openExternalMock, isDesktopShellMock, copyImageMock, toastMock } =vi.hoisted(() => ({@@ -224,6 +225,7 @@ function ClosablePreview({ attachment }: { attachment: Attachment }) {beforeEach(() => {vi.clearAllMocks();+ getAttachmentMock.mockReset().mockRejectedValue(new ApiError("no re-sign", 404, "Not Found"));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.@@ -284,11 +286,12 @@ describe("AttachmentPreviewModal — dispatch", () => {expect(img?.getAttribute("src")).toBe(url);});- it("renders a PDF iframe pointing at the signed download URL", async () => {+ it("renders a same-origin proxy PDF through the stable authenticated URL", async () => {const att = makeAttachment({ filename: "manual.pdf", content_type: "application/pdf" });+ getAttachmentMock.mockResolvedValueOnce({ ...att, download_url: `/api/attachments/${att.id}/signed-download?exp=${Math.floor(Date.now() / 1000) + 60}&sig=fresh` });render(<AttachmentPreviewModal source={{ kind: "full", attachment: att }} open onClose={() => {}} />);await waitFor(() => {- expect(document.querySelector("iframe")?.getAttribute("src")).toBe(att.download_url);+ expect(document.querySelector("iframe")?.getAttribute("src")).toBe(`/api/attachments/${att.id}/download`);});});@@ -616,6 +619,84 @@ describe("AttachmentPreviewModal — error states", () => {});describe("AttachmentPreviewModal — streamed media (MUL-8892)", () => {+ it.each(["video", "audio"] as const)("restores %s and its playback position after signing recovers from an outage", async (kind) => {+ const id = "11111111-2222-3333-4444-555555555555";+ const now = Date.now();+ const clock = vi.spyOn(Date, "now").mockReturnValue(now);+ const cap = (sig: string, exp: number) => `/api/attachments/${id}/signed-download?exp=${exp}&sig=${sig}`;+ const old = cap("first", Math.floor(now / 1000) + 60);+ const fresh = cap("recovered", Math.floor(now / 1000) + 120);+ const att = makeAttachment({ id, filename: kind === "audio" ? "clip.wav" : "clip.mp4", content_type: `${kind}/${kind === "audio" ? "wav" : "mp4"}`, download_url: `/api/attachments/${id}/download` });+ getAttachmentMock.mockReset();+ getAttachmentMock.mockResolvedValueOnce({ ...att, download_url: old })+ .mockRejectedValueOnce(new TypeError("Failed to fetch"))+ .mockRejectedValueOnce(new TypeError("Failed to fetch"))+ .mockRejectedValueOnce(new TypeError("Failed to fetch"))+ .mockResolvedValue({ ...att, download_url: fresh });+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 } } });+ try {+ rtlRender(<QueryClientProvider client={qc}><AttachmentPreviewModal source={{ kind: "full", attachment: att }} open onClose={() => {}} /></QueryClientProvider>);+ const audio = await waitFor(() => {+ const el = document.querySelector<HTMLMediaElement>(kind);+ expect(el?.getAttribute("src")).toBe(old);+ return el!;+ });+ audio.currentTime = 23;+ audio.playbackRate = 1.5;+ Object.defineProperty(audio, "paused", { configurable: true, value: false });+ const play = vi.spyOn(HTMLMediaElement.prototype, "play").mockResolvedValue();+ clock.mockReturnValue(now + 61000);+ fireEvent.error(audio);+ await waitFor(() => expect(screen.getByText("Couldn't load preview")).toBeInTheDocument(), { timeout: 6000 });+ act(() => { focusManager.setFocused(false); focusManager.setFocused(true); });+ await waitFor(() => expect(getAttachmentMock).toHaveBeenCalledTimes(5));+ expect(qc.getQueryData<Attachment>(["attachment-stream-resign", id])?.download_url).toBe(fresh);+ const restored = await waitFor(() => {+ const el = document.querySelector<HTMLMediaElement>(kind);+ expect(el?.getAttribute("src")).toBe(fresh);+ return el!;+ });+ fireEvent.loadedMetadata(restored);+ expect(restored.currentTime).toBe(23);+ expect(restored.playbackRate).toBe(1.5);+ expect(play).toHaveBeenCalled();+ play.mockRestore();+ } finally { clock.mockRestore(); qc.clear(); focusManager.setFocused(undefined); }+ });++ it.each(["video", "audio"] as const)("renews an expired local %s and restores the seek and play state", async (kind) => {+ const id = "11111111-2222-3333-4444-555555555555";+ const now = Date.now();+ const clock = vi.spyOn(Date, "now").mockReturnValue(now);+ const cap = (suffix: string, exp: number) => `/api/attachments/${id}/signed-download?exp=${exp}&sig=${suffix}`;+ const old = cap("first", Math.floor(now / 1000) + 60);+ const fresh = cap("renewed", Math.floor(now / 1000) + 120);+ const att = makeAttachment({ id, filename: kind === "audio" ? "clip.wav" : "clip.mp4", content_type: `${kind}/${kind === "audio" ? "wav" : "mp4"}`, download_url: `/api/attachments/${id}/download` });+ getAttachmentMock.mockResolvedValueOnce({ ...att, download_url: old }).mockResolvedValueOnce({ ...att, download_url: fresh });+ try {+ render(<AttachmentPreviewModal source={{ kind: "full", attachment: att }} open onClose={() => {}} />);+ const media = await waitFor(() => {+ const el = document.querySelector<HTMLMediaElement>(kind);+ expect(el?.getAttribute("src")).toBe(old);+ return el!;+ });+ media.currentTime = 23;+ media.playbackRate = 1.5;+ Object.defineProperty(media, "paused", { configurable: true, value: false });+ const play = vi.spyOn(media, "play").mockResolvedValue();+ clock.mockReturnValue(now + 61000);+ fireEvent.error(media);+ await waitFor(() => expect(media.getAttribute("src")).toBe(fresh));+ expect(document.querySelector(kind)).toBe(media);+ media.currentTime = 0;+ fireEvent.loadedMetadata(media);+ expect(media.currentTime).toBe(23);+ expect(media.playbackRate).toBe(1.5);+ expect(play).toHaveBeenCalledOnce();+ expect(getAttachmentMock).toHaveBeenCalledTimes(2);+ } finally { clock.mockRestore(); }+ });+// 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 = () =>@@ -647,7 +728,8 @@ describe("AttachmentPreviewModal — streamed media (MUL-8892)", () => {});});- it("signs a PDF afresh too", async () => {+ it.each(["", "https://api.example.test"])("signs a PDF afresh with API base '%s'", async (base) => {+ getBaseUrlMock.mockReturnValue(base);getAttachmentMock.mockResolvedValueOnce(makeAttachment({ download_url: "https://cdn.example.test/manual.pdf?Signature=fresh" }),);@@ -692,7 +774,7 @@ describe("AttachmentPreviewModal — streamed media (MUL-8892)", () => {fireEvent.error(video);- expect(document.querySelector("video")).toBeNull();+ await waitFor(() => 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]!);diff --git a/packages/views/editor/attachment-preview-modal.tsx b/packages/views/editor/attachment-preview-modal.tsxindex cc048fbec1..0f99d62b16 100644--- a/packages/views/editor/attachment-preview-modal.tsx+++ b/packages/views/editor/attachment-preview-modal.tsx@@ -56,7 +56,11 @@ import {type IconComponent,} from "@multica/ui/icons";import type { Attachment } from "@multica/core/types";-import { attachmentIdFromStorageURL } from "@multica/core/types/attachment-url";+import {+ attachmentIdFromDownloadURL,+ attachmentIdFromLocalUploadURL,+ attachmentIdFromStorageURL,+} from "@multica/core/types/attachment-url";import { useConfigStore } from "@multica/core/config";import { paths, useWorkspaceSlug } from "@multica/core/paths";import { createShortcutChord } from "@multica/core/shortcuts";@@ -195,7 +199,9 @@ function normalize(source: PreviewSource): PreviewState {filename: source.filename,contentType: "",mediaUrl: resolvePublicFileUrl(source.url) ?? source.url,- attachmentId: null,+ attachmentId:+ attachmentIdFromDownloadURL(source.url) ??+ attachmentIdFromLocalUploadURL(source.url) ?? null,sizeBytes: 0,kind: source.forceKind ?? getPreviewKind("", source.filename),};@@ -805,9 +811,12 @@ function PreviewPanel({// 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.attachmentId ??+ attachmentIdFromLocalUploadURL(state.mediaUrl) ??+ attachmentIdFromStorageURL(state.mediaUrl, cdnDomain),state.mediaUrl,kind === "video" || kind === "audio" || kind === "pdf",+ kind === "pdf",);const streamUrl = streamed.pending ? "" : streamed.url;@@ -1099,6 +1108,8 @@ function PreviewPanel({source={source}state={state}streamUrl={streamUrl}+ streamFailed={streamed.failed}+ onStreamError={streamed.refreshIfExpired}view={view}onDownload={handleDownload}downloading={downloading}@@ -1405,6 +1416,8 @@ function PreviewContent({source,state,streamUrl,+ streamFailed,+ onStreamError,view,onDownload,downloading,@@ -1415,6 +1428,8 @@ function PreviewContent({state: PreviewState;/** Where video, audio and PDF load from; empty while it is being signed. */streamUrl: string;+ streamFailed: boolean;+ onStreamError: () => Promise<boolean>;view: StageView;onDownload: () => void;downloading: boolean;@@ -1459,6 +1474,9 @@ function PreviewContent({</DocumentSheet>);+ if (kind === "pdf" && streamFailed) {+ return <UnsupportedFallback message={t(($) => $.attachment.preview_failed)} onDownload={onDownload} downloading={downloading} />;+ }if ((kind === "pdf" || kind === "video" || kind === "audio") && !streamUrl) {return <PreviewLoading />;}@@ -1477,12 +1495,11 @@ function PreviewContent({case "video":case "audio":return (- // Keyed on the URL: a failure belongs to the file that failed, not- // to the next one the sequence pages to.<MediaPlayer- key={streamUrl}+ key={state.attachmentId ?? state.mediaUrl}kind={kind}src={streamUrl}+ onExpired={onStreamError}onDownload={onDownload}downloading={downloading}/>@@ -1684,18 +1701,45 @@ function PreviewLoading() {function MediaPlayer({kind,src,+ onExpired,onDownload,downloading,}: {kind: "video" | "audio";src: string;+ onExpired: () => Promise<boolean>;onDownload: () => void;downloading: boolean;}) {const { t } = useT("editor");- const [failed, setFailed] = useState(false);+ const [failedSrc, setFailedSrc] = useState<string | null>(null);+ const mediaRef = useRef<HTMLMediaElement | null>(null);+ const resumeRef = useRef<{ currentTime: number; paused: boolean; playbackRate: number } | null>(null);++ useEffect(() => {+ const media = mediaRef.current;+ if (!media || media.getAttribute("src") === src) return;+ // Replacing an expired capability reloads the native player. Snapshot+ // before assigning src so renewal preserves both the seek and play state.+ const { currentTime, paused, playbackRate } = resumeRef.current ?? media;+ const restore = () => {+ media.currentTime = currentTime;+ media.playbackRate = playbackRate;+ if (!paused) void media.play().catch(() => {});+ resumeRef.current = null;+ };+ media.addEventListener("loadedmetadata", restore, { once: true });+ media.src = src;+ return () => media.removeEventListener("loadedmetadata", restore);+ }, [src]);++ const handleError = async () => {+ const media = mediaRef.current;+ if (media) resumeRef.current = { currentTime: media.currentTime, paused: media.paused, playbackRate: media.playbackRate };+ if (!(await onExpired())) setFailedSrc(src);+ };- if (failed) {+ if (failedSrc === src) {return (<UnsupportedFallbackmessage={t(($) => $.attachment.preview_failed)}@@ -1708,10 +1752,10 @@ function MediaPlayer({return (<div className="dark flex h-full w-full items-center justify-center p-8"><audio- src={src}+ ref={(element) => { mediaRef.current = element; }}controlsclassName="w-full max-w-xl"- onError={() => setFailed(true)}+ onError={handleError}/></div>);@@ -1719,10 +1763,10 @@ function MediaPlayer({return (<div className="flex h-full w-full items-center justify-center pb-4"><video- src={src}+ ref={(element) => { mediaRef.current = element; }}controlsclassName="h-full w-full object-contain"- onError={() => setFailed(true)}+ onError={handleError}/></div>);diff --git a/packages/views/editor/attachment.test.tsx b/packages/views/editor/attachment.test.tsxindex a7643a5584..7a18c54f27 100644--- a/packages/views/editor/attachment.test.tsx+++ b/packages/views/editor/attachment.test.tsx@@ -313,11 +313,11 @@ describe("Attachment — image dispatch", () => {);});- it("prefers a local disk /uploads URL over API markdown in split-origin self-host", () => {+ it("authenticates local disk images in split-origin self-host", async () => {getBaseUrlMock.mockReturnValue("https://api.example.test");const id = "11111111-2222-3333-4444-555555555555";const markdownUrl = `https://api.example.test/api/attachments/${id}/download`;- const mediaUrl = "https://api.example.test/uploads/workspaces/ws-1/shot.png";+ const mediaUrl = OBJECT_URL;const att = makeRecord({id,url: "/uploads/workspaces/ws-1/shot.png",@@ -325,6 +325,8 @@ describe("Attachment — image dispatch", () => {download_url: `/api/attachments/${id}/download`,});resolverState.attachments = [att];+ getAttachmentMock.mockResolvedValue({ ...att, download_url: `/api/attachments/${id}/signed-download?exp=1&sig=short` });+ getAttachmentBlobMock.mockResolvedValue(new Blob(["image"], { type: "image/png" }));renderWithQuery(<Attachment@@ -337,7 +339,8 @@ describe("Attachment — image dispatch", () => {/>,);- expect(document.querySelector("img")?.getAttribute("src")).toBe(mediaUrl);+ await waitFor(() => expect(document.querySelector("img")?.getAttribute("src")).toBe(mediaUrl));+ expect(getAttachmentBlobMock).toHaveBeenCalledWith(id);fireEvent.click(screen.getByRole("button", { name: "View" }));@@ -347,6 +350,19 @@ describe("Attachment — image dispatch", () => {expect(imageSrcs).toEqual([mediaUrl, mediaUrl]);});+ it.each(["draft", "historical body"])("authenticates a local %s without a current attachment list", async (source) => {+ const id = "11111111-2222-3333-4444-555555555555";+ const raw = `/uploads/workspaces/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee/${id}.png`;+ getBaseUrlMock.mockReturnValue("https://api.example.test");+ configStore.setState({ cdnDomain: "api.example.test", cdnSigned: false });+ const att = makeRecord({ id, url: raw, markdown_url: "", download_url: "" });+ getAttachmentMock.mockResolvedValue({ ...att, download_url: `/api/attachments/${id}/signed-download?exp=1&sig=short` });+ getAttachmentBlobMock.mockResolvedValue(new Blob(["image"], { type: "image/png" }));+ renderWithQuery(<Attachment attachment={source === "draft" ? { kind: "record", attachment: att } : { kind: "url", url: `https://old-host.test${raw}`, filename: "shot.png", forceKind: "image" }} />);+ await waitFor(() => expect(document.querySelector("img")?.getAttribute("src")).toBe(OBJECT_URL));+ expect(getAttachmentBlobMock).toHaveBeenCalledWith(id);+ });+it("opens preview with the same resolved media URL when a reopened draft record has no download_url", () => {configStore.setState({ cdnDomain: "cdn.example.test" });const id = "11111111-2222-3333-4444-555555555555";diff --git a/packages/views/editor/attachment.tsx b/packages/views/editor/attachment.tsxindex a46beb2e24..c4bed378b0 100644--- a/packages/views/editor/attachment.tsx+++ b/packages/views/editor/attachment.tsx@@ -41,7 +41,12 @@ import { copyText } from "@multica/ui/lib/clipboard";import { api } from "@multica/core/api";import { useConfigStore } from "@multica/core/config";import type { Attachment as AttachmentRecord } from "@multica/core/types";-import { attachmentIdFromStorageURL } from "@multica/core/types/attachment-url";+import {+ attachmentDownloadPath,+ attachmentIdFromDownloadURL,+ attachmentIdFromLocalUploadURL,+ attachmentIdFromStorageURL,+} from "@multica/core/types/attachment-url";import { useT } from "../i18n";import { DeferredTooltip } from "../common/deferred-tooltip";import { useAttachmentDownloadResolver } from "./attachment-download-context";@@ -228,8 +233,8 @@ function absolutizeMediaURL(rawUrl: string): string {// for rendering but must not replace durable Markdown references.//// Use known public/CDN URLs directly only when cdn_signed is false; unsigned URLs-// on a private CDN fail even when the domain matches. Local /uploads paths remain-// valid after origin normalization. Otherwise prefer the server's markdown_url,+// on a private CDN fail even when the domain matches. Historical local uploads+// use the authenticated API. Otherwise prefer the server's markdown_url,// then legacy storage URLs, then the original input.function pickInlineMediaURL(record: AttachmentRecord,@@ -244,19 +249,13 @@ function pickInlineMediaURL() {return dl;}+ if (attachmentIdFromLocalUploadURL(record.url)) return attachmentDownloadPath(record.id);if (!cdnSigned && storageURLMatchesCdnDomain(record.url, cdnDomain)) return record.url;- if (isSiteRelativeLocalUploadURL(record.url)) return record.url;if (record.markdown_url) return record.markdown_url;if (record.url) return record.url;return fallback;}-function isSiteRelativeLocalUploadURL(rawURL: string): boolean {- if (!rawURL || !rawURL.startsWith("/")) return false;- const path = rawURL.split(/[?#]/, 1)[0] ?? "";- return path === "/uploads" || path.startsWith("/uploads/");-}-function storageURLMatchesCdnDomain(rawURL: string, cdnDomain: string): boolean {const expected = normalizeHost(cdnDomain);if (!rawURL || !expected) return false;@@ -353,7 +352,7 @@ export function Attachment({if (mediaUrl) {preview.tryOpen({kind: "url",- url: mediaUrl,+ url: isObjectURL(mediaUrl) ? state.url : mediaUrl,filename: state.filename,// This dispatcher has already decided what the slot is — from the// call site's `forceKind`, or from a content-type the modal's@@ -371,7 +370,10 @@ export function Attachment({// its attachment id, so re-sign it instead of opening the bare URL,// which a signed CDN rejects outside the app.const attachmentId =- state.attachmentId ?? attachmentIdFromStorageURL(shareUrl, cdnDomain);+ state.attachmentId ??+ attachmentIdFromDownloadURL(shareUrl) ??+ attachmentIdFromLocalUploadURL(shareUrl) ??+ attachmentIdFromStorageURL(shareUrl, cdnDomain);if (attachmentId) {return download(attachmentId);}diff --git a/packages/views/editor/hooks/use-inline-media-url.test.tsx b/packages/views/editor/hooks/use-inline-media-url.test.tsxnew file mode 100644index 0000000000..72bc031521--- /dev/null+++ b/packages/views/editor/hooks/use-inline-media-url.test.tsx@@ -0,0 +1,133 @@+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 { ApiError } from "@multica/core/api/client";+import type { ReactNode } from "react";+import { useFreshStreamedMediaURL } from "./use-inline-media-url";++const { getAttachment, getAttachmentBlob, getBaseUrl } = vi.hoisted(() => ({+ getAttachment: vi.fn(), getAttachmentBlob: vi.fn(), getBaseUrl: vi.fn(() => "https://api.example.test"),+}));+vi.mock("@multica/core/api", () => ({ api: { getAttachment, 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}`;++function setup() {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const wrapper = ({ children }: { children: ReactNode }) => <QueryClientProvider client={client}>{children}</QueryClientProvider>;+ return { client, wrapper };+}+afterEach(() => {+ cleanup(); vi.useRealTimers(); vi.clearAllMocks(); vi.unstubAllGlobals();+ focusManager.setFocused(undefined);+ getBaseUrl.mockReturnValue("https://api.example.test");+});++describe("short-lived streamed attachment capabilities", () => {+ it("resolves a relative capability against the API origin and fetches again on reopen", async () => {+ getAttachment.mockResolvedValue({ download_url: capability(Math.floor(Date.now() / 1000) + 60) });+ const { wrapper } = setup();+ const first = renderHook(() => useFreshStreamedMediaURL(id, stable, true), { wrapper });+ await waitFor(() => expect(first.result.current.url).toContain("https://api.example.test/api/attachments/"));+ first.unmount();+ const second = renderHook(() => useFreshStreamedMediaURL(id, stable, true), { wrapper });+ await waitFor(() => expect(getAttachment).toHaveBeenCalledTimes(2));+ expect(second.result.current.url).toContain("/signed-download?");+ });++ it("keeps an open stream stable beyond TTL and on window focus", async () => {+ vi.useFakeTimers();+ getAttachment.mockImplementation(async () => ({ download_url: capability(Math.floor(Date.now() / 1000) + 60, String(getAttachment.mock.calls.length)) }));+ const { wrapper } = setup();+ const hook = renderHook(() => useFreshStreamedMediaURL(id, stable, true), { wrapper });+ await act(async () => { await vi.advanceTimersByTimeAsync(10); });+ const original = hook.result.current.url;+ expect(original).toContain("/signed-download?");+ await act(async () => {+ await vi.advanceTimersByTimeAsync(65000);+ focusManager.setFocused(false);+ focusManager.setFocused(true);+ await vi.advanceTimersByTimeAsync(10);+ });+ expect(getAttachment).toHaveBeenCalledTimes(1);+ expect(hook.result.current.pending).toBe(false);+ expect(hook.result.current.url).toBe(original);+ });++ it("does not retry a permission denial during expiry recovery", async () => {+ vi.useFakeTimers();+ getAttachment.mockResolvedValueOnce({ download_url: capability(Math.floor(Date.now() / 1000) + 60) });+ getAttachment.mockRejectedValue(new ApiError("membership revoked", 403, "Forbidden"));+ const { wrapper } = setup();+ const hook = renderHook(() => useFreshStreamedMediaURL(id, stable, true), { wrapper });+ await act(async () => { await vi.advanceTimersByTimeAsync(10); });+ await act(async () => { await vi.advanceTimersByTimeAsync(61000); });+ await act(async () => { expect(await hook.result.current.refreshIfExpired()).toBe(false); });+ await act(async () => { await vi.advanceTimersByTimeAsync(10); });+ expect(getAttachment).toHaveBeenCalledTimes(2);+ await act(async () => { expect(await hook.result.current.refreshIfExpired()).toBe(false); });+ expect(getAttachment).toHaveBeenCalledTimes(2);+ expect(hook.result.current.pending).toBe(false);+ });++ it("uses a stable authenticated PDF URL on same-origin web only for proxy storage", async () => {+ getBaseUrl.mockReturnValue("");+ getAttachment.mockResolvedValue({ download_url: capability(Math.floor(Date.now() / 1000) + 60) });+ const { wrapper } = setup();+ const hook = renderHook(() => useFreshStreamedMediaURL(id, stable, true, true), { wrapper });+ await waitFor(() => expect(hook.result.current.pending).toBe(false));+ expect(hook.result.current.url).toBe(stable);+ expect(getAttachment).toHaveBeenCalledWith(id);+ expect(getAttachmentBlob).not.toHaveBeenCalled();+ });++ it.each([+ ["S3 presign", "https://storage.example.test/manual.pdf?X-Amz-Signature=fresh"],+ ["CloudFront", "https://cdn.example.test/manual.pdf?Signature=fresh&Key-Pair-Id=test"],+ ])("uses the fresh inline URL for same-origin web PDFs with %s", async (_mode, inlineURL) => {+ getBaseUrl.mockReturnValue("");+ getAttachment.mockResolvedValue({ download_url: inlineURL, attachment_download_url: `${inlineURL}&response-content-disposition=attachment` });+ const { wrapper } = setup();+ const hook = renderHook(() => useFreshStreamedMediaURL(id, stable, true, true), { wrapper });+ await waitFor(() => expect(hook.result.current.url).toBe(inlineURL));+ expect(hook.result.current.pending).toBe(false);+ expect(getAttachment).toHaveBeenCalledWith(id);+ expect(getAttachmentBlob).not.toHaveBeenCalled();+ });++ it("fetches a cross-origin proxy PDF once and releases its typed blob on close", async () => {+ const create = vi.fn((_blob: Blob) => "blob:private-pdf");+ const revoke = vi.fn();+ vi.stubGlobal("URL", class extends URL { static createObjectURL = create; static revokeObjectURL = revoke; });+ getAttachment.mockResolvedValue({ download_url: capability(Math.floor(Date.now() / 1000) + 60) });+ getAttachmentBlob.mockResolvedValue(new Blob(["%PDF"], { type: "text/html" }));+ const { wrapper } = setup();+ const hook = renderHook(() => useFreshStreamedMediaURL(id, stable, true, true), { wrapper });+ await waitFor(() => expect(hook.result.current.url).toBe("blob:private-pdf"));+ expect(create.mock.calls[0]![0].type).toBe("application/pdf");+ vi.useFakeTimers();+ await act(async () => {+ await vi.advanceTimersByTimeAsync(65000);+ focusManager.setFocused(false); focusManager.setFocused(true);+ await vi.advanceTimersByTimeAsync(10);+ });+ expect(hook.result.current.url).toBe("blob:private-pdf");+ expect(getAttachment).toHaveBeenCalledTimes(1);+ expect(getAttachmentBlob).toHaveBeenCalledTimes(1);+ hook.unmount();+ expect(revoke).toHaveBeenCalledWith("blob:private-pdf");+ });++ it("cancels the PDF byte request when its viewer closes during loading", async () => {+ getAttachment.mockResolvedValue({ download_url: capability(Math.floor(Date.now() / 1000) + 60) });+ getAttachmentBlob.mockImplementation(() => new Promise(() => {}));+ const { wrapper } = setup();+ const hook = renderHook(() => useFreshStreamedMediaURL(id, stable, true, true), { wrapper });+ await waitFor(() => expect(getAttachmentBlob).toHaveBeenCalledTimes(1));+ const signal = getAttachmentBlob.mock.calls[0]![1] as AbortSignal;+ expect(signal.aborted).toBe(false);+ hook.unmount();+ expect(signal.aborted).toBe(true);+ });+});diff --git a/packages/views/editor/hooks/use-inline-media-url.ts b/packages/views/editor/hooks/use-inline-media-url.tsindex f622b89fa2..d92ad868fc 100644--- a/packages/views/editor/hooks/use-inline-media-url.ts+++ b/packages/views/editor/hooks/use-inline-media-url.ts@@ -12,7 +12,12 @@import { useEffect, useState } from "react";import { useQuery } from "@tanstack/react-query";import { api } from "@multica/core/api";-import { attachmentIdFromDownloadURL } from "@multica/core/types/attachment-url";+import { ApiError } from "@multica/core/api/client";+import {+ attachmentDownloadPath,+ attachmentIdFromDownloadURL,+ attachmentIdFromLocalUploadURL,+} from "@multica/core/types/attachment-url";// Keep refetches well inside the server's signed-URL TTL (30 min default,// server/internal/handler/file.go) so a re-render never serves an expired@@ -61,16 +66,12 @@ export function __resetInlineMediaBlobCacheForTests(): void {// the same re-sign the click-time download path already does — and swap in// 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+// CloudFront and presign URLs can load natively. Proxy capabilities last just+// 60 seconds, so images deliberately ignore those and fetch durable bytes+// through the authenticated client instead. Proxy is the default when `auto`+// mode encounters an internal storage host, such as docker-compose MinIO+// (`http://minio:9000`). Without a storage signature, pull authenticated bytes+// and render an object URL. `blobFallback` gates that on 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.//@@ -80,9 +81,10 @@ export function __resetInlineMediaBlobCacheForTests(): void {// instead of rendering it.export function useResignedInlineMedia(attachmentId: string | undefined,- pickedUrl: string,+ rawPickedUrl: string,blobFallback: boolean,): { url: string; pending: boolean } {+ const pickedUrl = resolveLegacyLocalMediaURL(rawPickedUrl);const idFromPickedUrl = attachmentIdFromDownloadURL(pickedUrl);const resignAttachmentId = attachmentId ?? idFromPickedUrl;const isCrossOriginWebURL = (() => {@@ -166,34 +168,139 @@ export function useResignedInlineMedia(//// 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.+// Proxy capabilities last only 60 seconds. Keep them in a separate query so+// image metadata caching cannot pin one into a native stream after it expires.+// Reopen authenticates again. Loaded media keeps its source until a native+// request fails after expiry, so reading/playing never triggers a periodic reload.export function useFreshStreamedMediaURL(attachmentId: string | undefined,- pickedUrl: string,+ rawPickedUrl: 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),+ pdf = false,+): { url: string; pending: boolean; failed: boolean; refreshIfExpired: () => Promise<boolean> } {+ const pickedUrl = resolveLegacyLocalMediaURL(rawPickedUrl);+ const id = attachmentId ?? attachmentIdFromDownloadURL(pickedUrl);+ const active = enabled && !!id && !!pickedUrl;+ const stablePDFURL = id ? absolutizeAPIPath(attachmentDownloadPath(id)) : "";+ const { data: fresh, error, isError, refetch } = useQuery({+ queryKey: ["attachment-stream-resign", id],+ queryFn: () => api.getAttachment(id as string),enabled: active,- staleTime: RESIGN_STALE_MS,- gcTime: RESIGN_STALE_MS,+ staleTime: Infinity,+ gcTime: 0,+ retry: retryAttachmentPreview,+ retryDelay: (attempt) => 1000 * 2 ** attempt,+ refetchOnMount: "always",+ refetchOnWindowFocus: recoverFailedPreview,+ refetchOnReconnect: recoverFailedPreview,});- 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 dl = fresh?.download_url ?? "";+ const expiresAt = capabilityExpiresAt(dl);+ // The authenticated route redirects to forced downloads for presign/CDN+ // storage. Use it for PDFs only after metadata confirms inline proxying.+ const sameOriginPDF = active && pdf && expiresAt !== undefined && isSameOriginHTTPURL(stablePDFURL);+ const proxyPDF = active && pdf && !sameOriginPDF && expiresAt !== undefined;+ const pdfBytes = useQuery({+ queryKey: ["attachment-preview-pdf", id],+ queryFn: async ({ signal }) => {+ const blob = await api.getAttachmentBlob(id as string, signal);+ // Never let an HTML file named *.pdf become same-origin active content.+ return blob.slice(0, blob.size, "application/pdf");+ },+ enabled: proxyPDF && !isError,+ staleTime: Infinity,+ gcTime: 0,+ retry: retryAttachmentPreview,+ retryDelay: (attempt) => 1000 * 2 ** attempt,+ refetchOnWindowFocus: recoverFailedPreview,+ refetchOnReconnect: recoverFailedPreview,+ });+ const pdfURL = usePDFObjectURL(proxyPDF && !isPermanentAttachmentError(error) ? pdfBytes.data : undefined);+ const refreshIfExpired = async () => {+ if (!active || isPermanentAttachmentError(error) || expiresAt === undefined || expiresAt > Date.now() + 5000) return false;+ const result = await refetch();+ return !result.isError && !!result.data?.download_url && result.data.download_url !== dl;+ };+ if (!active) return { url: pickedUrl, pending: false, failed: false, refreshIfExpired };+ if (sameOriginPDF) return { url: stablePDFURL, pending: false, failed: false, refreshIfExpired };+ // Cross-origin proxy PDFs cannot depend on iframe error events. Fetch their+ // complete authenticated bytes once; the local blob has no signature expiry.+ if (proxyPDF) {+ const failed = isError || pdfBytes.isError;+ return { url: pdfURL, pending: !failed && !pdfURL, failed, refreshIfExpired };+ }+ if (expiresAt !== undefined) {+ return { url: absolutizeAPIPath(dl), pending: false, failed: false, refreshIfExpired };+ }+ if (fresh) {const signed =/^https?:\/\//i.test(dl) && attachmentIdFromDownloadURL(dl) === undefined;- return { url: signed ? dl : pickedUrl, pending: false };+ return { url: signed ? dl : pickedUrl, pending: false, failed: false, refreshIfExpired };+ }+ const privatePDF = pdf && (attachmentIdFromDownloadURL(pickedUrl) !== undefined || capabilityExpiresAt(pickedUrl) !== undefined);+ return { url: pickedUrl, pending: !isError, failed: privatePDF && isError, refreshIfExpired };+}++function isPermanentAttachmentError(error: unknown): boolean {+ return error instanceof ApiError && error.status >= 400 && error.status < 500 && error.status !== 408 && error.status !== 429;+}++function retryAttachmentPreview(failures: number, error: unknown): boolean {+ return failures < 2 && !isPermanentAttachmentError(error);+}++function recoverFailedPreview(query: { state: { status: string; error: unknown } }): "always" | false {+ return query.state.status === "error" && !isPermanentAttachmentError(query.state.error) ? "always" : false;+}++function isSameOriginHTTPURL(url: string): boolean {+ if (typeof window === "undefined") return false;+ try {+ const parsed = new URL(url, window.location.href);+ return /^https?:$/.test(parsed.protocol) && parsed.origin === window.location.origin;+ } catch {+ return false;+ }+}++// PDFs can be large. Keep one local URL only while its viewer is mounted;+// unlike inline images, do not retain its bytes in the five-minute image cache.+function usePDFObjectURL(blob: Blob | undefined): string {+ const [current, setCurrent] = useState<{ blob: Blob; url: string }>();+ useEffect(() => {+ if (!blob) {+ setCurrent(undefined);+ return;+ }+ const url = URL.createObjectURL(blob);+ setCurrent({ blob, url });+ return () => URL.revokeObjectURL(url);+ }, [blob]);+ return current?.blob === blob ? current?.url ?? "" : "";+}++function absolutizeAPIPath(url: string): string {+ if (!url.startsWith("/") || url.startsWith("//")) return url;+ return `${(api.getBaseUrl?.() ?? "").replace(/\/+$/, "")}${url}`;+}++function resolveLegacyLocalMediaURL(url: string): string {+ const id = attachmentIdFromLocalUploadURL(url);+ return id ? absolutizeAPIPath(attachmentDownloadPath(id)) : url;+}++function capabilityExpiresAt(url: string): number | undefined {+ // Only the server's per-attachment capability has the short proxy TTL.+ try {+ const parsed = new URL(url, "https://attachment.invalid");+ if (!/^\/api\/attachments\/[^/]+\/signed-download$/.test(parsed.pathname)) return undefined;+ if (!parsed.searchParams.get("sig")) return undefined;+ const exp = Number(parsed.searchParams.get("exp"));+ return Number.isFinite(exp) && exp > 0 ? exp * 1000 : undefined;+ } catch {+ return undefined;}- return { url: pickedUrl, pending: !isError };}// useObjectURL turns a Blob into a `blob:` URL. The module cache keeps thediff --git a/packages/views/editor/preview-sequence-context.test.tsx b/packages/views/editor/preview-sequence-context.test.tsxindex bff6a5840c..56c18e6f23 100644--- a/packages/views/editor/preview-sequence-context.test.tsx+++ b/packages/views/editor/preview-sequence-context.test.tsx@@ -10,9 +10,10 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { useState, type ReactElement } from "react";import type { Attachment } from "@multica/core/types";-const { downloadMock, getBaseUrlMock, toastErrorMock } = vi.hoisted(() => ({+const { downloadMock, getBaseUrlMock, getAttachmentMock, toastErrorMock } = vi.hoisted(() => ({downloadMock: vi.fn(),getBaseUrlMock: vi.fn(() => ""),+ getAttachmentMock: vi.fn(),toastErrorMock: vi.fn(),}));@@ -22,8 +23,7 @@ vi.mock("@multica/core/api", () => ({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"))),+ getAttachment: getAttachmentMock,},PreviewTooLargeError: class extends Error {},PreviewUnsupportedError: class extends Error {},@@ -177,6 +177,9 @@ function nextButton(): HTMLButtonElement {beforeEach(() => {vi.clearAllMocks();+ // Navigation tests use successful metadata; retry behavior belongs to the+ // streamed-media tests, rather than delaying keyboard and paging assertions.+ getAttachmentMock.mockImplementation(async (id: string) => imageAttachment(Number(id[0])));});describe("PreviewSequenceProvider", () => {diff --git a/server/internal/handler/config.go b/server/internal/handler/config.goindex 5fa7bb8f0b..2a209fd61d 100644--- a/server/internal/handler/config.go+++ b/server/internal/handler/config.go@@ -8,6 +8,7 @@ import ("github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/featureflags"+ "github.com/multica-ai/multica/server/internal/storage")type AppConfig struct {@@ -16,8 +17,8 @@ type AppConfig struct {// use it only to recognize links belonging to this deployment.AttachmentPublicURL string `json:"attachment_public_url,omitempty"`// CdnSigned tells clients that the CDN domain above serves PRIVATE- // content through time-bounded signed URLs (CloudFront signing is- // enabled). When true, a raw storage URL on the CDN domain is NOT+ // content through authenticated downloads or time-bounded signed URLs.+ // When true, a raw storage URL on the CDN domain is NOT// publicly fetchable — renderers must not pick it as a native// <img>/<video> source and should fall back to the per-attachment// API endpoint or a freshly signed download_url instead (MUL-3254).@@ -132,6 +133,9 @@ func (h *Handler) GetConfig(w http.ResponseWriter, r *http.Request) {}config.AttachmentPublicURL = h.cfg.PublicURLconfig.CdnSigned = h.CFSigner != nil+ if _, local := h.Storage.(*storage.LocalStorage); local {+ config.CdnSigned = true+ }config.DaemonServerURL, config.DaemonAppURL = daemonSetupURLsFromEnv()config.DaemonSetupTarget = "self_host"config.VCSIntegrationAvailable = h.cfg.VCSIntegrationEnableddiff --git a/server/internal/handler/config_test.go b/server/internal/handler/config_test.goindex e927acff22..45db605846 100644--- a/server/internal/handler/config_test.go+++ b/server/internal/handler/config_test.go@@ -7,6 +7,7 @@ import ("testing""github.com/multica-ai/multica/server/internal/auth"+ "github.com/multica-ai/multica/server/internal/storage""github.com/multica-ai/multica/server/internal/testutil")@@ -49,6 +50,13 @@ func TestGetConfigReportsCdnSignedMode(t *testing.T) {if cfg.CdnDomain != "cdn.example.com" {t.Fatalf("cdn_domain: want cdn.example.com alongside cdn_signed, got %q", cfg.CdnDomain)}+ t.Setenv("LOCAL_UPLOAD_DIR", t.TempDir())+ t.Setenv("LOCAL_UPLOAD_BASE_URL", "https://local.example.test")+ testHandler.CFSigner = nil+ testHandler.Storage = storage.NewLocalStorageFromEnv()+ if cfg := fetch(); !cfg.CdnSigned || cfg.CdnDomain != "local.example.test" {+ t.Fatalf("local storage must declare private downloads even with a base URL: %+v", cfg)+ }}func TestGetConfigIncludesRuntimeAuthConfig(t *testing.T) {diff --git a/server/internal/handler/file.go b/server/internal/handler/file.goindex f3e1eb2580..33c1042e54 100644--- a/server/internal/handler/file.go+++ b/server/internal/handler/file.go@@ -75,23 +75,20 @@ type AttachmentResponse struct {// SHOULD persist into markdown bodies (issue descriptions, comments,// chat messages). It is computed per deployment policy by// buildMarkdownURL — preferring the storage URL when it is already a- // public, durable absolute URL (public CDN / LocalStorage with- // MULTICA_LOCAL_UPLOAD_BASE_URL), and otherwise prefixing+ // public, durable absolute URL (public CDN), and otherwise prefixing// MULTICA_PUBLIC_URL onto the stable per-attachment endpoint that the// server self-resigns / proxies on every request.//// Why a separate field from URL / DownloadURL:- // - URL is the raw storage object URL — fine for avatar/logo- // surfaces but may be private (S3 + CloudFront-signed mode) or- // site-relative (LocalStorage with no base URL configured).+ // - URL retains the storage URL for avatar/logo uploads. Bound local+ // attachments use the stable authenticated API URL so installed+ // clients enter their existing authenticated image-fetch path.// - DownloadURL is the URL the renderer uses for THIS response — it// can be a short-lived signed URL (CloudFront, S3 presign) and// therefore must NOT be persisted. It expires.// - MarkdownURL is contracted to be persistable: it never carries a- // TTL, and on every supported deployment shape it is loadable as- // a native browser resource fetch (no Authorization header required- // beyond the cookies/credentials the client already has on the- // resolved host).+ // TTL. Private attachments require cookies or an authenticated byte+ // fetch; token-mode clients cannot use this URL as a bare native src.//// MUL-3192 — fixes the Desktop / mobile-webview regression where the// previous site-relative `/api/attachments/<id>/download` link only@@ -169,6 +166,11 @@ func (h *Handler) attachmentToResponse(a db.Attachment, mode attachmentURLMode)SizeBytes: a.SizeBytes,CreatedAt: a.CreatedAt.Time.Format("2006-01-02T15:04:05Z07:00"),}+ // Installed clients recognize this API shape and fetch private image bytes+ // with credentials. Keep unbound upload URLs intact for avatar setters.+ if _, local := h.Storage.(*storage.LocalStorage); local && attachmentIsBound(a) {+ resp.URL = resp.MarkdownURL+ }// Only CloudFront mode overrides the stable path here; the presign and proxy// modes already leave DownloadURL as the stable path and resolve it at// download time, so stable mode is a no-op for them.@@ -198,16 +200,16 @@ func (h *Handler) attachmentToResponse(a db.Attachment, mode attachmentURLMode)}// buildMarkdownURL chooses the durable URL the client persists into-// markdown bodies. The contract is "absolute, no TTL, loadable as a native-// browser resource fetch on every supported client" (MUL-3192).+// markdown bodies. It has no TTL; private URLs require cookies or an+// authenticated client fetch rather than exposing the raw storage object.//// Decision://// 1. Persist `a.Url` only when the deployment has signaled the storage// backend serves URLs publicly without per-request auth:// - `Storage.CdnDomain()` is non-empty (operator configured a-// public-facing base URL — `S3_CDN_DOMAIN` for the S3 backend or-// `LOCAL_UPLOAD_BASE_URL` for LocalStorage), AND+// public-facing base URL — `S3_CDN_DOMAIN` for the S3 backend), AND+// - the backend is not LocalStorage (always private), AND// - `h.CFSigner` is nil (no per-request CloudFront signing — when// signing is on, the same CDN domain serves PRIVATE content via// time-bounded signed URLs and the raw `a.Url` is unauth-deny),@@ -219,7 +221,7 @@ func (h *Handler) attachmentToResponse(a db.Attachment, mode attachmentURLMode)//// 2. Every other shape — CloudFront-signed mode, S3 presign /proxy// against a private bucket without a CDN domain, raw S3 / R2 /-// MinIO, LocalStorage with no `LOCAL_UPLOAD_BASE_URL` — uses the+// MinIO, and all LocalStorage deployments — uses the// stable per-attachment endpoint that the server self-signs /// proxies on every request, anchored on `MULTICA_PUBLIC_URL` so the// persisted URL keeps working for clients that don't share the@@ -249,6 +251,9 @@ func (h *Handler) buildMarkdownURL(a db.Attachment, id string) string {// fetch — the only case where it is safe to persist `a.Url` into a markdown// body that will outlive the current session.func (h *Handler) storageURLIsPubliclyReadable(rawURL string) bool {+ if _, local := h.Storage.(*storage.LocalStorage); local {+ return false+ }if h.Storage == nil || h.CFSigner != nil {// CFSigner != nil is per-request signing; the CDN domain serves// private content via signed URLs and `a.Url` is the raw S3 URL.diff --git a/server/internal/handler/file_local_compat_test.go b/server/internal/handler/file_local_compat_test.gonew file mode 100644index 0000000000..93e5ae8b1b--- /dev/null+++ b/server/internal/handler/file_local_compat_test.go@@ -0,0 +1,48 @@+package handler++import (+ "testing"++ "github.com/multica-ai/multica/server/internal/storage"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestLocalAttachmentResponseCompatibility(t *testing.T) {+ t.Setenv("LOCAL_UPLOAD_DIR", t.TempDir())+ t.Setenv("LOCAL_UPLOAD_BASE_URL", "https://files.example.test")+ h := &Handler{Storage: storage.NewLocalStorageFromEnv(), cfg: Config{PublicURL: "https://api.example.test"}}+ id := "11111111-2222-3333-4444-555555555555"+ raw := "https://files.example.test/uploads/workspaces/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee/" + id + ".png"+ unbound := db.Attachment{ID: parseUUID(id), Url: raw}+ want := "https://api.example.test/api/attachments/" + id + "/download"+ for _, mode := range []attachmentURLMode{attachmentURLModeSigned, attachmentURLModeStable} {+ resp := h.attachmentToResponse(unbound, mode)+ if resp.URL != raw || resp.MarkdownURL != want {+ t.Fatalf("unbound avatar upload must retain storage URL and durable API markdown: %+v", resp)+ }+ for _, binding := range []string{"issue", "comment", "chat_session", "chat_message", "task"} {+ t.Run(binding, func(t *testing.T) {+ bound := unbound+ switch binding {+ case "issue":+ bound.IssueID = parseUUID(id)+ case "comment":+ bound.CommentID = parseUUID(id)+ case "chat_session":+ bound.ChatSessionID = parseUUID(id)+ case "chat_message":+ bound.ChatMessageID = parseUUID(id)+ case "task":+ bound.TaskID = parseUUID(id)+ }+ resp := h.attachmentToResponse(bound, mode)+ if resp.URL != want || resp.MarkdownURL != want || resp.DownloadURL != "/api/attachments/"+id+"/download" {+ t.Fatalf("bound response must use durable authenticated URLs: %+v", resp)+ }+ if bound.Url != raw {+ t.Fatal("response conversion changed the storage record")+ }+ })+ }+ }+}diff --git a/server/internal/handler/file_test.go b/server/internal/handler/file_test.goindex d91391cdb5..d6c58b1e88 100644--- a/server/internal/handler/file_test.go+++ b/server/internal/handler/file_test.go@@ -1784,7 +1784,7 @@ func TestIsTextPreviewable(t *testing.T) {// Matrix://// - public CDN durable URL ............... reuse a.Url verbatim-// - LocalStorage with PublicURL set ....... reuse a.Url (already absolute)+// - LocalStorage with PublicURL set ....... absolute API endpoint// - CloudFront-signed mode ................ never reuse a.Url (raw S3),// prefer absolute API endpoint// - LocalStorage relative + PublicURL set . prefix to absolute API endpoint