Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(editor): drag-and-drop file upload with file card display
Naiyuan Qing19a1bbba4a18
diff --git a/apps/web/components/common/file-upload-button.tsx b/apps/web/components/common/file-upload-button.tsxindex 0f993851fe..a52bd1dcdf 100644--- a/apps/web/components/common/file-upload-button.tsx+++ b/apps/web/components/common/file-upload-button.tsx@@ -3,7 +3,6 @@import { useRef } from "react";import { Paperclip } from "lucide-react";import { cn } from "@/lib/utils";-import { FILE_INPUT_ACCEPT } from "@/shared/constants/upload";interface FileUploadButtonProps {/** Called with the selected File — caller handles upload. */@@ -49,7 +48,6 @@ function FileUploadButton({ref={inputRef}type="file"className="hidden"- accept={FILE_INPUT_ACCEPT}onChange={handleChange}/></>diff --git a/apps/web/features/editor/content-editor.css b/apps/web/features/editor/content-editor.cssindex f1390a31ab..901184a675 100644--- a/apps/web/features/editor/content-editor.css+++ b/apps/web/features/editor/content-editor.css@@ -371,16 +371,46 @@vertical-align: middle;}-/* Images — shared styling for both editing and readonly */+/* Block-level NodeViews (fileCard) need to override the inline default above */+.rich-text-editor .file-card-node {+ display: block !important;+}++/* Images — generic fallback (non-NodeView contexts) */.rich-text-editor img {+ max-width: 100%;+ height: auto;border-radius: var(--radius);margin: 0.5rem 0;}-/* Uploading image placeholder — data-uploading attribute managed by ProseMirror schema */-.rich-text-editor img[data-uploading] {- opacity: 0.5;+/* Image NodeView — centered block with max-width cap */+.rich-text-editor .image-node {+ display: block !important;+ text-align: center;+}++.rich-text-editor .image-figure {+ position: relative;+ display: inline-block;+ max-width: min(100%, 640px);+ margin: 0.75rem 0;+}++.rich-text-editor .image-figure.image-selected .image-content {+ outline: 2px solid var(--brand);+ outline-offset: 2px;+}++.rich-text-editor .image-content {+ display: block;+ width: 100%;+ height: auto;border-radius: var(--radius);+}++.rich-text-editor .image-uploading {+ opacity: 0.5;animation: rte-upload-pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;}@@ -389,6 +419,46 @@50% { opacity: 0.3; }}+/* Readonly — zoom cursor on clickable images */+.rich-text-editor.readonly .image-figure {+ cursor: zoom-in;+}++/* Image toolbar — dark pill, top-right corner, appears on hover */+.rich-text-editor .image-toolbar {+ position: absolute;+ top: 0.5rem;+ right: 0.5rem;+ display: flex;+ gap: 1px;+ padding: 0.25rem;+ background: color-mix(in srgb, black 75%, transparent);+ backdrop-filter: blur(8px);+ border-radius: var(--radius);+ opacity: 0;+ transition: opacity 0.15s;+ z-index: 1;+}++.image-figure:hover .image-toolbar {+ opacity: 1;+}++.rich-text-editor .image-toolbar button {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 1.75rem;+ height: 1.75rem;+ border-radius: calc(var(--radius) - 2px);+ color: white;+ transition: background 0.15s;+}++.rich-text-editor .image-toolbar button:hover {+ background: color-mix(in srgb, white 15%, transparent);+}+/* Drag-and-drop overlay */.editor-drop-overlay {position: absolute;@@ -396,9 +466,9 @@display: flex;align-items: center;justify-content: center;- border: 2px dashed hsl(var(--primary));+ border: 2px dashed color-mix(in srgb, var(--brand) 40%, transparent);border-radius: var(--radius);- background: hsl(var(--primary) / 0.05);+ background: color-mix(in srgb, var(--brand) 3%, transparent);z-index: 10;pointer-events: none;}@@ -406,5 +476,5 @@.editor-drop-overlay p {font-size: 0.875rem;font-weight: 500;- color: hsl(var(--primary));+ color: color-mix(in srgb, var(--brand) 60%, transparent);}diff --git a/apps/web/features/editor/content-editor.tsx b/apps/web/features/editor/content-editor.tsxindex 1da31bd424..78d44b442c 100644--- a/apps/web/features/editor/content-editor.tsx+++ b/apps/web/features/editor/content-editor.tsx@@ -166,6 +166,17 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(};}, []);+ // Always clear drag overlay on any drop/dragend anywhere in the document+ useEffect(() => {+ const clear = () => setDragOver(false);+ document.addEventListener("drop", clear);+ document.addEventListener("dragend", clear);+ return () => {+ document.removeEventListener("drop", clear);+ document.removeEventListener("dragend", clear);+ };+ }, []);+// Readonly content update: when defaultValue changes and editor is readonly,// re-set the content (e.g. after editing a comment, the readonly view updates)useEffect(() => {@@ -199,7 +210,7 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(return (<div- className={cn("relative", dragOver && "editor-drag-over")}+ className={cn("relative min-h-full", dragOver && "editor-drag-over")}onDragEnter={(e) => {e.preventDefault();if (editable && e.dataTransfer.types.includes("Files"))@@ -212,7 +223,23 @@ const ContentEditor = forwardRef<ContentEditorRef, ContentEditorProps>(if (!e.currentTarget.contains(e.relatedTarget as Node))setDragOver(false);}}- onDrop={() => setDragOver(false)}+ onDrop={(e) => {+ const alreadyHandled = e.nativeEvent.defaultPrevented;+ e.preventDefault();+ setDragOver(false);+ // Only upload if ProseMirror didn't already handle the drop.+ // When drop lands on the editor area, ProseMirror's handleDrop+ // processes it and calls preventDefault on the native event.+ // This fallback only fires when the overlay intercepted the drop.+ if (alreadyHandled) return;+ const files = e.dataTransfer?.files;+ if (files?.length && editor && onUploadFileRef.current) {+ const endPos = editor.state.doc.content.size;+ for (const file of Array.from(files)) {+ uploadAndInsertFile(editor, file, onUploadFileRef.current, endPos);+ }+ }+ }}><EditorContent editor={editor} />{dragOver && (diff --git a/apps/web/features/editor/extensions/file-card.tsx b/apps/web/features/editor/extensions/file-card.tsxnew file mode 100644index 0000000000..a011b79211--- /dev/null+++ b/apps/web/features/editor/extensions/file-card.tsx@@ -0,0 +1,166 @@+"use client";++/**+ * FileCard — Tiptap node extension for rendering uploaded non-image files+ * as styled cards instead of plain markdown links.+ *+ * Markdown serialization: `[filename](href)` — standard link syntax.+ * Preprocessing in preprocess.ts converts standalone CDN file links back+ * to fileCard HTML on load, completing the roundtrip.+ */++import { Node, mergeAttributes } from "@tiptap/core";+import { ReactNodeViewRenderer, NodeViewWrapper } from "@tiptap/react";+import type { NodeViewProps } from "@tiptap/react";+import { FileText, Loader2, Download } from "lucide-react";+++// ---------------------------------------------------------------------------+// CDN URL detection+// ---------------------------------------------------------------------------++const IMAGE_EXTS = /\.(png|jpe?g|gif|webp|svg|ico|bmp|tiff?)$/i;++/** Check if a URL points to our upload CDN (CloudFront or S3 bucket). */+export function isCdnUrl(url: string): boolean {+ try {+ const u = new URL(url);+ return (+ u.hostname.endsWith(".copilothub.ai") ||+ u.hostname.endsWith(".amazonaws.com")+ );+ } catch {+ return false;+ }+}++/** Check if a CDN URL is a non-image file that should render as a file card. */+export function isFileCardUrl(url: string): boolean {+ return isCdnUrl(url) && !IMAGE_EXTS.test(new URL(url).pathname);+}++// ---------------------------------------------------------------------------+// Helpers+// ---------------------------------------------------------------------------++function formatFileSize(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;+}++// ---------------------------------------------------------------------------+// React NodeView+// ---------------------------------------------------------------------------++function FileCardView({ node }: NodeViewProps) {+ const href = (node.attrs.href as string) || "";+ const filename = (node.attrs.filename as string) || "";+ const fileSize = node.attrs.fileSize as number;+ const uploading = node.attrs.uploading as boolean;++ const openFile = () => {+ window.open(href, "_blank", "noopener,noreferrer");+ };++ return (+ <NodeViewWrapper as="div" className="file-card-node" data-type="fileCard">+ {/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}+ <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"+ contentEditable={false}+ onMouseDown={(e) => e.stopPropagation()}+ >+ {uploading ? (+ <Loader2 className="size-4 shrink-0 animate-spin text-muted-foreground" />+ ) : (+ <FileText className="size-4 shrink-0 text-muted-foreground" />+ )}+ <div className="min-w-0 flex-1">+ <p className="truncate text-sm">{uploading ? `Uploading ${filename}` : filename}</p>+ </div>+ {!uploading && href && (+ <button+ type="button"+ className="shrink-0 rounded-md p-1 text-muted-foreground transition-colors hover:bg-secondary hover:text-foreground"+ onMouseDown={(e) => {+ e.preventDefault();+ e.stopPropagation();+ openFile();+ }}+ >+ <Download className="size-3.5" />+ </button>+ )}+ </div>+ </NodeViewWrapper>+ );+}++// ---------------------------------------------------------------------------+// Tiptap Node Extension+// ---------------------------------------------------------------------------++export const FileCardExtension = Node.create({+ name: "fileCard",+ group: "block",+ atom: true,++ addAttributes() {+ return {+ href: {+ default: "",+ rendered: false, // Don't put href on DOM — prevents link behavior+ },+ filename: {+ default: "",+ rendered: false,+ },+ fileSize: {+ default: 0,+ rendered: false,+ },+ uploading: {+ default: false,+ rendered: false,+ },+ uploadId: {+ default: null,+ rendered: false,+ },+ };+ },++ parseHTML() {+ return [+ {+ tag: 'div[data-type="fileCard"]',+ getAttrs: (el) => ({+ href: (el as HTMLElement).getAttribute("data-href"),+ filename: (el as HTMLElement).getAttribute("data-filename"),+ }),+ },+ ];+ },++ renderHTML({ node, HTMLAttributes }) {+ return [+ "div",+ mergeAttributes(HTMLAttributes, {+ "data-type": "fileCard",+ "data-href": node.attrs.href,+ "data-filename": node.attrs.filename,+ }),+ ];+ },++ // Markdown serialization: fileCard → [filename](href)+ renderMarkdown: (node: any) => {+ const { href, filename } = node.attrs || {};+ return `[${filename || "file"}](${href})`;+ },++ addNodeView() {+ return ReactNodeViewRenderer(FileCardView);+ },+});diff --git a/apps/web/features/editor/extensions/file-upload.ts b/apps/web/features/editor/extensions/file-upload.tsindex d1e36ebbf4..309f229e84 100644--- a/apps/web/features/editor/extensions/file-upload.ts+++ b/apps/web/features/editor/extensions/file-upload.ts@@ -1,8 +1,42 @@import { Extension } from "@tiptap/core";import { Plugin, PluginKey } from "@tiptap/pm/state";-import { toast } from "sonner";import type { UploadResult } from "@/shared/hooks/use-file-upload";-import { isAllowedFileType } from "@/shared/constants/upload";++/** Find and remove a fileCard node by uploadId. */+// eslint-disable-next-line @typescript-eslint/no-explicit-any+function removeUploadingFileCard(editor: any, uploadId: string) {+ const { tr } = editor.state;+ let deleted = false;+ editor.state.doc.descendants((node: any, pos: number) => {+ if (deleted) return false;+ if (node.type.name === "fileCard" && node.attrs.uploadId === uploadId) {+ tr.delete(pos, pos + node.nodeSize);+ deleted = true;+ return false;+ }+ });+ if (deleted) editor.view.dispatch(tr);+}++/** Update a fileCard node from uploading state to final state with real URL. */+// eslint-disable-next-line @typescript-eslint/no-explicit-any+function finalizeFileCard(editor: any, uploadId: string, href: string) {+ const { tr } = editor.state;+ let updated = false;+ editor.state.doc.descendants((node: any, nodePos: number) => {+ if (updated) return false;+ if (node.type.name === "fileCard" && node.attrs.uploadId === uploadId) {+ tr.setNodeMarkup(nodePos, undefined, {+ ...node.attrs,+ href,+ uploading: false,+ });+ updated = true;+ return false;+ }+ });+ if (updated) editor.view.dispatch(tr);+}// eslint-disable-next-line @typescript-eslint/no-explicit-anyfunction removeImageBySrc(editor: any, src: string) {@@ -46,7 +80,9 @@ export async function uploadAndInsertFile(const result = await handler(file);if (result) {const { tr } = editor.state;+ let found = false;editor.state.doc.descendants((node: { type: { name: string }; attrs: { src: string } }, nodePos: number) => {+ if (found) return false;if (node.type.name === "image" && node.attrs.src === blobUrl) {tr.setNodeMarkup(nodePos, undefined, {...node.attrs,@@ -54,9 +90,11 @@ export async function uploadAndInsertFile(alt: result.filename,uploading: false,});+ found = true;+ return false;}});- editor.view.dispatch(tr);+ if (found) editor.view.dispatch(tr);} else {removeImageBySrc(editor, blobUrl);}@@ -66,14 +104,25 @@ export async function uploadAndInsertFile(URL.revokeObjectURL(blobUrl);}} else {- // Non-image: upload first, then insert link- const result = await handler(file);- if (!result) return;- const linkText = `[${result.filename}](${result.link})`;+ // Non-image: insert skeleton fileCard → upload → finalize with real URL+ const uploadId = crypto.randomUUID();+ const cardAttrs = { filename: file.name, href: "", fileSize: file.size, uploading: true, uploadId };+ const insertContent = { type: "fileCard", attrs: cardAttrs };if (pos !== undefined) {- editor.chain().focus().insertContentAt(pos, linkText).run();+ editor.chain().focus().insertContentAt(pos, insertContent).run();} else {- editor.chain().focus().insertContent(linkText).run();+ editor.chain().focus().insertContent(insertContent).run();+ }++ try {+ const result = await handler(file);+ if (result) {+ finalizeFileCard(editor, uploadId, result.link);+ } else {+ removeUploadingFileCard(editor, uploadId);+ }+ } catch {+ removeUploadingFileCard(editor, uploadId);}}}@@ -90,10 +139,6 @@ export function createFileUploadExtension(const handler = onUploadFileRef.current;if (!handler) return false;for (const file of Array.from(files)) {- if (!isAllowedFileType(file.type, file.name)) {- toast.error(`Unsupported file type: ${file.name}`);- continue;- }await uploadAndInsertFile(editor, file, handler);}return true;@@ -110,11 +155,21 @@ export function createFileUploadExtension(handleFiles(files);return true;},- handleDrop(_view, event) {- const files = (event as DragEvent).dataTransfer?.files;+ handleDrop(view, event) {+ const dragEvent = event as DragEvent;+ const files = dragEvent.dataTransfer?.files;if (!files?.length) return false;- if (!onUploadFileRef.current) return false;- handleFiles(files);+ const handler = onUploadFileRef.current;+ if (!handler) return false;+ // Resolve drop position from mouse coordinates.+ // Only the first file uses the drop position; subsequent files+ // append to the end to avoid stale position issues.+ const dropPos = view.posAtCoords({ left: dragEvent.clientX, top: dragEvent.clientY });+ const fileArray = Array.from(files);+ for (let i = 0; i < fileArray.length; i++) {+ const insertPos = i === 0 ? dropPos?.pos : undefined;+ uploadAndInsertFile(editor, fileArray[i]!, handler, insertPos);+ }return true;},},diff --git a/apps/web/features/editor/extensions/image-view.tsx b/apps/web/features/editor/extensions/image-view.tsxnew file mode 100644index 0000000000..945cc4b65d--- /dev/null+++ b/apps/web/features/editor/extensions/image-view.tsx@@ -0,0 +1,146 @@+"use client";++import { useEffect, useState } from "react";+import { createPortal } from "react-dom";+import { NodeViewWrapper } from "@tiptap/react";+import type { NodeViewProps } from "@tiptap/react";+import {+ Maximize2,+ Download,+ Link as LinkIcon,+ Trash2,+} from "lucide-react";+import { toast } from "sonner";+import { cn } from "@/lib/utils";++// ---------------------------------------------------------------------------+// Lightbox — full-screen image preview (ESC or click backdrop to close)+// ---------------------------------------------------------------------------++function ImageLightbox({+ src,+ alt,+ onClose,+}: {+ src: string;+ alt: string;+ onClose: () => void;+}) {+ useEffect(() => {+ const handler = (e: KeyboardEvent) => {+ if (e.key === "Escape") onClose();+ };+ document.addEventListener("keydown", handler);+ return () => document.removeEventListener("keydown", handler);+ }, [onClose]);++ return createPortal(+ // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions+ <div+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 cursor-zoom-out"+ onClick={onClose}+ >+ {/* eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions */}+ <img+ src={src}+ alt={alt}+ className="max-h-[90vh] max-w-[90vw] rounded-lg object-contain"+ onClick={(e) => e.stopPropagation()}+ />+ </div>,+ document.body,+ );+}++// ---------------------------------------------------------------------------+// Image NodeView — renders img with hover toolbar + lightbox+// ---------------------------------------------------------------------------++function ImageView({ node, editor, selected, deleteNode }: NodeViewProps) {+ const src = node.attrs.src as string;+ const alt = (node.attrs.alt as string) || "";+ const title = node.attrs.title as string | undefined;+ const uploading = node.attrs.uploading as boolean;++ const [lightbox, setLightbox] = useState(false);+ const isEditable = editor.isEditable;++ const handleView = () => setLightbox(true);++ 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");+ };++ const handleCopyLink = async () => {+ try {+ await navigator.clipboard.writeText(src);+ toast.success("Link copied");+ } catch {+ toast.error("Failed to copy link");+ }+ };++ return (+ <NodeViewWrapper className="image-node">+ {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */}+ <figure+ className={cn(+ "image-figure",+ selected && isEditable && "image-selected",+ )}+ contentEditable={false}+ onClick={!isEditable && !uploading ? handleView : undefined}+ >+ <img+ src={src}+ alt={alt}+ title={title || undefined}+ className={cn("image-content", uploading && "image-uploading")}+ draggable={false}+ />+ {!uploading && (+ <div+ className="image-toolbar"+ onMouseDown={(e) => e.stopPropagation()}+ onClick={(e) => e.stopPropagation()}+ >+ <button type="button" onClick={handleView} title="View image">+ <Maximize2 className="size-3.5" />+ </button>+ <button type="button" onClick={handleDownload} title="Download">+ <Download className="size-3.5" />+ </button>+ <button+ type="button"+ onClick={handleCopyLink}+ title="Copy link"+ >+ <LinkIcon className="size-3.5" />+ </button>+ {isEditable && (+ <button+ type="button"+ onClick={() => deleteNode()}+ title="Delete"+ >+ <Trash2 className="size-3.5" />+ </button>+ )}+ </div>+ )}+ </figure>+ {lightbox && (+ <ImageLightbox+ src={src}+ alt={alt}+ onClose={() => setLightbox(false)}+ />+ )}+ </NodeViewWrapper>+ );+}++export { ImageView, ImageLightbox };diff --git a/apps/web/features/editor/extensions/index.ts b/apps/web/features/editor/extensions/index.tsindex 4052c6d5f7..0444d58626 100644--- a/apps/web/features/editor/extensions/index.ts+++ b/apps/web/features/editor/extensions/index.ts@@ -41,6 +41,8 @@ import { CodeBlockView } from "./code-block-view";import { createMarkdownPasteExtension } from "./markdown-paste";import { createSubmitExtension } from "./submit-shortcut";import { createFileUploadExtension } from "./file-upload";+import { FileCardExtension } from "./file-card";+import { ImageView } from "./image-view";const lowlight = createLowlight(common);@@ -67,10 +69,12 @@ const ImageExtension = Image.extend({},};},+ addNodeView() {+ return ReactNodeViewRenderer(ImageView);+ },}).configure({inline: false,allowBase64: false,- HTMLAttributes: { style: "max-width: 100%; height: auto;" },});export interface EditorExtensionsOptions {@@ -106,6 +110,7 @@ export function createEditorExtensions(TableHeader,TableCell,Markdown,+ FileCardExtension,BaseMentionExtension.configure({HTMLAttributes: { class: "mention" },...(editable && options.queryClient ? { suggestion: createMentionSuggestion(options.queryClient) } : {}),diff --git a/apps/web/features/editor/readonly-content.tsx b/apps/web/features/editor/readonly-content.tsxindex 2dd5f8a1a3..3b2531d166 100644--- a/apps/web/features/editor/readonly-content.tsx+++ b/apps/web/features/editor/readonly-content.tsx@@ -16,7 +16,7 @@* - Rendering mentions with the same IssueMentionCard component and .mention class*/-import { useMemo } from "react";+import { useMemo, useState } from "react";import ReactMarkdown, {defaultUrlTransform,type Components,@@ -25,8 +25,11 @@ import remarkGfm from "remark-gfm";import rehypeRaw from "rehype-raw";import { createLowlight, common } from "lowlight";import { toHtml } from "hast-util-to-html";+import { Maximize2, Download, Link as LinkIcon, FileText } from "lucide-react";+import { toast } from "sonner";import { cn } from "@/lib/utils";import { IssueMentionCard } from "@/features/issues/components/issue-mention-card";+import { ImageLightbox } from "./extensions/image-view";import { preprocessMarkdown } from "./utils/preprocess";import "./content-editor.css";@@ -95,15 +98,80 @@ const components: Partial<Components> = {);},- // Images — constrain width (matches Tiptap Image extension inline style)- img: ({ src, alt, ...props }) => (- <img- src={src}- alt={alt ?? ""}- style={{ maxWidth: "100%", height: "auto" }}- {...props}- />- ),+ // Images — centered with toolbar + lightbox (matches Tiptap ImageView NodeView)+ img: function ReadonlyImage({ src, alt }) {+ 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("Link copied");+ } catch {+ toast.error("Failed to copy link");+ }+ };++ return (+ <span className="image-node">+ {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */}+ <span className="image-figure" onClick={handleView}>+ <img src={imgSrc} alt={imgAlt} className="image-content" draggable={false} />+ {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */}+ <span+ className="image-toolbar"+ onMouseDown={(e) => e.stopPropagation()}+ onClick={(e) => e.stopPropagation()}+ >+ <button type="button" onClick={handleView} title="View image">+ <Maximize2 className="size-3.5" />+ </button>+ <button type="button" onClick={handleDownload} title="Download">+ <Download className="size-3.5" />+ </button>+ <button type="button" onClick={handleCopyLink} title="Copy link">+ <LinkIcon className="size-3.5" />+ </button>+ </span>+ </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 href = (node?.properties?.dataHref as string) || "";+ 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>+ );+ }+ return <div {...props}>{children}</div>;+ },// Tables — wrap in tableWrapper div for border/radius/scroll (matches Tiptap)table: ({ children }) => (diff --git a/apps/web/features/editor/utils/preprocess.ts b/apps/web/features/editor/utils/preprocess.tsindex ffb4d25952..17f341a564 100644--- a/apps/web/features/editor/utils/preprocess.ts+++ b/apps/web/features/editor/utils/preprocess.ts@@ -1,5 +1,6 @@import { preprocessLinks } from "@/components/markdown/linkify";import { preprocessMentionShortcodes } from "@/components/markdown/mentions";+import { isFileCardUrl } from "../extensions/file-card";/*** Preprocess a markdown string before loading into Tiptap via contentType: 'markdown'.@@ -8,17 +9,40 @@ import { preprocessMentionShortcodes } from "@/components/markdown/mentions";* It does NOT convert to HTML — that was the old markdownToHtml.ts pipeline which* was deleted in the April 2026 refactor.*- * Two string→string transforms on raw Markdown:+ * Three string→string transforms on raw Markdown:* 1. Legacy mention shortcodes [@ id="..." label="..."] → [@Label](mention://member/id)* (old serialization format in database, migrated on read)* 2. Raw URLs → markdown links via linkify-it (so they render as clickable Link nodes)- *- * After this, @tiptap/markdown's parse() handles everything else: headings, lists,- * tables, code blocks, and our custom mention tokenizer ([@Name](mention://type/id)).+ * 3. CDN file links on their own line → HTML div for fileCard node parsing*/export function preprocessMarkdown(markdown: string): string {if (!markdown) return "";const step1 = preprocessMentionShortcodes(markdown);const step2 = preprocessLinks(step1);- return step2;+ const step3 = preprocessFileCards(step2);+ return step3;+}++/**+ * Convert standalone `[name](cdnUrl)` lines into HTML that Tiptap's fileCard+ * parseHTML can recognise. Only matches non-image CDN URLs on their own line.+ *+ * Input: `[report.pdf](https://multica-static.copilothub.ai/xxx.pdf)`+ * Output: `<div data-type="fileCard" data-href="url" data-filename="report.pdf"></div>`+ */+const FILE_LINK_LINE = /^\[([^\]]+)\]\((https?:\/\/[^)]+)\)$/;++function preprocessFileCards(markdown: string): string {+ return markdown+ .split("\n")+ .map((line) => {+ const trimmed = line.trim();+ const match = trimmed.match(FILE_LINK_LINE);+ if (!match) return line;+ const filename = match[1]!;+ const url = match[2]!;+ if (!isFileCardUrl(url)) return line;+ return `<div data-type="fileCard" data-href="${url}" data-filename="${filename}"></div>`;+ })+ .join("\n");}diff --git a/apps/web/features/issues/components/attachment-section.tsx b/apps/web/features/issues/components/attachment-section.tsxdeleted file mode 100644index 442f104311..0000000000--- a/apps/web/features/issues/components/attachment-section.tsx+++ /dev/null@@ -1,211 +0,0 @@-"use client";--import { useState } from "react";-import { Paperclip, FileText, Trash2, Download } from "lucide-react";-import type { Attachment } from "@/shared/types";--// ----------------------------------------------------------------------------// Helpers-// -----------------------------------------------------------------------------function isImageType(contentType: string): boolean {- return contentType.startsWith("image/");-}--function formatFileSize(bytes: number): string {- if (bytes < 1024) return `${bytes} B`;- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;-}--// ----------------------------------------------------------------------------// Props-// -----------------------------------------------------------------------------interface AttachmentSectionProps {- attachments: Attachment[];- onDelete?: (id: string) => void;- deleting?: boolean;-}--// ----------------------------------------------------------------------------// ImageThumbnail — shows delete confirmation overlay on click-// -----------------------------------------------------------------------------function ImageThumbnail({- attachment,- onDelete,- deleting,-}: {- attachment: Attachment;- onDelete?: (id: string) => void;- deleting?: boolean;-}) {- const [confirmDelete, setConfirmDelete] = useState(false);-- return (- <a- href={attachment.url}- target="_blank"- rel="noopener noreferrer"- className="group relative aspect-square overflow-hidden rounded-md border border-border bg-accent/10"- onClick={(e) => {- if (confirmDelete) e.preventDefault();- }}- >- {/* eslint-disable-next-line @next/next/no-img-element */}- <img- src={attachment.url}- alt={attachment.filename}- className="h-full w-full object-cover"- />-- {/* Hover overlay with delete button */}- {!confirmDelete && onDelete && (- <div className="absolute inset-0 flex items-end justify-end bg-black/0 opacity-0 transition-opacity group-hover:opacity-100">- <button- type="button"- className="m-1.5 flex h-6 w-6 items-center justify-center rounded bg-background/80 text-destructive hover:bg-background transition-colors"- onClick={(e) => {- e.preventDefault();- e.stopPropagation();- setConfirmDelete(true);- }}- >- <Trash2 className="h-3.5 w-3.5" />- </button>- </div>- )}-- {/* Delete confirmation overlay */}- {confirmDelete && (- <div className="absolute inset-0 flex flex-col items-center justify-center gap-2 bg-black/60 text-sm text-white">- <span>Delete?</span>- <div className="flex gap-2">- <button- type="button"- disabled={deleting}- className="rounded px-2 py-0.5 text-xs font-medium bg-destructive text-white hover:bg-destructive/90 transition-colors disabled:opacity-50"- onClick={(e) => {- e.preventDefault();- e.stopPropagation();- onDelete?.(attachment.id);- }}- >- Yes- </button>- <button- type="button"- className="rounded px-2 py-0.5 text-xs font-medium bg-background/80 text-foreground hover:bg-background transition-colors"- onClick={(e) => {- e.preventDefault();- e.stopPropagation();- setConfirmDelete(false);- }}- >- No- </button>- </div>- </div>- )}- </a>- );-}--// ----------------------------------------------------------------------------// FileCard — non-image attachment with download + delete on hover-// -----------------------------------------------------------------------------function FileCard({- attachment,- onDelete,- deleting,-}: {- attachment: Attachment;- onDelete?: (id: string) => void;- deleting?: boolean;-}) {- return (- <div className="group flex items-center gap-2 rounded-md border border-border bg-accent/10 px-3 py-2 transition-colors hover:bg-accent">- <FileText className="h-4 w-4 shrink-0 text-muted-foreground" />- <div className="min-w-0 flex-1">- <p className="truncate text-sm">{attachment.filename}</p>- <p className="text-xs text-muted-foreground">- {formatFileSize(attachment.size_bytes)}- </p>- </div>- <div className="flex shrink-0 items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100">- <a- href={attachment.download_url}- download={attachment.filename}- className="flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground transition-colors"- onClick={(e) => e.stopPropagation()}- >- <Download className="h-3.5 w-3.5" />- </a>- {onDelete && (- <button- type="button"- disabled={deleting}- className="flex h-6 w-6 items-center justify-center rounded text-destructive hover:bg-accent transition-colors disabled:opacity-50"- onClick={() => onDelete(attachment.id)}- >- <Trash2 className="h-3.5 w-3.5" />- </button>- )}- </div>- </div>- );-}--// ----------------------------------------------------------------------------// AttachmentSection-// -----------------------------------------------------------------------------export function AttachmentSection({- attachments,- onDelete,- deleting,-}: AttachmentSectionProps) {- if (attachments.length === 0) return null;-- const images = attachments.filter((a) => isImageType(a.content_type));- const files = attachments.filter((a) => !isImageType(a.content_type));-- return (- <div className="space-y-3">- <div className="flex items-center gap-1.5 text-sm font-medium text-muted-foreground">- <Paperclip className="h-4 w-4" />- <span>Attachments ({attachments.length})</span>- </div>-- {/* Image grid */}- {images.length > 0 && (- <div className="grid grid-cols-4 gap-2">- {images.map((a) => (- <ImageThumbnail- key={a.id}- attachment={a}- onDelete={onDelete}- deleting={deleting}- />- ))}- </div>- )}-- {/* File list */}- {files.length > 0 && (- <div className="flex flex-col gap-2">- {files.map((a) => (- <FileCard- key={a.id}- attachment={a}- onDelete={onDelete}- deleting={deleting}- />- ))}- </div>- )}- </div>- );-}diff --git a/apps/web/features/issues/components/comment-card.tsx b/apps/web/features/issues/components/comment-card.tsxindex 90e5040064..f804917e33 100644--- a/apps/web/features/issues/components/comment-card.tsx+++ b/apps/web/features/issues/components/comment-card.tsx@@ -438,6 +438,7 @@ function CommentCard({defaultValue={entry.content ?? ""}placeholder="Edit comment..."onSubmit={saveEdit}+ onUploadFile={(file) => uploadWithToast(file, { issueId })}debounceMs={100}/></div>diff --git a/apps/web/features/issues/components/issue-detail.tsx b/apps/web/features/issues/components/issue-detail.tsxindex 3c42400d3c..da21eb56bd 100644--- a/apps/web/features/issues/components/issue-detail.tsx+++ b/apps/web/features/issues/components/issue-detail.tsx@@ -63,7 +63,7 @@ import { StatusIcon, PriorityIcon, DueDatePicker, AssigneePicker, canAssignAgentimport { CommentCard } from "./comment-card";import { CommentInput } from "./comment-input";import { AgentLiveCard, TaskRunHistory } from "./agent-live-card";-import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";+import { useQuery, useQueryClient } from "@tanstack/react-query";import { useAuthStore } from "@/features/auth";import { useWorkspaceStore, useActorName } from "@/features/workspace";import { useWorkspaceId } from "@core/hooks";@@ -76,7 +76,6 @@ import { useIssueSubscribers } from "@/features/issues/hooks/use-issue-subscribeimport { ReactionBar } from "@/components/common/reaction-bar";import { useFileUpload } from "@/shared/hooks/use-file-upload";import { api } from "@/shared/api";-import { AttachmentSection } from "./attachment-section";import { timeAgo } from "@/shared/utils";function shortDate(date: string | null): string {@@ -194,18 +193,6 @@ export function IssueDetail({ issueId, onDelete, defaultSidebarOpen = true, layoconst { uploadWithToast } = useFileUpload();const queryClient = useQueryClient();- // Attachments- const { data: attachments } = useQuery({- queryKey: ["attachments", id],- queryFn: () => api.listAttachments(id),- staleTime: Infinity,- });- const deleteAttachment = useMutation({- mutationFn: (attachmentId: string) => api.deleteAttachment(attachmentId),- onSuccess: () => {- queryClient.invalidateQueries({ queryKey: ["attachments", id] });- },- });const { defaultLayout, onLayoutChanged } = useDefaultLayout({id: layoutId,});@@ -673,16 +660,6 @@ export function IssueDetail({ issueId, onDelete, defaultSidebarOpen = true, layo/></div>- {attachments && attachments.length > 0 && (- <div className="mt-4">- <AttachmentSection- attachments={attachments}- onDelete={(attId) => deleteAttachment.mutate(attId)}- deleting={deleteAttachment.isPending}- />- </div>- )}-<div className="my-8 border-t" />{/* Activity / Comments */}diff --git a/apps/web/shared/constants/__tests__/upload.test.ts b/apps/web/shared/constants/__tests__/upload.test.tsindex 4f0cc2b3dc..b1051002f8 100644--- a/apps/web/shared/constants/__tests__/upload.test.ts+++ b/apps/web/shared/constants/__tests__/upload.test.ts@@ -1,82 +1,8 @@import { describe, it, expect } from "vitest";-import {- isAllowedFileType,- ALLOWED_MIME_PATTERNS,- MAX_FILE_SIZE,-} from "../upload";+import { MAX_FILE_SIZE } from "../upload";describe("upload constants", () => {- it("allows standard image types", () => {- expect(isAllowedFileType("image/png")).toBe(true);- expect(isAllowedFileType("image/jpeg")).toBe(true);- expect(isAllowedFileType("image/gif")).toBe(true);- expect(isAllowedFileType("image/webp")).toBe(true);- expect(isAllowedFileType("image/svg+xml")).toBe(true);- });-- it("allows PDF", () => {- expect(isAllowedFileType("application/pdf")).toBe(true);- });-- it("allows text types via wildcard", () => {- expect(isAllowedFileType("text/plain")).toBe(true);- expect(isAllowedFileType("text/markdown")).toBe(true);- expect(isAllowedFileType("text/csv")).toBe(true);- expect(isAllowedFileType("text/html")).toBe(true);- expect(isAllowedFileType("text/x-python")).toBe(true);- });-- it("allows JSON", () => {- expect(isAllowedFileType("application/json")).toBe(true);- });-- it("rejects video/audio", () => {- expect(isAllowedFileType("video/mp4")).toBe(false);- expect(isAllowedFileType("audio/mpeg")).toBe(false);- });-- it("rejects Office binary formats", () => {- expect(- isAllowedFileType(- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",- ),- ).toBe(false);- });-- it("rejects unknown types", () => {- expect(isAllowedFileType("application/octet-stream")).toBe(false);- });-- it("handles case-insensitivity", () => {- expect(isAllowedFileType("IMAGE/PNG")).toBe(true);- expect(isAllowedFileType("Text/Plain")).toBe(true);- });-- it("rejects empty MIME type without filename", () => {- expect(isAllowedFileType("")).toBe(false);- });-- it("falls back to extension when MIME type is empty", () => {- expect(isAllowedFileType("", "main.go")).toBe(true);- expect(isAllowedFileType("", "lib.rs")).toBe(true);- expect(isAllowedFileType("", "config.toml")).toBe(true);- expect(isAllowedFileType("", "data.yaml")).toBe(true);- expect(isAllowedFileType("", "script.py")).toBe(true);- expect(isAllowedFileType("", "notes.md")).toBe(true);- });-- it("rejects unknown extension even with fallback", () => {- expect(isAllowedFileType("", "video.mp4")).toBe(false);- expect(isAllowedFileType("", "archive.zip")).toBe(false);- expect(isAllowedFileType("", "noext")).toBe(false);- });-it("exports MAX_FILE_SIZE as 100MB", () => {expect(MAX_FILE_SIZE).toBe(100 * 1024 * 1024);});-- it("exports ALLOWED_MIME_PATTERNS as non-empty array", () => {- expect(ALLOWED_MIME_PATTERNS).toBeInstanceOf(Array);- expect(ALLOWED_MIME_PATTERNS.length).toBeGreaterThan(0);- });});diff --git a/apps/web/shared/constants/upload.ts b/apps/web/shared/constants/upload.tsindex ee320dae8d..c5215d0c0a 100644--- a/apps/web/shared/constants/upload.ts+++ b/apps/web/shared/constants/upload.ts@@ -1,118 +1 @@-/**- * Upload file type configuration.- *- * Aligned with what Claude Code agents can natively read:- * - Images: multimodal vision (Read tool)- * - PDF: Read tool (max 20 pages at a time)- * - Text/code: Read tool (plain text)- * - JSON: Read tool (plain text)- *- * NOT supported (Agent can't read):- * - Video/audio: Claude has no AV processing- * - Office binary (.docx/.xlsx): needs conversion tools- * - Arbitrary binaries: no use case- */-export const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100 MB--/** MIME patterns — exact match or wildcard (e.g. "text/*") */-export const ALLOWED_MIME_PATTERNS: readonly string[] = [- // Images (Agent: multimodal vision)- "image/png",- "image/jpeg",- "image/gif",- "image/webp",- "image/svg+xml",- // Documents (Agent: Read tool)- "application/pdf",- // Text & code (Agent: Read tool, plain text)- "text/*",- // Structured data (Agent: Read tool)- "application/json",-];--/**- * Extra file extensions for the HTML accept attribute.- * Needed because browsers don't always map these extensions to MIME types.- */-const EXTRA_EXTENSIONS = [- ".md", ".markdown", ".csv", ".json",- ".ts", ".tsx", ".js", ".jsx",- ".py", ".go", ".rs", ".rb", ".java",- ".c", ".cpp", ".h", ".sql",- ".yaml", ".yml", ".toml", ".xml", ".sh",- ".ipynb",-];--/**- * HTML accept attribute value for <input type="file">.- * Derived from ALLOWED_MIME_PATTERNS + extra extensions.- */-export const FILE_INPUT_ACCEPT = [- ...ALLOWED_MIME_PATTERNS,- ...EXTRA_EXTENSIONS,-].join(",");--/**- * Extension-to-MIME fallback for files where `file.type` is empty.- * Browsers often report "" for .go, .rs, .toml, .yaml, etc.- */-const EXTENSION_MIME_MAP: Record<string, string> = {- ".md": "text/markdown",- ".markdown": "text/markdown",- ".txt": "text/plain",- ".csv": "text/csv",- ".json": "application/json",- ".html": "text/html",- ".htm": "text/html",- ".xml": "text/xml",- ".svg": "image/svg+xml",- ".ts": "text/x-typescript",- ".tsx": "text/x-typescript",- ".js": "text/javascript",- ".jsx": "text/javascript",- ".py": "text/x-python",- ".go": "text/x-go",- ".rs": "text/x-rust",- ".rb": "text/x-ruby",- ".java": "text/x-java",- ".c": "text/x-c",- ".cpp": "text/x-c++",- ".h": "text/x-c",- ".sql": "text/x-sql",- ".yaml": "text/yaml",- ".yml": "text/yaml",- ".toml": "text/x-toml",- ".sh": "text/x-sh",- ".ipynb": "application/json",-};--function matchesMimePattern(mimeType: string): boolean {- const ct = mimeType.toLowerCase();- return ALLOWED_MIME_PATTERNS.some((pattern) => {- if (pattern.endsWith("/*")) {- return ct.startsWith(pattern.slice(0, -1));- }- return ct === pattern;- });-}--/**- * Check if a file is an allowed upload type.- * Uses MIME type when available, falls back to extension for files- * where the browser reports an empty type (e.g. .go, .rs, .toml).- */-export function isAllowedFileType(mimeType: string, filename?: string): boolean {- if (mimeType && matchesMimePattern(mimeType)) return true;-- // Fallback: infer MIME from extension when browser reports empty type- if (filename) {- const ext = filename.lastIndexOf(".") >= 0- ? filename.slice(filename.lastIndexOf(".")).toLowerCase()- : "";- const inferred = EXTENSION_MIME_MAP[ext];- if (inferred && matchesMimePattern(inferred)) return true;- }-- return false;-}diff --git a/apps/web/shared/hooks/use-file-upload.ts b/apps/web/shared/hooks/use-file-upload.tsindex c6ef546734..d069089749 100644--- a/apps/web/shared/hooks/use-file-upload.ts+++ b/apps/web/shared/hooks/use-file-upload.ts@@ -4,7 +4,7 @@ import { useState, useCallback } from "react";import { toast } from "sonner";import { api } from "@/shared/api";import type { Attachment } from "@/shared/types";-import { MAX_FILE_SIZE, isAllowedFileType } from "@/shared/constants/upload";+import { MAX_FILE_SIZE } from "@/shared/constants/upload";export interface UploadResult {id: string;@@ -22,12 +22,6 @@ export function useFileUpload() {const upload = useCallback(async (file: File, ctx?: UploadContext): Promise<UploadResult | null> => {- if (!isAllowedFileType(file.type, file.name)) {- throw new Error(- `Unsupported file type: ${file.type || file.name.split(".").pop()}`,- );- }-if (file.size > MAX_FILE_SIZE) {throw new Error("File exceeds 100 MB limit");}diff --git a/docs/plans/2026-04-08-drag-upload-enhancement.md b/docs/plans/2026-04-08-drag-upload-enhancement.mdnew file mode 100644index 0000000000..1c614a4825--- /dev/null+++ b/docs/plans/2026-04-08-drag-upload-enhancement.md@@ -0,0 +1,227 @@+# Drag & Drop Upload Enhancement — Revised Plan++> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.++**Goal:** Clean drag-and-drop upload with visual feedback. Images render inline, non-images show as file cards. No file type restrictions (match Linear). No separate attachment section (URLs live in markdown).++**Architecture:** Frontend-only. Images use existing `` markdown. Non-images use `[name](url)` markdown, rendered as a styled card via Tiptap NodeView when URL matches our CDN. Backend unchanged.++**Tech Stack:** Tiptap ProseMirror, React, Tailwind CSS, shadcn tokens++---++## What We Keep (from previous work)++- **Drag overlay** — `content-editor.tsx` drag handlers + `content-editor.css` overlay styles+- **Image upload flow** — blob preview → upload → replace with real URL (existing `file-upload.ts`)+- **Non-image upload placeholder** — `⏳ Uploading filename...` → replaced with link (existing `file-upload.ts`)+- **`MAX_FILE_SIZE`** — 100MB limit++## What We Remove (redundant)++| File | What to remove |+|------|----------------|+| `attachment-section.tsx` | **Delete entire file** |+| `issue-detail.tsx` | attachment query, delete mutation, handleImageRemoved, AttachmentSection JSX, onImageRemoved prop, all `["attachments"]` cache invalidation, onUploadSuccess on CommentInput, `api` import (if unused after) |+| `content-editor.tsx` | `onImageRemoved` prop, `onImageRemovedRef` |+| `extensions/index.ts` | `onImageRemovedRef` option |+| `extensions/file-upload.ts` | `collectImageSrcs`, `imageRemovalTracker` plugin, `isAllowedFileType` check + import, `toast` import |+| `shared/constants/upload.ts` | Everything except `MAX_FILE_SIZE` — remove `ALLOWED_MIME_PATTERNS`, `FILE_INPUT_ACCEPT`, `EXTENSION_MIME_MAP`, `isAllowedFileType`, `matchesMimePattern` |+| `shared/constants/__tests__/upload.test.ts` | All tests except MAX_FILE_SIZE |+| `shared/hooks/use-file-upload.ts` | `isAllowedFileType` import + check |+| `components/common/file-upload-button.tsx` | `FILE_INPUT_ACCEPT` import + `accept` attribute |+| `comment-input.tsx` | `onUploadSuccess` prop |++## What We Add (new)++**File Card Node** — a Tiptap custom node that renders `[name](url)` as a styled card when the URL matches our CDN (`multica-static.copilothub.ai` or S3 bucket domain).++```+Editor view: ┌──────────────────────────┐+ │ 📄 report.pdf ⬇ │+ └──────────────────────────┘++Markdown storage: [report.pdf](https://multica-static.copilothub.ai/xxx.pdf)+```++- Only for non-image CDN URLs (images stay as ``)+- Regular external links (github.com, etc.) stay as normal links+- Card shows: file type icon + filename + download button+- Readonly mode shows the same card++---++## Task 1: Remove Redundant Code++**Files to modify:**+- Delete: `apps/web/features/issues/components/attachment-section.tsx`+- Modify: `apps/web/features/issues/components/issue-detail.tsx`+- Modify: `apps/web/features/issues/components/comment-input.tsx`+- Modify: `apps/web/features/editor/content-editor.tsx`+- Modify: `apps/web/features/editor/extensions/index.ts`+- Modify: `apps/web/features/editor/extensions/file-upload.ts`+- Modify: `apps/web/shared/constants/upload.ts`+- Modify: `apps/web/shared/constants/__tests__/upload.test.ts`+- Modify: `apps/web/shared/hooks/use-file-upload.ts`+- Modify: `apps/web/components/common/file-upload-button.tsx`++**What to do:**+1. Delete `attachment-section.tsx`+2. `issue-detail.tsx`: Remove AttachmentSection import, attachment useQuery, deleteAttachment useMutation, handleImageRemoved, onImageRemoved prop, all `["attachments"]` invalidation in handleDescriptionUpload (revert to simple `uploadWithToast` call), remove onUploadSuccess from CommentInput+3. `comment-input.tsx`: Remove `onUploadSuccess` prop+4. `content-editor.tsx`: Remove `onImageRemoved` prop + ref + wiring+5. `extensions/index.ts`: Remove `onImageRemovedRef` from interface + call+6. `extensions/file-upload.ts`: Remove `collectImageSrcs`, `imageRemovalTracker` plugin, `onImageRemovedRef` param, `isAllowedFileType` import + check, `toast` import (keep `toast` if still used — check)+7. `shared/constants/upload.ts`: Keep only `MAX_FILE_SIZE`. Delete everything else.+8. `shared/constants/__tests__/upload.test.ts`: Keep only `MAX_FILE_SIZE` test+9. `shared/hooks/use-file-upload.ts`: Remove `isAllowedFileType` import + check. Import `MAX_FILE_SIZE` stays.+10. `file-upload-button.tsx`: Remove `FILE_INPUT_ACCEPT` import + `accept` attribute++**Verification:**+```bash+pnpm typecheck && pnpm test+```++**Commit:** `refactor(upload): remove attachment section and file type whitelist`++---++## Task 2: File Card Tiptap Node++**Files:**+- Create: `apps/web/features/editor/extensions/file-card.ts`+- Create: `apps/web/features/editor/extensions/file-card-view.tsx`+- Modify: `apps/web/features/editor/extensions/index.ts`+- Modify: `apps/web/features/editor/content-editor.css`++**Design:**++The node intercepts markdown links `[name](url)` where URL matches our CDN, and renders them as a card NodeView.++```typescript+// Detection: URL starts with CDN domain or known S3 bucket pattern+function isCdnFileUrl(url: string): boolean {+ try {+ const u = new URL(url);+ return u.hostname.endsWith('.copilothub.ai') || u.hostname.endsWith('.amazonaws.com');+ } catch {+ return false;+ }+}++// Only match non-image files (images stay as )+function isFileCardLink(url: string): boolean {+ return isCdnFileUrl(url) && !isImageUrl(url);+}+```++**Node spec:**+- Node name: `fileCard`+- Attrs: `href`, `filename`+- Markdown serialize: `[filename](href)`+- Markdown parse: detect `[text](cdnUrl)` where cdnUrl is non-image CDN link+- NodeView: React component with file icon + name + download button++**Card UI (React NodeView):**+```tsx+<div className="file-card">+ <FileText className="h-4 w-4 text-muted-foreground" />+ <span className="truncate text-sm">{filename}</span>+ <a href={href} download={filename} className="...">+ <Download className="h-3.5 w-3.5" />+ </a>+</div>+```++**CSS:**+```css+.file-card {+ display: inline-flex;+ align-items: center;+ gap: 0.5rem;+ padding: 0.375rem 0.75rem;+ border: 1px solid hsl(var(--border));+ border-radius: var(--radius);+ background: hsl(var(--accent) / 0.1);+ margin: 0.25rem 0;+ max-width: 100%;+}+```++**Verification:**+```bash+pnpm typecheck && pnpm test+```++Manual:+1. Upload a PDF → card appears in editor (not plain link)+2. Upload a .go file → card appears+3. Upload an image → still renders inline (not as card)+4. Paste an external link → still renders as normal link (not card)+5. Save and reload → card still displays correctly+6. Switch to readonly mode → card still displays++**Commit:** `feat(editor): render CDN file links as styled cards`++---++## Task 3: Update Non-Image Upload to Use File Card++**Files:**+- Modify: `apps/web/features/editor/extensions/file-upload.ts`++Currently the non-image upload path inserts a markdown string `[name](url)`. After Task 2 adds the fileCard node, this should insert a `fileCard` node directly instead:++```typescript+// Instead of:+const linkText = `[${result.filename}](${result.link})`;+replacePlaceholder(editor, placeholder, linkText);++// Insert fileCard node:+replacePlaceholder(editor, placeholder, "");+editor.chain().focus().insertContent({+ type: "fileCard",+ attrs: { href: result.link, filename: result.filename },+}).run();+```++**Verification:**+```bash+pnpm typecheck && pnpm test+```++Manual: Upload a PDF → placeholder appears → replaced with file card (not plain text link)++**Commit:** `feat(upload): insert file card node for non-image uploads`++---++## Task 4: Full Verification++```bash+pnpm typecheck && pnpm test+```++Manual test all upload flows:+1. Drag image → overlay → drop → inline image with pulse → real image+2. Drag PDF → overlay → drop → placeholder → file card+3. Drag .mp4 → uploads normally (no type restriction) → file card+4. Paste image → inline image+5. Click 📎 → file picker shows all types → upload works+6. Readonly mode → cards and images display correctly+7. Save → reload → everything persists++**Commit:** fix any issues found++---++## Expected Outcome++| Before (current) | After |+|-------------------|-------|+| File type whitelist blocks .mp4/.zip/etc | All files accepted (like Linear) |+| Attachment Section below description | Gone — files live in markdown |+| Non-image files as plain `[name](url)` text | Styled file card with icon + download |+| Image removal tracker + attachment cache | Gone — simpler code |+| ~300 lines of attachment UI code | Deleted |+| ~100 lines of whitelist code | Replaced by 1 line: `MAX_FILE_SIZE` |diff --git a/docs/plans/2026-04-08-image-view-enhancement.md b/docs/plans/2026-04-08-image-view-enhancement.mdnew file mode 100644index 0000000000..603d948743--- /dev/null+++ b/docs/plans/2026-04-08-image-view-enhancement.md@@ -0,0 +1,452 @@+# Image View Enhancement Implementation Plan++> **For Claude:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task.++**Goal:** Add image hover toolbar (view/download/copy image/copy link/delete), lightbox preview, and smart sizing (centered, max-width capped) — matching Linear's image UX.++**Architecture:** Convert the Image extension from default `<img>` rendering to a React NodeView (`image-view.tsx`). The NodeView wraps `<img>` in a `<figure>` with a hover toolbar and lightbox portal. CSS handles centering and size cap. No new npm dependencies.++**Tech Stack:** Tiptap `ReactNodeViewRenderer`, lucide-react, sonner (toast), CSS, `createPortal` for lightbox++---++## Task 1: Create Image NodeView Component++**Files:**+- Create: `apps/web/features/editor/extensions/image-view.tsx`++**Step 1: Create the ImageView component**++```tsx+// apps/web/features/editor/extensions/image-view.tsx+"use client";++import { useEffect, useState } from "react";+import { createPortal } from "react-dom";+import { NodeViewWrapper } from "@tiptap/react";+import type { NodeViewProps } from "@tiptap/react";+import {+ Maximize2,+ Download,+ Copy,+ Link as LinkIcon,+ Trash2,+} from "lucide-react";+import { toast } from "sonner";+import { cn } from "@/lib/utils";++// ---------------------------------------------------------------------------+// Lightbox — full-screen image preview (ESC or click backdrop to close)+// ---------------------------------------------------------------------------++function ImageLightbox({+ src,+ alt,+ onClose,+}: {+ src: string;+ alt: string;+ onClose: () => void;+}) {+ useEffect(() => {+ const handler = (e: KeyboardEvent) => {+ if (e.key === "Escape") onClose();+ };+ document.addEventListener("keydown", handler);+ return () => document.removeEventListener("keydown", handler);+ }, [onClose]);++ return createPortal(+ // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions+ <div+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 cursor-zoom-out"+ onClick={onClose}+ >+ <img+ src={src}+ alt={alt}+ className="max-h-[90vh] max-w-[90vw] rounded-lg object-contain"+ />+ </div>,+ document.body,+ );+}++// ---------------------------------------------------------------------------+// Image NodeView — renders <img> with hover toolbar + lightbox+// ---------------------------------------------------------------------------++function ImageView({ node, editor, selected, deleteNode }: NodeViewProps) {+ const src = node.attrs.src as string;+ const alt = (node.attrs.alt as string) || "";+ const title = node.attrs.title as string | undefined;+ const uploading = node.attrs.uploading as boolean;++ const [lightbox, setLightbox] = useState(false);+ const isEditable = editor.isEditable;++ const handleView = () => setLightbox(true);++ const handleDownload = async () => {+ try {+ const res = await fetch(src);+ const blob = await res.blob();+ const url = URL.createObjectURL(blob);+ const a = document.createElement("a");+ a.href = url;+ a.download = alt || "image";+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ URL.revokeObjectURL(url);+ } catch {+ window.open(src, "_blank", "noopener,noreferrer");+ }+ };++ const handleCopyImage = async () => {+ try {+ const res = await fetch(src);+ const blob = await res.blob();+ await navigator.clipboard.write([+ new ClipboardItem({ [blob.type]: blob }),+ ]);+ toast.success("Image copied");+ } catch {+ // Fallback: copy link (Safari doesn't support async clipboard image)+ await navigator.clipboard.writeText(src);+ toast.success("Link copied");+ }+ };++ const handleCopyLink = async () => {+ await navigator.clipboard.writeText(src);+ toast.success("Link copied");+ };++ return (+ <NodeViewWrapper className="image-node">+ {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */}+ <figure+ className={cn(+ "image-figure",+ selected && isEditable && "image-selected",+ )}+ contentEditable={false}+ onClick={!isEditable && !uploading ? handleView : undefined}+ >+ <img+ src={src}+ alt={alt}+ title={title || undefined}+ className={cn("image-content", uploading && "image-uploading")}+ draggable={false}+ />+ {!uploading && (+ <div+ className="image-toolbar"+ onMouseDown={(e) => e.stopPropagation()}+ onClick={(e) => e.stopPropagation()}+ >+ <button type="button" onClick={handleView} title="View image">+ <Maximize2 className="size-3.5" />+ </button>+ <button type="button" onClick={handleDownload} title="Download">+ <Download className="size-3.5" />+ </button>+ <button+ type="button"+ onClick={handleCopyImage}+ title="Copy image"+ >+ <Copy className="size-3.5" />+ </button>+ <button+ type="button"+ onClick={handleCopyLink}+ title="Copy link"+ >+ <LinkIcon className="size-3.5" />+ </button>+ {isEditable && (+ <button+ type="button"+ onClick={() => deleteNode()}+ title="Delete"+ >+ <Trash2 className="size-3.5" />+ </button>+ )}+ </div>+ )}+ </figure>+ {lightbox && (+ <ImageLightbox+ src={src}+ alt={alt}+ onClose={() => setLightbox(false)}+ />+ )}+ </NodeViewWrapper>+ );+}++export { ImageView };+```++**Step 2: Verify file created**++Run: `ls apps/web/features/editor/extensions/image-view.tsx`+Expected: file exists++---++## Task 2: Wire Up NodeView in Image Extension++**Files:**+- Modify: `apps/web/features/editor/extensions/index.ts:59-75`++**Step 1: Add import**++At the top of `index.ts`, after the existing imports, add:++```typescript+import { ImageView } from "./image-view";+```++**Step 2: Update ImageExtension — add NodeView, remove inline style**++Replace the `ImageExtension` definition (lines 59-75) with:++```typescript+const ImageExtension = Image.extend({+ addAttributes() {+ return {+ ...this.parent?.(),+ uploading: {+ default: false,+ renderHTML: (attrs: Record<string, unknown>) =>+ attrs.uploading ? { "data-uploading": "" } : {},+ parseHTML: (el: HTMLElement) => el.hasAttribute("data-uploading"),+ },+ };+ },+ addNodeView() {+ return ReactNodeViewRenderer(ImageView);+ },+}).configure({+ inline: false,+ allowBase64: false,+});+```++Key changes:+- Added `addNodeView()` — images now render via React component+- Removed `HTMLAttributes: { style: "max-width: 100%; height: auto;" }` — sizing is now in CSS++**Step 3: Run typecheck**++Run: `pnpm typecheck`+Expected: PASS++**Step 4: Commit**++```bash+git add apps/web/features/editor/extensions/image-view.tsx apps/web/features/editor/extensions/index.ts+git commit -m "feat(editor): add Image NodeView with toolbar and lightbox++- React NodeView renders images with hover toolbar (view/download/copy/link/delete)+- Lightbox portal for full-screen preview (ESC or click to close)+- Copy image with clipboard API (fallback to copy link on Safari)+- Delete button in edit mode only+- Readonly: click image opens lightbox"+```++---++## Task 3: Update Image CSS — Centering, sizing, toolbar, lightbox++**Files:**+- Modify: `apps/web/features/editor/content-editor.css:379-395`++**Step 1: Replace image CSS rules**++Replace lines 379-395 (from `/* Images — shared styling */` through the `@keyframes` block) with:++```css+/* Images — generic fallback (non-NodeView contexts) */+.rich-text-editor img {+ max-width: 100%;+ height: auto;+ border-radius: var(--radius);+ margin: 0.5rem 0;+}++/* Image NodeView — centered block with max-width cap */+.rich-text-editor .image-node {+ display: block !important;+ text-align: center;+}++.rich-text-editor .image-figure {+ position: relative;+ display: inline-block;+ max-width: min(100%, 640px);+ margin: 0.75rem 0;+}++.rich-text-editor .image-figure.image-selected .image-content {+ outline: 2px solid var(--brand);+ outline-offset: 2px;+}++.rich-text-editor .image-content {+ display: block;+ width: 100%;+ height: auto;+ border-radius: var(--radius);+}++.rich-text-editor .image-uploading {+ opacity: 0.5;+ animation: rte-upload-pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;+}++@keyframes rte-upload-pulse {+ 0%, 100% { opacity: 0.5; }+ 50% { opacity: 0.3; }+}++/* Readonly — zoom cursor on clickable images */+.rich-text-editor.readonly .image-figure {+ cursor: zoom-in;+}++/* Image toolbar — dark pill, top-right corner, appears on hover */+.image-toolbar {+ position: absolute;+ top: 0.5rem;+ right: 0.5rem;+ display: flex;+ gap: 1px;+ padding: 0.25rem;+ background: color-mix(in srgb, black 75%, transparent);+ backdrop-filter: blur(8px);+ border-radius: var(--radius);+ opacity: 0;+ transition: opacity 0.15s;+ z-index: 1;+}++.image-figure:hover .image-toolbar {+ opacity: 1;+}++.image-toolbar button {+ display: flex;+ align-items: center;+ justify-content: center;+ width: 1.75rem;+ height: 1.75rem;+ border-radius: calc(var(--radius) - 2px);+ color: white;+ transition: background 0.15s;+}++.image-toolbar button:hover {+ background: color-mix(in srgb, white 15%, transparent);+}+```++**Step 2: Run typecheck**++Run: `pnpm typecheck`+Expected: PASS++**Step 3: Commit**++```bash+git add apps/web/features/editor/content-editor.css+git commit -m "style(editor): add image centering, sizing cap, and toolbar styles++- Images centered with max-width 640px cap (smart sizing)+- Dark hover toolbar with blur backdrop+- Selection outline for edit mode+- Zoom cursor for readonly mode+- Upload pulse animation preserved"+```++---++## Task 4: Full Verification++**Step 1: Run all checks**++Run: `pnpm typecheck && pnpm test`+Expected: all pass++**Step 2: Manual verification checklist**++Test in browser:++| # | Test | Expected |+|---|------|----------|+| 1 | Upload large screenshot | Centered, max 640px wide |+| 2 | Upload small image (< 300px) | Natural size, centered |+| 3 | Drag image into editor | Blob preview with pulse → real image |+| 4 | Hover image | Dark toolbar appears top-right (5 buttons edit, 4 readonly) |+| 5 | Toolbar → View image | Full-screen lightbox opens |+| 6 | Lightbox → ESC | Closes |+| 7 | Lightbox → click backdrop | Closes |+| 8 | Toolbar → Download | Browser downloads the image |+| 9 | Toolbar → Copy image | Toast "Image copied", image in clipboard |+| 10 | Toolbar → Copy link | Toast "Link copied", URL in clipboard |+| 11 | Toolbar → Delete | Image removed from editor |+| 12 | Click image (edit mode) | Blue selection outline appears |+| 13 | Select image → Backspace | Image deleted |+| 14 | Click image (readonly mode) | Opens lightbox directly |+| 15 | Readonly toolbar | No Delete button, other 4 buttons work |+| 16 | Save → reload | Images persist with correct styling |++**Step 3: Fix any issues, re-run checks**++Run: `pnpm typecheck && pnpm test`++**Step 4: Commit fixes (if any)**++---++## Architecture Notes++### Why NodeView instead of CSS-only?++The toolbar buttons (view/download/copy/delete) require interactive React components overlaid on the image. CSS-only can handle sizing/centering but cannot add click handlers. A NodeView is the standard Tiptap pattern for this — same as `CodeBlockView` (copy button) and `FileCardView` (download button) already in the codebase.++### Upload flow compatibility++The existing upload flow in `file-upload.ts` uses `tr.setNodeMarkup()` to update image attributes after upload. This works with NodeView because ProseMirror attribute changes trigger React re-renders via `ReactNodeViewRenderer`. Same mechanism used by `FileCardView`'s `finalizeFileCard()`.++### Markdown serialization++No changes needed. Images serialize as `` — standard markdown. The NodeView only affects editor rendering, not serialization. No width/height stored in markdown (sizing is purely CSS).++### Lightbox implementation++Uses `createPortal` to render outside the editor DOM tree, with a keyboard listener for ESC. Intentionally NOT using shadcn Dialog to keep it minimal — no focus trapping or complex accessibility needed for a simple image preview overlay.++### Browser compatibility: Copy image++`navigator.clipboard.write()` with `ClipboardItem` works in Chrome/Edge. Safari requires the clipboard write to be in the same user gesture (no async fetch before write), so it falls back to copying the link URL with a toast notification.++---++## Expected Outcome++| Before | After |+|--------|-------|+| Images stretch to 100% width, left-aligned | Centered, capped at 640px |+| No hover actions on images | 5-button toolbar: View, Download, Copy, Link, Delete |+| No image preview | Click-to-zoom lightbox (ESC/click to close) |+| Readonly images are static | Click to zoom, hover for toolbar (minus Delete) |+| Delete image: select + backspace only | Toolbar Delete button + keyboard |+| No visual selection feedback | Blue outline on selected image |