import { useCallback, useEffect, useRef, useState } from "preact/hooks"; import { Copy, Download, FileText, Image, LoaderCircle } from "lucide-preact"; import { attachmentSize, type AgentAttachment } from "@/lib/agent-attachments"; type Props = { file: AgentAttachment; inline?: boolean; download(file: AgentAttachment, signal?: AbortSignal): Promise }; /** Authenticated bytes only; no native credential, remote href, or public file serving. */ export function AgentAttachmentCard({ file, download, inline = false }: Props) { const [preview, setPreview] = useState(); const [error, setError] = useState(); const [busy, setBusy] = useState(false); const [copied, setCopied] = useState(false); const controller = useRef(); const transferring = useRef(false); useEffect(() => () => { if (preview) URL.revokeObjectURL(preview); }, [preview]); const retrieve = useCallback(async (show: boolean) => { if (transferring.current) return; transferring.current = true; const request = new AbortController(); controller.current = request; setBusy(true); setError(undefined); try { const blob = await download(file, request.signal); if (request.signal.aborted) return; const url = URL.createObjectURL(blob); if (show && file.kind === "image" && ["image/png", "image/jpeg", "image/gif", "image/webp"].includes(blob.type)) setPreview(url); else { const anchor = document.createElement("a"); anchor.href = url; anchor.download = file.filename; anchor.click(); setTimeout(() => URL.revokeObjectURL(url), 1000); } } catch (failure) { if (!request.signal.aborted) setError(failure instanceof Error ? failure.message : "Download failed."); } finally { if (controller.current === request) { transferring.current = false; if (!request.signal.aborted) setBusy(false); } } }, [download, file.id, file.sha256, file.mimeType, file.kind, file.sizeBytes, file.filename]); useEffect(() => { setPreview(undefined); setError(undefined); setBusy(false); transferring.current = false; if (inline && file.kind === "image") void retrieve(true); return () => { controller.current?.abort(); }; }, [inline, retrieve]); return
{file.filename}{attachmentSize(file.sizeBytes)}
{!inline && file.workspacePath ?
{file.workspacePath}
: null} {inline ?
{preview ? {file.filename} { setPreview(undefined); setError("Image could not be displayed."); }} /> : {error ? "Image unavailable" : "Loading image…"}}
: preview ? {file.filename} : null}
{file.kind === "image" && (!inline || error) ? : null}
{error ? {error} Retry using the buttons above. : null}
; }