Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(comments): support edit-time attachment removal (#2965)
YOMXXX7d24a8594ab0
diff --git a/packages/views/editor/attachment-card.tsx b/packages/views/editor/attachment-card.tsxindex 3ba7f6e350..2743882a5f 100644--- a/packages/views/editor/attachment-card.tsx+++ b/packages/views/editor/attachment-card.tsx@@ -9,7 +9,7 @@* that decision out of this file so this stays a single-purpose row UI.*/-import { Download, Eye, FileText, Loader2 } from "lucide-react";+import { Download, Eye, FileText, Loader2, Trash2 } from "lucide-react";import { useT } from "../i18n";import { getPreviewKind } from "./utils/preview";@@ -18,8 +18,10 @@ interface AttachmentCardChromeProps {uploading?: boolean;canPreview: boolean;canDownload: boolean;+ canDelete?: boolean;onPreview: () => void;onDownload: () => void;+ onDelete?: () => void;}function AttachmentCardChrome({@@ -27,8 +29,10 @@ function AttachmentCardChrome({uploading,canPreview,canDownload,+ canDelete,onPreview,onDownload,+ onDelete,}: AttachmentCardChromeProps) {const { t } = useT("editor");return (@@ -78,6 +82,21 @@ function AttachmentCardChrome({<Download className="size-3.5" /></button>)}+ {!uploading && canDelete && onDelete && (+ <button+ type="button"+ className="shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive"+ title={t(($) => $.attachment.remove)}+ aria-label={t(($) => $.attachment.remove)}+ onMouseDown={(e) => {+ e.preventDefault();+ e.stopPropagation();+ onDelete();+ }}+ >+ <Trash2 className="size-3.5" />+ </button>+ )}</div>);}@@ -101,6 +120,8 @@ export interface AttachmentCardProps {onPreview: () => void;/** Pressed when the Download button is clicked. */onDownload: () => void;+ /** Optional remove button, used by editable comment/file-card surfaces. */+ onDelete?: () => void;}export function AttachmentCard({@@ -111,6 +132,7 @@ export function AttachmentCard({uploading,onPreview,onDownload,+ onDelete,}: AttachmentCardProps) {const kind = filename ? getPreviewKind(contentType, filename) : null;// Media kinds (pdf/video/audio) are previewable from a URL alone — the@@ -130,8 +152,10 @@ export function AttachmentCard({uploading={uploading}canPreview={canPreview}canDownload={!!href}+ canDelete={!!onDelete}onPreview={onPreview}onDownload={onDownload}+ onDelete={onDelete}/></div>);diff --git a/packages/views/editor/attachment.tsx b/packages/views/editor/attachment.tsxindex 2d055248c8..f0e348d402 100644--- a/packages/views/editor/attachment.tsx+++ b/packages/views/editor/attachment.tsx@@ -190,6 +190,7 @@ export function Attachment({filename={state.filename}onPreview={openPreview}onDownload={handleDownload}+ onDelete={editable ? onDelete : undefined}/>{preview.modal}</>@@ -206,6 +207,7 @@ export function Attachment({uploading={state.uploading}onPreview={openPreview}onDownload={handleDownload}+ onDelete={editable ? onDelete : undefined}/>{preview.modal}</>diff --git a/packages/views/editor/extensions/file-card.tsx b/packages/views/editor/extensions/file-card.tsxindex e65b580bf1..2999a451c1 100644--- a/packages/views/editor/extensions/file-card.tsx+++ b/packages/views/editor/extensions/file-card.tsx@@ -29,16 +29,19 @@ const FILE_CARD_MARKDOWN_RE = new RegExp(// React NodeView — thin wrapper, all rendering lives in <Attachment>// ----------------------------------------------------------------------------export function FileCardView({ node }: NodeViewProps) {+export function FileCardView({ node, editor, deleteNode }: NodeViewProps) {const href = (node.attrs.href as string) || "";const filename = (node.attrs.filename as string) || "";const uploading = node.attrs.uploading as boolean;+ const editable = editor?.isEditable ?? false;return (<NodeViewWrapper as="div" className="file-card-node" data-type="fileCard"><div contentEditable={false}><Attachmentattachment={{ kind: "url", url: href, filename, uploading }}+ editable={editable}+ onDelete={editable ? deleteNode : undefined}/></div></NodeViewWrapper>diff --git a/packages/views/editor/html-attachment-preview.tsx b/packages/views/editor/html-attachment-preview.tsxindex 3c8e91764a..c7356bef64 100644--- a/packages/views/editor/html-attachment-preview.tsx+++ b/packages/views/editor/html-attachment-preview.tsx@@ -26,7 +26,7 @@* 80px placeholder and the toolbar pins itself open with all actions enabled.*/-import { Download, ExternalLink, Maximize2 } from "lucide-react";+import { Download, ExternalLink, Maximize2, Trash2 } from "lucide-react";import { cn } from "@multica/ui/lib/utils";import { paths, useWorkspaceSlug } from "@multica/core/paths";import { useT } from "../i18n";@@ -42,6 +42,7 @@ interface HtmlAttachmentPreviewProps {filename: string;onPreview: () => void;onDownload: () => void;+ onDelete?: () => void;}export function HtmlAttachmentPreview({@@ -49,6 +50,7 @@ export function HtmlAttachmentPreview({filename,onPreview,onDownload,+ onDelete,}: HtmlAttachmentPreviewProps) {const { t } = useT("editor");// Subscribe to the same React Query cache key the body consumes so the@@ -143,6 +145,21 @@ export function HtmlAttachmentPreview({><Download className="h-3.5 w-3.5" /></button>+ {onDelete && (+ <button+ type="button"+ className="flex h-6 w-6 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive"+ title={t(($) => $.attachment.remove)}+ aria-label={t(($) => $.attachment.remove)}+ onMouseDown={(e) => {+ e.preventDefault();+ e.stopPropagation();+ onDelete();+ }}+ >+ <Trash2 className="h-3.5 w-3.5" />+ </button>+ )}</div></div>);diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsxindex 5f7ea4c4a4..92fba66835 100644--- a/packages/views/issues/components/comment-card.tsx+++ b/packages/views/issues/components/comment-card.tsx@@ -121,7 +121,17 @@ function DeleteCommentDialog({// Standalone attachment list — renders attachments not already in the markdown// ----------------------------------------------------------------------------export function AttachmentList({ attachments, content, className }: { attachments?: Attachment[]; content?: string; className?: string }) {+export function AttachmentList({+ attachments,+ content,+ className,+ onRemove,+}: {+ attachments?: Attachment[];+ content?: string;+ className?: string;+ onRemove?: (attachmentId: string) => void;+}) {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.@@ -151,6 +161,8 @@ export function AttachmentList({ attachments, content, className }: { attachment<AttachmentRendererkey={a.id}attachment={{ kind: "record", attachment: a }}+ editable={!!onRemove}+ onDelete={onRemove ? () => onRemove(a.id) : undefined}/>))}</div>@@ -158,6 +170,34 @@ export function AttachmentList({ attachments, content, className }: { attachment);}+function collectActiveAttachmentIds(+ content: string,+ attachments: Attachment[],+ retainedStandaloneIds?: Set<string> | null,+): string[] {+ const ids = new Set<string>();+ for (const attachment of attachments) {+ if (content.includes(attachment.url)) ids.add(attachment.id);+ }+ for (const id of retainedStandaloneIds ?? []) ids.add(id);+ return [...ids];+}++function sameIdSet(a: string[], b: string[]): boolean {+ if (a.length !== b.length) return false;+ const set = new Set(a);+ return b.every((id) => set.has(id));+}++function initialStandaloneAttachmentIds(entry: TimelineEntry): Set<string> {+ const content = entry.content ?? "";+ return new Set(+ (entry.attachments ?? [])+ .filter((attachment) => !content.includes(attachment.url))+ .map((attachment) => attachment.id),+ );+}+// ---------------------------------------------------------------------------// Single comment row (used for both parent and replies within the same Card)// ---------------------------------------------------------------------------@@ -192,6 +232,7 @@ function CommentRow({// them to the comment (otherwise they'd remain orphaned at the issue level// and disappear after refresh).const [pendingAttachments, setPendingAttachments] = useState<Attachment[]>([]);+ const [retainedStandaloneIds, setRetainedStandaloneIds] = useState<Set<string> | null>(null);const editorAttachments = pendingAttachments.length > 0? [...(entry.attachments ?? []), ...pendingAttachments]: entry.attachments;@@ -229,6 +270,7 @@ function CommentRow({const startEdit = () => {cancelledRef.current = false;+ setRetainedStandaloneIds(initialStandaloneAttachmentIds(entry));setEditing(true);};@@ -236,6 +278,7 @@ function CommentRow({cancelledRef.current = true;setEditing(false);setPendingAttachments([]);+ setRetainedStandaloneIds(null);clearEditDraft(editDraftKey);};@@ -245,19 +288,25 @@ function CommentRow({?.getMarkdown()?.replace(/(\n\s*)+$/, "").trim();- if (!trimmed || trimmed === (entry.content ?? "").trim()) {+ if (!trimmed) return;+ const activeIds = collectActiveAttachmentIds(+ trimmed,+ [...(entry.attachments ?? []), ...pendingAttachments],+ retainedStandaloneIds,+ );+ const attachmentsChanged = !sameIdSet(activeIds, (entry.attachments ?? []).map((a) => a.id));+ if (trimmed === (entry.content ?? "").trim() && !attachmentsChanged) {setEditing(false);setPendingAttachments([]);+ setRetainedStandaloneIds(null);clearEditDraft(editDraftKey);return;}- const activeIds = pendingAttachments- .filter((a) => trimmed.includes(a.url))- .map((a) => a.id);try {- await onEdit(entry.id, trimmed, activeIds.length > 0 ? activeIds : undefined);+ await onEdit(entry.id, trimmed, activeIds);setEditing(false);setPendingAttachments([]);+ setRetainedStandaloneIds(null);clearEditDraft(editDraftKey);} catch (err) {toast.error(@@ -271,6 +320,9 @@ function CommentRow({const reactions = entry.reactions ?? [];const contentText = entry.content ?? "";const isLongContent = contentText.length > 500 || contentText.split("\n").length > 8;+ const standaloneEditAttachments = (entry.attachments ?? []).filter((attachment) =>+ retainedStandaloneIds?.has(attachment.id),+ );return (<div className={`py-3${isTemp ? " opacity-60" : ""}`}>@@ -366,10 +418,25 @@ function CommentRow({/></div><div className="flex items-center justify-between mt-2">- <FileUploadButton- size="sm"- onSelect={(file) => editEditorRef.current?.uploadFile(file)}- />+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ {standaloneEditAttachments.length > 0 && (+ <AttachmentList+ attachments={standaloneEditAttachments}+ className="max-w-full"+ onRemove={(attachmentId) =>+ setRetainedStandaloneIds((ids) => {+ const next = new Set(ids ?? []);+ next.delete(attachmentId);+ return next;+ })+ }+ />+ )}+ <FileUploadButton+ size="sm"+ onSelect={(file) => editEditorRef.current?.uploadFile(file)}+ />+ </div><div className="flex items-center gap-2"><Button size="sm" variant="ghost" onClick={cancelEdit}>{t(($) => $.comment.cancel_edit)}</Button><Button size="sm" variant="outline" onClick={saveEdit}>{t(($) => $.comment.save_action)}</Button>@@ -430,6 +497,7 @@ function CommentCardImpl({const cancelledRef = useRef(false);// Pending uploads from the root-comment edit pass — same rationale as CommentRow.const [parentPendingAttachments, setParentPendingAttachments] = useState<Attachment[]>([]);+ const [parentRetainedStandaloneIds, setParentRetainedStandaloneIds] = useState<Set<string> | null>(null);const parentEditorAttachments = parentPendingAttachments.length > 0? [...(entry.attachments ?? []), ...parentPendingAttachments]: entry.attachments;@@ -464,6 +532,7 @@ function CommentCardImpl({const startEdit = () => {cancelledRef.current = false;+ setParentRetainedStandaloneIds(initialStandaloneAttachmentIds(entry));setEditing(true);};@@ -471,6 +540,7 @@ function CommentCardImpl({cancelledRef.current = true;setEditing(false);setParentPendingAttachments([]);+ setParentRetainedStandaloneIds(null);clearParentEditDraft(parentEditDraftKey);};@@ -480,19 +550,25 @@ function CommentCardImpl({?.getMarkdown()?.replace(/(\n\s*)+$/, "").trim();- if (!trimmed || trimmed === (entry.content ?? "").trim()) {+ if (!trimmed) return;+ const activeIds = collectActiveAttachmentIds(+ trimmed,+ [...(entry.attachments ?? []), ...parentPendingAttachments],+ parentRetainedStandaloneIds,+ );+ const attachmentsChanged = !sameIdSet(activeIds, (entry.attachments ?? []).map((a) => a.id));+ if (trimmed === (entry.content ?? "").trim() && !attachmentsChanged) {setEditing(false);setParentPendingAttachments([]);+ setParentRetainedStandaloneIds(null);clearParentEditDraft(parentEditDraftKey);return;}- const activeIds = parentPendingAttachments- .filter((a) => trimmed.includes(a.url))- .map((a) => a.id);try {- await onEdit(entry.id, trimmed, activeIds.length > 0 ? activeIds : undefined);+ await onEdit(entry.id, trimmed, activeIds);setEditing(false);setParentPendingAttachments([]);+ setParentRetainedStandaloneIds(null);clearParentEditDraft(parentEditDraftKey);} catch (err) {toast.error(@@ -513,6 +589,9 @@ function CommentCardImpl({const reactions = entry.reactions ?? [];const contentText = entry.content ?? "";const isLongContent = contentText.length > 500 || contentText.split("\n").length > 8;+ const parentStandaloneEditAttachments = (entry.attachments ?? []).filter((attachment) =>+ parentRetainedStandaloneIds?.has(attachment.id),+ );const isHighlighted = highlightedCommentId === entry.id;@@ -665,10 +744,25 @@ function CommentCardImpl({/></div><div className="flex items-center justify-between mt-2">- <FileUploadButton- size="sm"- onSelect={(file) => editEditorRef.current?.uploadFile(file)}- />+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ {parentStandaloneEditAttachments.length > 0 && (+ <AttachmentList+ attachments={parentStandaloneEditAttachments}+ className="max-w-full"+ onRemove={(attachmentId) =>+ setParentRetainedStandaloneIds((ids) => {+ const next = new Set(ids ?? []);+ next.delete(attachmentId);+ return next;+ })+ }+ />+ )}+ <FileUploadButton+ size="sm"+ onSelect={(file) => editEditorRef.current?.uploadFile(file)}+ />+ </div><div className="flex items-center gap-2"><Button size="sm" variant="ghost" onClick={cancelEdit}>{t(($) => $.comment.cancel_edit)}</Button><Button size="sm" variant="outline" onClick={saveEdit}>{t(($) => $.comment.save_action)}</Button>diff --git a/packages/views/locales/en/editor.json b/packages/views/locales/en/editor.jsonindex 59e51ea1ba..4a140c2204 100644--- a/packages/views/locales/en/editor.json+++ b/packages/views/locales/en/editor.json@@ -41,7 +41,8 @@"preview_too_large": "File is too large to preview. Please download.","preview_unsupported": "This file type can't be previewed.","close": "Close",- "open_in_new_tab": "Open in new tab"+ "open_in_new_tab": "Open in new tab",+ "remove": "Remove attachment"},"link_hover": {"copy_link": "Copy link",diff --git a/packages/views/locales/zh-Hans/editor.json b/packages/views/locales/zh-Hans/editor.jsonindex 48e9ed2279..c9db7364d3 100644--- a/packages/views/locales/zh-Hans/editor.json+++ b/packages/views/locales/zh-Hans/editor.json@@ -41,7 +41,8 @@"preview_too_large": "文件太大,无法在线预览,请下载查看。","preview_unsupported": "该文件类型暂不支持预览。","close": "关闭",- "open_in_new_tab": "在新标签页打开"+ "open_in_new_tab": "在新标签页打开",+ "remove": "移除附件"},"link_hover": {"copy_link": "复制链接",diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex b210063af2..b2a1f60949 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -1024,8 +1024,8 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {}var req struct {- Content string `json:"content"`- AttachmentIDs []string `json:"attachment_ids"`+ Content string `json:"content"`+ AttachmentIDs *[]string `json:"attachment_ids"`}if err := json.NewDecoder(r.Body).Decode(&req); err != nil {writeError(w, http.StatusBadRequest, "invalid request body")@@ -1036,9 +1036,14 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {return}- attachmentIDs, ok := parseUUIDSliceOrBadRequest(w, req.AttachmentIDs, "attachment_ids")- if !ok {- return+ var attachmentIDs []pgtype.UUID+ replaceAttachments := req.AttachmentIDs != nil+ if replaceAttachments {+ var ok bool+ attachmentIDs, ok = parseUUIDSliceOrBadRequest(w, *req.AttachmentIDs, "attachment_ids")+ if !ok {+ return+ }}// NOTE: See CreateComment — Markdown is sanitized at render/edit time, not here.@@ -1053,12 +1058,17 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {return}- // Bind any newly uploaded attachments referenced in the edited content so- // they appear in the timeline's comment.attachments after refresh. Existing- // attachments already point at this comment via the upload flow; passing- // them again is a no-op at the SQL level.- if len(attachmentIDs) > 0 {- h.linkAttachmentsByIDs(r.Context(), comment.ID, existing.IssueID, attachmentIDs)+ // Replace the comment attachment set when a modern client sends+ // attachment_ids. Older clients omit the field; in that case preserve the+ // existing attachment links rather than unlinking everything.+ if replaceAttachments {+ if err := h.Queries.ReplaceCommentAttachments(r.Context(), db.ReplaceCommentAttachmentsParams{+ CommentID: comment.ID,+ IssueID: existing.IssueID,+ Column3: attachmentIDs,+ }); err != nil {+ slog.Error("failed to replace comment attachments", "error", err)+ }}// Fetch reactions and attachments for the updated comment.diff --git a/server/pkg/db/generated/attachment.sql.go b/server/pkg/db/generated/attachment.sql.goindex 53b309ba7a..510cc1762d 100644--- a/server/pkg/db/generated/attachment.sql.go+++ b/server/pkg/db/generated/attachment.sql.go@@ -447,3 +447,27 @@ func (q *Queries) ListAttachmentsByIssue(ctx context.Context, arg ListAttachment}return items, nil}++const replaceCommentAttachments = `-- name: ReplaceCommentAttachments :exec+UPDATE attachment+SET comment_id = CASE+ WHEN id = ANY($3::uuid[]) THEN $1+ ELSE NULL+END+WHERE issue_id = $2+ AND (+ comment_id = $1+ OR (comment_id IS NULL AND id = ANY($3::uuid[]))+ )+`++type ReplaceCommentAttachmentsParams struct {+ CommentID pgtype.UUID `json:"comment_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ Column3 []pgtype.UUID `json:"column_3"`+}++func (q *Queries) ReplaceCommentAttachments(ctx context.Context, arg ReplaceCommentAttachmentsParams) error {+ _, err := q.db.Exec(ctx, replaceCommentAttachments, arg.CommentID, arg.IssueID, arg.Column3)+ return err+}diff --git a/server/pkg/db/queries/attachment.sql b/server/pkg/db/queries/attachment.sqlindex bfac7ee21d..b13b96e039 100644--- a/server/pkg/db/queries/attachment.sql+++ b/server/pkg/db/queries/attachment.sql@@ -44,6 +44,18 @@ WHERE issue_id = $2AND comment_id IS NULLAND id = ANY($3::uuid[]);+-- name: ReplaceCommentAttachments :exec+UPDATE attachment+SET comment_id = CASE+ WHEN id = ANY($3::uuid[]) THEN $1+ ELSE NULL+END+WHERE issue_id = $2+ AND (+ comment_id = $1+ OR (comment_id IS NULL AND id = ANY($3::uuid[]))+ );+-- name: LinkAttachmentsToChatMessage :execUPDATE attachmentSET chat_message_id = $1