Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat(web): preview community text attachments (#462)

Gener7f15a6f71c48
diff --git a/src/web/src/app/api/community/messages/[id]/route.test.ts b/src/web/src/app/api/community/messages/[id]/route.test.ts
index e910a6ba8..70f744bfb 100644
--- a/src/web/src/app/api/community/messages/[id]/route.test.ts
+++ b/src/web/src/app/api/community/messages/[id]/route.test.ts
@@ -140,7 +140,7 @@ describe("GET /api/community/messages/[id]", () => {
// id-addressed render URL (attachments fold), served by the canonical
// channels/{targetId}/attachments/{attachmentId} door.
expect(body.attachments).toEqual([
- { kind: "image", name: "photo.png", url: "/api/community/channels/c1/attachments/att_1" },
+ { kind: "image", name: "photo.png", url: "/api/community/channels/c1/attachments/att_1", contentType: "image/png", sizeBytes: 12345 },
])
// Reactions came through with `me: true` since userId matches.
expect(body.reactions).toEqual([
diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsx
index db9f3b2a5..fb4587de5 100644
--- a/src/web/src/app/c/me/[dmId]/page.tsx
+++ b/src/web/src/app/c/me/[dmId]/page.tsx
@@ -9,7 +9,7 @@ import { Avatar } from "@/components/community/avatar"
import { MessageList } from "@/components/community/message-list"
import { MessageContextSheet } from "@/components/community/message-context-sheet"
import { Composer, ComposerSkeleton, type SendAttachment } from "@/components/community/composer"
-import type { ImagePreview, OpenProfile } from "@/components/community/_types"
+import type { FileAttachment, ImagePreview, OpenProfile } from "@/components/community/_types"
import {
useCommunityStore,
useCurrentChannelId,
@@ -295,10 +295,13 @@ function DmView() {
onPreviewImage: (image: ImagePreview) => {
uiHandlers.previewImage?.(image)
},
- onDownloadFile: (url: string) => {
+ onPreviewAttachment: (attachment: FileAttachment) => {
+ uiHandlers.previewAttachment?.(attachment)
+ },
+ onDownloadFile: (url: string, name: string) => {
const a = document.createElement("a")
a.href = url
- a.download = url.split("/").pop() ?? "file"
+ a.download = name
a.click()
},
}), [toggleReaction, toggleMark, dmId, currentUser.id, messages, retryDmMessage, uiHandlers, advanceOnboardingAfterSend])
@@ -383,6 +386,7 @@ function DmView() {
onRetry={dmBlocked ? undefined : messageActions.onRetry}
onDismiss={dmBlocked ? undefined : messageActions.onDismiss}
onPreviewImage={messageActions.onPreviewImage}
+ onPreviewAttachment={messageActions.onPreviewAttachment}
onDownloadFile={messageActions.onDownloadFile}
onOpenProfile={openProfile}
resolveUserName={resolveUserName}
diff --git a/src/web/src/components/community/_types.ts b/src/web/src/components/community/_types.ts
index f444831cb..101ea4934 100644
--- a/src/web/src/components/community/_types.ts
+++ b/src/web/src/components/community/_types.ts
@@ -78,9 +78,18 @@ export type Category = {
}
// ── Messages ───────────────────────────────────────────────────────────────
+type AttachmentMetadata = {
+ name: string
+ url: string
+ contentType?: string
+ sizeBytes?: number
+}
+
+export type FileAttachment = AttachmentMetadata & { kind: "file"; size: string }
+
export type Attachment =
- | { kind: "image"; name: string; url: string; thumbnailUrl?: string; width?: number; height?: number }
- | { kind: "file"; name: string; url: string; size: string }
+ | (AttachmentMetadata & { kind: "image"; thumbnailUrl?: string; width?: number; height?: number })
+ | FileAttachment
export type ImagePreview = { originalUrl: string; thumbnailUrl?: string; name: string }
diff --git a/src/web/src/components/community/attachment-card.test.ts b/src/web/src/components/community/attachment-card.test.ts
new file mode 100644
index 000000000..f5403889b
--- /dev/null
+++ b/src/web/src/components/community/attachment-card.test.ts
@@ -0,0 +1,58 @@
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { describe, expect, it, vi } from "vitest"
+import { AttachmentCard } from "./attachment-card"
+import type { FileAttachment } from "./_types"
+
+function attachment(overrides: Partial<FileAttachment> = {}): FileAttachment {
+ return {
+ kind: "file",
+ name: "notes.md",
+ url: "/attachments/a1",
+ contentType: "text/markdown",
+ sizeBytes: 128,
+ size: "128 B",
+ ...overrides,
+ }
+}
+
+describe("AttachmentCard", () => {
+ it("opens previewable text through the shared preview handler", () => {
+ const onPreview = vi.fn()
+ const onDownload = vi.fn()
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(React.createElement(AttachmentCard, {
+ attachment: attachment(),
+ onPreview,
+ onDownload,
+ }))
+ })
+ const button = renderer!.root.findByType("button")
+ expect(button.props["data-attachment-category"]).toBe("text")
+ expect(button.props["aria-label"]).toBe("Preview notes.md")
+ act(() => button.props.onClick())
+ expect(onPreview).toHaveBeenCalledWith(attachment())
+ expect(onDownload).not.toHaveBeenCalled()
+ })
+
+ it("downloads unsupported files and preserves the original filename", () => {
+ const onPreview = vi.fn()
+ const onDownload = vi.fn()
+ const pdf = attachment({ name: "报告.pdf", contentType: "application/pdf" })
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(React.createElement(AttachmentCard, {
+ attachment: pdf,
+ onPreview,
+ onDownload,
+ }))
+ })
+ const button = renderer!.root.findByType("button")
+ expect(button.props["data-attachment-category"]).toBe("pdf")
+ expect(button.props["aria-label"]).toBe("Download 报告.pdf")
+ act(() => button.props.onClick())
+ expect(onDownload).toHaveBeenCalledWith("/attachments/a1", "报告.pdf")
+ expect(onPreview).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/components/community/attachment-card.tsx b/src/web/src/components/community/attachment-card.tsx
new file mode 100644
index 000000000..f69d58315
--- /dev/null
+++ b/src/web/src/components/community/attachment-card.tsx
@@ -0,0 +1,74 @@
+"use client"
+
+import type { LucideIcon } from "lucide-react"
+import {
+ Archive,
+ Download,
+ Eye,
+ File,
+ FileAudio,
+ FileCode2,
+ FileImage,
+ FileSpreadsheet,
+ FileText,
+ FileVideo,
+ Presentation,
+} from "lucide-react"
+import type { FileAttachment } from "./_types"
+import { tid } from "@/lib/community/testids"
+import {
+ resolveAttachmentPresentation,
+ type AttachmentCategory,
+} from "@/lib/community/attachment-presentation"
+
+const CATEGORY_ICONS: Record<AttachmentCategory, LucideIcon> = {
+ image: FileImage,
+ pdf: FileText,
+ document: FileText,
+ spreadsheet: FileSpreadsheet,
+ presentation: Presentation,
+ text: FileText,
+ code: FileCode2,
+ audio: FileAudio,
+ video: FileVideo,
+ archive: Archive,
+ unknown: File,
+}
+
+export function AttachmentCard({
+ attachment,
+ onPreview,
+ onDownload,
+}: {
+ attachment: FileAttachment
+ onPreview?: (attachment: FileAttachment) => void
+ onDownload?: (url: string, name: string) => void
+}) {
+ const presentation = resolveAttachmentPresentation(attachment.name, attachment.contentType)
+ const Icon = CATEGORY_ICONS[presentation.category]
+ const canPreview = presentation.previewKind !== null && !!onPreview
+ const ActionIcon = canPreview ? Eye : Download
+ const action = canPreview ? "Preview" : "Download"
+
+ return (
+ <button
+ type="button"
+ data-testid={tid.attachmentCard(attachment.name)}
+ data-attachment-category={presentation.category}
+ onClick={() => canPreview
+ ? onPreview(attachment)
+ : onDownload?.(attachment.url, attachment.name)}
+ className="flex w-full max-w-[320px] items-center gap-3 rounded-lg border border-border bg-card p-2 text-left transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
+ aria-label={`${action} ${attachment.name}`}
+ >
+ <Icon className="size-7 shrink-0 text-muted-foreground" />
+ <div className="min-w-0 flex-1">
+ <div className="truncate text-sm font-medium text-primary">{attachment.name}</div>
+ {attachment.size && (
+ <div className="text-xs text-muted-foreground">{attachment.size}</div>
+ )}
+ </div>
+ <ActionIcon className="size-4 shrink-0 text-muted-foreground" />
+ </button>
+ )
+}
diff --git a/src/web/src/components/community/attachment-preview-sheet.test.ts b/src/web/src/components/community/attachment-preview-sheet.test.ts
new file mode 100644
index 000000000..fe6a84e2d
--- /dev/null
+++ b/src/web/src/components/community/attachment-preview-sheet.test.ts
@@ -0,0 +1,124 @@
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { afterEach, describe, expect, it, vi } from "vitest"
+import { AttachmentPreviewSheet, readAttachmentText } from "./attachment-preview-sheet"
+import type { FileAttachment } from "./_types"
+
+vi.mock("@/components/ui/sheet", () => ({
+ Sheet: ({ children }: { children: React.ReactNode }) => React.createElement("div", null, children),
+ SheetContent: ({ children, ...props }: React.ComponentProps<"section">) => React.createElement("section", props, children),
+ SheetHeader: ({ children, ...props }: React.ComponentProps<"header">) => React.createElement("header", props, children),
+ SheetTitle: ({ children, ...props }: React.ComponentProps<"h2">) => React.createElement("h2", props, children),
+ SheetDescription: ({ children, ...props }: React.ComponentProps<"p">) => React.createElement("p", props, children),
+ SheetBody: ({ children, ...props }: React.ComponentProps<"main">) => React.createElement("main", props, children),
+}))
+
+vi.mock("@/components/ui/sheet-resize-handle", () => ({
+ useSheetResize: () => ({
+ width: 520,
+ onPointerDown: vi.fn(),
+ onPointerMove: vi.fn(),
+ onPointerUp: vi.fn(),
+ }),
+ SheetResizeHandle: () => null,
+}))
+
+vi.mock("./message-body", () => ({
+ MessageBody: ({ text }: { text: string }) => React.createElement("article", { "data-markdown": true }, text),
+}))
+
+function file(overrides: Partial<FileAttachment> = {}): FileAttachment {
+ return {
+ kind: "file",
+ name: "notes.md",
+ url: "/attachments/a1",
+ contentType: "text/markdown",
+ sizeBytes: 128,
+ size: "128 B",
+ ...overrides,
+ }
+}
+
+async function flush(): Promise<void> {
+ await act(async () => {
+ await Promise.resolve()
+ await Promise.resolve()
+ })
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+})
+
+describe("readAttachmentText", () => {
+ it("rejects denied and oversized responses", async () => {
+ await expect(readAttachmentText(new Response("no", { status: 404 }))).rejects.toThrow("404")
+ await expect(readAttachmentText(new Response("large", {
+ headers: { "content-length": String(1024 * 1024 + 1) },
+ }))).rejects.toThrow("too large")
+ })
+
+ it("limits a streamed response even without content-length", async () => {
+ const response = new Response(new Uint8Array([1, 2, 3, 4]))
+ await expect(readAttachmentText(response, 3)).rejects.toThrow("too large")
+ })
+})
+
+describe("AttachmentPreviewSheet", () => {
+ it("fetches private Markdown, renders it safely, and exposes metadata/download", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response("# Hello", { status: 200 }))
+ vi.stubGlobal("fetch", fetchMock)
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(AttachmentPreviewSheet, {
+ attachment: file(),
+ open: true,
+ onOpenChange: vi.fn(),
+ }))
+ })
+ await flush()
+ expect(fetchMock).toHaveBeenCalledWith("/attachments/a1", expect.objectContaining({ credentials: "same-origin" }))
+ expect(renderer!.root.findByProps({ "data-markdown": true }).children).toEqual(["# Hello"])
+ const download = renderer!.root.findByProps({ "data-testid": "community-attachment-preview-download" })
+ expect(download.props.href).toBe("/attachments/a1")
+ expect(download.props.download).toBe("notes.md")
+ expect(renderer!.root.findByType("p").children.join("")).toContain("text/markdown · 128 B")
+ })
+
+ it("aborts the old request on switch and never paints its stale result", async () => {
+ const requests: Array<{
+ resolve: (response: Response) => void
+ signal: AbortSignal
+ }> = []
+ vi.stubGlobal("fetch", vi.fn((_url: string, init: RequestInit) => new Promise<Response>((resolve) => {
+ requests.push({ resolve, signal: init.signal as AbortSignal })
+ })))
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(React.createElement(AttachmentPreviewSheet, {
+ attachment: file(),
+ open: true,
+ onOpenChange: vi.fn(),
+ }))
+ })
+ expect(requests).toHaveLength(1)
+
+ await act(async () => {
+ renderer!.update(React.createElement(AttachmentPreviewSheet, {
+ attachment: file({ name: "second.txt", url: "/attachments/a2", contentType: "text/plain" }),
+ open: true,
+ onOpenChange: vi.fn(),
+ }))
+ })
+ expect(requests[0]?.signal.aborted).toBe(true)
+ expect(requests).toHaveLength(2)
+
+ requests[1]!.resolve(new Response("second", { status: 200 }))
+ await flush()
+ expect(renderer!.root.findAllByType("pre")[0]?.children).toEqual(["second"])
+
+ requests[0]!.resolve(new Response("stale", { status: 200 }))
+ await flush()
+ expect(renderer!.root.findAllByType("pre")[0]?.children).toEqual(["second"])
+ })
+})
diff --git a/src/web/src/components/community/attachment-preview-sheet.tsx b/src/web/src/components/community/attachment-preview-sheet.tsx
new file mode 100644
index 000000000..ecd1835cf
--- /dev/null
+++ b/src/web/src/components/community/attachment-preview-sheet.tsx
@@ -0,0 +1,209 @@
+"use client"
+
+import { useEffect, useState } from "react"
+import { ArrowLeft, Download, Loader2, X } from "lucide-react"
+import { buttonVariants } from "@/components/ui/button"
+import {
+ Sheet,
+ SheetBody,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle,
+} from "@/components/ui/sheet"
+import { SheetResizeHandle, useSheetResize } from "@/components/ui/sheet-resize-handle"
+import { cn } from "@/lib/utils"
+import { MessageBody } from "./message-body"
+import type { FileAttachment } from "./_types"
+import { tid } from "@/lib/community/testids"
+import {
+ formatAttachmentSize,
+ MAX_TEXT_ATTACHMENT_PREVIEW_BYTES,
+ resolveAttachmentPresentation,
+} from "@/lib/community/attachment-presentation"
+
+type PreviewState =
+ | { status: "idle" | "loading"; content: null; error: null }
+ | { status: "ready"; content: string; error: null }
+ | { status: "error"; content: null; error: string }
+
+const IDLE_STATE: PreviewState = { status: "idle", content: null, error: null }
+
+export async function readAttachmentText(
+ response: Response,
+ maxBytes = MAX_TEXT_ATTACHMENT_PREVIEW_BYTES,
+ signal?: AbortSignal,
+): Promise<string> {
+ if (!response.ok) throw new Error(`Couldn’t load this attachment (${response.status})`)
+ const declaredLength = Number(response.headers.get("content-length"))
+ if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
+ throw new Error("This file is too large to preview")
+ }
+ if (!response.body) {
+ const bytes = new Uint8Array(await response.arrayBuffer())
+ if (bytes.byteLength > maxBytes) throw new Error("This file is too large to preview")
+ return new TextDecoder().decode(bytes)
+ }
+
+ const reader = response.body.getReader()
+ const decoder = new TextDecoder()
+ let byteLength = 0
+ let content = ""
+ try {
+ while (true) {
+ if (signal?.aborted) throw new DOMException("Aborted", "AbortError")
+ const { done, value } = await reader.read()
+ if (done) break
+ byteLength += value.byteLength
+ if (byteLength > maxBytes) {
+ await reader.cancel()
+ throw new Error("This file is too large to preview")
+ }
+ content += decoder.decode(value, { stream: true })
+ }
+ return content + decoder.decode()
+ } finally {
+ reader.releaseLock()
+ }
+}
+
+export function AttachmentPreviewSheet({
+ attachment,
+ open,
+ onOpenChange,
+}: {
+ attachment: FileAttachment | null
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const [selected, setSelected] = useState<FileAttachment | null>(attachment)
+ const [preview, setPreview] = useState<PreviewState>(IDLE_STATE)
+ const { width, onPointerDown, onPointerMove, onPointerUp } = useSheetResize({
+ defaultWidth: 520,
+ minWidth: 320,
+ maxWidthRatio: 0.8,
+ })
+
+ useEffect(() => {
+ if (attachment) setSelected(attachment)
+ }, [attachment])
+
+ useEffect(() => {
+ if (!open || !selected) {
+ setPreview(IDLE_STATE)
+ return
+ }
+ const presentation = resolveAttachmentPresentation(selected.name, selected.contentType)
+ if (!presentation.previewKind) {
+ setPreview({ status: "error", content: null, error: "This file type can’t be previewed" })
+ return
+ }
+ if (selected.sizeBytes !== undefined && selected.sizeBytes > MAX_TEXT_ATTACHMENT_PREVIEW_BYTES) {
+ setPreview({ status: "error", content: null, error: "This file is too large to preview" })
+ return
+ }
+
+ const controller = new AbortController()
+ let active = true
+ setPreview({ status: "loading", content: null, error: null })
+ fetch(selected.url, { credentials: "same-origin", signal: controller.signal })
+ .then((response) => readAttachmentText(response, MAX_TEXT_ATTACHMENT_PREVIEW_BYTES, controller.signal))
+ .then((content) => {
+ if (active) setPreview({ status: "ready", content, error: null })
+ })
+ .catch((error: unknown) => {
+ if (!active || controller.signal.aborted) return
+ setPreview({
+ status: "error",
+ content: null,
+ error: error instanceof Error ? error.message : "Couldn’t load this attachment",
+ })
+ })
+ return () => {
+ active = false
+ controller.abort()
+ }
+ }, [open, selected])
+
+ const presentation = selected
+ ? resolveAttachmentPresentation(selected.name, selected.contentType)
+ : null
+ const size = selected
+ ? formatAttachmentSize(selected.sizeBytes) || selected.size
+ : ""
+
+ return (
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent
+ data-testid={tid.attachmentPreviewSheet}
+ side="right"
+ showCloseButton={false}
+ style={{ width: `min(${width}px, 100vw)`, maxWidth: "none" }}
+ className="data-[side=right]:sm:inset-y-2 data-[side=right]:sm:right-2 data-[side=right]:sm:h-auto data-[side=right]:sm:rounded-xl data-[side=right]:sm:border"
+ >
+ <SheetResizeHandle
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={onPointerUp}
+ />
+ <SheetHeader className="pr-4 sm:pr-6">
+ <div className="flex min-w-0 items-center gap-2">
+ <button
+ type="button"
+ className={cn(buttonVariants({ variant: "ghost", size: "icon-sm" }), "size-11 shrink-0 sm:hidden")}
+ onClick={() => onOpenChange(false)}
+ aria-label="Close attachment preview"
+ >
+ <ArrowLeft className="size-4" />
+ </button>
+ <div className="min-w-0 flex-1">
+ <SheetTitle className="truncate">{selected?.name ?? "Attachment"}</SheetTitle>
+ <SheetDescription className="truncate">
+ {[selected?.contentType || presentation?.category, size].filter(Boolean).join(" · ")}
+ </SheetDescription>
+ </div>
+ {selected && (
+ <a
+ data-testid={tid.attachmentPreviewDownload}
+ href={selected.url}
+ download={selected.name}
+ className={buttonVariants({ variant: "outline", size: "sm", className: "h-11 sm:h-7" })}
+ >
+ <Download className="size-3.5" />
+ Download
+ </a>
+ )}
+ <button
+ type="button"
+ className={buttonVariants({ variant: "ghost", size: "icon-sm", className: "size-11 sm:size-7" })}
+ onClick={() => onOpenChange(false)}
+ aria-label="Close attachment preview"
+ >
+ <X className="size-4" />
+ </button>
+ </div>
+ </SheetHeader>
+ <SheetBody data-testid={tid.attachmentPreviewContent} className="min-h-0">
+ {preview.status === "loading" && (
+ <div className="flex items-center justify-center gap-2 py-8 text-sm text-muted-foreground">
+ <Loader2 className="size-4 animate-spin" />
+ Loading preview…
+ </div>
+ )}
+ {preview.status === "error" && (
+ <div className="flex min-h-40 flex-col items-center justify-center gap-2 text-center">
+ <p className="text-sm font-medium">Preview unavailable</p>
+ <p className="max-w-72 text-sm text-muted-foreground">{preview.error}</p>
+ </div>
+ )}
+ {preview.status === "ready" && presentation?.previewKind === "markdown" && (
+ <MessageBody text={preview.content} />
+ )}
+ {preview.status === "ready" && presentation?.previewKind !== "markdown" && (
+ <pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm text-foreground">{preview.content}</pre>
+ )}
+ </SheetBody>
+ </SheetContent>
+ </Sheet>
+ )
+}
diff --git a/src/web/src/components/community/message-channel-controller.tsx b/src/web/src/components/community/message-channel-controller.tsx
index 41cba910d..1de3ecd8a 100644
--- a/src/web/src/components/community/message-channel-controller.tsx
+++ b/src/web/src/components/community/message-channel-controller.tsx
@@ -6,7 +6,7 @@ import { toast } from "sonner"
import { deriveThreadName, type MentionType } from "@alook/shared"
import { apiFetch, toastApiError } from "@/lib/api/client"
import { avatarInitial } from "@/lib/community/avatar"
-import type { ImagePreview, Msg } from "@/components/community/_types"
+import type { FileAttachment, ImagePreview, Msg } from "@/components/community/_types"
import type { SendAttachment } from "@/components/community/composer"
import type { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"
import {
@@ -47,6 +47,7 @@ type Viewer = {
type MessageUiHandlers = {
navigate?: (serverId: string, channelId: string) => void
previewImage?: (image: ImagePreview) => void
+ previewAttachment?: (attachment: FileAttachment) => void
}
export function MessageChannelController({
@@ -373,10 +374,11 @@ export function MessageChannelController({
})
},
onPreviewImage: (image: ImagePreview) => actionContext.current.uiHandlers.previewImage?.(image),
- onDownloadFile: (url: string) => {
+ onPreviewAttachment: (attachment: FileAttachment) => actionContext.current.uiHandlers.previewAttachment?.(attachment),
+ onDownloadFile: (url: string, name: string) => {
const link = document.createElement("a")
link.href = url
- link.download = url.split("/").pop() ?? "file"
+ link.download = name
link.click()
},
}), [
@@ -510,7 +512,8 @@ export type MessageChannelControllerValue = {
onRetry: (id: string) => void
onDismiss: (id: string) => void
onPreviewImage: (image: ImagePreview) => void
- onDownloadFile: (url: string) => void
+ onPreviewAttachment: (attachment: FileAttachment) => void
+ onDownloadFile: (url: string, name: string) => void
}
threadActions: Omit<MessageChannelControllerValue["messageActions"], "onCreateThread"> & {
onCreateThread: undefined
diff --git a/src/web/src/components/community/message-context-sheet.tsx b/src/web/src/components/community/message-context-sheet.tsx
index 6ae8ec3ff..4fad7e8ba 100644
--- a/src/web/src/components/community/message-context-sheet.tsx
+++ b/src/web/src/components/community/message-context-sheet.tsx
@@ -18,7 +18,7 @@ import { DateDivider } from "./dividers"
import { useCurrentUser } from "@/contexts/community/current-user"
import { useUiHandlers } from "@/stores/community"
import { usePinMessage, useUnpinMessage, useCreateThread, useToggleMark } from "@/hooks/community/mutations"
-import type { ImagePreview, Msg, OpenProfile, Reaction, RenderMsg } from "./_types"
+import type { FileAttachment, ImagePreview, Msg, OpenProfile, Reaction, RenderMsg } from "./_types"
import type { MessagesPage } from "@/hooks/community/use-messages"
export type ReplyTarget = { id: string; authorName: string; text: string }
@@ -320,10 +320,14 @@ export function MessageContextSheet({
uiHandlers.previewImage?.(image)
}, [uiHandlers])
- const onDownloadFile = useCallback((url: string) => {
+ const onPreviewAttachment = useCallback((attachment: FileAttachment) => {
+ uiHandlers.previewAttachment?.(attachment)
+ }, [uiHandlers])
+
+ const onDownloadFile = useCallback((url: string, name: string) => {
const a = document.createElement("a")
a.href = url
- a.download = url.split("/").pop() ?? "file"
+ a.download = name
a.click()
}, [])
@@ -431,6 +435,7 @@ export function MessageContextSheet({
onMark={onMarkId}
onCreateThread={type === "channel" ? onCreateThreadId : undefined}
onPreviewImage={onPreviewImage}
+ onPreviewAttachment={onPreviewAttachment}
onDownloadFile={onDownloadFile}
/>
)}
@@ -456,6 +461,7 @@ function ContextRows({
onMark,
onCreateThread,
onPreviewImage,
+ onPreviewAttachment,
onDownloadFile,
}: {
rows: RenderMsg[]
@@ -473,7 +479,8 @@ function ContextRows({
onMark?: (id: string) => void
onCreateThread?: (id: string) => void
onPreviewImage: (image: ImagePreview) => void
- onDownloadFile: (url: string) => void
+ onPreviewAttachment: (attachment: FileAttachment) => void
+ onDownloadFile: (url: string, name: string) => void
}) {
// Single-message share from the peek sheet. The sheet has no select-mode
// context (it's a read-only preview), so Share opens the dialog directly on
@@ -516,6 +523,7 @@ function ContextRows({
onCreateThreadId={onCreateThread}
onCopyId={onCopy}
onPreviewImage={onPreviewImage}
+ onPreviewAttachment={onPreviewAttachment}
onDownloadFile={onDownloadFile}
resolveUserName={resolveUserName}
onShareSingleId={onShareSingleId}
diff --git a/src/web/src/components/community/message-list.tsx b/src/web/src/components/community/message-list.tsx
index b12935287..bb814d565 100644
--- a/src/web/src/components/community/message-list.tsx
+++ b/src/web/src/components/community/message-list.tsx
@@ -16,14 +16,14 @@ import { useScrollAnchor } from "@/hooks/community/use-scroll-anchor"
import { flattenMessageItems } from "./message-list-items"
import { VirtualRows } from "./virtual-cursor-list"
import { useVirtualCursorSentinel } from "@/hooks/community/use-virtual-cursor-sentinel"
-import type { ImagePreview, Msg, OpenProfile } from "./_types"
+import type { FileAttachment, ImagePreview, Msg, OpenProfile } from "./_types"
// Channel message list — welcome hero, date dividers, messages (with the NEW divider),
// and typing indicator. Data via props.
export function MessageList({
channel, messages, loading, pinnedIds, newDividerBefore, typingUsers, onOpenThread, onOpenProfile,
onToggleReaction, onReact,
- onReply, onPin, onMark, onCreateThread, onCopy, onEdit, onRetry, onDismiss, onPreviewImage, onDownloadFile,
+ onReply, onPin, onMark, onCreateThread, onCopy, onEdit, onRetry, onDismiss, onPreviewImage, onPreviewAttachment, onDownloadFile,
resolveUserName, scrollToMessageId, hero, variant = "channel", onScrollRoot, viewerUserId, initialScrollReady = true,
onScrollTargetConsumed,
hasMore, isFetchingOlder, onLoadOlder,
@@ -48,7 +48,8 @@ export function MessageList({
onRetry?: (id: string) => void
onDismiss?: (id: string) => void
onPreviewImage?: (image: ImagePreview) => void
- onDownloadFile?: (name: string) => void
+ onPreviewAttachment?: (attachment: FileAttachment) => void
+ onDownloadFile?: (url: string, name: string) => void
resolveUserName?: (userId: string) => string
scrollToMessageId?: string | null
hero?: React.ReactNode
@@ -468,6 +469,7 @@ export function MessageList({
onDismissId={onDismiss}
onJumpToId={jumpTo}
onPreviewImage={onPreviewImage}
+ onPreviewAttachment={onPreviewAttachment}
onDownloadFile={onDownloadFile}
resolveUserName={resolveUserName}
onImageLoad={onImageLoad}
diff --git a/src/web/src/components/community/message-row.tsx b/src/web/src/components/community/message-row.tsx
index 1667ba070..e93340eb9 100644
--- a/src/web/src/components/community/message-row.tsx
+++ b/src/web/src/components/community/message-row.tsx
@@ -2,7 +2,7 @@
import { memo, useCallback } from "react"
import { Message } from "./message"
-import type { ImagePreview, RenderMsg, OpenProfile } from "./_types"
+import type { FileAttachment, ImagePreview, RenderMsg, OpenProfile } from "./_types"
// A thin, memoized per-row wrapper between the virtualized list and `Message`.
//
@@ -34,7 +34,8 @@ export interface MessageRowProps {
onDismissId?: (id: string) => void
onJumpToId?: (id: string) => void
onPreviewImage?: (image: ImagePreview) => void
- onDownloadFile?: (name: string) => void
+ onPreviewAttachment?: (attachment: FileAttachment) => void
+ onDownloadFile?: (url: string, name: string) => void
resolveUserName?: (userId: string) => string
onImageLoad?: () => void
// Multi-select share. `selectMode`/`selected` are plain booleans (pass-through);
@@ -53,7 +54,7 @@ function MessageRowImpl(props: MessageRowProps) {
const {
m, viewerUserId, pinned, highlighted, onOpenThread, onOpenProfile,
onToggleReactionId, onReactId, onReplyId, onPinId, onMarkId, onCreateThreadId,
- onCopyId, onEditId, onRetryId, onDismissId, onJumpToId, onPreviewImage, onDownloadFile,
+ onCopyId, onEditId, onRetryId, onDismissId, onJumpToId, onPreviewImage, onPreviewAttachment, onDownloadFile,
resolveUserName, onImageLoad,
selectMode, selected, onToggleSelectId, onEnterSelectId, onShareSingleId,
} = props
@@ -106,6 +107,7 @@ function MessageRowImpl(props: MessageRowProps) {
onRetry={onRetryId ? onRetry : undefined}
onDismiss={onDismissId ? onDismiss : undefined}
onPreviewImage={onPreviewImage}
+ onPreviewAttachment={onPreviewAttachment}
onDownloadFile={onDownloadFile}
resolveUserName={resolveUserName}
onImageLoad={onImageLoad}
diff --git a/src/web/src/components/community/message.render.test.ts b/src/web/src/components/community/message.render.test.ts
index 7c6edb28d..0995644b1 100644
--- a/src/web/src/components/community/message.render.test.ts
+++ b/src/web/src/components/community/message.render.test.ts
@@ -177,6 +177,31 @@ describe("Message image attachment layout", () => {
})
})
+describe("Message file attachment", () => {
+ it("opens previewable files through the shared attachment card", () => {
+ const onPreviewAttachment = vi.fn()
+ const file = {
+ kind: "file" as const,
+ name: "notes.md",
+ url: "/notes",
+ contentType: "text/markdown",
+ sizeBytes: 128,
+ size: "128 B",
+ }
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(makeTree({
+ m: baseMsg({ attachments: [file] }),
+ onOpenThread: vi.fn(),
+ onPreviewAttachment,
+ }), { createNodeMock: () => genericMock })
+ })
+ const card = renderer!.root.findByProps({ "data-testid": "community-attachment-card-notes.md" })
+ act(() => card.props.onClick())
+ expect(onPreviewAttachment).toHaveBeenCalledWith(file)
+ })
+})
+
describe("Message lazy overlays", () => {
it("does not remount the row when the pointer enters an author button", () => {
const interactiveTarget = { closest: vi.fn(() => ({})) }
diff --git a/src/web/src/components/community/message.tsx b/src/web/src/components/community/message.tsx
index abba28f14..1c5abf403 100644
--- a/src/web/src/components/community/message.tsx
+++ b/src/web/src/components/community/message.tsx
@@ -5,7 +5,7 @@ import { useMessageMarked } from "@/hooks/community/use-inbox"
import type React from "react"
import {
MessagesSquare, UserPlus, SmilePlus, Reply,
- MoreHorizontal, FileText, Download, X, Share, Check,
+ MoreHorizontal, X, Share, Check,
} from "lucide-react"
import { ContextMenu, ContextMenuTrigger, ContextMenuContent } from "@/components/ui/context-menu"
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent } from "@/components/ui/dropdown-menu"
@@ -21,8 +21,9 @@ import { tid } from "@/lib/community/testids"
import { avatarInitial } from "@/lib/community/avatar"
import { displayName } from "@/lib/community/display-name"
import { stripInlineMarkup } from "@alook/shared"
-import type { ImagePreview, RenderMsg, OpenProfile } from "./_types"
+import type { FileAttachment, ImagePreview, RenderMsg, OpenProfile } from "./_types"
import { attachmentAspectRatio } from "./attachment-layout"
+import { AttachmentCard } from "./attachment-card"
// Whether the "Share as Image" action is offered for a message. Share is
// computed inside `Message` from the message alone (no handler is threaded in),
@@ -47,7 +48,7 @@ export function shouldActivateMessageOverlays(target: EventTarget | null): boole
function MessageImpl({
m, compact, pinned, onOpenThread, onOpenProfile, onJumpReply,
onToggleReaction, onReact, onReply, onPin, onMark, onCreateThread, onCopy, onEdit, onRetry, onDismiss,
- onPreviewImage, onDownloadFile, highlighted, resolveUserName, onImageLoad,
+ onPreviewImage, onPreviewAttachment, onDownloadFile, highlighted, resolveUserName, onImageLoad,
selectMode, selected, onToggleSelect, onEnterSelect, onShareSingle,
viewerUserId,
}: {
@@ -71,7 +72,8 @@ function MessageImpl({
onRetry?: () => void
onDismiss?: () => void
onPreviewImage?: (image: ImagePreview) => void
- onDownloadFile?: (name: string) => void
+ onPreviewAttachment?: (attachment: FileAttachment) => void
+ onDownloadFile?: (url: string, name: string) => void
highlighted?: boolean
resolveUserName?: (userId: string) => string
onImageLoad?: () => void
@@ -288,20 +290,7 @@ function MessageImpl({
/>
</button>
)
- return (
- <button
- key={i}
- onClick={() => onDownloadFile?.(a.url)}
- className="flex w-full max-w-[320px] items-center gap-3 rounded-lg border border-border bg-card p-2 text-left transition-colors hover:bg-accent"
- >
- <FileText className="size-7 shrink-0 text-muted-foreground" />
- <div className="min-w-0 flex-1">
- <div className="truncate text-sm font-medium text-primary">{a.name}</div>
- <div className="text-xs text-muted-foreground">{a.size}</div>
- </div>
- <Download className="size-4 shrink-0 text-muted-foreground" />
- </button>
- )
+ return <AttachmentCard key={i} attachment={a} onPreview={onPreviewAttachment} onDownload={onDownloadFile} />
})}
</div>
)}
@@ -529,6 +518,7 @@ function messagePropsEqual(prev: MessageProps, next: MessageProps): boolean {
prev.onRetry === next.onRetry &&
prev.onDismiss === next.onDismiss &&
prev.onPreviewImage === next.onPreviewImage &&
+ prev.onPreviewAttachment === next.onPreviewAttachment &&
prev.onDownloadFile === next.onDownloadFile &&
prev.resolveUserName === next.resolveUserName &&
prev.onImageLoad === next.onImageLoad &&
diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsx
index 11e37ec0c..ca8e28d26 100644
--- a/src/web/src/components/community/shell-frame.tsx
+++ b/src/web/src/components/community/shell-frame.tsx
@@ -26,9 +26,10 @@ import { InboxPopover } from "./community-inbox-popover"
import { UserSettings } from "./edit-profile-dialog"
import { ProfileCard } from "./profile-card"
import { ImageLightbox } from "./image-lightbox"
+import { AttachmentPreviewSheet } from "./attachment-preview-sheet"
import { ImageCropDialog } from "./image-crop-dialog"
import { validateIconSourceFile } from "@/lib/community/image-crop"
-import type { ImagePreview, Marked, MobileZone, Profile, View } from "./_types"
+import type { FileAttachment, ImagePreview, Marked, MobileZone, Profile, View } from "./_types"
import {
resolveProfileContextLabel,
resolveProfileServerId,
@@ -186,6 +187,7 @@ export function ShellFrame({
initialStatusText: string | null
} | null>(null)
const [preview, setPreview] = useState<ImagePreview | null>(null)
+ const [attachmentPreview, setAttachmentPreview] = useState<FileAttachment | null>(null)
const [pendingAvatarCrop, setPendingAvatarCrop] = useState<{ src: string; fileName: string } | null>(null)
// Rail wiring — universal, since navigation is URL-driven and doesn't
@@ -439,6 +441,7 @@ export function ShellFrame({
)
const previewImage = useCallback((image: ImagePreview) => setPreview(image), [])
+ const previewAttachment = useCallback((attachment: FileAttachment) => setAttachmentPreview(attachment), [])
const goBackMobile = useCallback(() => setMobileZone("nav"), [setMobileZone])
// Navigate for channel/server-ref pills. They live deep in the memoized
// Streamdown message tree where a subtree `useRouter().push` is a no-op; the
@@ -454,11 +457,12 @@ export function ShellFrame({
useEffect(() => {
useCommunityStore.getState().registerUiHandlers({
previewImage,
+ previewAttachment,
openProfile,
goBackMobile,
navigate,
})
- }, [previewImage, openProfile, goBackMobile, navigate])
+ }, [previewImage, previewAttachment, openProfile, goBackMobile, navigate])
// Inline self-status save from the `ProfileCard` header (see status-editor.tsx).
// Mirrors `userSettingsDialog`'s onSave status branch exactly — both save
@@ -746,6 +750,7 @@ export function ShellFrame({
</div>
{profile && <ProfileCard key={`${profile.data.userId ?? profile.data.name}:${profile.x}:${profile.y}`} data={profile.data} x={profile.x} y={profile.y} bp={bp} onClose={() => setProfile(null)} onMessage={profileMessage} isSelf={!!profile.data.userId && profile.data.userId === currentUser.id} onUpdateStatus={updateOwnStatus} initialStatusEmoji={profile.initialStatusEmoji} initialStatusText={profile.initialStatusText} />}
{preview && <ImageLightbox image={preview} onClose={() => setPreview(null)} />}
+ <AttachmentPreviewSheet attachment={attachmentPreview} open={!!attachmentPreview} onOpenChange={(open) => { if (!open) setAttachmentPreview(null) }} />
{userSettingsDialog}
{avatarCropDialog}
{extraDialogs}
@@ -771,6 +776,7 @@ export function ShellFrame({
)}
{profile && <ProfileCard key={`${profile.data.userId ?? profile.data.name}:${profile.x}:${profile.y}`} data={profile.data} x={profile.x} y={profile.y} bp={bp} onClose={() => setProfile(null)} onMessage={profileMessage} isSelf={!!profile.data.userId && profile.data.userId === currentUser.id} onUpdateStatus={updateOwnStatus} />}
{preview && <ImageLightbox image={preview} onClose={() => setPreview(null)} />}
+ <AttachmentPreviewSheet attachment={attachmentPreview} open={!!attachmentPreview} onOpenChange={(open) => { if (!open) setAttachmentPreview(null) }} />
{userSettingsDialog}
{avatarCropDialog}
{extraDialogs}
diff --git a/src/web/src/components/community/text-channel-surface.tsx b/src/web/src/components/community/text-channel-surface.tsx
index e229180a9..4ed944d8f 100644
--- a/src/web/src/components/community/text-channel-surface.tsx
+++ b/src/web/src/components/community/text-channel-surface.tsx
@@ -13,7 +13,7 @@ import { MessageList } from "@/components/community/message-list"
import {
MessageChannelController,
} from "@/components/community/message-channel-controller"
-import type { ImagePreview, OpenProfile, RightPanel } from "@/components/community/_types"
+import type { FileAttachment, ImagePreview, OpenProfile, RightPanel } from "@/components/community/_types"
export function TextChannelSurface({
channelId,
@@ -54,6 +54,7 @@ export function TextChannelSurface({
uiHandlers: {
navigate?: (serverId: string, channelId: string) => void
previewImage?: (image: ImagePreview) => void
+ previewAttachment?: (attachment: FileAttachment) => void
}
onOpenThread: (threadId: string) => void
onOpenProfile: OpenProfile
diff --git a/src/web/src/components/community/thread-channel-surface.test.ts b/src/web/src/components/community/thread-channel-surface.test.ts
index fcc6cd9c3..477c97bda 100644
--- a/src/web/src/components/community/thread-channel-surface.test.ts
+++ b/src/web/src/components/community/thread-channel-surface.test.ts
@@ -237,7 +237,7 @@ describe("ThreadChannelSurface ownership", () => {
expect(props.uiHandlers.previewImage).toHaveBeenCalledWith("https://example.test/image.png")
const anchor = { href: "", download: "", click: vi.fn() }
vi.stubGlobal("document", { createElement: vi.fn(() => anchor) })
- act(() => opener.props.onDownloadFile?.("https://example.test/report.pdf"))
+ act(() => opener.props.onDownloadFile?.("https://example.test/report.pdf", "report.pdf"))
expect(anchor).toEqual(expect.objectContaining({
href: "https://example.test/report.pdf",
download: "report.pdf",
diff --git a/src/web/src/components/community/thread-channel-surface.tsx b/src/web/src/components/community/thread-channel-surface.tsx
index f47b76cbc..470a2eb6a 100644
--- a/src/web/src/components/community/thread-channel-surface.tsx
+++ b/src/web/src/components/community/thread-channel-surface.tsx
@@ -14,7 +14,7 @@ import { MessageChannelController } from "@/components/community/message-channel
import { MessageContextSheet } from "@/components/community/message-context-sheet"
import { MessageList } from "@/components/community/message-list"
import { ThreadOpener } from "@/components/community/thread-opener"
-import type { ImagePreview, OpenProfile, RightPanel } from "@/components/community/_types"
+import type { FileAttachment, ImagePreview, OpenProfile, RightPanel } from "@/components/community/_types"
import type { ChannelMemberPanelProps } from "@/components/community/channel-member-view-model"
const ignoreNestedThread = () => {}
@@ -72,6 +72,7 @@ export function ThreadChannelSurface({
uiHandlers: {
navigate?: (serverId: string, channelId: string) => void
previewImage?: (image: ImagePreview) => void
+ previewAttachment?: (attachment: FileAttachment) => void
}
onOpenChild: (childId: string) => void
onOpenProfile: OpenProfile
@@ -156,10 +157,11 @@ export function ThreadChannelSurface({
viewerUserId={viewer.id}
onOpenProfile={onOpenProfile}
onPreviewImage={(image) => uiHandlers.previewImage?.(image)}
- onDownloadFile={(url) => {
+ onPreviewAttachment={(attachment) => uiHandlers.previewAttachment?.(attachment)}
+ onDownloadFile={(url, name) => {
const link = document.createElement("a")
link.href = url
- link.download = url.split("/").pop() ?? "file"
+ link.download = name
link.click()
}}
onJump={parentChannelId
diff --git a/src/web/src/components/community/thread-opener.test.ts b/src/web/src/components/community/thread-opener.test.ts
index 087d5e646..b980dafef 100644
--- a/src/web/src/components/community/thread-opener.test.ts
+++ b/src/web/src/components/community/thread-opener.test.ts
@@ -84,4 +84,35 @@ describe("ThreadOpener image attachment layout", () => {
originalUrl: "/original", thumbnailUrl: "/thumbnail", name: "photo.png",
})
})
+
+ it("uses the same previewable file card as regular messages", () => {
+ const onPreviewAttachment = vi.fn()
+ const file = {
+ kind: "file" as const,
+ name: "notes.md",
+ url: "/notes",
+ contentType: "text/markdown",
+ sizeBytes: 128,
+ size: "128 B",
+ }
+ useMessageMock.mockReturnValue({
+ isLoading: false,
+ isError: false,
+ message: {
+ id: "opener_1", type: "chat", authorId: "u1", authorName: "Alice",
+ content: "Notes", createdAt: "2026-08-08T00:00:00.000Z",
+ attachments: [file],
+ },
+ })
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(ThreadOpener, { parentMessageId: "opener_1", onPreviewAttachment }),
+ { createNodeMock: () => genericMock },
+ )
+ })
+ const card = renderer!.root.findByProps({ "data-testid": "community-attachment-card-notes.md" })
+ act(() => card.props.onClick())
+ expect(onPreviewAttachment).toHaveBeenCalledWith(file)
+ })
})
diff --git a/src/web/src/components/community/thread-opener.tsx b/src/web/src/components/community/thread-opener.tsx
index 4abc62529..aa271f246 100644
--- a/src/web/src/components/community/thread-opener.tsx
+++ b/src/web/src/components/community/thread-opener.tsx
@@ -1,6 +1,6 @@
"use client"
-import { MessagesSquare, FileText, Download, ArrowUpRight } from "lucide-react"
+import { MessagesSquare, ArrowUpRight } from "lucide-react"
import { Avatar } from "./avatar"
import { MessageBody } from "./message-body"
import { attachmentAspectRatio } from "./attachment-layout"
@@ -10,7 +10,8 @@ import { NumberTicker } from "@/components/ui/number-ticker"
import { avatarInitial } from "@/lib/community/avatar"
import { useMessage } from "@/hooks/community/use-message"
import { tid } from "@/lib/community/testids"
-import type { ImagePreview, OpenProfile } from "./_types"
+import type { FileAttachment, ImagePreview, OpenProfile } from "./_types"
+import { AttachmentCard } from "./attachment-card"
// Thread opener — the parent message the thread was created from, pinned at
// the top of the thread's message list. Deliberately styled like a REGULAR
@@ -31,6 +32,7 @@ export function ThreadOpener({
viewerUserId,
onOpenProfile,
onPreviewImage,
+ onPreviewAttachment,
onDownloadFile,
onJump,
}: {
@@ -38,7 +40,8 @@ export function ThreadOpener({
viewerUserId: string
onOpenProfile?: OpenProfile
onPreviewImage?: (image: ImagePreview) => void
- onDownloadFile?: (url: string) => void
+ onPreviewAttachment?: (attachment: FileAttachment) => void
+ onDownloadFile?: (url: string, name: string) => void
// Jump to the parent message in its channel. When provided, a hover-revealed
// "Jump" button appears in the opener's top-right.
onJump?: () => void
@@ -133,22 +136,7 @@ export function ThreadOpener({
/>
</button>
)
- return (
- <button
- key={i}
- onClick={() => onDownloadFile?.(a.url)}
- className="flex w-full max-w-[320px] items-center gap-3 rounded-lg border border-border bg-card p-2 text-left transition-colors hover:bg-accent"
- >
- <FileText className="size-7 shrink-0 text-muted-foreground" />
- <div className="min-w-0 flex-1">
- <div className="truncate text-sm font-medium text-primary">{a.name}</div>
- {"size" in a && a.size && (
- <div className="text-xs text-muted-foreground">{a.size}</div>
- )}
- </div>
- <Download className="size-4 shrink-0 text-muted-foreground" />
- </button>
- )
+ return <AttachmentCard key={i} attachment={a} onPreview={onPreviewAttachment} onDownload={onDownloadFile} />
})}
</div>
)}
diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.ts
index e16b2a1e7..9b5278c2e 100644
--- a/src/web/src/hooks/community/mutations/messages.ts
+++ b/src/web/src/hooks/community/mutations/messages.ts
@@ -11,6 +11,7 @@ import { apiFetch, toastApiError } from "@/lib/api/client"
import { ApiError } from "@/lib/errors"
import { communityKeys } from "@/lib/query-keys"
import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"
+import { formatAttachmentSize } from "@/lib/community/attachment-presentation"
import { attachmentThumbnailUrl, attachmentUrl } from "@/lib/community/storage"
import {
projectPostedMessage,
@@ -167,6 +168,8 @@ export function toAttachmentVm(
kind: "image",
name: a.filename,
url,
+ contentType: a.contentType,
+ sizeBytes: a.size,
...(a.hasThumbnail ? { thumbnailUrl: attachmentThumbnailUrl(channelId, a.id) } : {}),
width: a.width,
height: a.height,
@@ -175,7 +178,9 @@ export function toAttachmentVm(
kind: "file",
name: a.filename,
url,
- size: a.size ? `${Math.round(a.size / 1024)} KB` : "",
+ contentType: a.contentType,
+ sizeBytes: a.size,
+ size: formatAttachmentSize(a.size),
}
}
diff --git a/src/web/src/hooks/community/mutations/to-attachment-vm.test.ts b/src/web/src/hooks/community/mutations/to-attachment-vm.test.ts
index c799547a8..1e8980c8b 100644
--- a/src/web/src/hooks/community/mutations/to-attachment-vm.test.ts
+++ b/src/web/src/hooks/community/mutations/to-attachment-vm.test.ts
@@ -36,6 +36,8 @@ describe("toAttachmentVm", () => {
kind: "image",
name: "a.png",
url: "/api/community/channels/c1/attachments/att_1",
+ contentType: "image/png",
+ sizeBytes: 1000,
width: 1920,
height: 1080,
})
@@ -52,6 +54,8 @@ describe("toAttachmentVm", () => {
kind: "image",
name: "a.png",
url: "/api/community/channels/c1/attachments/att_1",
+ contentType: "image/png",
+ sizeBytes: 1000,
width: undefined,
height: undefined,
})
@@ -68,7 +72,9 @@ describe("toAttachmentVm", () => {
kind: "file",
name: "a.pdf",
url: "/api/community/channels/c1/attachments/att_2",
- size: "2 KB",
+ contentType: "application/pdf",
+ sizeBytes: 2048,
+ size: "2.0 KB",
})
})
@@ -83,7 +89,7 @@ describe("toAttachmentVm", () => {
width: 1920,
height: 1080,
})
- expect(result).toEqual({ kind: "file", name: "unsafe.img", url: "/api/community/channels/c1/attachments/att_3", size: "2 KB" })
+ expect(result).toEqual({ kind: "file", name: "unsafe.img", url: "/api/community/channels/c1/attachments/att_3", contentType, sizeBytes: 2048, size: "2.0 KB" })
},
)
})
diff --git a/src/web/src/lib/community/attachment-presentation.test.ts b/src/web/src/lib/community/attachment-presentation.test.ts
new file mode 100644
index 000000000..2f4aa127e
--- /dev/null
+++ b/src/web/src/lib/community/attachment-presentation.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from "vitest"
+import {
+ formatAttachmentSize,
+ resolveAttachmentPresentation,
+} from "./attachment-presentation"
+
+describe("resolveAttachmentPresentation", () => {
+ it.each([
+ ["report.pdf", "application/pdf", "pdf", null],
+ ["sheet.bin", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "spreadsheet", null],
+ ["slides.bin", "application/vnd.ms-powerpoint", "presentation", null],
+ ["voice.bin", "audio/mpeg", "audio", null],
+ ["clip.bin", "video/mp4", "video", null],
+ ["data.bin", "application/json; charset=utf-8", "code", "code"],
+ ["readme.bin", "text/markdown", "text", "markdown"],
+ ["notes.bin", "text/plain", "text", "text"],
+ ])("uses MIME for %s", (filename, contentType, category, previewKind) => {
+ expect(resolveAttachmentPresentation(filename, contentType)).toEqual({ category, previewKind })
+ })
+
+ it.each([
+ ["README.md", undefined, "text", "markdown"],
+ ["config.json", "application/octet-stream", "code", "code"],
+ [".env.local", "", "code", "code"],
+ ["deck.pptx", undefined, "presentation", null],
+ ["bundle.zip", "binary/octet-stream", "archive", null],
+ ])("falls back to the extension for generic MIME: %s", (filename, contentType, category, previewKind) => {
+ expect(resolveAttachmentPresentation(filename, contentType)).toEqual({ category, previewKind })
+ })
+
+ it("does not execute active or unknown content", () => {
+ expect(resolveAttachmentPresentation("page.html", "text/html")).toEqual({ category: "unknown", previewKind: null })
+ expect(resolveAttachmentPresentation("vector.svg", "image/svg+xml")).toEqual({ category: "image", previewKind: null })
+ expect(resolveAttachmentPresentation("payload.bin", "application/x-custom")).toEqual({ category: "unknown", previewKind: null })
+ })
+})
+
+describe("formatAttachmentSize", () => {
+ it("formats bytes with stable binary units", () => {
+ expect(formatAttachmentSize(0)).toBe("0 B")
+ expect(formatAttachmentSize(1536)).toBe("1.5 KB")
+ expect(formatAttachmentSize(2 * 1024 * 1024)).toBe("2.0 MB")
+ })
+})
diff --git a/src/web/src/lib/community/attachment-presentation.ts b/src/web/src/lib/community/attachment-presentation.ts
new file mode 100644
index 000000000..31cdb0cf6
--- /dev/null
+++ b/src/web/src/lib/community/attachment-presentation.ts
@@ -0,0 +1,154 @@
+export const MAX_TEXT_ATTACHMENT_PREVIEW_BYTES = 1024 * 1024
+
+export type AttachmentCategory =
+ | "image"
+ | "pdf"
+ | "document"
+ | "spreadsheet"
+ | "presentation"
+ | "text"
+ | "code"
+ | "audio"
+ | "video"
+ | "archive"
+ | "unknown"
+
+type AttachmentPreviewKind = "markdown" | "text" | "code"
+
+export type AttachmentPresentation = {
+ category: AttachmentCategory
+ previewKind: AttachmentPreviewKind | null
+}
+
+const GENERIC_CONTENT_TYPES = new Set(["", "application/octet-stream", "binary/octet-stream"])
+
+const MIME_PRESENTATIONS: ReadonlyArray<{
+ matches: (contentType: string) => boolean
+ category: AttachmentCategory
+ previewKind?: AttachmentPreviewKind
+}> = [
+ { matches: (type) => type === "text/markdown" || type === "text/x-markdown", category: "text", previewKind: "markdown" },
+ { matches: (type) => type === "application/json" || type.endsWith("+json"), category: "code", previewKind: "code" },
+ { matches: (type) => [
+ "application/javascript",
+ "application/typescript",
+ "application/sql",
+ "application/toml",
+ "application/x-yaml",
+ "application/yaml",
+ "application/xml",
+ "text/css",
+ "text/javascript",
+ "text/typescript",
+ "text/x-python",
+ "text/x-shellscript",
+ "text/x-sql",
+ "text/yaml",
+ ].includes(type), category: "code", previewKind: "code" },
+ { matches: (type) => type === "application/pdf", category: "pdf" },
+ { matches: (type) => type.includes("spreadsheet") || type.includes("excel") || type === "text/csv", category: "spreadsheet" },
+ { matches: (type) => type.includes("presentation") || type.includes("powerpoint"), category: "presentation" },
+ { matches: (type) => type.includes("wordprocessing") || type === "application/msword" || type === "application/rtf", category: "document" },
+ { matches: (type) => type.startsWith("audio/"), category: "audio" },
+ { matches: (type) => type.startsWith("video/"), category: "video" },
+ { matches: (type) => type.startsWith("image/"), category: "image" },
+ { matches: (type) => type === "application/zip" || type === "application/x-7z-compressed" || type === "application/x-rar-compressed" || type === "application/gzip" || type === "application/x-tar", category: "archive" },
+ { matches: (type) => type.startsWith("text/") && type !== "text/html", category: "text", previewKind: "text" },
+]
+
+const EXTENSION_PRESENTATIONS: Readonly<Record<string, AttachmentPresentation>> = {
+ md: { category: "text", previewKind: "markdown" },
+ markdown: { category: "text", previewKind: "markdown" },
+ txt: { category: "text", previewKind: "text" },
+ log: { category: "text", previewKind: "text" },
+ csv: { category: "spreadsheet", previewKind: null },
+ json: { category: "code", previewKind: "code" },
+ jsonl: { category: "code", previewKind: "code" },
+ js: { category: "code", previewKind: "code" },
+ jsx: { category: "code", previewKind: "code" },
+ ts: { category: "code", previewKind: "code" },
+ tsx: { category: "code", previewKind: "code" },
+ css: { category: "code", previewKind: "code" },
+ scss: { category: "code", previewKind: "code" },
+ sql: { category: "code", previewKind: "code" },
+ sh: { category: "code", previewKind: "code" },
+ bash: { category: "code", previewKind: "code" },
+ py: { category: "code", previewKind: "code" },
+ rb: { category: "code", previewKind: "code" },
+ go: { category: "code", previewKind: "code" },
+ rs: { category: "code", previewKind: "code" },
+ java: { category: "code", previewKind: "code" },
+ c: { category: "code", previewKind: "code" },
+ h: { category: "code", previewKind: "code" },
+ cpp: { category: "code", previewKind: "code" },
+ yaml: { category: "code", previewKind: "code" },
+ yml: { category: "code", previewKind: "code" },
+ toml: { category: "code", previewKind: "code" },
+ ini: { category: "code", previewKind: "code" },
+ conf: { category: "code", previewKind: "code" },
+ env: { category: "code", previewKind: "code" },
+ xml: { category: "code", previewKind: "code" },
+ pdf: { category: "pdf", previewKind: null },
+ doc: { category: "document", previewKind: null },
+ docx: { category: "document", previewKind: null },
+ rtf: { category: "document", previewKind: null },
+ xls: { category: "spreadsheet", previewKind: null },
+ xlsx: { category: "spreadsheet", previewKind: null },
+ ppt: { category: "presentation", previewKind: null },
+ pptx: { category: "presentation", previewKind: null },
+ mp3: { category: "audio", previewKind: null },
+ wav: { category: "audio", previewKind: null },
+ m4a: { category: "audio", previewKind: null },
+ mp4: { category: "video", previewKind: null },
+ mov: { category: "video", previewKind: null },
+ webm: { category: "video", previewKind: null },
+ zip: { category: "archive", previewKind: null },
+ gz: { category: "archive", previewKind: null },
+ tar: { category: "archive", previewKind: null },
+ rar: { category: "archive", previewKind: null },
+ "7z": { category: "archive", previewKind: null },
+ png: { category: "image", previewKind: null },
+ jpg: { category: "image", previewKind: null },
+ jpeg: { category: "image", previewKind: null },
+ gif: { category: "image", previewKind: null },
+ webp: { category: "image", previewKind: null },
+ svg: { category: "image", previewKind: null },
+ html: { category: "code", previewKind: null },
+ htm: { category: "code", previewKind: null },
+}
+
+function filenameExtension(filename: string): string {
+ const basename = filename.toLowerCase().split(/[\\/]/).pop() ?? ""
+ if (basename.startsWith(".env")) return "env"
+ const dot = basename.lastIndexOf(".")
+ return dot > -1 ? basename.slice(dot + 1) : ""
+}
+
+export function resolveAttachmentPresentation(
+ filename: string,
+ contentType?: string | null,
+): AttachmentPresentation {
+ const normalizedType = contentType?.split(";", 1)[0]?.trim().toLowerCase() ?? ""
+ if (!GENERIC_CONTENT_TYPES.has(normalizedType)) {
+ for (const presentation of MIME_PRESENTATIONS) {
+ if (presentation.matches(normalizedType)) {
+ return {
+ category: presentation.category,
+ previewKind: presentation.previewKind ?? null,
+ }
+ }
+ }
+ return { category: "unknown", previewKind: null }
+ }
+ return EXTENSION_PRESENTATIONS[filenameExtension(filename)] ?? {
+ category: "unknown",
+ previewKind: null,
+ }
+}
+
+export function formatAttachmentSize(bytes?: number): string {
+ if (bytes === undefined || !Number.isFinite(bytes) || bytes < 0) return ""
+ if (bytes < 1024) return `${bytes} B`
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
+}
diff --git a/src/web/src/lib/community/enrich-messages.test.ts b/src/web/src/lib/community/enrich-messages.test.ts
index 74bbe7c16..de4c67249 100644
--- a/src/web/src/lib/community/enrich-messages.test.ts
+++ b/src/web/src/lib/community/enrich-messages.test.ts
@@ -93,6 +93,8 @@ describe("enrichMessages attachment projection", () => {
kind: "image",
name: "photo.png",
url: "/api/community/channels/c1/attachments/att_1",
+ contentType: "image/png",
+ sizeBytes: 100,
thumbnailUrl: "/api/community/channels/c1/attachments/att_1/thumbnail",
width: 640,
height: 480,
diff --git a/src/web/src/lib/community/message-payload.ts b/src/web/src/lib/community/message-payload.ts
index 7e31f10cb..7f4ab7d80 100644
--- a/src/web/src/lib/community/message-payload.ts
+++ b/src/web/src/lib/community/message-payload.ts
@@ -44,7 +44,7 @@ export type MessageRow = {
type ReplyTargetRow = { id: string; authorName: string; content: string | null }
-type UiAttachment = { kind: "image" | "file"; name: string; url: string; thumbnailUrl?: string; size?: string; width?: number; height?: number }
+type UiAttachment = { kind: "image" | "file"; name: string; url: string; thumbnailUrl?: string; contentType?: string; size?: string; sizeBytes?: number; width?: number; height?: number }
type WsAttachment = { id: string; filename: string; url: string; thumbnailUrl?: string; contentType?: string; size?: number; width?: number; height?: number }
type UiReaction = { emoji: string; count: number; me: boolean; userIds: string[] }
diff --git a/src/web/src/lib/community/message-stream.test.ts b/src/web/src/lib/community/message-stream.test.ts
index 343e0654c..ea329d6b4 100644
--- a/src/web/src/lib/community/message-stream.test.ts
+++ b/src/web/src/lib/community/message-stream.test.ts
@@ -484,9 +484,9 @@ describe("attachment ownership effects", () => {
expect(retried?.localUploads[0].height).toBe(480)
expect(retried?.uploadStatus).toBe("pending")
expect(materializeMessageStream([], state)[0].attachments).toEqual([
- { kind: "file", name: "notes.txt", url: "blob:a", size: "1 KB" },
- { kind: "image", name: "photo.png", url: "blob:b", width: 320, height: 240 },
- { kind: "file", name: "copy.txt", url: "blob:a", size: "1 KB" },
+ { kind: "file", name: "notes.txt", url: "blob:a", contentType: "text/plain", sizeBytes: 1024, size: "1.0 KB" },
+ { kind: "image", name: "photo.png", url: "blob:b", contentType: "image/png", sizeBytes: 2048, width: 320, height: 240 },
+ { kind: "file", name: "copy.txt", url: "blob:a", contentType: "text/plain", sizeBytes: 1024, size: "1.0 KB" },
])
})
diff --git a/src/web/src/lib/community/message-stream.ts b/src/web/src/lib/community/message-stream.ts
index d888539a3..8bcd6d3e1 100644
--- a/src/web/src/lib/community/message-stream.ts
+++ b/src/web/src/lib/community/message-stream.ts
@@ -1,6 +1,7 @@
import type { Msg } from "@/components/community/_types"
import type { MentionType } from "@alook/shared"
import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"
+import { formatAttachmentSize } from "@/lib/community/attachment-presentation"
export const MAX_LIVE_MESSAGE_DELTAS = 500
@@ -176,6 +177,8 @@ function localUploadAttachments(
kind: "image",
name: upload.file.name,
url: upload.previewObjectUrl,
+ contentType: upload.file.type,
+ sizeBytes: upload.file.size,
width: upload.width,
height: upload.height,
})
@@ -185,7 +188,9 @@ function localUploadAttachments(
kind: "file",
name: upload.file.name,
url: upload.previewObjectUrl,
- size: upload.file.size ? `${Math.round(upload.file.size / 1024)} KB` : "",
+ contentType: upload.file.type,
+ sizeBytes: upload.file.size,
+ size: formatAttachmentSize(upload.file.size),
})
}
return attachments.length > 0 ? attachments : undefined
diff --git a/src/web/src/lib/community/message-wire.test.ts b/src/web/src/lib/community/message-wire.test.ts
index 61fc1a414..8cf3fba6d 100644
--- a/src/web/src/lib/community/message-wire.test.ts
+++ b/src/web/src/lib/community/message-wire.test.ts
@@ -62,9 +62,9 @@ describe("projectCommunityMessageCreate", () => {
}))
expect(projected.embeds).toEqual([{ title: "Card", url: "https://example.com" }])
expect(projected.attachments).toEqual([
- { kind: "image", name: "photo.png", url: "/photo", width: 640, height: 480 },
- { kind: "file", name: "doc.pdf", url: "/doc", size: "2 KB" },
- { kind: "file", name: "unsafe.svg", url: "/unsafe", size: "1 KB" },
+ { kind: "image", name: "photo.png", url: "/photo", contentType: "image/png", sizeBytes: 2048, width: 640, height: 480 },
+ { kind: "file", name: "doc.pdf", url: "/doc", contentType: "application/pdf", sizeBytes: 2048, size: "2.0 KB" },
+ { kind: "file", name: "unsafe.svg", url: "/unsafe", contentType: "image/svg+xml", sizeBytes: 1024, size: "1.0 KB" },
])
})
})
diff --git a/src/web/src/lib/community/message-wire.ts b/src/web/src/lib/community/message-wire.ts
index 4672bc019..d6763cdf5 100644
--- a/src/web/src/lib/community/message-wire.ts
+++ b/src/web/src/lib/community/message-wire.ts
@@ -2,6 +2,7 @@ import type { CommunityMessageCreate } from "@alook/shared"
import type { Msg } from "@/components/community/_types"
import { avatarInitial } from "@/lib/community/avatar"
import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"
+import { formatAttachmentSize } from "@/lib/community/attachment-presentation"
import type { CanonicalMessage } from "@/lib/community/message-stream"
type UiEmbed = NonNullable<Msg["embeds"]>[number]
@@ -97,6 +98,8 @@ export function projectCommunityMessageCreate(
kind: "image" as const,
name: attachment.filename,
url: attachment.url,
+ contentType: attachment.contentType,
+ sizeBytes: attachment.size,
...(attachment.thumbnailUrl ? { thumbnailUrl: attachment.thumbnailUrl } : {}),
width: attachment.width ?? undefined,
height: attachment.height ?? undefined,
@@ -106,7 +109,9 @@ export function projectCommunityMessageCreate(
kind: "file" as const,
name: attachment.filename,
url: attachment.url,
- size: attachment.size ? `${Math.round(attachment.size / 1024)} KB` : "",
+ contentType: attachment.contentType,
+ sizeBytes: attachment.size,
+ size: formatAttachmentSize(attachment.size),
}
})
const embeds = message.embeds?.flatMap((embed) => {
diff --git a/src/web/src/lib/community/messages.test.ts b/src/web/src/lib/community/messages.test.ts
index 839ebb107..a3a298496 100644
--- a/src/web/src/lib/community/messages.test.ts
+++ b/src/web/src/lib/community/messages.test.ts
@@ -72,7 +72,7 @@ describe("groupAttachments", () => {
{ id: "att1", messageId: "m1", targetId: "c1", filename: "a.png", r2Key: "channel/c1/uuid/a.png", contentType: "image/png", size: 1000, width: 1920, height: 1080 },
])
expect(result.m1).toEqual([
- { kind: "image", name: "a.png", url: "/api/community/channels/c1/attachments/att1", width: 1920, height: 1080 },
+ { kind: "image", name: "a.png", url: "/api/community/channels/c1/attachments/att1", contentType: "image/png", sizeBytes: 1000, width: 1920, height: 1080 },
])
})
@@ -81,7 +81,7 @@ describe("groupAttachments", () => {
{ id: "att1", messageId: "m1", targetId: "c1", filename: "a.png", r2Key: "channel/c1/uuid/a.png", contentType: "image/png", size: 1000, width: null, height: null },
])
expect(result.m1).toEqual([
- { kind: "image", name: "a.png", url: "/api/community/channels/c1/attachments/att1", width: undefined, height: undefined },
+ { kind: "image", name: "a.png", url: "/api/community/channels/c1/attachments/att1", contentType: "image/png", sizeBytes: 1000, width: undefined, height: undefined },
])
})
@@ -90,7 +90,7 @@ describe("groupAttachments", () => {
{ id: "att1", messageId: "m1", targetId: "c1", filename: "a.pdf", r2Key: "channel/c1/uuid/a.pdf", contentType: "application/pdf", size: 2048, width: 1920, height: 1080 },
])
expect(result.m1).toEqual([
- { kind: "file", name: "a.pdf", url: "/api/community/channels/c1/attachments/att1", size: "2.0 KB" },
+ { kind: "file", name: "a.pdf", url: "/api/community/channels/c1/attachments/att1", contentType: "application/pdf", sizeBytes: 2048, size: "2.0 KB" },
])
})
@@ -101,7 +101,7 @@ describe("groupAttachments", () => {
{ id: "att1", messageId: "m1", targetId: "c1", filename: "unsafe.img", r2Key: "channel/c1/uuid/unsafe.img", contentType, size: 2048, width: 1920, height: 1080 },
])
expect(result.m1).toEqual([
- { kind: "file", name: "unsafe.img", url: "/api/community/channels/c1/attachments/att1", size: "2.0 KB" },
+ { kind: "file", name: "unsafe.img", url: "/api/community/channels/c1/attachments/att1", contentType, sizeBytes: 2048, size: "2.0 KB" },
])
},
)
@@ -112,7 +112,7 @@ describe("groupAttachments", () => {
{ id: "att1", messageId: "m1", targetId: "c1", filename: "linked.png", r2Key: "channel/c1/uuid/linked.png", contentType: "image/png", size: 100, width: null, height: null },
])
expect(result).toEqual({
- m1: [{ kind: "image", name: "linked.png", url: "/api/community/channels/c1/attachments/att1", width: undefined, height: undefined }],
+ m1: [{ kind: "image", name: "linked.png", url: "/api/community/channels/c1/attachments/att1", contentType: "image/png", sizeBytes: 100, width: undefined, height: undefined }],
})
})
})
diff --git a/src/web/src/lib/community/messages.ts b/src/web/src/lib/community/messages.ts
index ebd73c6b0..81a3e5d99 100644
--- a/src/web/src/lib/community/messages.ts
+++ b/src/web/src/lib/community/messages.ts
@@ -1,14 +1,8 @@
import { DEFAULT_MESSAGE_PAGE_SIZE, MAX_MESSAGE_PAGE_SIZE } from "@alook/shared"
import { isInlineAttachmentContentType } from "./attachment-content-type"
+import { formatAttachmentSize } from "./attachment-presentation"
import { attachmentThumbnailUrl, attachmentUrl } from "./storage"
-// Format file sizes for display
-function formatBytes(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`
-}
-
// Parse cursor from query params (format: "createdAt|id")
export function parseCursor(cursorParam: string | null): { createdAt: string; id: string } | undefined {
if (!cursorParam) return undefined
@@ -154,8 +148,8 @@ export function buildMemberPaginatedResponse<T extends { joinedAt: string; id: s
// the read paths never surface them.
export function groupAttachments(
attachments: Array<{ id: string; messageId: string | null; targetId: string; filename: string; r2Key: string; thumbnailR2Key?: string | null; contentType: string | null; size: number | null; width?: number | null; height?: number | null }>
-): Record<string, Array<{ kind: "image" | "file"; name: string; url: string; thumbnailUrl?: string; size?: string; width?: number; height?: number }>> {
- const map: Record<string, Array<{ kind: "image" | "file"; name: string; url: string; thumbnailUrl?: string; size?: string; width?: number; height?: number }>> = {}
+): Record<string, Array<{ kind: "image" | "file"; name: string; url: string; thumbnailUrl?: string; contentType?: string; size?: string; sizeBytes?: number; width?: number; height?: number }>> {
+ const map: Record<string, Array<{ kind: "image" | "file"; name: string; url: string; thumbnailUrl?: string; contentType?: string; size?: string; sizeBytes?: number; width?: number; height?: number }>> = {}
for (const a of attachments) {
if (!a.messageId) continue
const kind = isInlineAttachmentContentType(a.contentType) ? "image" : "file"
@@ -163,12 +157,14 @@ export function groupAttachments(
kind,
name: a.filename,
url: attachmentUrl(a.targetId, a.id),
+ ...(a.contentType ? { contentType: a.contentType } : {}),
+ ...(a.size !== null ? { sizeBytes: a.size } : {}),
...(kind === "image" && a.thumbnailR2Key
? { thumbnailUrl: attachmentThumbnailUrl(a.targetId, a.id) }
: {}),
- ...(kind === "file" && a.size ? { size: formatBytes(a.size) } : {}),
+ ...(kind === "file" && a.size !== null ? { size: formatAttachmentSize(a.size) } : {}),
...(kind === "image" ? { width: a.width ?? undefined, height: a.height ?? undefined } : {}),
- } as { kind: "image" | "file"; name: string; url: string; thumbnailUrl?: string; size?: string; width?: number; height?: number }
+ } as { kind: "image" | "file"; name: string; url: string; thumbnailUrl?: string; contentType?: string; size?: string; sizeBytes?: number; width?: number; height?: number }
;(map[a.messageId] ??= []).push(entry)
}
return map
diff --git a/src/web/src/lib/community/testids.test.ts b/src/web/src/lib/community/testids.test.ts
index 8126f3a68..9263a7019 100644
--- a/src/web/src/lib/community/testids.test.ts
+++ b/src/web/src/lib/community/testids.test.ts
@@ -19,6 +19,13 @@ describe("community QA selectors", () => {
expect(tid.profileContextBadge).toBe("community-profile-context-badge")
})
+ it("exposes attachment preview selectors from one canonical map", () => {
+ expect(tid.attachmentCard("notes.md")).toBe("community-attachment-card-notes.md")
+ expect(tid.attachmentPreviewSheet).toBe("community-attachment-preview-sheet")
+ expect(tid.attachmentPreviewDownload).toBe("community-attachment-preview-download")
+ expect(tid.attachmentPreviewContent).toBe("community-attachment-preview-content")
+ })
+
it("exposes only the four stable My Bots bug-report flow selectors", () => {
expect(tid.botReportProblemItem).toBe("bot-report-problem-item")
expect(tid.botReportProblemDialog).toBe("bot-report-problem-dialog")
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 06c160fef..0a5e175f9 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -37,6 +37,10 @@ export const tid = {
message: (id: string) => `community-message-${id}`,
messageImage: (id: string, index: number) => `community-message-image-${id}-${index}`,
threadOpenerImage: (index: number) => `community-thread-opener-image-${index}`,
+ attachmentCard: (name: string) => `community-attachment-card-${name}`,
+ attachmentPreviewSheet: "community-attachment-preview-sheet",
+ attachmentPreviewDownload: "community-attachment-preview-download",
+ attachmentPreviewContent: "community-attachment-preview-content",
channelRow: (id: string) => `community-channel-row-${id}`,
serverIcon: (id: string) => `community-server-icon-${id}`,
dmRow: (id: string) => `community-dm-row-${id}`,
diff --git a/src/web/src/stores/community/index.ts b/src/web/src/stores/community/index.ts
index 6ef776e58..6fd09c144 100644
--- a/src/web/src/stores/community/index.ts
+++ b/src/web/src/stores/community/index.ts
@@ -73,6 +73,7 @@ type CommunitySubscription = {
type CommunityUiHandlers = {
previewImage?: (image: import("@/components/community/_types").ImagePreview) => void
+ previewAttachment?: (attachment: import("@/components/community/_types").FileAttachment) => void
openProfile?: (name: string, e: React.MouseEvent, discriminator?: string, userId?: string) => void
goBackMobile?: () => void
// Jump to message `seq` within the CURRENT channel/DM — the page registers
@@ -277,6 +278,7 @@ export const useCurrentChannelMeta = () =>
*/
const stableUiHandlers: CommunityUiHandlers = {
previewImage: (url) => useCommunityStore.getState().uiHandlers.previewImage?.(url),
+ previewAttachment: (attachment) => useCommunityStore.getState().uiHandlers.previewAttachment?.(attachment),
openProfile: (name, e, discriminator, userId) =>
useCommunityStore.getState().uiHandlers.openProfile?.(name, e, discriminator, userId),
goBackMobile: () => useCommunityStore.getState().uiHandlers.goBackMobile?.(),