Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
feat(community): forum post composer — attachments, @-mentions, empty-body allowed
Gus85045ac910d4
diff --git a/src/web/src/app/api/community/channels/[id]/posts/route.test.ts b/src/web/src/app/api/community/channels/[id]/posts/route.test.tsindex 1f50ab33d..6dc6c97a6 100644--- a/src/web/src/app/api/community/channels/[id]/posts/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/posts/route.test.ts@@ -49,6 +49,19 @@ vi.mock("@alook/shared", async () => {communityMention: {createMentions: vi.fn(async () => []),},+ communityAttachment: {+ createAttachment: vi.fn(async (_db: unknown, args: Record<string, unknown>) => ({+ id: "att_1",+ filename: args.filename,+ r2Key: args.r2Key,+ contentType: args.contentType,+ size: args.size,+ width: args.width,+ height: args.height,+ })),+ listByMessageIds: vi.fn(async () => []),+ unreserveAttachments: vi.fn(async () => {}),+ },communityThread: {addThreadParticipants: vi.fn(async () => {}),listParticipantsForChannels: (...a: unknown[]) => mockListParticipantsForChannels(...a),@@ -150,6 +163,79 @@ describe("POST /api/community/channels/[id]/posts — name normalization", () =>expect(res.status).toBe(400)expect(mockCreateChannel).not.toHaveBeenCalled()})++ it("returns messageCount 0 in the response (body IS the first message, not a reply)", async () => {+ mockCreateChannel.mockResolvedValue({+ id: "post1",+ name: "solo",+ createdAt: "2026-07-02T00:00:00.000Z",+ })+ const res = await POST(postReq({ name: "solo", content: "hi" }), ctx)+ expect(res.status).toBe(201)+ const body = await res.json()+ expect(body.post.messageCount).toBe(0)+ })+})++describe("POST /api/community/channels/[id]/posts — content + attachments contract", () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockGetChannelForMember.mockResolvedValue({ id: "ch1", serverId: "s1", type: "forum", tags: [] })+ mockCreateMessage.mockResolvedValue({ id: "m1", createdAt: "2026-07-02T00:00:00.000Z" })+ mockGetMessage.mockResolvedValue({+ id: "m1",+ authorId: "u1",+ authorName: "Alice",+ authorImage: null,+ content: "",+ type: "default",+ mentionType: null,+ replyToId: null,+ embeds: null,+ channelId: "post1",+ dmConversationId: null,+ seq: 1,+ createdAt: "2026-07-02T00:00:00.000Z",+ })+ mockGetUserSelf.mockResolvedValue({ id: "u1", name: "Alice", image: null })+ mockGetUserInternal.mockResolvedValue({ id: "u1", name: "Alice", isBot: false })+ mockFanOutToChannel.mockResolvedValue(undefined)+ mockCreateChannel.mockResolvedValue({+ id: "post1",+ name: "my-post",+ createdAt: "2026-07-02T00:00:00.000Z",+ })+ })++ it("empty content + zero attachments returns 400", async () => {+ const res = await POST(postReq({ name: "my post", content: "" }), ctx)+ expect(res.status).toBe(400)+ const body = await res.json()+ expect(body.error).toBe("post is empty")+ expect(mockCreateChannel).not.toHaveBeenCalled()+ })++ it("empty content + one valid attachment creates the post (attachments-only path)", async () => {+ const attachments = [+ { url: "/api/community/media/abc.png", filename: "abc.png", contentType: "image/png", size: 100, width: 10, height: 10 },+ ]+ const res = await POST(postReq({ name: "img", content: "", attachments }), ctx)+ expect(res.status).toBe(201)+ // Route passes attachments through to createCommunityMessage.+ expect(mockCreateChannel).toHaveBeenCalled()+ })++ it("threads mentionType through to createCommunityMessage / first message", async () => {+ const res = await POST(+ postReq({ name: "heads up", content: "Heads up @everyone", mentionType: "everyone" }),+ ctx,+ )+ expect(res.status).toBe(201)+ // The mock records the createMessage call — the pipeline lifts mentionType+ // out of `body` and lands it on the row.+ const call = mockCreateMessage.mock.calls[0]?.[1]+ expect(call?.mentionType).toBe("everyone")+ })})describe("GET /api/community/channels/[id]/posts — authorId", () => {diff --git a/src/web/src/app/api/community/channels/[id]/posts/route.ts b/src/web/src/app/api/community/channels/[id]/posts/route.tsindex f859bb973..39164f3d1 100644--- a/src/web/src/app/api/community/channels/[id]/posts/route.ts+++ b/src/web/src/app/api/community/channels/[id]/posts/route.ts@@ -96,7 +96,9 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {return {id: t.id,name: t.name,- messageCount: t.messageCount ?? 0,+ // Excludes the body message — the body IS the first message; the badge+ // shows reply count, not total message count.+ messageCount: Math.max(0, (t.messageCount ?? 0) - 1),lastMessageAt: t.lastMessageAt ?? t.createdAt,parent: { authorName, text: preview },authorId: t.creatorId ?? "",@@ -124,7 +126,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError("channel is not a forum", 400)}- let body: { name?: string; content?: string }+ let body: { name?: string; content?: string; attachments?: unknown; mentionType?: unknown }try {body = await req.json()} catch {@@ -143,10 +145,13 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {return writeError("name is required", 400)}- if (!body.content || typeof body.content !== "string" || body.content.trim().length === 0) {- return writeError("content is required", 400)+ const content = typeof body.content === "string" ? body.content : ""+ const hasContent = content.trim().length > 0+ const hasAttachments = Array.isArray(body.attachments) && body.attachments.length > 0+ if (!hasContent && !hasAttachments) {+ return writeError("post is empty", 400)}- if (body.content.length > MAX_MESSAGE_CONTENT_LENGTH) {+ if (hasContent && content.length > MAX_MESSAGE_CONTENT_LENGTH) {return writeError(`content must be ≤ ${MAX_MESSAGE_CONTENT_LENGTH} characters`, 400)}@@ -181,7 +186,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {db,authorId: ctx.userId,target: { kind: "channel", channelId: postChannel.id, serverId: channel.serverId },- body: { content: body.content },+ body: { content, attachments: body.attachments, mentionType: body.mentionType },})if (!created.ok) return writeError(created.error, created.status)const message = created.row@@ -207,13 +212,15 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {post: {id: postChannel.id,name: postChannel.name,- messageCount: 1,+ // Excludes the body message — the body IS the first message; the badge+ // shows reply count, so a freshly created post reads 0.+ messageCount: 0,lastMessageAt: message.createdAt,- parent: { authorName, text: body.content.slice(0, MESSAGE_PREVIEW_LENGTH) },+ parent: { authorName, text: content.slice(0, MESSAGE_PREVIEW_LENGTH) },authorId: ctx.userId,authorAvatar,tags: [],- preview: body.content.slice(0, MESSAGE_PREVIEW_LENGTH),+ preview: content.slice(0, MESSAGE_PREVIEW_LENGTH),// A fresh post's only participant is its creator (just enrolled above).participants: [{ id: ctx.userId, name: authorName, avatar: authorAvatar }],},diff --git a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsxindex b47837781..98eae3d5d 100644--- a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx+++ b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx@@ -10,6 +10,7 @@ import { ChannelHeader, ChannelHeaderSkeleton, type ChannelNotifLevel } from "@/import { MessageList } from "@/components/community/message-list"import { Composer, ComposerSkeleton, type SendAttachment } from "@/components/community/composer"import { ForumView, ForumViewSkeleton } from "@/components/community/forum-view"+import type { NewForumPost } from "@/components/community/create-forum-post"import { CommunityPanelSheet } from "@/components/community/community-panel-sheet"import { ThreadOpener } from "@/components/community/thread-opener"import { AddMembersDialog } from "@/components/community/add-members-dialog"@@ -682,15 +683,17 @@ function ChannelView() {communityWsSendTyping({ channelId })}- const createForumPost = async (post: { name: string; content: string }) => {- try {- const data = await createForumPostMut.mutateAsync({ channelId, ...post })- // A post is its own child channel — open it, same as clicking a post row.- enterThread(data.post.id)- } catch (e) {- toastApiError(e, "Failed to create post")- }- }+ const createForumPost = useCallback(async (post: NewForumPost) => {+ const data = await createForumPostMut.mutateAsync({+ channelId,+ name: post.name,+ content: post.content,+ attachments: post.attachments,+ mentionType: post.mentionType,+ })+ // A post is its own child channel — open it, same as clicking a post row.+ enterThread(data.post.id)+ }, [channelId, createForumPostMut, enterThread])const myRole = members.find((m) => m.userId === currentUser.id)?.role// The unit's creator (thread/channel/post) — drives the manage-context@@ -971,6 +974,9 @@ function ChannelView() {/><main className="flex min-h-0 min-w-0 flex-1 flex-col"><ForumView+ forumChannelId={channelId}+ members={composerMembers}+ onSearchMembers={membersHook.searchMembers}posts={forumPosts}loading={forumPostsLoading}onOpenPost={enterThread}diff --git a/src/web/src/components/community/composer.tsx b/src/web/src/components/community/composer.tsxindex 22ac0c786..216425b02 100644--- a/src/web/src/components/community/composer.tsx+++ b/src/web/src/components/community/composer.tsx@@ -1,6 +1,6 @@"use client"-import { useEffect, useRef, useState } from "react"+import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from "react"import { createPortal } from "react-dom"import { AtSign, FileIcon, ImageIcon, PlusCircle, Smile, Upload, Users, X } from "lucide-react"import { useEditor, EditorContent } from "@tiptap/react"@@ -46,12 +46,19 @@ export function pendingFilesToSendAttachments(pendingFiles: PendingFile[]): Sendreturn pendingFiles.map((pf) => ({ file: pf.file, width: pf.width, height: pf.height }))}-// Composer — plain-text TipTap editor with a chat-style @-mention popover.-// Users type raw markdown which MessageBody/Streamdown renders on display.-// Enter sends, Shift+Enter adds a newline; while the mention popover is open-// Enter/Tab/Arrow keys drive selection instead. @everyone / @here are virtual-// candidates in channel + thread contexts (hidden in DM).-export function Composer({ channel, context, members, onSearchMembers, channelRefCandidates = [], onSend, onTyping, replyingTo, onCancelReply, autoFocus = false }: {+type ComposerMode = "chat" | "forumPostBody"++export type ComposerHandle = {+ focusEditor: () => void+ submitNow: () => void+ resetAfterSubmit: () => void+ isEmpty: () => boolean+ // Trigger the hidden file input's picker. Used by consumers that render+ // their own attach button outside the composer's absolute-positioned frame.+ openFilePicker: () => void+}++export type ComposerProps = {channel: stringcontext: MentionContextmembers: Member[]@@ -73,7 +80,52 @@ export function Composer({ channel, context, members, onSearchMembers, channelRe// Auto-focus the editor on mount and on channel change. Desktop only —// callers pass `bp !== "mobile"` to avoid unexpected soft-keyboard pop-up.autoFocus?: boolean-}) {+ // `"chat"` (default) — Enter sends, Shift+Enter newline, `send()` clears.+ // `"forumPostBody"` — inverted: Enter newline, Shift+Enter submits; `send()`+ // does NOT clear so the parent can await mutation success before resetting.+ mode?: ComposerMode+ // Placeholder override — used by `forumPostBody` to swap the chat-composer+ // relic string. Falls back to the mode-derived default when absent.+ placeholder?: string+ // Hide the composer's built-in emoji-picker button (bottom-right). Used by+ // the forum-post composer, where emoji is dropped from the compose surface.+ hideEmoji?: boolean+ // Hide the composer's built-in attach button (bottom-left). Used by the+ // forum-post composer, which renders its own attach button in the footer+ // row and drives it through `ComposerHandle.openFilePicker()`.+ hideAttach?: boolean+ // Fires only on emptiness-state transitions (`hasContent` flips), not every+ // keystroke. Used by the forum-post orchestrator to drive the footer button's+ // `disabled` state without mirroring editor content in parent React state.+ onDirty?: (hasContent: boolean) => void+}++// Composer — plain-text TipTap editor with a chat-style @-mention popover.+// Users type raw markdown which MessageBody/Streamdown renders on display.+// In `mode="chat"` (default) Enter sends, Shift+Enter adds a newline. In+// `mode="forumPostBody"` the mapping is inverted (Enter = newline,+// Shift+Enter = submit) to match /w's issue-sheet convention. While the+// mention popover is open Enter/Tab/Arrow keys drive selection instead.+// @everyone / @here are virtual candidates in channel + thread contexts+// (hidden in DM).+export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Composer({+ channel,+ context,+ members,+ onSearchMembers,+ channelRefCandidates = [],+ onSend,+ onTyping,+ replyingTo,+ onCancelReply,+ autoFocus = false,+ mode = "chat",+ placeholder,+ hideEmoji = false,+ hideAttach = false,+ onDirty,+}, ref) {+ const isForumPostBody = mode === "forumPostBody"const {pendingFiles,setPendingFiles,@@ -204,14 +256,14 @@ export function Composer({ channel, context, members, onSearchMembers, channelRelistItem: false,listKeymap: false,}),- Placeholder.configure({ placeholder: context === "channel" ? `Message /${channel}` : `Message ${channel}` }),+ Placeholder.configure({ placeholder: placeholder ?? (context === "channel" ? `Message /${channel}` : `Message ${channel}`) }),mentionExtension,channelRefExtension,],editorProps: {attributes: {class: "outline-none",- enterkeyhint: "send",+ enterkeyhint: isForumPostBody ? "enter" : "send",},handleKeyDown: (_view, event) => {// editorProps.handleKeyDown runs BEFORE the suggestion plugin's keymap,@@ -225,6 +277,15 @@ export function Composer({ channel, context, members, onSearchMembers, channelRechannelRefPopupRef.current.items.length > 0 && channelRefPopupRef.current.command !== nullif (mentionOpen || channelRefOpen) return false+ if (isForumPostBody) {+ if (event.key === "Enter" && event.shiftKey && !event.isComposing) {+ event.preventDefault()+ send()+ return true+ }+ return false+ }+if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {event.preventDefault()send()@@ -248,9 +309,32 @@ export function Composer({ channel, context, members, onSearchMembers, channelRe},onUpdate: () => {fireTyping()+ emitDirtyTransition()},})+ // Emitted-emptiness ref — used by the onDirty transition logic below to fire+ // only when the boolean flips. Initialized to false because the editor mounts+ // empty and no attachments exist yet.+ const prevHasContentRef = useRef<boolean>(false)+ const onDirtyRef = useRef(onDirty)+ useEffect(() => { onDirtyRef.current = onDirty }, [onDirty])+ const emitDirtyTransition = () => {+ if (!editor) return+ const next = !editor.isEmpty || pendingFiles.length > 0+ if (next === prevHasContentRef.current) return+ prevHasContentRef.current = next+ onDirtyRef.current?.(next)+ }+ // Attachment-side emptiness flips (drops, picker, removal) also feed onDirty.+ useEffect(() => {+ emitDirtyTransition()+ // emitDirtyTransition reads editor + pendingFiles by closure, so bind to+ // both. It's a stable inner closure — the dependency list is intentionally+ // the observed state, not the function.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [pendingFiles, editor])+const send = () => {if (!editor || (editor.isEmpty && pendingFiles.length === 0)) return// Block separator `\n\n` — paragraph breaks serialize as a markdown blank@@ -261,19 +345,42 @@ export function Composer({ channel, context, members, onSearchMembers, channelReconst markdown = editor.isEmpty ? "" : editor.getText({ blockSeparator: "\n\n" }).trim()const mentionType = detectMentionType(markdown)onSend?.(markdown, pendingFilesToSendAttachments(pendingFiles), mentionType)+ // In forumPostBody mode the parent needs to await mutation success before+ // clearing — otherwise a failed create wipes the user's typed content.+ // Reset is delegated to the parent via `resetAfterSubmit()` on the ref.+ if (isForumPostBody) returneditor.commands.clearContent()setPendingFiles([])setMentionPopup(EMPTY_MENTION_STATE)setChannelRefPopup(EMPTY_CHANNEL_REF_STATE)}+ useImperativeHandle(ref, () => ({+ focusEditor: () => { editor?.commands.focus("end") },+ submitNow: () => {+ if (!editor || (editor.isEmpty && pendingFiles.length === 0)) return+ send()+ },+ resetAfterSubmit: () => {+ if (!editor) return+ editor.commands.clearContent()+ setPendingFiles([])+ setMentionPopup(EMPTY_MENTION_STATE)+ setChannelRefPopup(EMPTY_CHANNEL_REF_STATE)+ },+ isEmpty: () => !editor || (editor.isEmpty && pendingFiles.length === 0),+ openFilePicker: () => { fileInputRef.current?.click() },+ }))+// Auto-focus on mount + on channel switch. `<Composer>` is not remounted// per channel (only `<MessageList>` is keyed by channelId), so keying this// effect on `channel` is what refocuses when the user navigates channels.+ // Skipped in forumPostBody mode — the parent controls focus (starts on the+ // title, jumps to the body on Enter).useEffect(() => {- if (!autoFocus || !editor) return+ if (!autoFocus || !editor || isForumPostBody) returneditor.commands.focus("end")- }, [autoFocus, editor, channel])+ }, [autoFocus, editor, channel, isForumPostBody])// Refocus editor after a drop so the user can start typing without// clicking. The drop landed on the composer container — the intent is@@ -285,7 +392,7 @@ export function Composer({ channel, context, members, onSearchMembers, channelRereturn (<div- className="relative px-3 pb-3 pt-0"+ className={isForumPostBody ? "relative" : "relative px-3 pb-3 pt-0"}onDragEnter={handleDragEnter}onDragLeave={handleDragLeave}onDragOver={handleDragOver}@@ -326,7 +433,7 @@ export function Composer({ channel, context, members, onSearchMembers, channelRe</div>)}- <div className={`relative bg-muted shadow-(--e1) ring-1 ring-border/40 transition-shadow focus-within:ring-2 focus-within:ring-ring/60 ${replyingTo || pendingFiles.length > 0 ? "rounded-b-xl" : "rounded-xl"}`}>+ <div className={`relative ${isForumPostBody ? "bg-transparent ring-0" : "bg-muted shadow-(--e1) ring-1 ring-border/40 transition-shadow focus-within:ring-2 focus-within:ring-ring/60"} ${replyingTo || pendingFiles.length > 0 ? "rounded-b-xl" : "rounded-xl"}`}>{dragging && (<divclassName={`pointer-events-none absolute inset-0 z-10 grid place-items-center border-2 border-dashed border-ring bg-background/80 ${replyingTo || pendingFiles.length > 0 ? "rounded-b-xl" : "rounded-xl"}`}@@ -348,30 +455,34 @@ export function Composer({ channel, context, members, onSearchMembers, channelReonChange={handleFileSelect}className="hidden"/>- <div className="chat-composer relative px-12 py-3" data-testid={tid.composerInput}>- <EditorContent editor={editor} className="max-h-40 overflow-y-auto thin-scrollbar text-base chat-input-line-height outline-none" />+ <div className={`chat-composer relative py-3 ${isForumPostBody ? "px-2" : "px-12"}`} data-testid={tid.composerInput}>+ <EditorContent editor={editor} className={`${isForumPostBody ? "max-h-60" : "max-h-40"} overflow-y-auto thin-scrollbar text-base chat-input-line-height outline-none`} /></div>{/* Attach button — fixed bottom-left */}- <DropdownMenu onOpenChange={(open) => { if (!open) editor?.commands.focus() }}>- <DropdownMenuTrigger- render={<button data-testid={tid.composerAttach} className="absolute left-2 bottom-2 grid size-8 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground aria-expanded:bg-accent aria-expanded:text-foreground" aria-label="Add" />}- >- <PlusCircle className="size-5" />- </DropdownMenuTrigger>- <DropdownMenuContent side="top" align="start" className="w-44">- <DropdownMenuItem onClick={() => { fileInputRef.current?.click(); editor?.commands.focus() }}><Upload className="size-4" /> Upload a File</DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ {!hideAttach && (+ <DropdownMenu onOpenChange={(open) => { if (!open) editor?.commands.focus() }}>+ <DropdownMenuTrigger+ render={<button data-testid={tid.composerAttach} className="absolute left-2 bottom-2 grid size-8 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground aria-expanded:bg-accent aria-expanded:text-foreground" aria-label="Add" />}+ >+ <PlusCircle className="size-5" />+ </DropdownMenuTrigger>+ <DropdownMenuContent side="top" align="start" className="w-44">+ <DropdownMenuItem onClick={() => { fileInputRef.current?.click(); editor?.commands.focus() }}><Upload className="size-4" /> Upload a File</DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )}{/* Emoji button — fixed bottom-right */}- <EmojiPickerPopover side="top" align="end" onPick={(e) => editor?.chain().focus().insertContent(e).run()}>- <button className="absolute right-2 bottom-2 grid size-8 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground aria-expanded:bg-accent aria-expanded:text-foreground" aria-label="Emoji picker">- <Smile className="size-5" />- </button>- </EmojiPickerPopover>+ {!hideEmoji && (+ <EmojiPickerPopover side="top" align="end" onPick={(e) => editor?.chain().focus().insertContent(e).run()}>+ <button className="absolute right-2 bottom-2 grid size-8 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground aria-expanded:bg-accent aria-expanded:text-foreground" aria-label="Emoji picker">+ <Smile className="size-5" />+ </button>+ </EmojiPickerPopover>+ )}</div></div>)-}+})// Loading placeholder for <Composer>. Same outer footprint (px-3 pb-3 pt-0 +// rounded surface) so the message list above stays anchored across channeldiff --git a/src/web/src/components/community/create-forum-post.test.ts b/src/web/src/components/community/create-forum-post.test.tsnew file mode 100644index 000000000..a81da8470--- /dev/null+++ b/src/web/src/components/community/create-forum-post.test.ts@@ -0,0 +1,97 @@+/**+ * Server-render probes for CreateForumPost. Composer is mocked because it+ * mounts a real tiptap editor (needs DOM); everything else here is pure JSX+ * that renderToStaticMarkup can walk.+ */+import { describe, it, expect, vi } from "vitest"+import { createElement } from "react"+import { renderToStaticMarkup } from "react-dom/server"++vi.mock("./composer", () => ({+ Composer: (props: Record<string, unknown>) =>+ createElement("div", {+ "data-testid": "mock-composer",+ "data-mode": (props.mode as string) ?? "chat",+ "data-hide-emoji": String(!!props.hideEmoji),+ "data-placeholder": (props.placeholder as string) ?? "",+ }),+}))++vi.mock("@/hooks/community/mutations/uploads", () => ({+ useUploadFile: () => ({ mutateAsync: vi.fn() }),+ zipUploadResultsWithDimensions: () => [],+}))++import { CreateForumPost } from "./create-forum-post"++function render(over: Partial<Parameters<typeof CreateForumPost>[0]> = {}) {+ return renderToStaticMarkup(+ createElement(CreateForumPost, {+ forumChannelId: "cha_forum",+ members: [],+ onCancel: () => {},+ onCreatePost: async () => {},+ ...over,+ }),+ )+}++describe("CreateForumPost — copy + structure", () => {+ it("renders the region role + label so keyboard/SR users land in a named region", () => {+ const html = render()+ expect(html).toContain('role="region"')+ expect(html).toContain('aria-label="Create post"')+ })++ it("renders the title placeholder \"New post\" (not the old \"Title\")", () => {+ const html = render()+ expect(html).toContain('placeholder="New post"')+ expect(html).not.toContain('placeholder="Title"')+ })++ it("renders the composer in forumPostBody mode with hideEmoji + the body placeholder", () => {+ const html = render()+ expect(html).toContain('data-testid="mock-composer"')+ expect(html).toContain('data-mode="forumPostBody"')+ expect(html).toContain('data-hide-emoji="true"')+ expect(html).toContain('data-placeholder="What do you want to discuss?"')+ })++ it("renders a Create post footer button that is initially disabled (title + body both empty)", () => {+ const html = render()+ expect(html).toContain("Create post")+ // renderToStaticMarkup emits a bare `disabled` attribute for disabled={true}.+ // Find the button and check `disabled` is present within the same tag.+ const idx = html.indexOf(">Create post<")+ expect(idx).toBeGreaterThan(-1)+ const tagOpen = html.lastIndexOf("<button", idx)+ expect(tagOpen).toBeGreaterThan(-1)+ const tag = html.slice(tagOpen, idx)+ expect(tag).toMatch(/\sdisabled(=|\s|>)/)+ })++ it("does NOT render an emoji picker button or a slug hint", () => {+ const html = render()+ expect(html).not.toContain('aria-label="Emoji picker"')+ // Old surface's SlugHint muted-line copy pattern.+ expect(html).not.toContain("Will be saved as")+ })++ it("renders the Shift+Enter keyboard hint", () => {+ const html = render()+ // The <Kbd> component renders the shift + enter glyphs.+ expect(html).toContain("⇧")+ expect(html).toContain("⏎")+ })++ it("caps the title input at MAX_CHANNEL_NAME_LENGTH", () => {+ const html = render()+ // MAX_CHANNEL_NAME_LENGTH = 100+ expect(html).toContain('maxLength="100"')+ })++ it("renders the X cancel button with the correct aria-label", () => {+ const html = render()+ expect(html).toContain('aria-label="Cancel post"')+ })+})diff --git a/src/web/src/components/community/create-forum-post.tsx b/src/web/src/components/community/create-forum-post.tsxindex f8893b755..35caddd8a 100644--- a/src/web/src/components/community/create-forum-post.tsx+++ b/src/web/src/components/community/create-forum-post.tsx@@ -1,61 +1,207 @@"use client"-import { useState } from "react"-import { X, Smile } from "lucide-react"+import { useCallback, useRef, useState } from "react"+import { PlusCircle, Upload, X } from "lucide-react"import { Button } from "@/components/ui/button"-import { EmojiPickerPopover } from "./emoji-picker"-import { SlugHint } from "./slug-hint"-import { previewSlug } from "@/lib/community/slug-preview"+import { Kbd } from "@/components/ui/kbd"+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from "@/components/ui/dropdown-menu"+import { onEnterSubmit } from "@/lib/ime"+import { toastApiError } from "@/lib/api/client"+import { MAX_CHANNEL_NAME_LENGTH, type MentionType } from "@alook/shared"+import { Composer, type ComposerHandle, type SendAttachment } from "./composer"+import type { Member } from "./_types"+import {+ useUploadFile,+ zipUploadResultsWithDimensions,+ type UploadedAttachment,+} from "@/hooks/community/mutations/uploads"-// Tags are added AFTER creation from the post card's tag dialog, not here — the-// create form stays focused on title + body.-export type NewForumPost = { name: string; content: string }+// A forum post's body IS the first message in its thread — content plus any+// attachments and the audience-broadcast `mentionType` extracted from the body+// text. Tags are added AFTER creation from the post card's tag dialog, not here.+export type NewForumPost = {+ name: string+ content: string+ attachments?: UploadedAttachment[]+ mentionType?: MentionType+}-export function CreateForumPost({ onCancel, onPost }: {+export function CreateForumPost({+ forumChannelId,+ members,+ onSearchMembers,+ onCancel,+ onCreatePost,+}: {+ // The parent forum channel's id — used as the upload target so R2 objects+ // live under the same access-scope as the post.+ forumChannelId: string+ members: Member[]+ onSearchMembers?: (query: string) => voidonCancel: () => void- onPost: (post: NewForumPost) => void+ // Async — the page owns the mutation call + `enterThread` navigation. This+ // handler either resolves (success — child clears its state) or rejects+ // (failure — child toasts and preserves state for retry).+ onCreatePost: (post: NewForumPost) => Promise<void>}) {const [title, setTitle] = useState("")- const [body, setBody] = useState("")+ const [bodyHasContent, setBodyHasContent] = useState(false)+ const [isSubmitting, setIsSubmitting] = useState(false)+ // Ref-mirrored `isSubmitting` — the state-based flag is set asynchronously,+ // so a rapid second Shift+Enter (which fires the editor's keydown BEFORE+ // React commits `setIsSubmitting(true)`) sees a stale `false` and double-+ // submits. The button's own `disabled` attribute blocks click-based+ // double-submits, but keyboard submits go straight through the composer.+ const submittingRef = useRef(false)+ const bodyComposerRef = useRef<ComposerHandle>(null)+ const uploadFile = useUploadFile()++ // Retry cache: files already uploaded to R2 skip re-upload on retry after a+ // create failure. Mutation-only (ref, not state) — read inside the async+ // submit path. Cleared after a successful create.+ const uploadedCacheRef = useRef<Map<File, UploadedAttachment>>(new Map())++ const canSubmit = title.trim().length > 0 && bodyHasContent++ const onCancelGuarded = useCallback(() => {+ // Belt-and-suspenders: Escape mid-upload from ANY source (title, root,+ // composer body, footer button) is a no-op. Prevents orphaned R2 objects+ // and half-submitted posts.+ if (isSubmitting) return+ onCancel()+ }, [isSubmitting, onCancel])- const titlePreview = previewSlug(title)- const submit = () => {- const name = title.trim()- if (!titlePreview.slug) return- onPost({ name, content: body.trim() })+ const focusBody = () => bodyComposerRef.current?.focusEditor()++ const doSubmit = async (markdown: string, attachments: SendAttachment[] | undefined, mentionType: MentionType | undefined) => {+ if (!canSubmit || submittingRef.current) return+ submittingRef.current = true+ setIsSubmitting(true)+ try {+ const pending = attachments ?? []+ let uploaded: UploadedAttachment[] = []+ if (pending.length > 0) {+ const results = await Promise.all(+ pending.map(async (att) => {+ const cached = uploadedCacheRef.current.get(att.file)+ if (cached) return cached+ const res = await uploadFile.mutateAsync({+ target: { channelId: forumChannelId },+ file: att.file,+ })+ uploadedCacheRef.current.set(att.file, res)+ return res+ }),+ )+ uploaded = zipUploadResultsWithDimensions(results, pending)+ }+ try {+ await onCreatePost({+ name: title.trim(),+ content: markdown,+ attachments: uploaded.length > 0 ? uploaded : undefined,+ mentionType,+ })+ } catch (e) {+ toastApiError(e, "Failed to create post")+ return+ }+ uploadedCacheRef.current.clear()+ bodyComposerRef.current?.resetAfterSubmit()+ setTitle("")+ } catch (e) {+ toastApiError(e, "Failed to upload attachment")+ } finally {+ submittingRef.current = false+ setIsSubmitting(false)+ }+ }++ const handleBodySubmit = (markdown: string, attachments: SendAttachment[] | undefined, mentionType: MentionType | undefined) => {+ void doSubmit(markdown, attachments, mentionType)}return (- <div className="m-3 overflow-hidden rounded-lg border border-border bg-card">- <div className="flex items-start gap-3 p-3">- <button onClick={onCancel} className="mt-1 grid size-6 shrink-0 place-items-center rounded text-muted-foreground hover:bg-accent hover:text-foreground" aria-label="Cancel post">+ <div+ role="region"+ aria-label="Create post"+ onKeyDown={(e) => {+ if (e.key === "Escape" && !e.defaultPrevented) {+ e.stopPropagation()+ onCancelGuarded()+ }+ }}+ className="flex w-full min-w-0 shrink-0 flex-col border-b border-border px-4 py-3"+ >+ <div className="flex items-center gap-2 px-2">+ <input+ value={title}+ onChange={(e) => setTitle(e.target.value)}+ onKeyDown={onEnterSubmit(focusBody, { onEscape: onCancelGuarded })}+ placeholder="New post"+ autoFocus+ maxLength={MAX_CHANNEL_NAME_LENGTH}+ className="w-full min-w-0 bg-transparent text-2xl font-semibold outline-none placeholder:text-muted-foreground"+ />+ <button+ type="button"+ onClick={onCancelGuarded}+ className="grid size-6 shrink-0 place-items-center rounded text-muted-foreground hover:bg-accent hover:text-foreground"+ aria-label="Cancel post"+ ><X className="size-5" /></button>- <div className="min-w-0 flex-1">- <input- value={title}- onChange={(e) => setTitle(e.target.value)}- placeholder="Title"- className="w-full bg-transparent text-lg font-semibold outline-none placeholder:text-muted-foreground"- />- <SlugHint {...titlePreview} />- <textarea- value={body}- onChange={(e) => setBody(e.target.value)}- placeholder="Enter a message…"- rows={2}- className="mt-1 w-full resize-none bg-transparent text-sm leading-relaxed outline-none placeholder:text-muted-foreground"- />- </div></div>-- <div className="flex items-center justify-between border-t border-border px-3 py-2">- <EmojiPickerPopover side="top" align="start" onPick={(e) => setBody((b) => b + e)}>- <button className="grid size-7 place-items-center rounded text-muted-foreground hover:bg-accent hover:text-foreground aria-expanded:text-foreground" aria-label="Emoji picker">- <Smile className="size-5" />- </button>- </EmojiPickerPopover>- <Button size="sm" onClick={submit} disabled={!titlePreview.slug || !body.trim()}>Post</Button>+ <Composer+ ref={bodyComposerRef}+ mode="forumPostBody"+ hideEmoji+ hideAttach+ channel=""+ context="channel"+ members={members}+ onSearchMembers={onSearchMembers}+ channelRefCandidates={[]}+ placeholder="What do you want to discuss?"+ onSend={handleBodySubmit}+ onDirty={setBodyHasContent}+ />+ <div className="mt-2 flex items-center gap-3">+ <DropdownMenu>+ <DropdownMenuTrigger+ render={(+ <button+ type="button"+ className="grid size-8 place-items-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground aria-expanded:bg-accent aria-expanded:text-foreground"+ aria-label="Add"+ />+ )}+ >+ <PlusCircle className="size-5" />+ </DropdownMenuTrigger>+ <DropdownMenuContent side="top" align="start" className="w-44">+ <DropdownMenuItem onClick={() => bodyComposerRef.current?.openFilePicker()}>+ <Upload className="size-4" /> Upload a File+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ <span className="ml-auto flex items-center gap-1 text-xs text-muted-foreground">+ <Kbd>⇧</Kbd>+ <span>+</span>+ <Kbd>⏎</Kbd>+ </span>+ <Button+ size="sm"+ onClick={() => bodyComposerRef.current?.submitNow()}+ disabled={!canSubmit || isSubmitting}+ >+ {isSubmitting ? "Creating…" : "Create post"}+ </Button></div></div>)diff --git a/src/web/src/components/community/forum-view.test.ts b/src/web/src/components/community/forum-view.test.tsindex 42dfa68e3..d6bf41785 100644--- a/src/web/src/components/community/forum-view.test.ts+++ b/src/web/src/components/community/forum-view.test.ts@@ -25,7 +25,12 @@ function makePost(over: Partial<ForumPost> = {}): ForumPost {function render(posts: ForumPost[]): string {return renderToStaticMarkup(- createElement(ForumView, { posts, onOpenPost: () => {} })+ createElement(ForumView, {+ forumChannelId: "cha_forum",+ members: [],+ posts,+ onOpenPost: () => {},+ }))}@@ -37,6 +42,8 @@ function renderWithDelete(): string {return renderToStaticMarkup(createElement(ForumView, {+ forumChannelId: "cha_forum",+ members: [],posts,onOpenPost: () => {},onDeletePost: () => {},@@ -127,3 +134,24 @@ describe("ForumView post delete button", () => {expect(html).not.toContain("Delete post?")})})++describe("ForumView filter bar / composer swap", () => {+ it("shows the New Post trigger by default (not the composer)", () => {+ const html = render([makePost()])+ // The trigger button renders on first paint, in the filter bar slot.+ expect(html).toContain("New Post")+ // The composer's aria-label region only exists in composing mode.+ expect(html).not.toContain('aria-label="Create post"')+ })+})++describe("ForumView post card messageCount guard", () => {+ it("clamps a negative messageCount to 0 on render", () => {+ // Simulates a stale/cached response where the server hadn't yet subtracted+ // the body message. The defensive Math.max(0, …) guard keeps the badge+ // non-negative.+ const html = render([makePost({ messageCount: -3 })])+ // No "-3" anywhere in the rendered badge.+ expect(html).not.toContain(">-3<")+ })+})diff --git a/src/web/src/components/community/forum-view.tsx b/src/web/src/components/community/forum-view.tsxindex 08ca8cb5a..6d25b4011 100644--- a/src/web/src/components/community/forum-view.tsx+++ b/src/web/src/components/community/forum-view.tsx@@ -1,6 +1,6 @@"use client"-import { useState } from "react"+import { useRef, useState } from "react"import { MessagesSquare, ListChevronsUpDown, Plus, Tag, Trash2 } from "lucide-react"import { Button } from "@/components/ui/button"import { formatRelativeTime } from "./format-time"@@ -13,7 +13,7 @@ import { CreateForumPost, type NewForumPost } from "./create-forum-post"import { PostTagDialog } from "./post-tag-dialog"import { ConfirmDialog } from "@/components/ui/confirm-dialog"import { tid } from "@/lib/community/testids"-import type { ForumPost } from "./_types"+import type { ForumPost, Member } from "./_types"// Max member avatars shown in a post card's AvatarGroup before collapsing to a// "+N" bubble. Creator is always first.@@ -25,13 +25,22 @@ const MAX_AVATARS = 4// forum-level tag vocabulary. Per-post tags are edited from a hover icon on each// card (creator + server managers), not a forum-wide manage mode.export function ForumView({+ forumChannelId,+ members,+ onSearchMembers,posts, loading, onOpenPost, onCreatePost, onEditPostTags, canEditPostTags, savingTagsFor,onDeletePost, canDeletePost, deletingPost,}: {+ forumChannelId: string+ members: Member[]+ onSearchMembers?: (query: string) => voidposts: ForumPost[]loading?: booleanonOpenPost: (id: string) => void- onCreatePost?: (post: NewForumPost) => void+ // Async — page owns the mutation + `enterThread` navigation and either+ // resolves or rejects. `CreateForumPost` catches rejection to toast and+ // preserve composer state for retry.+ onCreatePost?: (post: NewForumPost) => Promise<void>// Save handler for a single post's tags. Absent → tag editing disabled.onEditPostTags?: (postId: string, tags: string[]) => void// Whether the current user may edit a given post's tags (creator or manager).@@ -49,46 +58,63 @@ export function ForumView({const [composing, setComposing] = useState(false)const [editingTagsFor, setEditingTagsFor] = useState<ForumPost | null>(null)const [deletingFor, setDeletingFor] = useState<ForumPost | null>(null)+ const newPostTriggerRef = useRef<HTMLButtonElement>(null)// Deduped union of every post's tags — the forum's tag list is derived, not// stored. Only rendered when non-empty.const allTags = [...new Set(posts.flatMap((p) => p.tags))].sort()const filtered = tag === "All" ? posts : posts.filter((p) => p.tags.includes(tag))++ const closeCompose = () => {+ setComposing(false)+ // Focus returns to the trigger so keyboard/screen-reader users don't lose+ // their place. `queueMicrotask` so the trigger has re-rendered before we+ // reach for its ref.+ queueMicrotask(() => newPostTriggerRef.current?.focus())+ }+return (<>- {composing && (+ {/* Composer OR filter bar in the same slot — swapping (not stacking)+ keeps the post list below anchored. */}+ {composing ? (<CreateForumPost- onCancel={() => setComposing(false)}- onPost={(post) => { onCreatePost?.(post); setComposing(false) }}+ forumChannelId={forumChannelId}+ members={members}+ onSearchMembers={onSearchMembers}+ onCancel={closeCompose}+ onCreatePost={async (post) => {+ if (!onCreatePost) return+ await onCreatePost(post)+ closeCompose()+ }}/>- )}-- {/* filter bar — derived tag chips on the left (hidden when there are no- tags anywhere), New Post on the right. */}- <div className="flex shrink-0 items-center gap-2 border-b border-border px-4 py-2">- <div className="flex min-w-0 flex-1 flex-wrap items-center gap-2">- {allTags.length > 0 && (- <>- <Badge variant={tag === "All" ? "default" : "secondary"} className="shrink-0 cursor-pointer" render={<button onClick={() => setTag("All")} />}>All</Badge>- {allTags.map((t) => (- <Badge- key={t}- variant={tag === t ? "default" : "secondary"}- className="shrink-0 cursor-pointer"- data-testid={tid.forumTagChip(t)}- render={<button onClick={() => setTag(t)} />}- >- {`#${t}`}- </Badge>- ))}- </>- )}- </div>- <div className="flex shrink-0 items-center gap-1">- <Button size="sm" onClick={() => setComposing(true)}><Plus className="size-4" /> New Post</Button>+ ) : (+ <div className="flex shrink-0 items-center gap-2 border-b border-border px-4 py-2">+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-2">+ {allTags.length > 0 && (+ <>+ <Badge variant={tag === "All" ? "default" : "secondary"} className="shrink-0 cursor-pointer" render={<button onClick={() => setTag("All")} />}>All</Badge>+ {allTags.map((t) => (+ <Badge+ key={t}+ variant={tag === t ? "default" : "secondary"}+ className="shrink-0 cursor-pointer"+ data-testid={tid.forumTagChip(t)}+ render={<button onClick={() => setTag(t)} />}+ >+ {`#${t}`}+ </Badge>+ ))}+ </>+ )}+ </div>+ <div className="flex shrink-0 items-center gap-1">+ <Button size="sm" ref={newPostTriggerRef} onClick={() => setComposing(true)}><Plus className="size-4" /> New Post</Button>+ </div></div>- </div>+ )}<main className="flex-1 overflow-y-auto thin-scrollbar p-4">{loading && posts.length === 0 ? (@@ -159,7 +185,7 @@ export function ForumView({<Badge key={t} variant="secondary">#{t}</Badge>))}<span className="ml-auto flex items-center gap-1 text-xs text-muted-foreground">- <MessagesSquare className="size-3.5" /> {p.messageCount}+ <MessagesSquare className="size-3.5" /> {Math.max(0, p.messageCount)}</span></div></div>diff --git a/src/web/src/hooks/community/mutations/forum.test.ts b/src/web/src/hooks/community/mutations/forum.test.tsindex 927e7976e..aaf501028 100644--- a/src/web/src/hooks/community/mutations/forum.test.ts+++ b/src/web/src/hooks/community/mutations/forum.test.ts@@ -85,6 +85,70 @@ function makePost(id: string): ForumPost {}}+describe("useCreateForumPost", () => {+ it("POSTs JSON with name + content only when no attachments/mentionType are provided", async () => {+ const { useCreateForumPost } = await load()+ useCreateForumPost()+ const created = makePost("p_new")+ apiFetchMock.mockResolvedValueOnce({ post: created })++ await runMutation({ channelId: "forum_1", name: "hi", content: "body" })++ expect(apiFetchMock).toHaveBeenCalledTimes(1)+ const [path, init] = apiFetchMock.mock.calls[0]+ expect(path).toBe("/api/community/channels/forum_1/posts")+ expect((init as { method?: string }).method).toBe("POST")+ const body = JSON.parse((init as { body: string }).body)+ expect(body.name).toBe("hi")+ expect(body.content).toBe("body")+ // Non-present fields serialize as `undefined` → dropped by JSON.stringify.+ expect(body.attachments).toBeUndefined()+ expect(body.mentionType).toBeUndefined()+ })++ it("threads attachments + mentionType through to the request body", async () => {+ const { useCreateForumPost } = await load()+ useCreateForumPost()+ apiFetchMock.mockResolvedValueOnce({ post: makePost("p_new") })++ const attachments = [{+ url: "/api/community/media/abc.png",+ filename: "abc.png",+ contentType: "image/png",+ size: 100,+ width: 10,+ height: 10,+ }]+ await runMutation({+ channelId: "forum_1",+ name: "heads up",+ content: "Heads up @everyone",+ attachments,+ mentionType: "everyone",+ })++ const [, init] = apiFetchMock.mock.calls[0]+ const body = JSON.parse((init as { body: string }).body)+ expect(body.attachments).toEqual(attachments)+ expect(body.mentionType).toBe("everyone")+ })++ it("prepends the fresh post to the forum's cached list on success", async () => {+ const { useCreateForumPost } = await load()+ useCreateForumPost()+ capturedQc.setQueryData<ForumPostsResponse>(communityKeys.forumPosts("forum_1"), {+ posts: [makePost("p_old")],+ })+ const fresh = makePost("p_new")+ apiFetchMock.mockResolvedValueOnce({ post: fresh })++ await runMutation({ channelId: "forum_1", name: "n", content: "c" })++ const cache = capturedQc.getQueryData<ForumPostsResponse>(communityKeys.forumPosts("forum_1"))+ expect(cache?.posts.map((p) => p.id)).toEqual(["p_new", "p_old"])+ })+})+describe("useDeleteForumPost", () => {it("DELETEs the post channel and removes it from the forum's cached list on success", async () => {const { useDeleteForumPost } = await load()diff --git a/src/web/src/hooks/community/mutations/forum.ts b/src/web/src/hooks/community/mutations/forum.tsindex 47c9f29eb..318ac6568 100644--- a/src/web/src/hooks/community/mutations/forum.ts+++ b/src/web/src/hooks/community/mutations/forum.ts@@ -5,23 +5,32 @@ import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import type { ForumPost } from "@/components/community/_types"import type { ForumPostsResponse } from "@/hooks/community/use-channel-panels"+import type { UploadedAttachment } from "@/hooks/community/mutations/uploads"+import type { MentionType } from "@alook/shared"export type CreateForumPostArgs = {channelId: stringname: stringcontent: string+ // Pre-uploaded R2 URLs (not raw files) — the client uploads via+ // `useUploadFile` before firing this mutation, and the server persists them+ // as `community_message_attachment` rows on the post's first message.+ attachments?: UploadedAttachment[]+ // Propagated to the first message so `@everyone`/`@here` audience broadcast+ // fires end-to-end.+ mentionType?: MentionType}export type CreateForumPostResult = { post: ForumPost }export function useCreateForumPost() {const queryClient = useQueryClient()return useMutation<CreateForumPostResult, Error, CreateForumPostArgs>({- mutationFn: async ({ channelId, name, content }) => {+ mutationFn: async ({ channelId, name, content, attachments, mentionType }) => {return apiFetch<CreateForumPostResult>(`/api/community/channels/${channelId}/posts`,{method: "POST",- body: JSON.stringify({ name, content }),+ body: JSON.stringify({ name, content, attachments, mentionType }),},)},diff --git a/src/web/src/lib/ime.test.ts b/src/web/src/lib/ime.test.tsindex 3a43b345c..409411caf 100644--- a/src/web/src/lib/ime.test.ts+++ b/src/web/src/lib/ime.test.ts@@ -42,12 +42,22 @@ describe("onEnterSubmit", () => {expect(e.preventDefault).toHaveBeenCalled()})- it("calls onEscape on Escape", () => {+ it("calls onEscape on Escape and prevents default", () => {const fn = vi.fn()const onEscape = vi.fn()- onEnterSubmit(fn, { onEscape })(key({ key: "Escape" }))+ const e = key({ key: "Escape" })+ onEnterSubmit(fn, { onEscape })(e)expect(onEscape).toHaveBeenCalledOnce()expect(fn).not.toHaveBeenCalled()+ expect(e.preventDefault).toHaveBeenCalled()+ })++ it("Escape without onEscape does NOT prevent default and fires no callback", () => {+ const fn = vi.fn()+ const e = key({ key: "Escape" })+ onEnterSubmit(fn)(e)+ expect(fn).not.toHaveBeenCalled()+ expect(e.preventDefault).not.toHaveBeenCalled()})it("ignores Shift+Enter by default but honors allowShift", () => {diff --git a/src/web/src/lib/ime.ts b/src/web/src/lib/ime.tsindex 1a9781691..289a39f39 100644--- a/src/web/src/lib/ime.ts+++ b/src/web/src/lib/ime.ts@@ -20,7 +20,10 @@ export function onEnterSubmit(return (e: EnterKeyEvent) => {if (isImeConfirming(e)) returnif (e.key === "Escape") {- opts?.onEscape?.()+ if (opts?.onEscape) {+ e.preventDefault()+ opts.onEscape()+ }return}if (e.key === "Enter") {diff --git a/src/web/src/test/e2e-ui/15-mention-scope.spec.ts b/src/web/src/test/e2e-ui/15-mention-scope.spec.tsindex e35ee81a1..5fee71431 100644--- a/src/web/src/test/e2e-ui/15-mention-scope.spec.ts+++ b/src/web/src/test/e2e-ui/15-mention-scope.spec.ts@@ -162,23 +162,25 @@ test.describe.serial("mentions — candidate scope", () => {await expect(opt.carol).toHaveCount(0)})- test("new forum post composer has no @ autocomplete (plain textarea)", async ({ asUser }) => {+ test("new forum post composer supports @-mentions like the chat composer", async ({ asUser }) => {const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${privateForumId}`)await page.waitForURL(new RegExp(privateForumId), { timeout: 20_000, waitUntil: "commit" })// Open the create-post form.await page.getByRole("button", { name: "New Post" }).click()- const body = page.getByPlaceholder("Enter a message…")+ // Body is the shared community <Composer> — a ProseMirror contenteditable,+ // NOT a plain <textarea>. Locate via the composer's testid, since Tiptap+ // exposes its placeholder as `data-placeholder` (a ProseMirror decoration)+ // rather than the HTML `placeholder` attribute Playwright's+ // `getByPlaceholder` matches.+ const body = composerEditable(page)await expect(body).toBeVisible({ timeout: 10_000 })- // It's a real <textarea>, not a TipTap contenteditable.- expect(await body.evaluate((el) => el.tagName)).toBe("TEXTAREA")- // Typing @ yields no mention popup options at all.+ // Typing @ opens the same mention popup the chat composer uses.await body.click()await body.pressSequentially("@bob")- await expect(page.getByTestId(tid.mentionOption(bob.id))).toHaveCount(0)- await expect(page.getByTestId(tid.mentionOption("everyone"))).toHaveCount(0)+ await expect(page.getByTestId(tid.mentionOption(bob.id))).toBeVisible({ timeout: 15_000 })})test("1:1 DM composer has no @ popup at all (no members, no everyone/here)", async ({ asUser }) => {