Skip to content

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

Go

fix(editor): open attachment links in the in-app viewer instead of the raw URL (MUL-9566) (#10886)

Jiayuan Zhangd4ab1bcc38e9
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index d7b3141611..fddbe43500 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -4449,8 +4449,12 @@ export class ApiClient {
// `download_url` on every call (30 min expiry), so the click-time
// download flow uses this endpoint to avoid handing the user a stale
// signed URL cached in TanStack Query.
- async getAttachment(id: string): Promise<Attachment> {
- const raw = await this.fetch<unknown>(`/api/attachments/${id}`);
+ // `workspace` targets the workspace that owns the attachment when it is not
+ // the current one (a link pasted from another workspace).
+ async getAttachment(id: string, workspace?: WorkspaceScope): Promise<Attachment> {
+ const raw = await this.fetch<unknown>(`/api/attachments/${id}`, {
+ headers: workspaceHeader(workspace),
+ });
return parseWithFallback(raw, AttachmentResponseSchema, EMPTY_ATTACHMENT, {
endpoint: "GET /api/attachments/{id}",
});
@@ -4484,10 +4488,13 @@ export class ApiClient {
// the modal can render specific fallbacks instead of generic failure.
async getAttachmentTextContent(
id: string,
+ workspace?: WorkspaceScope,
): Promise<{ text: string; originalContentType: string }> {
let res: Response;
try {
- res = await this.fetchRaw(`/api/attachments/${id}/content`);
+ res = await this.fetchRaw(`/api/attachments/${id}/content`, {
+ headers: workspaceHeader(workspace),
+ });
} catch (err) {
if (err instanceof ApiError) {
if (err.status === 413) throw new PreviewTooLargeError();
diff --git a/packages/views/chat/components/chat-input-draft-isolation.test.tsx b/packages/views/chat/components/chat-input-draft-isolation.test.tsx
index e639713f5e..1cbc60add1 100644
--- a/packages/views/chat/components/chat-input-draft-isolation.test.tsx
+++ b/packages/views/chat/components/chat-input-draft-isolation.test.tsx
@@ -94,6 +94,10 @@ vi.mock("../../editor/attachment-download-context", () => ({
AttachmentDownloadProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));
+vi.mock("../../editor/use-open-attachment-link", () => ({
+ useOpenAttachmentLink: () => ({ resolve: () => undefined, open: () => false, modal: null }),
+}));
+
vi.mock("@tiptap/react", () => ({
useEditor: (options: {
onCreate?: (args: { editor: unknown }) => void;
diff --git a/packages/views/editor/attachment-link-cross-workspace.test.tsx b/packages/views/editor/attachment-link-cross-workspace.test.tsx
new file mode 100644
index 0000000000..e35e6542d6
--- /dev/null
+++ b/packages/views/editor/attachment-link-cross-workspace.test.tsx
@@ -0,0 +1,205 @@
+/**
+ * A link can name a file from another workspace the reader belongs to. The
+ * link opener resolves it by attachment, and every request the viewer makes
+ * afterwards — text body, stream re-sign, Download — must target the
+ * workspace that owns it, not the current route's, or the server answers 404.
+ *
+ * Real viewer, real download hook, real link opener; only the API is mocked,
+ * and it answers the way the server does: an id-keyed request scoped to the
+ * wrong workspace is not found.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import type { Attachment, Workspace } from "@multica/core/types";
+import { workspaceKeys } from "@multica/core/workspace/queries";
+
+const CURRENT_WS = "aaaaaaaa-0000-4000-8000-000000000000";
+const OWNER_WS = "bbbbbbbb-0000-4000-8000-000000000000";
+const ID = "01a13179-08aa-7898-ae86-3a1994d2147e";
+const FORCED_URL = "https://cdn.example/x?response-content-disposition=attachment";
+
+const { api, openInNewTab } = vi.hoisted(() => ({
+ api: {
+ getBaseUrl: () => "",
+ getAttachmentForDownload: vi.fn(),
+ getAttachment: vi.fn(),
+ getAttachmentTextContent: vi.fn(),
+ getAttachmentBlob: vi.fn(),
+ },
+ openInNewTab: vi.fn(),
+}));
+
+vi.mock("@multica/core/api", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/api")>()),
+ api,
+}));
+
+vi.mock("@multica/core/paths", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@multica/core/paths")>()),
+ useWorkspaceSlug: () => "alpha",
+}));
+
+vi.mock("../navigation", () => ({
+ useAppOrigin: () => "https://app.example",
+ useNavigation: () => ({
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ pathname: "/alpha/issues/ALP-1",
+ searchParams: new URLSearchParams(),
+ hash: "",
+ openInNewTab,
+ getShareableUrl: (p: string) => `https://app.example${p}`,
+ }),
+}));
+
+// Every string renders as its key path, so the test can find controls by key.
+function keyPath(path: string[] = []): unknown {
+ return new Proxy(
+ {},
+ {
+ get: (_t, k) =>
+ k === Symbol.toPrimitive ? () => path.join(".") : keyPath([...path, String(k)]),
+ },
+ );
+}
+vi.mock("../i18n", () => ({
+ useT: () => ({ t: (sel: (s: unknown) => unknown) => String(sel(keyPath())) }),
+}));
+
+vi.mock("sonner", () => ({ toast: { error: vi.fn(), success: vi.fn() } }));
+
+vi.mock("./readonly-content", () => ({
+ ReadonlyContent: ({ content }: { content: string }) => (
+ <div data-testid="readonly-content">{content}</div>
+ ),
+}));
+
+import { useOpenAttachmentLink } from "./use-open-attachment-link";
+
+function record(overrides: Partial<Attachment>): Attachment {
+ return {
+ id: ID,
+ workspace_id: OWNER_WS,
+ issue_id: null,
+ comment_id: null,
+ uploader_type: "member",
+ uploader_id: "u",
+ filename: "notes.md",
+ url: `https://cdn.example/workspaces/${OWNER_WS}/${ID}.md`,
+ download_url: `https://cdn.example/workspaces/${OWNER_WS}/${ID}.md?Signature=s`,
+ attachment_download_url: FORCED_URL,
+ content_type: "text/markdown",
+ size_bytes: 12,
+ created_at: "2026-11-18T00:00:00Z",
+ ...overrides,
+ } as Attachment;
+}
+
+function notFound(): Promise<never> {
+ return Promise.reject(Object.assign(new Error("attachment not found"), { status: 404 }));
+}
+
+function ownerScoped(scope: unknown): boolean {
+ return (scope as { workspaceId?: string } | undefined)?.workspaceId === OWNER_WS;
+}
+
+function LinkOpener({ href }: { href: string }) {
+ const link = useOpenAttachmentLink();
+ return (
+ <>
+ <button type="button" onClick={() => link.open(href)}>
+ open link
+ </button>
+ {link.modal}
+ </>
+ );
+}
+
+function renderOpener(href: string) {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ client.setQueryData<Workspace[]>(workspaceKeys.list(), [
+ { id: CURRENT_WS, slug: "alpha" } as Workspace,
+ { id: OWNER_WS, slug: "bravo" } as Workspace,
+ ]);
+ return render(
+ <QueryClientProvider client={client}>
+ <LinkOpener href={href} />
+ </QueryClientProvider>,
+ );
+}
+
+let clickedDownloads: string[] = [];
+
+beforeEach(() => {
+ clickedDownloads = [];
+ vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function (this: HTMLAnchorElement) {
+ if (this.hasAttribute("download")) clickedDownloads.push(this.href);
+ });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ api.getAttachmentForDownload.mockReset();
+ api.getAttachment.mockReset();
+ api.getAttachmentTextContent.mockReset();
+ openInNewTab.mockReset();
+});
+
+describe("a link to another workspace's attachment", () => {
+ it("reads the text body and downloads from the owning workspace", async () => {
+ const att = record({});
+ api.getAttachmentForDownload.mockResolvedValue(att);
+ api.getAttachmentTextContent.mockImplementation((_id: string, scope?: unknown) =>
+ ownerScoped(scope) ? Promise.resolve({ text: "# Notes", originalContentType: "" }) : notFound(),
+ );
+ api.getAttachment.mockImplementation((_id: string, scope?: unknown) =>
+ ownerScoped(scope) ? Promise.resolve(att) : notFound(),
+ );
+ renderOpener(`/api/attachments/${ID}/download`);
+
+ fireEvent.click(screen.getByText("open link"));
+
+ expect(await screen.findByTestId("readonly-content")).toHaveTextContent("# Notes");
+ expect(api.getAttachmentTextContent).toHaveBeenCalledWith(ID, { workspaceId: OWNER_WS });
+
+ fireEvent.click(screen.getAllByRole("button", { name: /download/i })[0]!);
+
+ await waitFor(() => expect(clickedDownloads).toEqual([FORCED_URL]));
+ expect(api.getAttachment).toHaveBeenCalledWith(ID, { workspaceId: OWNER_WS });
+ });
+
+ it("re-signs a video's stream against the owning workspace", async () => {
+ const signed = `https://cdn.example/workspaces/${OWNER_WS}/${ID}.mp4?Signature=fresh`;
+ const att = record({ filename: "clip.mp4", content_type: "video/mp4", download_url: signed });
+ api.getAttachmentForDownload.mockResolvedValue(att);
+ api.getAttachment.mockImplementation((_id: string, scope?: unknown) =>
+ ownerScoped(scope) ? Promise.resolve(att) : notFound(),
+ );
+ renderOpener(`/api/attachments/${ID}/download`);
+
+ fireEvent.click(screen.getByText("open link"));
+
+ await waitFor(() => expect(document.querySelector("video")?.getAttribute("src")).toBe(signed));
+ expect(api.getAttachment).toHaveBeenCalledWith(ID, { workspaceId: OWNER_WS });
+ });
+
+ it("opens the full-page preview under the owning workspace", async () => {
+ api.getAttachmentForDownload.mockResolvedValue(record({ filename: "clip.mp4", content_type: "video/mp4" }));
+ api.getAttachment.mockImplementation(() => notFound());
+ renderOpener(`/api/attachments/${ID}/download`);
+
+ fireEvent.click(screen.getByText("open link"));
+ const openTab = await screen.findByRole("button", { name: /open_in_new_tab/ });
+ await act(async () => {
+ fireEvent.click(openTab);
+ });
+
+ expect(openInNewTab).toHaveBeenCalledWith(
+ expect.stringMatching(new RegExp(`^/bravo/attachments/${ID}/preview`)),
+ "clip.mp4",
+ { activate: true },
+ );
+ });
+});
diff --git a/packages/views/editor/attachment-preview-modal.test.tsx b/packages/views/editor/attachment-preview-modal.test.tsx
index 82a56aec36..f5cc35983e 100644
--- a/packages/views/editor/attachment-preview-modal.test.tsx
+++ b/packages/views/editor/attachment-preview-modal.test.tsx
@@ -337,7 +337,7 @@ describe("AttachmentPreviewModal — dispatch", () => {
const att = makeAttachment({ filename: "README.md", content_type: "text/markdown" });
render(<AttachmentPreviewModal source={{ kind: "full", attachment: att }} open onClose={() => {}} />);
- expect(getAttachmentTextContentMock).toHaveBeenCalledWith("att-1");
+ expect(getAttachmentTextContentMock).toHaveBeenCalledWith("att-1", { workspaceId: "ws-1" });
await waitFor(() => {
expect(screen.getByTestId("readonly-content")).toBeTruthy();
@@ -703,7 +703,7 @@ describe("AttachmentPreviewModal — streamed media (MUL-8892)", () => {
const att = staleVideo();
render(<AttachmentPreviewModal source={{ kind: "full", attachment: att }} open onClose={() => {}} />);
- expect(getAttachmentMock).toHaveBeenCalledWith("att-1");
+ expect(getAttachmentMock).toHaveBeenCalledWith("att-1", { workspaceId: "ws-1" });
expect(document.querySelector("video")).toBeNull();
expect(screen.getByText("Loading preview…")).toBeInTheDocument();
@@ -767,7 +767,7 @@ describe("AttachmentPreviewModal — streamed media (MUL-8892)", () => {
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");
+ expect(downloadMock).toHaveBeenCalledWith("att-1", "ws-1");
});
});
@@ -790,7 +790,7 @@ describe("AttachmentPreviewModal — controls", () => {
const buttons = screen.getAllByRole("button", { name: "Download" });
expect(buttons.length).toBeGreaterThan(0);
fireEvent.click(buttons[0]!);
- expect(downloadMock).toHaveBeenCalledWith("att-1");
+ expect(downloadMock).toHaveBeenCalledWith("att-1", "ws-1");
});
it("describes the file by type and size instead of its MIME type", () => {
@@ -1059,7 +1059,7 @@ describe("attachment preview download feedback", () => {
expect(button).toHaveAttribute("aria-busy", "true");
expect(button.querySelector(".animate-spin")).toBeInTheDocument();
fireEvent.click(button);
- expect(downloadMock).toHaveBeenCalledExactlyOnceWith(attachment.id);
+ expect(downloadMock).toHaveBeenCalledExactlyOnceWith(attachment.id, attachment.workspace_id);
await act(async () => pending.resolve());
@@ -1083,7 +1083,7 @@ describe("attachment preview download feedback", () => {
expect(button.querySelector(".animate-spin")).toBeInTheDocument();
fireEvent.click(button);
}
- expect(downloadMock).toHaveBeenCalledExactlyOnceWith(attachment.id);
+ expect(downloadMock).toHaveBeenCalledExactlyOnceWith(attachment.id, attachment.workspace_id);
await act(async () => pending.resolve());
});
@@ -1143,7 +1143,10 @@ describe("attachment preview download feedback", () => {
expect(button).toBeEnabled();
fireEvent.click(button);
- expect(downloadMock.mock.calls).toEqual([[first.id], [second.id]]);
+ expect(downloadMock.mock.calls).toEqual([
+ [first.id, first.workspace_id],
+ [second.id, second.workspace_id],
+ ]);
await act(async () => firstDownload.resolve());
expect(button).toBeDisabled();
await act(async () => secondDownload.resolve());
@@ -1842,7 +1845,7 @@ describe("AttachmentPreviewModal — expired cached image access", () => {
onImageError={onImageError}
/>,
);
- expect(getAttachmentMock).toHaveBeenCalledWith(att.id);
+ expect(getAttachmentMock).toHaveBeenCalledWith(att.id, { workspaceId: att.workspace_id });
expect(document.querySelector('img[src*="Signature=expired"]')).toBeNull();
expect(screen.getByText("Loading preview…")).toBeInTheDocument();
expect(onImageError).not.toHaveBeenCalled();
@@ -1943,7 +1946,7 @@ it.each(["pending", "denied"])(
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));
+ await waitFor(() => expect(getAttachmentMock).toHaveBeenCalledWith(b.id, { workspaceId: b.workspace_id }));
client.setQueryData(["attachment-inline-resign", a.id], a, {
updatedAt: Date.now() - 6 * 60 * 1000,
});
diff --git a/packages/views/editor/attachment-preview-modal.tsx b/packages/views/editor/attachment-preview-modal.tsx
index 9424d61d99..7b91c2440f 100644
--- a/packages/views/editor/attachment-preview-modal.tsx
+++ b/packages/views/editor/attachment-preview-modal.tsx
@@ -57,7 +57,9 @@ import {
X,
type IconComponent,
} from "@multica/ui/icons";
-import type { Attachment } from "@multica/core/types";
+import { useQueryClient } from "@tanstack/react-query";
+import type { Attachment, Workspace } from "@multica/core/types";
+import { workspaceKeys } from "@multica/core/workspace/queries";
import {
attachmentIdFromDownloadURL,
attachmentIdFromLocalUploadURL,
@@ -170,6 +172,12 @@ interface PreviewState {
contentType: string;
mediaUrl: string;
attachmentId: string | null;
+ /**
+ * Workspace that owns the attachment, when known. Id-keyed requests target
+ * it rather than the current route's workspace, so a file linked from
+ * another workspace the reader belongs to still previews and downloads.
+ */
+ workspaceId: string | null;
/** 0 when unknown (URL-only source). */
sizeBytes: number;
/**
@@ -202,6 +210,7 @@ function normalize(source: PreviewSource): PreviewState {
contentType: source.attachment.content_type,
mediaUrl: resolvePreviewMediaUrl(source.attachment),
attachmentId: source.attachment.id,
+ workspaceId: source.attachment.workspace_id || null,
sizeBytes: source.attachment.size_bytes,
kind: getPreviewKind(
source.attachment.content_type,
@@ -216,6 +225,7 @@ function normalize(source: PreviewSource): PreviewState {
attachmentId:
attachmentIdFromDownloadURL(source.url) ??
attachmentIdFromLocalUploadURL(source.url) ?? null,
+ workspaceId: null,
sizeBytes: 0,
kind: source.forceKind ?? getPreviewKind("", source.filename),
};
@@ -420,6 +430,7 @@ export function PreviewImagePrefetch({ source }: { source: PreviewSource }) {
metadataSource: source.kind === "url" && state.attachmentId
? "markdown-link"
: "workspace",
+ workspaceId: state.workspaceId ?? undefined,
},
);
@@ -478,6 +489,7 @@ export function AttachmentPreviewModal({
// useWorkspaceSlug (not useWorkspacePaths) — returns null outside a
// workspace route instead of throwing, so the new-tab button just hides.
const slug = useWorkspaceSlug();
+ const queryClient = useQueryClient();
const navigation = useNavigation();
// The html kind's current address, for "Open in new tab". Tagged with its
// file so one document's address never follows the reader to the next.
@@ -554,7 +566,7 @@ export function AttachmentPreviewModal({
const attachmentId =
state.attachmentId ?? attachmentIdFromStorageURL(state.mediaUrl, cdnDomain);
if (attachmentId) {
- return download(attachmentId);
+ return download(attachmentId, state.workspaceId ?? undefined);
}
return openExternal(state.mediaUrl);
};
@@ -562,9 +574,18 @@ export function AttachmentPreviewModal({
// Open-in-new-tab: the full-page route (/attachments/{id}/preview) shows
// every previewable kind, but loads the file by id — a URL-only source has
// none, and a file the viewer cannot show gains nothing from a tab.
- const canOpenInNewTab = kind !== null && !!slug && !!state.attachmentId;
+ // The route lives under the workspace that owns the file, which a file
+ // linked from another workspace does not share with the current page. A
+ // workspace missing from the reader's list has no route to open.
+ const ownerSlug = (() => {
+ if (!slug || !state.workspaceId) return slug;
+ const workspaces = queryClient.getQueryData<Workspace[]>(workspaceKeys.list());
+ if (!workspaces) return slug;
+ return workspaces.find((w) => w.id === state.workspaceId)?.slug ?? null;
+ })();
+ const canOpenInNewTab = kind !== null && !!ownerSlug && !!state.attachmentId;
const handleOpenInNewTab = () => {
- if (!slug || !state.attachmentId) return;
+ if (!ownerSlug || !state.attachmentId) return;
const address =
htmlAddressRef.current?.attachmentId === state.attachmentId
? htmlAddressRef.current.address
@@ -574,7 +595,7 @@ export function AttachmentPreviewModal({
address ? `loc=${encodeURIComponent(address)}` : "",
].filter(Boolean);
const query = params.length > 0 ? `?${params.join("&")}` : "";
- const path = `${paths.workspace(slug).attachmentPreview(state.attachmentId)}${query}`;
+ const path = `${paths.workspace(ownerSlug).attachmentPreview(state.attachmentId)}${query}`;
if (navigation.openInNewTab) {
navigation.openInNewTab(path, state.filename, { activate: true });
} else {
@@ -708,7 +729,7 @@ const renderViewerHtmlFrame: HtmlFrameRenderer = ({ html, title, location }) =>
// no tree to switch to. Shares the stage's query, so nothing is fetched twice.
function useStructuredParse(state: PreviewState, enabled: boolean) {
const format = enabled ? structuredFormat(state.contentType, state.filename) : null;
- const query = useAttachmentHtmlText(format ? state.attachmentId : null);
+ const query = useAttachmentHtmlText(format ? state.attachmentId : null, state.workspaceId);
const text = query.data?.text;
return useMemo(
() => (format && text !== undefined ? parseStructured(text, format) : null),
@@ -823,6 +844,7 @@ function PreviewPanel({
metadataSource: source.kind === "url" && state.attachmentId
? "markdown-link"
: "workspace",
+ workspaceId: state.workspaceId ?? undefined,
currentMetadata: kind === "image" ? currentImageMetadata : undefined,
},
);
@@ -856,6 +878,7 @@ function PreviewPanel({
state.mediaUrl,
kind === "video" || kind === "audio" || kind === "pdf",
kind === "pdf",
+ state.workspaceId,
);
const streamUrl = streamed.pending ? "" : streamed.url;
@@ -866,7 +889,10 @@ function PreviewPanel({
const canCopyImage = kind === "image" && isDesktopShell();
const canCopyText =
kind !== null && TEXT_BACKED_KINDS.has(kind) && (kind !== "html" || htmlSource);
- const copyContent = useAttachmentHtmlText(canCopyText ? state.attachmentId : null);
+ const copyContent = useAttachmentHtmlText(
+ canCopyText ? state.attachmentId : null,
+ state.workspaceId,
+ );
const handleCopyText = async () => {
if (!copyContent.data || copyContent.isError) return;
if (await copyText(copyContent.data.text)) {
@@ -1731,6 +1757,7 @@ function PreviewContent({
return (
<TextBackedPreview
attachmentId={state.attachmentId!}
+ workspaceId={state.workspaceId}
onDownload={onDownload}
downloading={downloading}
render={(text) => (
@@ -1748,6 +1775,7 @@ function PreviewContent({
return (
<TextBackedPreview
attachmentId={state.attachmentId!}
+ workspaceId={state.workspaceId}
onDownload={onDownload}
downloading={downloading}
render={(text) =>
@@ -1769,6 +1797,7 @@ function PreviewContent({
return (
<TextBackedPreview
attachmentId={state.attachmentId!}
+ workspaceId={state.workspaceId}
onDownload={onDownload}
downloading={downloading}
render={(text) => (
@@ -1785,6 +1814,7 @@ function PreviewContent({
return (
<TextBackedPreview
attachmentId={state.attachmentId!}
+ workspaceId={state.workspaceId}
onDownload={onDownload}
downloading={downloading}
render={(text) => {
@@ -1821,6 +1851,7 @@ function PreviewContent({
return (
<TextBackedPreview
attachmentId={state.attachmentId!}
+ workspaceId={state.workspaceId}
onDownload={onDownload}
downloading={downloading}
render={(text) => code(text, extensionToLanguage(state.filename))}
@@ -1864,17 +1895,19 @@ function DocumentSheet({
// is much longer than any plausible preview session.
function TextBackedPreview({
attachmentId,
+ workspaceId,
onDownload,
downloading,
render,
}: {
attachmentId: string;
+ workspaceId: string | null;
onDownload: () => void;
downloading: boolean;
render: (text: string) => ReactNode;
}) {
const { t } = useT("editor");
- const query = useAttachmentHtmlText(attachmentId);
+ const query = useAttachmentHtmlText(attachmentId, workspaceId);
if (query.isLoading) return <PreviewLoading />;
if (query.error) {
diff --git a/packages/views/editor/content-editor.test.tsx b/packages/views/editor/content-editor.test.tsx
index e008273616..b84bb8527c 100644
--- a/packages/views/editor/content-editor.test.tsx
+++ b/packages/views/editor/content-editor.test.tsx
@@ -1,6 +1,7 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
import { createRef, useState } from "react";
+import { createPortal } from "react-dom";
import type { Attachment } from "@multica/core/types";
import type { UploadResult } from "@multica/core/hooks/use-file-upload";
@@ -80,6 +81,21 @@ vi.mock("./attachment-download-context", () => ({
},
}));
+const openAttachmentLinkMock = vi.hoisted(() => vi.fn((_href: string) => false));
+const attachmentLinkModal = vi.hoisted<{ current: React.ReactNode }>(() => ({ current: null }));
+const attachmentLinkRecords = vi.hoisted<{ current?: ReadonlyArray<Attachment> }>(() => ({}));
+vi.mock("./use-open-attachment-link", () => ({
+ useOpenAttachmentLink: (attachments?: ReadonlyArray<Attachment>) => {
+ // The hover card inside the editor calls it too, without records.
+ if (attachments) attachmentLinkRecords.current = attachments;
+ return {
+ resolve: () => undefined,
+ open: openAttachmentLinkMock,
+ modal: attachmentLinkModal.current,
+ };
+ },
+}));
+
const editorRef = vi.hoisted<{ current: unknown }>(() => ({ current: null }));
const onCreateFired = vi.hoisted(() => ({ value: false }));
// Transaction listeners registered via `editor.on("transaction", …)`. The
@@ -154,6 +170,7 @@ vi.mock("@tiptap/react", () => ({
}));
import { ContentEditor, type ContentEditorRef } from "./content-editor";
+import { NavigationProvider, type NavigationAdapter } from "../navigation";
describe("ContentEditor", () => {
beforeEach(() => {
@@ -167,6 +184,7 @@ describe("ContentEditor", () => {
onCreateFired.value = false;
latestEditorOptions.current = undefined;
providerProps.attachments = undefined;
+ attachmentLinkRecords.current = undefined;
capturedExtOptions.current = undefined;
preprocessMarkdownMock.mockImplementation((value: string) => value);
});
@@ -196,6 +214,116 @@ describe("ContentEditor", () => {
expect(shell).toHaveClass("min-w-0");
});
+ describe("link clicks", () => {
+ type DomHandler = (view: unknown, event: MouseEvent) => boolean;
+ const domHandler = (name: "click" | "auxclick") =>
+ (latestEditorOptions.current as unknown as {
+ editorProps: { handleDOMEvents: Record<string, DomHandler> };
+ }).editorProps.handleDOMEvents[name]!;
+ const clickOn = (href: string, init: MouseEventInit = {}) => {
+ const anchor = document.createElement("a");
+ anchor.setAttribute("href", href);
+ document.body.appendChild(anchor);
+ const event = new MouseEvent("click", { bubbles: true, cancelable: true, ...init });
+ Object.defineProperty(event, "target", { value: anchor });
+ return event;
+ };
+ const cdnVideo =
+ "https://static.example/workspaces/0e0e0e0e-0000-4000-8000-000000000000/01a13179-08aa-7898-ae86-3a1994d2147e.mp4";
+ const desktopNavigation = {
+ push: vi.fn(),
+ replace: vi.fn(),
+ back: vi.fn(),
+ pathname: "/acme/issues",
+ searchParams: new URLSearchParams(),
+ hash: "",
+ getShareableUrl: (path: string) => `https://app.example${path}`,
+ openInNewTab: vi.fn(),
+ } as unknown as NavigationAdapter;
+
+ it("opens an attachment link in the app instead of the browser", () => {
+ openAttachmentLinkMock.mockReturnValueOnce(true);
+ const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
+ render(<ContentEditor />);
+
+ expect(domHandler("click")({}, clickOn(cdnVideo))).toBe(true);
+
+ expect(openAttachmentLinkMock).toHaveBeenCalledWith(cdnVideo);
+ expect(openSpy).not.toHaveBeenCalled();
+ openSpy.mockRestore();
+ });
+
+ // Web: a modified or middle click keeps opening the link in a new
+ // browser tab, as it did before attachment links opened the viewer.
+ it.each([
+ ["Cmd-click", "click", { metaKey: true }],
+ ["Ctrl-click", "click", { ctrlKey: true }],
+ ["Shift-click", "click", { shiftKey: true }],
+ ["middle click", "auxclick", { button: 1 }],
+ ] as const)("leaves a web %s on an attachment link to the browser", (_label, name, init) => {
+ const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
+ render(<ContentEditor />);
+
+ domHandler(name)({}, clickOn(cdnVideo, init));
+
+ expect(openAttachmentLinkMock).not.toHaveBeenCalled();
+ expect(openSpy).toHaveBeenCalledWith(cdnVideo, "_blank", "noopener,noreferrer");
+ openSpy.mockRestore();
+ });
+
+ // Desktop has no browser tab to give, so those clicks open in the app too.
+ it.each([
+ ["Cmd-click", "click", { metaKey: true }],
+ ["middle click", "auxclick", { button: 1 }],
+ ] as const)("opens a desktop %s on an attachment link in the app", (_label, name, init) => {
+ openAttachmentLinkMock.mockReturnValueOnce(true);
+ const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
+ render(
+ <NavigationProvider value={desktopNavigation}>
+ <ContentEditor />
+ </NavigationProvider>,
+ );
+
+ expect(domHandler(name)({}, clickOn(cdnVideo, init))).toBe(true);
+
+ expect(openAttachmentLinkMock).toHaveBeenCalledWith(cdnVideo);
+ expect(openSpy).not.toHaveBeenCalled();
+ openSpy.mockRestore();
+ });
+
+ it("still opens a regular link in the browser", () => {
+ const openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
+ render(<ContentEditor />);
+
+ domHandler("click")({}, clickOn("https://github.com/multica-ai/multica"));
+
+ expect(openSpy).toHaveBeenCalledWith(
+ "https://github.com/multica-ai/multica",
+ "_blank",
+ "noopener,noreferrer",
+ );
+ openSpy.mockRestore();
+ });
+ });
+
+ it("ignores presses that bubble out of a portaled overlay", () => {
+ // React delivers a portal's events to its React parent — the editor shell
+ // — although the press landed outside the shell's DOM.
+ attachmentLinkModal.current = createPortal(
+ <div data-testid="overlay-surface" />,
+ document.body,
+ );
+ try {
+ render(<ContentEditor placeholder="Add description..." />);
+
+ fireEvent.mouseDown(screen.getAllByTestId("overlay-surface")[0]!);
+
+ expect(mockFocus).not.toHaveBeenCalled();
+ } finally {
+ attachmentLinkModal.current = null;
+ }
+ });
+
it("does not hijack clicks that land inside the ProseMirror node", () => {
render(<ContentEditor placeholder="Add description..." />);
@@ -854,6 +982,39 @@ describe("ContentEditor — in-session attachment tracking (MUL-3192)", () => {
expect(providerProps.attachments?.[0]?.id).toBe("uploaded-1");
});
+ // The editor runs its own hooks above the provider it renders, so the link
+ // opener cannot read the provider: it must get the same records directly,
+ // or a legacy storage link to a record the editor holds opens raw.
+ it("hands attachment links the same records as the provider, uploads included", async () => {
+ const seeded = makeAttachment("seed-1");
+ let capturedHandler: ((file: File) => Promise<UploadResult | null>) | undefined;
+ uploadAndInsertFileMock.mockImplementation(
+ async (_editor: unknown, file: File, handler: typeof capturedHandler) => {
+ capturedHandler = handler;
+ await handler?.(file);
+ },
+ );
+ let imperativeRef: { uploadFile: (file: File) => void } | null = null;
+ render(
+ <ContentEditor
+ attachments={[seeded]}
+ onUploadFile={async () => asUploadResult(makeAttachment("uploaded-1"))}
+ ref={(r) => {
+ imperativeRef = r;
+ }}
+ />,
+ );
+ expect(attachmentLinkRecords.current).toEqual([seeded]);
+
+ await act(async () => {
+ imperativeRef?.uploadFile(new File(["payload"], "clip.mp4", { type: "video/mp4" }));
+ });
+
+ expect(capturedHandler).toBeTypeOf("function");
+ expect(attachmentLinkRecords.current?.map((a) => a.id)).toEqual(["seed-1", "uploaded-1"]);
+ expect(attachmentLinkRecords.current).toBe(providerProps.attachments);
+ });
+
it("merges in-session uploads with the caller's attachments prop, preferring the prop on id collision", async () => {
// The pre-loaded record carries a freshly-signed download_url; the
// upload result for the same id has an older download_url. After merge
diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsx
index 1a199e0dba..992db8578b 100644
--- a/packages/views/editor/content-editor.tsx
+++ b/packages/views/editor/content-editor.tsx
@@ -66,12 +66,13 @@ import {
import { configStore } from "@multica/core/config";
import { preprocessMarkdown } from "./utils/preprocess";
import { repairEmptyListItems } from "./utils/repair-list-items";
-import { resolveClickIntent, useAppOrigin } from "../navigation";
+import { resolveClickIntent, useAppOrigin, useOptionalNavigation } from "../navigation";
import { openLink, isMentionHref } from "./utils/link-handler";
import { EditorBubbleMenu } from "./bubble-menu";
import { posFromAnchor, type TextAnchor } from "./text-anchor";
import { insertDictation } from "./utils/insert-dictation";
import { useLinkHover, LinkHoverCard } from "./link-hover-card";
+import { useOpenAttachmentLink } from "./use-open-attachment-link";
import { AttachmentDownloadProvider } from "./attachment-download-context";
import "katex/dist/katex.min.css";
import "./styles/index.css";
@@ -520,6 +521,18 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
const appOriginRef = useRef(appOrigin);
appOriginRef.current = appOrigin;
+ // A link to one of this deployment's attachments opens in the viewer
+ // rather than as a raw storage URL in the browser. This component renders
+ // the AttachmentDownloadProvider itself, so its records are passed in.
+ const attachmentLink = useOpenAttachmentLink(providerAttachments);
+ const openAttachmentLinkRef = useRef(attachmentLink.open);
+ openAttachmentLinkRef.current = attachmentLink.open;
+ // `openInNewTab` present means Desktop, which has no browser tab to give a
+ // modified or middle click; on web those still open the link in one.
+ const desktopTabs = !!useOptionalNavigation()?.openInNewTab;
+ const desktopTabsRef = useRef(desktopTabs);
+ desktopTabsRef.current = desktopTabs;
+
// Keep refs in sync without recreating editor
onUpdateRef.current = onUpdate;
onSubmitRef.current = onSubmit;
@@ -685,6 +698,13 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
if (!href || isMentionHref(href)) return false;
event.preventDefault();
+ const modified = event.metaKey || event.ctrlKey || event.shiftKey;
+ if (
+ (desktopTabsRef.current || !modified) &&
+ openAttachmentLinkRef.current(href)
+ ) {
+ return true;
+ }
openLink(
href,
workspaceSlugRef.current,
@@ -703,6 +723,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
const href = target.closest("a")?.getAttribute("href");
if (!href || isMentionHref(href)) return false;
event.preventDefault();
+ if (desktopTabsRef.current && openAttachmentLinkRef.current(href)) return true;
openLink(
href,
workspaceSlugRef.current,
@@ -1035,6 +1056,9 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
if (!editor) return;
const target = event.target as HTMLElement;
+ // React events bubble through portals: a press inside an overlay (the
+ // attachment viewer) is not a press on the editor's empty area.
+ if (!event.currentTarget.contains(target)) return;
if (target.closest(".ProseMirror")) return;
if (target.closest("a, button, input, textarea, [role='button'], [data-node-view-wrapper]")) return;
@@ -1056,6 +1080,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(
<EditorBubbleMenu editor={editor} currentIssueId={currentIssueId} selectionAction={selectionAction} />
)}
<LinkHoverCard {...hover} />
+ {attachmentLink.modal}
</div>
</AttachmentDownloadProvider>
);
diff --git a/packages/views/editor/hooks/use-attachment-html-text.ts b/packages/views/editor/hooks/use-attachment-html-text.ts
index 0a525650b3..ccdf367135 100644
--- a/packages/views/editor/hooks/use-attachment-html-text.ts
+++ b/packages/views/editor/hooks/use-attachment-html-text.ts
@@ -14,10 +14,20 @@
import { useQuery } from "@tanstack/react-query";
import { api } from "@multica/core/api";
-export function useAttachmentHtmlText(attachmentId: string | null | undefined) {
+/**
+ * `workspaceId` is the workspace that owns the attachment, when it may differ
+ * from the current route's (a file linked from another workspace).
+ */
+export function useAttachmentHtmlText(
+ attachmentId: string | null | undefined,
+ workspaceId?: string | null,
+) {
return useQuery({
queryKey: ["attachment-content", attachmentId ?? ""] as const,
- queryFn: () => api.getAttachmentTextContent(attachmentId as string),
+ queryFn: () =>
+ workspaceId
+ ? api.getAttachmentTextContent(attachmentId as string, { workspaceId })
+ : api.getAttachmentTextContent(attachmentId as string),
enabled: !!attachmentId,
// 413 / 415 won't become 200 on retry; a transport error is easier to
// recover from by re-opening than waiting on background retries with
diff --git a/packages/views/editor/hooks/use-inline-media-url.ts b/packages/views/editor/hooks/use-inline-media-url.ts
index e02f90835c..fb2b807d3f 100644
--- a/packages/views/editor/hooks/use-inline-media-url.ts
+++ b/packages/views/editor/hooks/use-inline-media-url.ts
@@ -92,10 +92,13 @@ export function useResignedInlineMedia(
{
refreshOnMount = false,
metadataSource = "workspace",
+ workspaceId,
currentMetadata,
}: {
refreshOnMount?: boolean;
metadataSource?: "workspace" | "markdown-link";
+ /** Workspace that owns the attachment, when it may not be the current one. */
+ workspaceId?: string;
currentMetadata?: Attachment;
} = {},
): { url: string; pending: boolean; failed: boolean } {
@@ -126,7 +129,9 @@ export function useResignedInlineMedia(
: ["attachment-inline-resign", resignAttachmentId],
queryFn: () => metadataSource === "markdown-link"
? api.getAttachmentForDownload(resignAttachmentId as string)
- : api.getAttachment(resignAttachmentId as string),
+ : workspaceId
+ ? api.getAttachment(resignAttachmentId as string, { workspaceId })
+ : api.getAttachment(resignAttachmentId as string),
enabled: needsResign && !currentMetadata,
staleTime: refreshOnMount ? PREVIEW_RESIGN_STALE_MS : RESIGN_STALE_MS,
gcTime: RESIGN_STALE_MS,
@@ -226,6 +231,7 @@ export function useFreshStreamedMediaURL(
rawPickedUrl: string,
enabled: boolean,
pdf = false,
+ workspaceId?: string | null,
): { url: string; pending: boolean; failed: boolean; refreshIfExpired: () => Promise<boolean> } {
const pickedUrl = resolveLegacyLocalMediaURL(rawPickedUrl);
const id = attachmentId ?? attachmentIdFromDownloadURL(pickedUrl);
@@ -233,7 +239,10 @@ export function useFreshStreamedMediaURL(
const stablePDFURL = id ? absolutizeAPIPath(attachmentDownloadPath(id)) : "";
const { data: fresh, error, isError, refetch } = useQuery({
queryKey: ["attachment-stream-resign", id],
- queryFn: () => api.getAttachment(id as string),
+ queryFn: () =>
+ workspaceId
+ ? api.getAttachment(id as string, { workspaceId })
+ : api.getAttachment(id as string),
enabled: active,
staleTime: Infinity,
gcTime: 0,
diff --git a/packages/views/editor/link-hover-card.tsx b/packages/views/editor/link-hover-card.tsx
index e314090330..e0f53e076c 100644
--- a/packages/views/editor/link-hover-card.tsx
+++ b/packages/views/editor/link-hover-card.tsx
@@ -21,6 +21,7 @@ import { useAppOrigin } from "../navigation";
import { useT } from "../i18n";
import { openLink, isMentionHref } from "./utils/link-handler";
import { useEditorOverlayOwner } from "./overlay-owner";
+import { useOpenAttachmentLink } from "./use-open-attachment-link";
function truncateUrl(url: string, max = 48): string {
if (url.length <= max) return url;
@@ -145,6 +146,7 @@ function LinkHoverCard({
const appOrigin = useAppOrigin();
const { t } = useT("editor");
const overlayOwner = useEditorOverlayOwner();
+ const attachmentLink = useOpenAttachmentLink();
// Position the card when the portal div is mounted (ref callback).
// Using useEffect would race with portal rendering — the div might
@@ -173,8 +175,6 @@ function LinkHoverCard({
if (!visible) setPositioned(false);
}, [visible]);
- if (!visible || !anchorEl) return null;
-
const handleCopy = async (e: React.MouseEvent) => {
e.stopPropagation();
e.preventDefault();
@@ -188,50 +188,61 @@ function LinkHoverCard({
const handleOpen = (e: React.MouseEvent) => {
e.stopPropagation();
e.preventDefault();
+ if (attachmentLink.open(href)) return;
openLink(href, slug, appOrigin);
};
- return createPortal(
- <div
- ref={setCardRef}
- className="link-hover-card"
- data-editor-overlay-owner={overlayOwner}
- style={{
- position: "fixed",
- top: pos.top,
- left: pos.left,
- zIndex: 50,
- display: positioned ? undefined : "none",
- }}
- onMouseEnter={onCardEnter}
- onMouseLeave={onCardLeave}
- >
- <span
- className="min-w-0 flex-1 truncate text-caption text-muted-foreground px-1"
- title={href}
- >
- {truncateUrl(href)}
- </span>
- <IconButton
- size="icon-xs"
- variant="ghost"
- className="text-muted-foreground"
- onClick={handleCopy}
- label={t(($) => $.link_hover.copy_link)}
- >
- <Copy className="size-3.5" />
- </IconButton>
- <IconButton
- size="icon-xs"
- variant="ghost"
- className="text-muted-foreground"
- onClick={handleOpen}
- label={t(($) => $.link_hover.open_link)}
- >
- <ExternalLink className="size-3.5" />
- </IconButton>
- </div>,
- document.body,
+ // The viewer keeps one position in the tree whether or not the card shows:
+ // the card hides as soon as the pointer leaves it, which must not remount
+ // the viewer opened from it.
+ return (
+ <>
+ {attachmentLink.modal}
+ {visible && anchorEl
+ ? createPortal(
+ <div
+ ref={setCardRef}
+ className="link-hover-card"
+ data-editor-overlay-owner={overlayOwner}
+ style={{
+ position: "fixed",
+ top: pos.top,
+ left: pos.left,
+ zIndex: 50,
+ display: positioned ? undefined : "none",
+ }}
+ onMouseEnter={onCardEnter}
+ onMouseLeave={onCardLeave}
+ >
+ <span
+ className="min-w-0 flex-1 truncate text-caption text-muted-foreground px-1"
+ title={href}
+ >
+ {truncateUrl(href)}
+ </span>
+ <IconButton
+ size="icon-xs"
+ variant="ghost"
+ className="text-muted-foreground"
+ onClick={handleCopy}
+ label={t(($) => $.link_hover.copy_link)}
+ >
+ <Copy className="size-3.5" />
+ </IconButton>
+ <IconButton
+ size="icon-xs"
+ variant="ghost"
+ className="text-muted-foreground"
+ onClick={handleOpen}
+ label={t(($) => $.link_hover.open_link)}
+ >
+ <ExternalLink className="size-3.5" />
+ </IconButton>
+ </div>,
+ document.body,
+ )
+ : null}
+ </>
);
}
diff --git a/packages/views/editor/use-download-attachment.ts b/packages/views/editor/use-download-attachment.ts
index f73457896b..df1a0d1535 100644
--- a/packages/views/editor/use-download-attachment.ts
+++ b/packages/views/editor/use-download-attachment.ts
@@ -113,18 +113,25 @@ function hasDesktopDownloadBridge(): boolean {
*/
export function useDownloadAttachment(
source: "workspace" | "markdown-link" = "workspace",
-): (attachmentId: string) => Promise<void> {
+): (attachmentId: string, workspaceId?: string) => Promise<void> {
const { t } = useT("editor");
const workspaceSlug = useWorkspaceSlug();
+ const fetchMetadata = useCallback(
+ (attachmentId: string, workspaceId: string | undefined) => {
+ if (source === "markdown-link") return api.getAttachmentForDownload(attachmentId);
+ return workspaceId
+ ? api.getAttachment(attachmentId, { workspaceId })
+ : api.getAttachment(attachmentId);
+ },
+ [source],
+ );
return useCallback(
- async (attachmentId: string) => {
+ async (attachmentId: string, workspaceId?: string) => {
const failed = () => toast.error(t(($) => $.attachment.download_failed));
if (hasDesktopDownloadBridge()) {
try {
- const fresh = await (source === "markdown-link"
- ? api.getAttachmentForDownload(attachmentId)
- : api.getAttachment(attachmentId));
+ const fresh = await fetchMetadata(attachmentId, workspaceId);
// Prefer the forced-attachment URL (Content-Disposition: attachment in
// every storage mode) so the native save writes the file rather than
// opening media inline; fall back to the load-intent `download_url` for
@@ -155,9 +162,7 @@ export function useDownloadAttachment(
// failures still produce the existing toast instead of a silent failed
// navigation) and where the server hands back the download URLs it mints
// for this response.
- const fresh = await (source === "markdown-link"
- ? api.getAttachmentForDownload(attachmentId)
- : api.getAttachment(attachmentId));
+ const fresh = await fetchMetadata(attachmentId, workspaceId);
if (typeof document === "undefined") {
failed();
return;
@@ -196,6 +201,6 @@ export function useDownloadAttachment(
failed();
}
},
- [t, workspaceSlug, source],
+ [t, workspaceSlug, fetchMetadata],
);
}
diff --git a/packages/views/editor/use-open-attachment-link.test.tsx b/packages/views/editor/use-open-attachment-link.test.tsx
new file mode 100644
index 0000000000..d9523ae77b
--- /dev/null
+++ b/packages/views/editor/use-open-attachment-link.test.tsx
@@ -0,0 +1,164 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { act, renderHook } from "@testing-library/react";
+import type { Attachment } from "@multica/core/types";
+
+const { getAttachmentForDownload, openAt, tryOpen, download, toastError } = vi.hoisted(() => ({
+ getAttachmentForDownload: vi.fn(),
+ openAt: vi.fn(() => false),
+ tryOpen: vi.fn(() => true),
+ download: vi.fn(),
+ toastError: vi.fn(),
+}));
+
+vi.mock("@multica/core/api", () => ({
+ api: { getBaseUrl: () => "https://api.example", getAttachmentForDownload },
+}));
+vi.mock("@multica/core/config", () => ({
+ useConfigStore: (select: (s: { attachmentPublicUrl: string; cdnDomain: string }) => unknown) =>
+ select({ attachmentPublicUrl: "https://files.example", cdnDomain: "static.example" }),
+}));
+vi.mock("../navigation", () => ({ useAppOrigin: () => "https://app.example" }));
+vi.mock("../i18n", () => ({ useT: () => ({ t: () => "Download failed" }) }));
+vi.mock("sonner", () => ({ toast: { error: toastError } }));
+vi.mock("./preview-sequence-context", () => ({ usePreviewSequence: () => ({ openAt }) }));
+vi.mock("./attachment-preview-modal", () => ({
+ useAttachmentPreview: () => ({ open: vi.fn(), tryOpen, modal: null }),
+}));
+vi.mock("./use-download-attachment", () => ({ useDownloadAttachment: () => download }));
+
+import { resolveAttachmentLinkId, useOpenAttachmentLink } from "./use-open-attachment-link";
+
+const ID = "01a13179-08aa-7898-ae86-3a1994d2147e";
+const WS = "0e0e0e0e-0000-4000-8000-000000000000";
+
+const CTX = {
+ appOrigin: "https://app.example",
+ attachmentPublicUrl: "https://files.example",
+ cdnDomain: "static.example",
+};
+
+function record(overrides: Partial<Attachment> = {}): Attachment {
+ return {
+ id: ID,
+ filename: "demo.mp4",
+ content_type: "video/mp4",
+ url: `https://legacy-bucket.s3.amazonaws.com/${WS}/demo.mp4`,
+ download_url: "",
+ size_bytes: 1,
+ ...overrides,
+ } as Attachment;
+}
+
+describe("resolveAttachmentLinkId", () => {
+ it.each([
+ ["a site-relative download URL", `/api/attachments/${ID}/download`],
+ ["a download URL on the app origin", `https://app.example/api/attachments/${ID}/download`],
+ ["a download URL on the public attachment origin", `https://files.example/api/attachments/${ID}/download`],
+ ["a download URL on the API origin", `https://api.example/api/attachments/${ID}/download`],
+ ["a storage URL on the CDN", `https://static.example/workspaces/${WS}/${ID}.mp4`],
+ ["a signed storage URL on the CDN", `https://static.example/workspaces/${WS}/${ID}.mp4?Signature=x&Key-Pair-Id=k`],
+ ["a local upload URL", `/uploads/workspaces/${WS}/${ID}.mp4`],
+ ])("resolves %s", (_label, href) => {
+ expect(resolveAttachmentLinkId(href, CTX)).toBe(ID);
+ });
+
+ it.each([
+ ["another deployment's download URL", `https://other.example/api/attachments/${ID}/download`],
+ ["a credentialed download URL", `https://user:[email protected]/api/attachments/${ID}/download`],
+ ["a storage path on another host", `https://other.example/workspaces/${WS}/${ID}.mp4`],
+ ["a non-attachment path on the CDN", "https://static.example/marketing/launch.mp4"],
+ ["an external link", "https://github.com/multica-ai/multica"],
+ ["an empty href", ""],
+ ])("leaves %s alone", (_label, href) => {
+ expect(resolveAttachmentLinkId(href, CTX)).toBeUndefined();
+ });
+
+ it("matches a legacy storage URL against the surface's records", () => {
+ const att = record();
+ expect(resolveAttachmentLinkId(att.url, { ...CTX, attachments: [att] })).toBe(ID);
+ expect(resolveAttachmentLinkId(att.url, CTX)).toBeUndefined();
+ });
+});
+
+describe("useOpenAttachmentLink", () => {
+ const cdnLink = `https://static.example/workspaces/${WS}/${ID}.mp4`;
+
+ beforeEach(() => {
+ getAttachmentForDownload.mockReset();
+ openAt.mockReset().mockReturnValue(false);
+ tryOpen.mockReset().mockReturnValue(true);
+ download.mockReset();
+ toastError.mockReset();
+ });
+
+ it("resolves a legacy storage URL against records the caller passes in", async () => {
+ const att = record();
+ getAttachmentForDownload.mockResolvedValue(att);
+ const { result } = renderHook(() => useOpenAttachmentLink([att]));
+
+ await act(async () => {
+ expect(result.current.open(att.url)).toBe(true);
+ });
+
+ expect(getAttachmentForDownload).toHaveBeenCalledWith(ID);
+ });
+
+ it("does nothing for a regular link", () => {
+ const { result } = renderHook(() => useOpenAttachmentLink());
+ expect(result.current.open("https://github.com/multica-ai/multica")).toBe(false);
+ expect(openAt).not.toHaveBeenCalled();
+ expect(getAttachmentForDownload).not.toHaveBeenCalled();
+ });
+
+ it("opens the file at its place in the surface's viewer, pinned to it", async () => {
+ openAt.mockReturnValue(true);
+ const { result } = renderHook(() => useOpenAttachmentLink());
+
+ await act(async () => {
+ expect(result.current.open(cdnLink)).toBe(true);
+ });
+
+ expect(openAt).toHaveBeenCalledWith(ID, { stayOnError: true });
+ expect(getAttachmentForDownload).not.toHaveBeenCalled();
+ });
+
+ it("opens a file outside the surface in the standalone viewer with fresh metadata", async () => {
+ const fresh = record({ download_url: `${cdnLink}?Signature=fresh` });
+ getAttachmentForDownload.mockResolvedValue(fresh);
+ const { result } = renderHook(() => useOpenAttachmentLink());
+
+ await act(async () => {
+ result.current.open(cdnLink);
+ });
+
+ expect(tryOpen).toHaveBeenCalledWith({ kind: "full", attachment: fresh });
+ expect(download).not.toHaveBeenCalled();
+ });
+
+ it("downloads a file the viewer cannot show", async () => {
+ getAttachmentForDownload.mockResolvedValue(
+ record({ filename: "bundle.zip", content_type: "application/zip" }),
+ );
+ tryOpen.mockReturnValue(false);
+ const { result } = renderHook(() => useOpenAttachmentLink());
+
+ await act(async () => {
+ result.current.open(cdnLink);
+ });
+
+ expect(download).toHaveBeenCalledWith(ID);
+ });
+
+ it("reports a failed lookup", async () => {
+ getAttachmentForDownload.mockRejectedValue(new Error("403"));
+ const { result } = renderHook(() => useOpenAttachmentLink());
+
+ await act(async () => {
+ result.current.open(cdnLink);
+ });
+
+ expect(toastError).toHaveBeenCalledWith("Download failed");
+ expect(tryOpen).not.toHaveBeenCalled();
+ expect(download).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/views/editor/use-open-attachment-link.tsx b/packages/views/editor/use-open-attachment-link.tsx
new file mode 100644
index 0000000000..24bf328723
--- /dev/null
+++ b/packages/views/editor/use-open-attachment-link.tsx
@@ -0,0 +1,170 @@
+"use client";
+
+/**
+ * Open a link that points at one of this deployment's attachments inside the
+ * app — the surface's viewer, the standalone preview, or a download — instead
+ * of handing the raw storage URL to the browser (MUL-9566).
+ *
+ * A plain link is how agents and pasted content most often reference a file:
+ * `[demo.mp4](https://static.multica.ai/workspaces/<ws>/<id>.mp4)` written
+ * inline, a bare CDN URL that linkify turned into an anchor, or the stable
+ * `/api/attachments/<id>/download` URL. Opened as an ordinary link, a video
+ * lands on the CDN host's native player in a fresh tab with no history, and a
+ * signed CDN rejects the bare URL outright. Every link entry point (readonly
+ * content, the editor, the hover card's Open button) goes through here first
+ * and only falls back to `openLink` when the href is not an attachment.
+ */
+
+import { useCallback, type ReactNode } from "react";
+import { toast } from "sonner";
+import { api } from "@multica/core/api";
+import { matchAttachmentByURL } from "@multica/core/attachments/image-sequence";
+import { useConfigStore } from "@multica/core/config";
+import type { Attachment } from "@multica/core/types";
+import {
+ attachmentIdFromDownloadURL,
+ attachmentIdFromLocalUploadURL,
+ attachmentIdFromStorageURL,
+} from "@multica/core/types/attachment-url";
+import { useAppOrigin } from "../navigation";
+import { useT } from "../i18n";
+import { useAttachmentDownloadResolver } from "./attachment-download-context";
+import { useAttachmentPreview } from "./attachment-preview-modal";
+import { usePreviewSequence } from "./preview-sequence-context";
+import { useDownloadAttachment } from "./use-download-attachment";
+
+export interface AttachmentLinkContext {
+ /** The app's public origin (`useAppOrigin`). */
+ appOrigin: string | null;
+ /** Origin the server persists attachment URLs under (`/api/config`). */
+ attachmentPublicUrl: string;
+ /** Storage CDN hostname (`/api/config`). */
+ cdnDomain: string;
+ /** Records of the surrounding surface, for legacy exact-URL references. */
+ attachments?: ReadonlyArray<Attachment>;
+}
+
+/**
+ * Id of the attachment `href` points at on THIS deployment; `undefined` for
+ * anything else.
+ *
+ * The `/api/attachments/<id>/download` and `/uploads/workspaces/...` path
+ * shapes alone do not establish which deployment owns a link: another Multica
+ * instance uses the same shapes with unrelated ids. They count only when
+ * site-relative or on one of this deployment's own origins. A storage URL is
+ * recognized by the configured CDN hostname. A record of the surrounding
+ * surface matches on exact URL, which covers legacy bodies that persisted a
+ * storage URL on another host (direct S3).
+ */
+export function resolveAttachmentLinkId(
+ href: string,
+ ctx: AttachmentLinkContext,
+): string | undefined {
+ if (!href) return undefined;
+ const pathId = attachmentIdFromDownloadURL(href) ?? attachmentIdFromLocalUploadURL(href);
+ if (pathId && isOwnOrigin(href, ctx)) return pathId;
+ const storageId = attachmentIdFromStorageURL(href, ctx.cdnDomain);
+ if (storageId) return storageId;
+ const record = matchAttachmentByURL(href, ctx.attachments);
+ return record?.id;
+}
+
+function isOwnOrigin(href: string, ctx: AttachmentLinkContext): boolean {
+ if (href.startsWith("/") && !href.startsWith("//")) return true;
+ // PublicURL can differ from both the web app origin and the browser's
+ // same-origin API proxy, so all three count as this deployment.
+ try {
+ const target = new URL(href);
+ if (target.username || target.password) return false;
+ const ownOrigins = [ctx.appOrigin, api.getBaseUrl?.(), ctx.attachmentPublicUrl];
+ return ownOrigins.some((base) => {
+ if (!base) return false;
+ try {
+ return new URL(base).origin === target.origin;
+ } catch {
+ return false;
+ }
+ });
+ } catch {
+ return false;
+ }
+}
+
+export interface OpenAttachmentLinkHandle {
+ /** The attachment id `href` points at, or `undefined` when it is a regular link. */
+ resolve: (href: string) => string | undefined;
+ /**
+ * Open the attachment `href` points at inside the app. Returns false — and
+ * does nothing — when `href` is not an attachment of this deployment, so the
+ * caller falls back to its regular link handling.
+ */
+ open: (href: string) => boolean;
+ /** Render this for the standalone preview. */
+ modal: ReactNode;
+}
+
+/**
+ * `attachments` are records a caller holds outside any surrounding
+ * `AttachmentDownloadProvider` — a component that renders the provider itself
+ * runs its own hooks above it. They match alongside the provider's records.
+ */
+export function useOpenAttachmentLink(
+ attachments?: ReadonlyArray<Attachment>,
+): OpenAttachmentLinkHandle {
+ const { t } = useT("editor");
+ const appOrigin = useAppOrigin();
+ const attachmentPublicUrl = useConfigStore((s) => s.attachmentPublicUrl);
+ const cdnDomain = useConfigStore((s) => s.cdnDomain);
+ const { resolveAttachment } = useAttachmentDownloadResolver();
+ const { openAt } = usePreviewSequence();
+ const preview = useAttachmentPreview();
+ const { tryOpen } = preview;
+ const download = useDownloadAttachment("markdown-link");
+
+ const resolve = useCallback(
+ (href: string) => {
+ const surfaceRecord = resolveAttachment(href);
+ return resolveAttachmentLinkId(href, {
+ appOrigin,
+ attachmentPublicUrl,
+ cdnDomain,
+ attachments: surfaceRecord ? [surfaceRecord, ...(attachments ?? [])] : attachments,
+ });
+ },
+ [resolveAttachment, attachments, appOrigin, attachmentPublicUrl, cdnDomain],
+ );
+
+ const openById = useCallback(
+ async (attachmentId: string) => {
+ // The link names this file: if it fails to load, stay on it and say so
+ // rather than showing the reader a different one.
+ if (openAt(attachmentId, { stayOnError: true })) return;
+ let record: Attachment;
+ try {
+ // Fresh metadata: the record carries the content type the viewer
+ // dispatches on and a newly signed URL to play from. Resolved by the
+ // attachment, not the current workspace, as a pasted link may come
+ // from another one.
+ record = await api.getAttachmentForDownload(attachmentId);
+ } catch {
+ toast.error(t(($) => $.attachment.download_failed));
+ return;
+ }
+ if (record.id && tryOpen({ kind: "full", attachment: record })) return;
+ await download(attachmentId);
+ },
+ [openAt, tryOpen, download, t],
+ );
+
+ const open = useCallback(
+ (href: string) => {
+ const attachmentId = resolve(href);
+ if (!attachmentId) return false;
+ void openById(attachmentId);
+ return true;
+ },
+ [resolve, openById],
+ );
+
+ return { resolve, open, modal: preview.modal };
+}
diff --git a/packages/views/rich-content/app-url-link-routing.test.tsx b/packages/views/rich-content/app-url-link-routing.test.tsx
index 139bc35cae..1fe3774578 100644
--- a/packages/views/rich-content/app-url-link-routing.test.tsx
+++ b/packages/views/rich-content/app-url-link-routing.test.tsx
@@ -13,6 +13,7 @@ import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
import { act, render, screen } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { configStore } from "@multica/core/config";
+import type { Attachment } from "@multica/core/types";
const APP_ORIGIN = "https://app.example";
@@ -47,14 +48,44 @@ vi.mock("../editor/link-hover-card", () => ({
}));
// Intercepted-attachment-link click handler. A plain `<a>` to the API-host
-// attachment endpoint cannot authenticate a bare navigation (WK-11), so the
-// renderer must hand the click to this hook instead of `window.open`. We mock
-// the module so the test asserts the dispatch, not the download plumbing.
+// attachment endpoint cannot authenticate a bare navigation (WK-11), and a raw
+// CDN link lands on the storage host's media page (MUL-9566), so the renderer
+// opens the file in the viewer and downloads only what the viewer cannot show.
+// The download hook is mocked so the test asserts the dispatch, not the
+// download plumbing.
const downloadAttachmentSpy = vi.fn();
vi.mock("../editor/use-download-attachment", () => ({
useDownloadAttachment: () => downloadAttachmentSpy,
}));
+const getAttachmentForDownload = vi.hoisted(() => vi.fn());
+vi.mock("@multica/core/api", () => ({
+ api: { getBaseUrl: () => "", getAttachmentForDownload },
+}));
+
+const toastError = vi.hoisted(() => vi.fn());
+vi.mock("sonner", () => ({ toast: { error: toastError, success: vi.fn() } }));
+
+const CDN_DOMAIN = "static.example";
+const WS_ID = "0e0e0e0e-0000-4000-8000-000000000000";
+
+function attachmentRecord(id: string, filename: string, contentType: string): Attachment {
+ return {
+ id,
+ workspace_id: WS_ID,
+ issue_id: null,
+ comment_id: null,
+ uploader_type: "member",
+ uploader_id: "u",
+ filename,
+ url: `https://${CDN_DOMAIN}/workspaces/${WS_ID}/${id}`,
+ download_url: `https://${CDN_DOMAIN}/workspaces/${WS_ID}/${id}?Signature=s`,
+ content_type: contentType,
+ size_bytes: 1024,
+ created_at: "2026-11-18T00:00:00Z",
+ } as Attachment;
+}
+
vi.mock("mermaid", () => ({
default: { initialize: vi.fn(), render: vi.fn() },
}));
@@ -68,6 +99,7 @@ beforeEach(() => {
navigatedPaths = [];
act(() => {
configStore.getState().setAttachmentPublicUrl("https://multica-api.erlinerd.com");
+ configStore.getState().setCdnConfig({ cdnDomain: CDN_DOMAIN });
});
window.addEventListener("multica:navigate", captureNavigate);
openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
@@ -77,8 +109,11 @@ afterEach(() => {
window.removeEventListener("multica:navigate", captureNavigate);
vi.restoreAllMocks();
downloadAttachmentSpy.mockClear();
+ getAttachmentForDownload.mockReset();
+ toastError.mockClear();
act(() => {
configStore.getState().setAttachmentPublicUrl("");
+ configStore.getState().setCdnConfig({ cdnDomain: "" });
});
});
@@ -152,33 +187,98 @@ describe("RichContent link routing", () => {
// WK-11: a plain-link attachment download URL (the shape `buildMarkdownURL`
// persists into bodies in private-storage deployments — absolute, API-host
- // pinned) cannot authenticate a bare navigation, so it must be routed through
- // the credentialed download hook rather than window.open.
- it("routes a UUID attachment download link through the download hook (WK-11)", () => {
+ // pinned) cannot authenticate a bare navigation, so it must never reach
+ // window.open. A file the viewer cannot show downloads through the
+ // credentialed hook.
+ it("downloads a non-previewable attachment link through the download hook (WK-11)", async () => {
const id = "01a13179-08aa-7898-ae86-3a1994d2147e";
const download = `https://multica-api.erlinerd.com/api/attachments/${id}/download`;
- renderContent(`[audit-report.md](${download})`);
+ getAttachmentForDownload.mockResolvedValue(attachmentRecord(id, "audit.zip", "application/zip"));
+ renderContent(`[audit.zip](${download})`);
- screen.getByText("audit-report.md").click();
+ screen.getByText("audit.zip").click();
- // Not opened as an unauthenticated external navigation, and not treated as
- // an in-app path.
+ await vi.waitFor(() => expect(downloadAttachmentSpy).toHaveBeenCalledWith(id));
+ expect(getAttachmentForDownload).toHaveBeenCalledWith(id);
expect(openSpy).not.toHaveBeenCalled();
expect(navigatedPaths).toEqual([]);
- expect(downloadAttachmentSpy).toHaveBeenCalledWith(id);
});
- it("recognizes the API-host link when runtime config arrives after rendering", () => {
+ it("recognizes the API-host link when runtime config arrives after rendering", async () => {
const id = "01a13179-08aa-7898-ae86-3a1994d2147e";
const download = `https://multica-api.erlinerd.com/api/attachments/${id}/download`;
+ getAttachmentForDownload.mockResolvedValue(attachmentRecord(id, "report.zip", "application/zip"));
act(() => configStore.getState().setAttachmentPublicUrl(""));
- renderContent(`[report.pdf](${download})`);
+ renderContent(`[report.zip](${download})`);
act(() => configStore.getState().setAttachmentPublicUrl("https://multica-api.erlinerd.com"));
- screen.getByText("report.pdf").click();
+ screen.getByText("report.zip").click();
+
+ await vi.waitFor(() => expect(downloadAttachmentSpy).toHaveBeenCalledWith(id));
+ expect(openSpy).not.toHaveBeenCalled();
+ });
+
+ // MUL-9566: a video link played on the storage host's native page, in a tab
+ // with no way back into the app. It plays in the viewer instead.
+ it("plays a video download link in the viewer", async () => {
+ const id = "01a13179-08aa-7898-ae86-3a1994d2147e";
+ getAttachmentForDownload.mockResolvedValue(attachmentRecord(id, "demo.mp4", "video/mp4"));
+ renderContent(`[demo.mp4](/api/attachments/${id}/download)`);
+
+ screen.getByText("demo.mp4").click();
+
+ expect(await screen.findByRole("dialog", { name: "demo.mp4" })).toBeTruthy();
+ expect(openSpy).not.toHaveBeenCalled();
+ expect(downloadAttachmentSpy).not.toHaveBeenCalled();
+ });
+
+ it("plays an inline CDN video link in the viewer instead of opening the raw URL", async () => {
+ const id = "01a13179-08aa-7898-ae86-3a1994d2147e";
+ const cdnUrl = `https://${CDN_DOMAIN}/workspaces/${WS_ID}/${id}.mp4`;
+ getAttachmentForDownload.mockResolvedValue(attachmentRecord(id, "demo.mp4", "video/mp4"));
+ // Inline, so it stays a link rather than becoming a file card.
+ renderContent(`The recording: [demo.mp4](${cdnUrl}) — have a look.`);
- expect(downloadAttachmentSpy).toHaveBeenCalledWith(id);
+ screen.getByText("demo.mp4").click();
+
+ expect(await screen.findByRole("dialog", { name: "demo.mp4" })).toBeTruthy();
+ expect(getAttachmentForDownload).toHaveBeenCalledWith(id);
+ expect(openSpy).not.toHaveBeenCalled();
+ });
+
+ it("plays a bare CDN video URL in the viewer", async () => {
+ const id = "01a13179-08aa-7898-ae86-3a1994d2147e";
+ const cdnUrl = `https://${CDN_DOMAIN}/workspaces/${WS_ID}/${id}.mp4`;
+ getAttachmentForDownload.mockResolvedValue(attachmentRecord(id, "demo.mp4", "video/mp4"));
+ renderContent(`Recording at ${cdnUrl} for review.`);
+
+ screen.getByText(cdnUrl).click();
+
+ expect(await screen.findByRole("dialog", { name: "demo.mp4" })).toBeTruthy();
+ expect(openSpy).not.toHaveBeenCalled();
+ });
+
+ it("reports a failed lookup instead of falling back to the raw URL", async () => {
+ const id = "01a13179-08aa-7898-ae86-3a1994d2147e";
+ const cdnUrl = `https://${CDN_DOMAIN}/workspaces/${WS_ID}/${id}.mp4`;
+ getAttachmentForDownload.mockRejectedValue(new Error("403"));
+ renderContent(`See [demo.mp4](${cdnUrl}) here.`);
+
+ screen.getByText("demo.mp4").click();
+
+ await vi.waitFor(() => expect(toastError).toHaveBeenCalled());
expect(openSpy).not.toHaveBeenCalled();
+ expect(downloadAttachmentSpy).not.toHaveBeenCalled();
+ });
+
+ it("keeps a non-attachment path on the CDN host external", () => {
+ const other = `https://${CDN_DOMAIN}/marketing/launch.mp4`;
+ renderContent(`See [launch](${other}) here.`);
+
+ screen.getByText("launch").click();
+
+ expect(getAttachmentForDownload).not.toHaveBeenCalled();
+ expect(openSpy).toHaveBeenCalledWith(other, "_blank", "noopener,noreferrer");
});
it("does not intercept a non-UUID /api/attachments link", () => {
diff --git a/packages/views/rich-content/rich-content.tsx b/packages/views/rich-content/rich-content.tsx
index 5a1aa3f70b..4429cf2ddf 100644
--- a/packages/views/rich-content/rich-content.tsx
+++ b/packages/views/rich-content/rich-content.tsx
@@ -42,9 +42,7 @@ import rehypeSanitize from "rehype-sanitize";
import { cn } from "@multica/ui/lib/utils";
import { useWorkspaceSlug } from "@multica/core/paths";
import { useConfigStore } from "@multica/core/config";
-import { api } from "@multica/core/api";
import type { Attachment } from "@multica/core/types";
-import { attachmentIdFromDownloadURL } from "@multica/core/types";
import {
isAllowedFileCardHref,
isIssueIdentifier,
@@ -69,7 +67,7 @@ import {
import { preprocessMarkdown } from "../editor/utils/preprocess";
import { highlightToHtml } from "../editor/utils/highlight-markdown";
import { AttachmentDownloadProvider } from "../editor/attachment-download-context";
-import { useDownloadAttachment } from "../editor/use-download-attachment";
+import { useOpenAttachmentLink } from "../editor/use-open-attachment-link";
import { Attachment as AttachmentRenderer } from "../editor/attachment";
import { computeClosedFences, type ClosedFence } from "./streaming-fence";
import { remarkRepairCjkStrongTrailingWhitespace } from "./cjk-emphasis";
@@ -207,40 +205,10 @@ function unfurlableEntityLink(
return entity;
}
-function ownAttachmentDownloadId(
- href: string,
- appOrigin: string | null,
- attachmentPublicUrl: string,
-): string | undefined {
- const id = attachmentIdFromDownloadURL(href);
- if (!id) return undefined;
- if (href.startsWith("/") && !href.startsWith("//")) return id;
-
- // The path and UUID alone do not establish which deployment owns a link.
- // PublicURL can differ from both the web app origin and the browser's
- // same-origin API proxy, so the server supplies that origin via /api/config.
- try {
- const target = new URL(href);
- if (target.username || target.password) return undefined;
- const ownOrigins = [appOrigin, api.getBaseUrl?.(), attachmentPublicUrl];
- return ownOrigins.some((base) => {
- if (!base) return false;
- try {
- return new URL(base).origin === target.origin;
- } catch {
- return false;
- }
- }) ? id : undefined;
- } catch {
- return undefined;
- }
-}
-
function RichLink({ href, children }: { href?: string; children?: ReactNode }) {
const slug = useWorkspaceSlug();
const appOrigin = useAppOrigin();
- const attachmentPublicUrl = useConfigStore((s) => s.attachmentPublicUrl);
- const downloadAttachment = useDownloadAttachment("markdown-link");
+ const attachmentLink = useOpenAttachmentLink();
// Platform probe only: `openInNewTab` present means desktop, where native
// anchor behavior is a dead end and every click must be intercepted. Absent
// (web), modified clicks are left to the browser — the only way to get a
@@ -251,22 +219,15 @@ function RichLink({ href, children }: { href?: string; children?: ReactNode }) {
return <span className="slash-command">{children}</span>;
}
- // An attachment download URL written as a plain link — the shape the
- // server persists into bodies via `buildMarkdownURL`, which in private-
- // storage deployments is ABSOLUTE and pinned to the API host
- // (`MULTICA_PUBLIC_URL`). A bare navigation there cannot authenticate:
- // web's session cookie is host-locked to the API origin and
- // SameSite=Strict (and Desktop/mobile carry a bearer token no <a> can
- // send), so the browser gets `401 missing authorization`. Route through
- // the download hook instead, which refreshes the authenticated metadata
- // and navigates to the credential-bearing URL the server mints for this
- // click (capability / presign / CloudFront, per deployment mode). Same
- // click-time re-sign the file-card renderer already does (MUL-3130).
- // Also require this deployment's origin; another Multica instance may use
- // the same path shape with unrelated attachment IDs.
- const attachmentId = href
- ? ownAttachmentDownloadId(href, appOrigin, attachmentPublicUrl)
- : undefined;
+ // A link to one of this deployment's attachments — the stable download URL
+ // `buildMarkdownURL` persists, or a raw storage URL on the CDN. A bare
+ // navigation there either cannot authenticate (the API host's session
+ // cookie is host-locked and SameSite=Strict; Desktop/mobile carry a bearer
+ // token no <a> can send) or lands on the CDN's native media page in a tab
+ // with no way back into the app. The file opens in the app's viewer
+ // instead, and one the viewer cannot show downloads through the
+ // credentialed download hook.
+ const isAttachmentLink = href ? !!attachmentLink.resolve(href) : false;
if (isMentionHref(href)) {
const match = href.match(/^mention:\/\/(member|agent|issue|project|all)\/(.+)$/);
@@ -302,21 +263,16 @@ function RichLink({ href, children }: { href?: string; children?: ReactNode }) {
e.preventDefault();
return;
}
- // An attachment link downloads through the re-sign path instead of a
- // credential-less navigation (see attachmentId note above). This holds
- // on every platform: web's session cookie is host-locked to the API
- // origin and SameSite=Strict, and Desktop/mobile carry a bearer token
- // no <a> can send, so a bare navigation 401s either way. The download
- // hook owns the per-platform mechanism (capability anchor on web,
- // native bridge on Desktop). Modified clicks stay native — the browser
- // owns "open in background tab" and the raw URL remains the durable
- // reference.
- if (attachmentId && !e.metaKey && !e.ctrlKey && !e.shiftKey) {
+ // Modified clicks on web stay native — the browser owns "open in
+ // background tab" and the raw URL remains the durable reference.
+ // Desktop has no such tab to give, so every click opens in the app.
+ const modified = e.metaKey || e.ctrlKey || e.shiftKey;
+ if (isAttachmentLink && (desktopTabs || !modified)) {
e.preventDefault();
- void downloadAttachment(attachmentId);
+ attachmentLink.open(href);
return;
}
- if (!desktopTabs && (e.metaKey || e.ctrlKey || e.shiftKey)) return;
+ if (!desktopTabs && modified) return;
e.preventDefault();
openLink(href, slug, appOrigin, resolveClickIntent(e));
}}
@@ -327,6 +283,7 @@ function RichLink({ href, children }: { href?: string; children?: ReactNode }) {
// (denied, then dropped by the http/https allowlist), so route it.
if (!desktopTabs) return;
e.preventDefault();
+ if (attachmentLink.open(href)) return;
openLink(href, slug, appOrigin, "background-tab");
}}
>
@@ -334,6 +291,17 @@ function RichLink({ href, children }: { href?: string; children?: ReactNode }) {
</a>
);
+ // The viewer renders beside the anchor, not in it: React events bubble
+ // through portals, so clicks inside the viewer would reach the anchor.
+ if (isAttachmentLink) {
+ return (
+ <>
+ {plainLink}
+ {attachmentLink.modal}
+ </>
+ );
+ }
+
// A bare in-app entity URL renders as the chip its mention form would.
const entity = href
? unfurlableEntityLink(href, children, slug, appOrigin)