Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(attachments): re-sign CloudFront download URLs at click time (#2407)
Bohan Jiang352e838b01fa
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex 29e10b9b32..304d3df430 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -144,4 +144,59 @@ describe("ApiClient", () => {expect(headers["X-Client-Version"]).toBeUndefined();expect(headers["X-Client-OS"]).toBeUndefined();});++ describe("getAttachment", () => {+ it("returns the parsed attachment for a well-formed response", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ id: "att-1",+ workspace_id: "ws-1",+ issue_id: null,+ comment_id: null,+ uploader_type: "member",+ uploader_id: "u-1",+ filename: "report.md",+ url: "https://static.example.test/ws/att-1.md",+ download_url:+ "https://static.example.test/ws/att-1.md?Policy=p&Signature=s&Key-Pair-Id=k",+ content_type: "text/markdown",+ size_bytes: 123,+ created_at: "2026-05-11T00:00:00Z",+ }),+ { status: 200, headers: { "Content-Type": "application/json" } },+ ),+ ),+ );++ const client = new ApiClient("https://api.example.test");+ const att = await client.getAttachment("att-1");++ expect(att.id).toBe("att-1");+ expect(att.download_url).toContain("Policy=");+ });++ it("falls back to an empty attachment when the response is missing download_url", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ id: "att-1" }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ ),+ );++ const client = new ApiClient("https://api.example.test");+ const att = await client.getAttachment("att-1");++ // parseWithFallback returns the EMPTY_ATTACHMENT record so callers can+ // safely read `download_url` without crashing — they'll see "" and+ // surface a user-facing error instead of opening `undefined`.+ expect(att.id).toBe("");+ expect(att.download_url).toBe("");+ });+ });});diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 52bb43cbae..1399b90dca 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -88,8 +88,10 @@ import { createRequestId } from "../utils";import { getCurrentSlug } from "../platform/workspace-storage";import { parseWithFallback } from "./schema";import {+ AttachmentResponseSchema,ChildIssuesResponseSchema,CommentsListSchema,+ EMPTY_ATTACHMENT,EMPTY_LIST_ISSUES_RESPONSE,EMPTY_TIMELINE_ENTRIES,ListIssuesResponseSchema,@@ -1099,6 +1101,17 @@ export class ApiClient {return this.fetch(`/api/issues/${issueId}/attachments`);}+ // Fetches a fresh attachment metadata record. The server re-signs+ // `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}`);+ return parseWithFallback(raw, AttachmentResponseSchema, EMPTY_ATTACHMENT, {+ endpoint: "GET /api/attachments/{id}",+ });+ }+async deleteAttachment(id: string): Promise<void> {await this.fetch(`/api/attachments/${id}`, { method: "DELETE" });}diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 1c402acd95..a2047738f8 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -1,5 +1,5 @@import { z } from "zod";-import type { ListIssuesResponse, TimelineEntry } from "../types";+import type { Attachment, ListIssuesResponse, TimelineEntry } from "../types";// ---------------------------------------------------------------------------// Schemas for the highest-risk API endpoints — those whose responses drive@@ -38,10 +38,40 @@ const ReactionSchema = z.object({created_at: z.string(),});+// Nested attachments embedded in timeline/comment responses stay lenient on+// purpose: a single malformed attachment must not knock the whole timeline+// into the fallback `[]`.const AttachmentSchema = z.object({id: z.string(),}).loose();+// Standalone attachment lookup (`GET /api/attachments/{id}`) is the source of+// truth for click-time download URLs. The two fields the download flow opens+// in a new tab — `download_url` and `url` — must be strings, otherwise we'd+// happily `window.open(undefined)`. `filename` gates the toast/title and is+// also enforced so a missing value falls back to the empty record below.+export const AttachmentResponseSchema = z.object({+ id: z.string(),+ url: z.string(),+ download_url: z.string(),+ filename: z.string(),+}).loose();++export const EMPTY_ATTACHMENT: Attachment = {+ id: "",+ workspace_id: "",+ issue_id: null,+ comment_id: null,+ uploader_type: "",+ uploader_id: "",+ filename: "",+ url: "",+ download_url: "",+ content_type: "",+ size_bytes: 0,+ created_at: "",+};+// All object schemas use `.loose()` so unknown server-side fields pass// through unchanged. zod 4's `.object()` defaults to STRIP, which would// silently drop new fields and surface as a "field neither showed up indiff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.tsindex 9d449b8516..0e479b491b 100644--- a/packages/core/issues/queries.ts+++ b/packages/core/issues/queries.ts@@ -28,6 +28,10 @@ export const issueKeys = {subscribers: (issueId: string) =>["issues", "subscribers", issueId] as const,usage: (issueId: string) => ["issues", "usage", issueId] as const,+ /** Issue-level attachments — used by the description editor so its+ * inline file-card / image NodeViews can re-sign download URLs at+ * click time. */+ attachments: (issueId: string) => ["issues", "attachments", issueId] as const,/** Per-issue task list (issue-detail Execution log section). */tasks: (issueId: string) => ["issues", "tasks", issueId] as const,/** Prefix-match key for invalidating tasks across all issues — used by@@ -169,3 +173,14 @@ export function issueUsageOptions(issueId: string) {queryFn: () => api.getIssueUsage(issueId),});}++// Backs the description editor's fresh-sign download flow: NodeViews resolve+// an attachment id by matching the markdown URL against this list. The list+// is workspace-private metadata and lives on the same cache lifetime as the+// rest of the issue detail surface.+export function issueAttachmentsOptions(issueId: string) {+ return queryOptions({+ queryKey: issueKeys.attachments(issueId),+ queryFn: () => api.listAttachments(issueId),+ });+}diff --git a/packages/views/editor/attachment-download-context.tsx b/packages/views/editor/attachment-download-context.tsxnew file mode 100644index 0000000000..3321ceb507--- /dev/null+++ b/packages/views/editor/attachment-download-context.tsx@@ -0,0 +1,77 @@+"use client";++import { createContext, useContext, useMemo, type ReactNode } from "react";+import type { Attachment } from "@multica/core/types";+import { openExternal } from "../platform";+import { useDownloadAttachment } from "./use-download-attachment";++interface ResolvedDownload {+ // Returns the attachment id for a URL referenced in the markdown, or+ // `undefined` if it's an external link we don't manage.+ resolveAttachmentId: (url: string) => string | undefined;+ // Called by NodeView click handlers. Re-signs through `getAttachment` when+ // the URL maps to a known attachment; falls back to `openExternal` for+ // external URLs so Electron still routes through the IPC bridge instead of+ // letting `window.open` hit the `setWindowOpenHandler` deny path.+ openByUrl: (url: string) => void;+}++const AttachmentDownloadContext = createContext<ResolvedDownload | null>(null);++interface ProviderProps {+ attachments?: Attachment[];+ children: ReactNode;+}++/**+ * Provides a click-time download handler to Tiptap NodeViews mounted inside+ * `ContentEditor`. Without a provider the consumer falls back to opening the+ * raw URL via `openExternal` — same behaviour as before this hook existed.+ */+export function AttachmentDownloadProvider({ attachments, children }: ProviderProps) {+ const download = useDownloadAttachment();+ const value = useMemo<ResolvedDownload>(+ () => ({+ resolveAttachmentId: (url) => {+ if (!url || !attachments?.length) return undefined;+ return attachments.find((a) => a.url === url)?.id;+ },+ openByUrl: (url) => {+ const id = url && attachments?.length+ ? attachments.find((a) => a.url === url)?.id+ : undefined;+ if (id) {+ download(id);+ return;+ }+ if (url) openExternal(url);+ },+ }),+ [attachments, download],+ );+ return (+ <AttachmentDownloadContext.Provider value={value}>+ {children}+ </AttachmentDownloadContext.Provider>+ );+}++/**+ * Returns the click-time download handler installed by a surrounding+ * `AttachmentDownloadProvider`, or a fallback that just opens the raw URL+ * externally. Used by file-card and image NodeViews so they can stay+ * usable in editor surfaces that haven't been wired up yet.+ */+export function useAttachmentDownloadResolver(): ResolvedDownload {+ const ctx = useContext(AttachmentDownloadContext);+ // Hooks-must-be-unconditional: always create the fallback object, but+ // memoization is unnecessary here because each NodeView render also+ // re-runs the click handler closure.+ if (ctx) return ctx;+ return {+ resolveAttachmentId: () => undefined,+ openByUrl: (url) => {+ if (url) openExternal(url);+ },+ };+}diff --git a/packages/views/editor/content-editor.tsx b/packages/views/editor/content-editor.tsxindex 1457c64b88..c7eae59917 100644--- a/packages/views/editor/content-editor.tsx+++ b/packages/views/editor/content-editor.tsx@@ -42,12 +42,14 @@ import { cn } from "@multica/ui/lib/utils";import type { UploadResult } from "@multica/core/hooks/use-file-upload";import { useWorkspaceSlug } from "@multica/core/paths";import { useQueryClient } from "@tanstack/react-query";+import type { Attachment } from "@multica/core/types";import { createEditorExtensions } from "./extensions";import { uploadAndInsertFile } from "./extensions/file-upload";import { preprocessMarkdown } from "./utils/preprocess";import { openLink, isMentionHref } from "./utils/link-handler";import { EditorBubbleMenu } from "./bubble-menu";import { useLinkHover, LinkHoverCard } from "./link-hover-card";+import { AttachmentDownloadProvider } from "./attachment-download-context";import "katex/dist/katex.min.css";import "./content-editor.css";@@ -92,6 +94,15 @@ interface ContentEditorProps {* system prompts, where the content is fed to an LLM as plain text).*/disableMentions?: boolean;+ /**+ * Attachments referenced by this content. The download buttons on file+ * cards and images inside the editor look up an attachment by `url` and+ * fetch a fresh CloudFront signature at click time, so a stale URL+ * persisted in markdown never opens. Pass `issue.attachments` /+ * `comment.attachments` etc.; omit when no attachment context is+ * available (NodeView buttons fall back to opening the raw URL).+ */+ attachments?: Attachment[];}interface ContentEditorRef {@@ -126,6 +137,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(submitOnEnter = false,currentIssueId,disableMentions = false,+ attachments,},ref,) {@@ -257,17 +269,19 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(if (!editor) return null;return (- <div- ref={wrapperRef}- className="relative flex min-h-full flex-col"- onMouseDown={handleContainerMouseDown}- >- <EditorContent className="flex-1 min-h-full" editor={editor} />- {showBubbleMenu && (- <EditorBubbleMenu editor={editor} currentIssueId={currentIssueId} />- )}- <LinkHoverCard {...hover} />- </div>+ <AttachmentDownloadProvider attachments={attachments}>+ <div+ ref={wrapperRef}+ className="relative flex min-h-full flex-col"+ onMouseDown={handleContainerMouseDown}+ >+ <EditorContent className="flex-1 min-h-full" editor={editor} />+ {showBubbleMenu && (+ <EditorBubbleMenu editor={editor} currentIssueId={currentIssueId} />+ )}+ <LinkHoverCard {...hover} />+ </div>+ </AttachmentDownloadProvider>);},);diff --git a/packages/views/editor/extensions/file-card.tsx b/packages/views/editor/extensions/file-card.tsxindex dd00303d59..aa95c7cc86 100644--- a/packages/views/editor/extensions/file-card.tsx+++ b/packages/views/editor/extensions/file-card.tsx@@ -19,6 +19,7 @@ import { ReactNodeViewRenderer, NodeViewWrapper } from "@tiptap/react";import type { NodeViewProps } from "@tiptap/react";import { FileText, Loader2, Download } from "lucide-react";import { useT } from "../../i18n";+import { useAttachmentDownloadResolver } from "../attachment-download-context";// ---------------------------------------------------------------------------@@ -34,9 +35,10 @@ function FileCardView({ node }: NodeViewProps) {const href = (node.attrs.href as string) || "";const filename = (node.attrs.filename as string) || "";const uploading = node.attrs.uploading as boolean;+ const { openByUrl } = useAttachmentDownloadResolver();const openFile = () => {- window.open(href, "_blank", "noopener,noreferrer");+ openByUrl(href);};return (diff --git a/packages/views/editor/extensions/image-view.tsx b/packages/views/editor/extensions/image-view.tsxindex 4ddf06700e..4ed588218c 100644--- a/packages/views/editor/extensions/image-view.tsx+++ b/packages/views/editor/extensions/image-view.tsx@@ -13,6 +13,7 @@ import {import { toast } from "sonner";import { cn } from "@multica/ui/lib/utils";import { useT } from "../../i18n";+import { useAttachmentDownloadResolver } from "../attachment-download-context";// ---------------------------------------------------------------------------// Lightbox — full-screen image preview (ESC or click backdrop to close)@@ -61,6 +62,7 @@ function ImageView({ node, editor, selected, deleteNode }: NodeViewProps) {const alt = (node.attrs.alt as string) || "";const title = node.attrs.title as string | undefined;const uploading = node.attrs.uploading as boolean;+ const { openByUrl } = useAttachmentDownloadResolver();const [lightbox, setLightbox] = useState(false);const isEditable = editor.isEditable;@@ -70,8 +72,9 @@ function ImageView({ node, editor, selected, deleteNode }: NodeViewProps) {const handleDownload = () => {// Cross-origin CDN images can't be fetched as blob (CORS),// and <a download> is ignored for cross-origin URLs.- // Open in new tab — user can right-click → Save As.- window.open(src, "_blank", "noopener,noreferrer");+ // Re-sign through the provider when the src maps to a known+ // attachment; otherwise just open externally.+ openByUrl(src);};const handleCopyLink = async () => {diff --git a/packages/views/editor/index.ts b/packages/views/editor/index.tsindex a2e492c8b8..f360c59dee 100644--- a/packages/views/editor/index.ts+++ b/packages/views/editor/index.ts@@ -12,3 +12,5 @@ export { copyMarkdown } from "./utils/clipboard";export { ReadonlyContent } from "./readonly-content";export { useFileDropZone } from "./use-file-drop-zone";export { FileDropOverlay } from "./file-drop-overlay";+export { useDownloadAttachment } from "./use-download-attachment";+export { AttachmentDownloadProvider } from "./attachment-download-context";diff --git a/packages/views/editor/readonly-content.tsx b/packages/views/editor/readonly-content.tsxindex 7c559ce79a..e9ea02e4a0 100644--- a/packages/views/editor/readonly-content.tsx+++ b/packages/views/editor/readonly-content.tsx@@ -16,7 +16,7 @@* - Rendering mentions with the same IssueMentionCard component and .mention class*/-import { isValidElement, memo, useMemo, useRef, useState } from "react";+import { isValidElement, memo, useCallback, useMemo, useRef, useState } from "react";import ReactMarkdown, {defaultUrlTransform,type Components,@@ -34,14 +34,17 @@ import { Maximize2, Download, Link as LinkIcon, FileText } from "lucide-react";import { toast } from "sonner";import { cn } from "@multica/ui/lib/utils";import { useWorkspacePaths, useWorkspaceSlug } from "@multica/core/paths";+import type { Attachment } from "@multica/core/types";import { useNavigation } from "../navigation";import { useT } from "../i18n";+import { openExternal } from "../platform";import { IssueMentionCard } from "../issues/components/issue-mention-card";import { ImageLightbox } from "./extensions/image-view";import { useLinkHover, LinkHoverCard } from "./link-hover-card";import { openLink, isMentionHref } from "./utils/link-handler";import { preprocessMarkdown } from "./utils/preprocess";import { MermaidDiagram } from "./mermaid-diagram";+import { useDownloadAttachment } from "./use-download-attachment";import "katex/dist/katex.min.css";import "./content-editor.css";@@ -160,139 +163,209 @@ function ReadonlyLink({);}-const components: Partial<Components> = {- // Links — route mention:// to mention components, others show preview card- a: ReadonlyLink,-- // Images — centered with toolbar + lightbox (matches Tiptap ImageView NodeView)- img: function ReadonlyImage({ src, alt }) {- const { t } = useT("editor");- const [lightbox, setLightbox] = useState(false);- const imgSrc = typeof src === "string" ? src : "";- const imgAlt = alt ?? "";-- const handleView = () => setLightbox(true);- const handleDownload = () => {- window.open(imgSrc, "_blank", "noopener,noreferrer");- };- const handleCopyLink = async () => {- try {- await navigator.clipboard.writeText(imgSrc);- toast.success(t(($) => $.image.link_copied));- } catch {- toast.error(t(($) => $.image.copy_link_failed));- }- };-- return (- <span className="image-node">- <span className="image-figure" onClick={handleView}>- <img src={imgSrc} alt={imgAlt} className="image-content" draggable={false} />- <span- className="image-toolbar"- onMouseDown={(e) => e.stopPropagation()}- onClick={(e) => e.stopPropagation()}- >- <button type="button" onClick={handleView} title={t(($) => $.image.view)}>- <Maximize2 className="size-3.5" />- </button>- <button type="button" onClick={handleDownload} title={t(($) => $.image.download)}>- <Download className="size-3.5" />- </button>- <button type="button" onClick={handleCopyLink} title={t(($) => $.image.copy_link)}>- <LinkIcon className="size-3.5" />- </button>- </span>+// Image renderer with a download button that prefers fresh-signed URLs.+// Lifted out of the components map so it can call hooks; receives the+// attachment lookup as props so the components map can stay a pure+// data-build inside `ReadonlyContent`'s `useMemo`.+function ReadonlyImage({+ src,+ alt,+ resolveAttachmentId,+ onDownload,+}: {+ src?: string;+ alt?: string;+ resolveAttachmentId: (url: string) => string | undefined;+ onDownload: (attachmentId: string) => void;+}) {+ const { t } = useT("editor");+ const [lightbox, setLightbox] = useState(false);+ const imgSrc = typeof src === "string" ? src : "";+ const imgAlt = alt ?? "";++ const handleView = () => setLightbox(true);+ const handleDownload = () => {+ const id = imgSrc ? resolveAttachmentId(imgSrc) : undefined;+ if (id) {+ onDownload(id);+ return;+ }+ // External image — no attachment record to re-sign through. Falling back+ // to `openExternal` keeps us off `window.open(...)` (which Electron's+ // setWindowOpenHandler would route through openExternalSafely anyway,+ // but only after rejecting non-http schemes loudly).+ if (imgSrc) openExternal(imgSrc);+ };+ const handleCopyLink = async () => {+ try {+ await navigator.clipboard.writeText(imgSrc);+ toast.success(t(($) => $.image.link_copied));+ } catch {+ toast.error(t(($) => $.image.copy_link_failed));+ }+ };++ return (+ <span className="image-node">+ <span className="image-figure" onClick={handleView}>+ <img src={imgSrc} alt={imgAlt} className="image-content" draggable={false} />+ <span+ className="image-toolbar"+ onMouseDown={(e) => e.stopPropagation()}+ onClick={(e) => e.stopPropagation()}+ >+ <button type="button" onClick={handleView} title={t(($) => $.image.view)}>+ <Maximize2 className="size-3.5" />+ </button>+ <button type="button" onClick={handleDownload} title={t(($) => $.image.download)}>+ <Download className="size-3.5" />+ </button>+ <button type="button" onClick={handleCopyLink} title={t(($) => $.image.copy_link)}>+ <LinkIcon className="size-3.5" />+ </button></span>- {lightbox && (- <ImageLightbox src={imgSrc} alt={imgAlt} onClose={() => setLightbox(false)} />- )}</span>- );- },+ {lightbox && (+ <ImageLightbox src={imgSrc} alt={imgAlt} onClose={() => setLightbox(false)} />+ )}+ </span>+ );+}- // FileCard — intercept <div data-type="fileCard"> from preprocessMarkdown- div: ({ node, children, ...props }) => {- const dataType = node?.properties?.dataType as string | undefined;- if (dataType === "fileCard") {- const rawHref = (node?.properties?.dataHref as string) || "";- // Only allow http(s) URLs to prevent javascript: and other dangerous schemes.- const href = /^https?:\/\//i.test(rawHref) ? rawHref : "";- const filename = (node?.properties?.dataFilename as string) || "";- return (- <div className="my-1 flex items-center gap-2 rounded-md border border-border bg-muted/50 px-2.5 py-1 transition-colors hover:bg-muted">- <FileText className="size-4 shrink-0 text-muted-foreground" />- <div className="min-w-0 flex-1">- <p className="truncate text-sm">{filename}</p>- </div>- {href && (- <button- type="button"- className="shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"- onClick={() => window.open(href, "_blank", "noopener,noreferrer")}- >- <Download className="size-3.5" />- </button>- )}- </div>- );+// Inline file card — same download semantics as the standalone attachment+// list: fresh-sign through `useDownloadAttachment` when the href matches a+// known attachment, otherwise hand the raw URL to the platform's external+// opener.+function ReadonlyFileCard({+ href,+ filename,+ resolveAttachmentId,+ onDownload,+}: {+ href: string;+ filename: string;+ resolveAttachmentId: (url: string) => string | undefined;+ onDownload: (attachmentId: string) => void;+}) {+ const handleClick = () => {+ const id = resolveAttachmentId(href);+ if (id) {+ onDownload(id);+ return;}- return <div {...props}>{children}</div>;- },-- // Tables — wrap in tableWrapper div for border/radius/scroll (matches Tiptap)- table: ({ children }) => (- <div className="tableWrapper">- <table>{children}</table>+ openExternal(href);+ };+ return (+ <div className="my-1 flex items-center gap-2 rounded-md border border-border bg-muted/50 px-2.5 py-1 transition-colors hover:bg-muted">+ <FileText className="size-4 shrink-0 text-muted-foreground" />+ <div className="min-w-0 flex-1">+ <p className="truncate text-sm">{filename}</p>+ </div>+ {href && (+ <button+ type="button"+ className="shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"+ onClick={handleClick}+ >+ <Download className="size-3.5" />+ </button>+ )}</div>- ),+ );+}- // Code — lowlight highlighting for blocks, plain render for inline- code: ({ className, children, node, ...props }) => {- const lang = /language-(\w+)/.exec(className || "")?.[1];- const isBlock =- node?.position &&- node.position.start.line !== node.position.end.line;+function buildComponents(+ resolveAttachmentId: (url: string) => string | undefined,+ onDownload: (attachmentId: string) => void,+): Partial<Components> {+ return {+ // Links — route mention:// to mention components, others show preview card+ a: ReadonlyLink,- if (isBlock && lang === "mermaid") {- return <MermaidDiagram chart={String(children).replace(/\n$/, "")} />;- }+ // Images — centered with toolbar + lightbox (matches Tiptap ImageView NodeView)+ img: ({ src, alt }) => (+ <ReadonlyImage+ src={typeof src === "string" ? src : undefined}+ alt={alt ?? undefined}+ resolveAttachmentId={resolveAttachmentId}+ onDownload={onDownload}+ />+ ),- if (!isBlock && !lang) {- // Inline code — CSS handles styling via .rich-text-editor code- return <code {...props}>{children}</code>;- }+ // FileCard — intercept <div data-type="fileCard"> from preprocessMarkdown+ div: ({ node, children, ...props }) => {+ const dataType = node?.properties?.dataType as string | undefined;+ if (dataType === "fileCard") {+ const rawHref = (node?.properties?.dataHref as string) || "";+ // Only allow http(s) URLs to prevent javascript: and other dangerous schemes.+ const href = /^https?:\/\//i.test(rawHref) ? rawHref : "";+ const filename = (node?.properties?.dataFilename as string) || "";+ return (+ <ReadonlyFileCard+ href={href}+ filename={filename}+ resolveAttachmentId={resolveAttachmentId}+ onDownload={onDownload}+ />+ );+ }+ return <div {...props}>{children}</div>;+ },- // Block code — highlight with lowlight, output hljs classes- const code = String(children).replace(/\n$/, "");- try {- const tree = lang- ? lowlight.highlight(lang, code)- : lowlight.highlightAuto(code);- return (- <code- className={cn("hljs", lang && `language-${lang}`)}- dangerouslySetInnerHTML={{ __html: toHtml(tree) }}- />- );- } catch {- // Fallback — render without highlighting- return (- <code className={className} {...props}>- {children}- </code>- );- }- },+ // Tables — wrap in tableWrapper div for border/radius/scroll (matches Tiptap)+ table: ({ children }) => (+ <div className="tableWrapper">+ <table>{children}</table>+ </div>+ ),- // Pre — pass through (CSS handles styling via .rich-text-editor pre)- pre: ({ children }) => {- if (isValidElement(children) && children.type === MermaidDiagram) {- return <>{children}</>;- }- return <pre>{children}</pre>;- },-};+ // Code — lowlight highlighting for blocks, plain render for inline+ code: ({ className, children, node, ...props }) => {+ const lang = /language-(\w+)/.exec(className || "")?.[1];+ const isBlock =+ node?.position &&+ node.position.start.line !== node.position.end.line;++ if (isBlock && lang === "mermaid") {+ return <MermaidDiagram chart={String(children).replace(/\n$/, "")} />;+ }++ if (!isBlock && !lang) {+ // Inline code — CSS handles styling via .rich-text-editor code+ return <code {...props}>{children}</code>;+ }++ // Block code — highlight with lowlight, output hljs classes+ const code = String(children).replace(/\n$/, "");+ try {+ const tree = lang+ ? lowlight.highlight(lang, code)+ : lowlight.highlightAuto(code);+ return (+ <code+ className={cn("hljs", lang && `language-${lang}`)}+ dangerouslySetInnerHTML={{ __html: toHtml(tree) }}+ />+ );+ } catch {+ // Fallback — render without highlighting+ return (+ <code className={className} {...props}>+ {children}+ </code>+ );+ }+ },++ // Pre — pass through (CSS handles styling via .rich-text-editor pre)+ pre: ({ children }) => {+ if (isValidElement(children) && children.type === MermaidDiagram) {+ return <>{children}</>;+ }+ return <pre>{children}</pre>;+ },+ };+}// ---------------------------------------------------------------------------// Component@@ -301,19 +374,46 @@ const components: Partial<Components> = {interface ReadonlyContentProps {content: string;className?: string;+ /**+ * Attachments associated with the surrounding entity (comment / issue+ * body). When the markdown contains an inline `<img>` or file card whose+ * URL matches one of these attachments, the download button re-signs the+ * URL at click time via `useDownloadAttachment` instead of opening the+ * potentially stale link embedded in the markdown.+ *+ * Callers SHOULD pass a stable reference (e.g. the field on a memoized+ * timeline entry); a fresh array on every parent render busts the memo.+ */+ attachments?: Attachment[];}// Memoized so a long timeline of comments (Inbox + IssueDetail) does not// re-run the full react-markdown + rehype-* + lowlight pipeline on every-// parent re-render. Props are `content` and `className` (both strings), so-// React.memo's default shallow comparison is value-equality here.+// parent re-render. Props are `content`/`className`/`attachments`, all+// shallow-comparable; stability is the caller's responsibility for the+// array.export const ReadonlyContent = memo(function ReadonlyContent({content,className,+ attachments,}: ReadonlyContentProps) {const processed = useMemo(() => preprocessMarkdown(content), [content]);const wrapperRef = useRef<HTMLDivElement>(null);const hover = useLinkHover(wrapperRef);+ const download = useDownloadAttachment();++ const resolveAttachmentId = useCallback(+ (url: string): string | undefined => {+ if (!url || !attachments?.length) return undefined;+ return attachments.find((a) => a.url === url)?.id;+ },+ [attachments],+ );++ const components = useMemo(+ () => buildComponents(resolveAttachmentId, download),+ [resolveAttachmentId, download],+ );return (<div ref={wrapperRef} className={cn("rich-text-editor readonly text-sm", className)}>diff --git a/packages/views/editor/use-download-attachment.test.tsx b/packages/views/editor/use-download-attachment.test.tsxnew file mode 100644index 0000000000..ac22594fe9--- /dev/null+++ b/packages/views/editor/use-download-attachment.test.tsx@@ -0,0 +1,108 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { act, renderHook, waitFor } from "@testing-library/react";++// Hoisted mock for the API singleton: vi.mock factories cannot reference+// outside-of-scope vars, but vi.hoisted runs before the import graph.+const getAttachmentMock = vi.hoisted(() => vi.fn());++vi.mock("@multica/core/api", () => ({+ api: { getAttachment: getAttachmentMock },+}));++vi.mock("../platform", () => ({+ openExternal: vi.fn(),+}));++vi.mock("sonner", () => ({+ toast: { error: vi.fn(), success: vi.fn() },+}));++vi.mock("../i18n", () => ({+ useT: () => ({ t: (sel: (s: { attachment: { download_failed: string } }) => string) => sel({ attachment: { download_failed: "Couldn't fetch a download link. Try again in a moment." } }) }),+}));++import { useDownloadAttachment } from "./use-download-attachment";+import { openExternal } from "../platform";+import { toast } from "sonner";++const SIGNED_URL =+ "https://static.example.test/file.md?Policy=p&Signature=s&Key-Pair-Id=k";++beforeEach(() => {+ vi.clearAllMocks();+});++afterEach(() => {+ vi.restoreAllMocks();+ // Scrub the desktop bridge between tests so suites don't leak state.+ delete (window as unknown as { desktopAPI?: unknown }).desktopAPI;+});++describe("useDownloadAttachment (web)", () => {+ it("opens a placeholder tab synchronously, then navigates it to the freshly signed URL", async () => {+ getAttachmentMock.mockResolvedValueOnce({+ id: "att-1",+ url: "https://static.example.test/file.md",+ download_url: SIGNED_URL,+ filename: "file.md",+ });++ const placeholder = { opener: window, location: { href: "about:blank" }, close: vi.fn() };+ const openSpy = vi.spyOn(window, "open").mockReturnValue(placeholder as unknown as Window);++ const { result } = renderHook(() => useDownloadAttachment());++ await act(async () => {+ await result.current("att-1");+ });++ // Placeholder MUST be opened synchronously during the click — otherwise+ // popup blockers won't honour the gesture.+ expect(openSpy).toHaveBeenCalledWith("about:blank", "_blank");+ expect(getAttachmentMock).toHaveBeenCalledWith("att-1");+ // Disown the opener and redirect to the signed URL.+ expect(placeholder.opener).toBeNull();+ expect(placeholder.location.href).toBe(SIGNED_URL);+ });++ it("closes the placeholder and shows a toast when the fetch fails", async () => {+ getAttachmentMock.mockRejectedValueOnce(new Error("boom"));+ const placeholder = { opener: window, location: { href: "about:blank" }, close: vi.fn() };+ vi.spyOn(window, "open").mockReturnValue(placeholder as unknown as Window);++ const { result } = renderHook(() => useDownloadAttachment());++ await act(async () => {+ await result.current("att-1");+ });++ expect(placeholder.close).toHaveBeenCalled();+ await waitFor(() => expect(toast.error).toHaveBeenCalled());+ });+});++describe("useDownloadAttachment (desktop)", () => {+ it("skips the placeholder tab and hands the signed URL to openExternal", async () => {+ (window as unknown as { desktopAPI: { openExternal: () => void } }).desktopAPI = {+ openExternal: vi.fn(),+ };+ getAttachmentMock.mockResolvedValueOnce({+ id: "att-1",+ url: "https://static.example.test/file.md",+ download_url: SIGNED_URL,+ filename: "file.md",+ });+ const openSpy = vi.spyOn(window, "open");++ const { result } = renderHook(() => useDownloadAttachment());++ await act(async () => {+ await result.current("att-1");+ });++ // No placeholder — Electron's setWindowOpenHandler would reject+ // about:blank, so we go straight to the platform's IPC bridge.+ expect(openSpy).not.toHaveBeenCalled();+ expect(openExternal).toHaveBeenCalledWith(SIGNED_URL);+ });+});diff --git a/packages/views/editor/use-download-attachment.ts b/packages/views/editor/use-download-attachment.tsnew file mode 100644index 0000000000..559400bef6--- /dev/null+++ b/packages/views/editor/use-download-attachment.ts@@ -0,0 +1,92 @@+"use client";++import { useCallback } from "react";+import { toast } from "sonner";+import { api } from "@multica/core/api";+import { openExternal } from "../platform";+import { useT } from "../i18n";++interface DesktopBridge {+ openExternal?: (u: string) => Promise<void> | void;+}++// Detected at call time, not module load — the bridge is injected by the+// Electron preload after `window` exists, and reading it lazily lets the+// same hook work in both renderers without a build-time fork.+function hasDesktopBridge(): boolean {+ if (typeof window === "undefined") return false;+ const bridge = (window as unknown as { desktopAPI?: DesktopBridge }).desktopAPI;+ return Boolean(bridge?.openExternal);+}++/**+ * Returns a callback that downloads an attachment by ID through a freshly+ * signed CloudFront URL. The server re-signs `download_url` on every+ * `GET /api/attachments/{id}` call, so this flow sidesteps stale signatures+ * cached in TanStack Query / inlined in markdown.+ *+ * Two execution shapes, picked at call time:+ *+ * - **Web**: open a same-origin `about:blank` tab *synchronously* inside+ * the click handler — popup blockers (Safari especially) only consider+ * the gesture frame, not the later async settle. The placeholder tab+ * keeps the user activation receipt; after the fetch resolves we navigate+ * it. We can NOT pass `"noopener"` to `window.open` because the HTML+ * spec (`dom-open` step 17) makes that return `null`, which would leave+ * us nothing to navigate. We disown the opener manually after the fetch.+ *+ * - **Desktop**: `window.open` is intercepted by Electron's+ * `setWindowOpenHandler` and routed through `openExternalSafely`, which+ * rejects `about:blank`. So on desktop we fetch first, then hand the URL+ * to `openExternal()` which IPCs into `shell.openExternal` and opens the+ * system browser.+ */+export function useDownloadAttachment(): (attachmentId: string) => Promise<void> {+ const { t } = useT("editor");+ return useCallback(+ async (attachmentId: string) => {+ const failed = () => toast.error(t(($) => $.attachment.download_failed));++ if (hasDesktopBridge()) {+ try {+ const fresh = await api.getAttachment(attachmentId);+ if (!fresh.download_url) {+ failed();+ return;+ }+ openExternal(fresh.download_url);+ } catch {+ failed();+ }+ return;+ }++ // Web: claim the popup permission synchronously, then hydrate the URL.+ // `window.open` here returns a WindowProxy because we deliberately+ // omit `noopener`; we revoke the back-channel ourselves once we have+ // the real URL.+ const placeholder = typeof window !== "undefined"+ ? window.open("about:blank", "_blank")+ : null;+ try {+ const fresh = await api.getAttachment(attachmentId);+ if (!fresh.download_url) {+ placeholder?.close();+ failed();+ return;+ }+ if (placeholder) {+ placeholder.opener = null;+ placeholder.location.href = fresh.download_url;+ } else if (typeof window !== "undefined") {+ // Popup blocked outright — last-resort navigate the current tab.+ window.location.href = fresh.download_url;+ }+ } catch {+ placeholder?.close();+ failed();+ }+ },+ [t],+ );+}diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsxindex 99a0cfefa1..e897bcb866 100644--- a/packages/views/issues/components/comment-card.tsx+++ b/packages/views/issues/components/comment-card.tsx@@ -30,7 +30,7 @@ import { QuickEmojiPicker } from "@multica/ui/components/common/quick-emoji-pickimport { cn } from "@multica/ui/lib/utils";import { useActorName } from "@multica/core/workspace/hooks";import { timeAgo } from "@multica/core/utils";-import { ContentEditor, type ContentEditorRef, copyMarkdown, ReadonlyContent, useFileDropZone, FileDropOverlay } from "../../editor";+import { ContentEditor, type ContentEditorRef, copyMarkdown, ReadonlyContent, useFileDropZone, FileDropOverlay, useDownloadAttachment } from "../../editor";import { FileUploadButton } from "@multica/ui/components/common/file-upload-button";import { useFileUpload } from "@multica/core/hooks/use-file-upload";import { api } from "@multica/core/api";@@ -122,6 +122,7 @@ function DeleteCommentDialog({// ---------------------------------------------------------------------------function AttachmentList({ attachments, content, className }: { attachments?: Attachment[]; content?: string; className?: string }) {+ const download = useDownloadAttachment();if (!attachments?.length) return null;// Skip attachments whose URL is already referenced in the markdown content,// and duplicates of the same file (same name/type/size) that are referenced.@@ -155,15 +156,13 @@ function AttachmentList({ attachments, content, className }: { attachments?: Att<div className="min-w-0 flex-1"><p className="truncate text-sm">{a.filename}</p></div>- {a.download_url && (- <button- type="button"- className="shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"- onClick={() => window.open(a.download_url, "_blank", "noopener,noreferrer")}- >- <Download className="size-3.5" />- </button>- )}+ <button+ type="button"+ className="shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"+ onClick={() => download(a.id)}+ >+ <Download className="size-3.5" />+ </button></div>))}</div>@@ -326,6 +325,7 @@ function CommentRow({onUploadFile={(file) => uploadWithToast(file, { issueId })}debounceMs={100}currentIssueId={issueId}+ attachments={entry.attachments}/></div><div className="flex items-center justify-between mt-2">@@ -343,7 +343,7 @@ function CommentRow({) : (<><div className="mt-1.5 pl-8 text-sm leading-relaxed text-foreground/85">- <ReadonlyContent content={entry.content ?? ""} />+ <ReadonlyContent content={entry.content ?? ""} attachments={entry.attachments} /></div><AttachmentList attachments={entry.attachments} content={entry.content} className="mt-1.5 pl-8" />{!isTemp && (@@ -587,6 +587,7 @@ function CommentCardImpl({onUploadFile={(file) => uploadWithToast(file, { issueId })}debounceMs={100}currentIssueId={issueId}+ attachments={entry.attachments}/></div><div className="flex items-center justify-between mt-2">@@ -604,7 +605,7 @@ function CommentCardImpl({) : (<><div className="pl-10 text-sm leading-relaxed text-foreground/85">- <ReadonlyContent content={entry.content ?? ""} />+ <ReadonlyContent content={entry.content ?? ""} attachments={entry.attachments} /></div><AttachmentList attachments={entry.attachments} content={entry.content} className="mt-1.5 pl-10" />{!isTemp && (diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsxindex e2fadd674f..71bab62cca 100644--- a/packages/views/issues/components/issue-detail.test.tsx+++ b/packages/views/issues/components/issue-detail.test.tsx@@ -109,6 +109,10 @@ vi.mock("../../navigation", () => ({vi.mock("../../editor", () => ({useFileDropZone: () => ({ isDragOver: false, dropZoneProps: {} }),FileDropOverlay: () => null,+ // No-op so comment-card's AttachmentList can render without hitting the+ // real API singleton; tests that care about download wiring should write+ // dedicated specs against `use-download-attachment.test.tsx`.+ useDownloadAttachment: () => vi.fn(),ReadonlyContent: ({ content }: { content: string }) => (<div data-testid="readonly-content">{content}</div>),@@ -198,6 +202,7 @@ const mockApiObj = vi.hoisted(() => ({listIssueReactions: vi.fn().mockResolvedValue([]),addIssueReaction: vi.fn(),removeIssueReaction: vi.fn(),+ listAttachments: vi.fn().mockResolvedValue([]),addCommentReaction: vi.fn(),removeCommentReaction: vi.fn(),listMembers: vi.fn().mockResolvedValue([{ user_id: "user-1", name: "Test User", email: "[email protected]", role: "admin" }]),diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex 5faeb57765..2300190362 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -55,7 +55,7 @@ import { useAuthStore } from "@multica/core/auth";import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";import { useActorName } from "@multica/core/workspace/hooks";import { useWorkspaceId } from "@multica/core/hooks";-import { issueListOptions, issueDetailOptions, childIssuesOptions, issueUsageOptions } from "@multica/core/issues/queries";+import { issueListOptions, issueDetailOptions, childIssuesOptions, issueUsageOptions, issueAttachmentsOptions } from "@multica/core/issues/queries";import { memberListOptions, agentListOptions } from "@multica/core/workspace/queries";import { useRecentIssuesStore } from "@multica/core/issues/stores";import { useIssueSelectionStore } from "@multica/core/issues/stores/selection-store";@@ -536,6 +536,12 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr// Token usageconst { data: usage } = useQuery(issueUsageOptions(id));+ // Attachments uploaded against this issue. Drives the description+ // editor's click-time fresh-sign download: NodeViews match+ // `src`/`href` against this list to resolve an attachment id before+ // calling `/api/attachments/{id}`.+ const { data: issueAttachments } = useQuery(issueAttachmentsOptions(id));+// Sub-issue queriesconst parentIssueId = issue?.parent_issue_id;const { data: parentIssue = null } = useQuery({@@ -976,6 +982,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tronUploadFile={handleDescriptionUpload}debounceMs={1500}currentIssueId={id}+ attachments={issueAttachments}/><div className="flex items-center gap-1 mt-3">diff --git a/packages/views/locales/en/editor.json b/packages/views/locales/en/editor.jsonindex 72b9b052f7..46a822e17a 100644--- a/packages/views/locales/en/editor.json+++ b/packages/views/locales/en/editor.json@@ -33,6 +33,9 @@"link_copied": "Link copied","copy_link_failed": "Failed to copy link"},+ "attachment": {+ "download_failed": "Couldn't fetch a download link. Try again in a moment."+ },"link_hover": {"copy_link": "Copy link","open_link": "Open link",diff --git a/packages/views/locales/zh-Hans/editor.json b/packages/views/locales/zh-Hans/editor.jsonindex 5b5ff5150e..d733077c7b 100644--- a/packages/views/locales/zh-Hans/editor.json+++ b/packages/views/locales/zh-Hans/editor.json@@ -33,6 +33,9 @@"link_copied": "已复制链接","copy_link_failed": "复制链接失败"},+ "attachment": {+ "download_failed": "下载链接获取失败,请稍后重试。"+ },"link_hover": {"copy_link": "复制链接","open_link": "打开链接",