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
fix(community): preserve accepted messages across refetches
Gusddc42a7a743c
diff --git a/src/shared/src/community-ws-events.ts b/src/shared/src/community-ws-events.tsindex 81091f2ab..b8df761ee 100644--- a/src/shared/src/community-ws-events.ts+++ b/src/shared/src/community-ws-events.ts@@ -16,6 +16,7 @@ export type CommunityMessageCreate = {channelId: stringmessage: {id: string+ seq: numberauthorId: stringauthorName: stringauthorAvatar?: stringdiff --git a/src/shared/src/db/queries/community/friendship.ts b/src/shared/src/db/queries/community/friendship.tsindex f171d88a8..213f8c956 100644--- a/src/shared/src/db/queries/community/friendship.ts+++ b/src/shared/src/db/queries/community/friendship.ts@@ -433,6 +433,7 @@ export async function sendRequest(channelId: dm.id,message: {id: msg.id,+ seq: msg.seq,authorId: botId,authorName: botP?.name ?? "",content: msg.content,@@ -1091,6 +1092,7 @@ export async function ownerDecideOnRow(channelId: dm.id,message: {id: msg.id,+ seq: msg.seq,authorId: row.addresseeId,authorName: botP?.name ?? "",content: msg.content,diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.test.tsindex 6a18f5046..194ab7eda 100644--- a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts@@ -9,6 +9,7 @@ const mockGetChannelForMember = vi.fn()const mockGetChannel = vi.fn()const mockCreateMessage = vi.fn()const mockGetMessage = vi.fn()+const mockGetMessageByAuthorAndNonce = vi.fn()const mockGetMessageInScope = vi.fn()const mockGetMessagesByIdsInScope = vi.fn()const mockListMembers = vi.fn()@@ -53,6 +54,7 @@ vi.mock("@alook/shared", async () => {communityMessage: {createMessage: (...a: unknown[]) => mockCreateMessage(...a),getMessage: (...a: unknown[]) => mockGetMessage(...a),+ getMessageByAuthorAndNonce: (...a: unknown[]) => mockGetMessageByAuthorAndNonce(...a),getMessageInScope: (...a: unknown[]) => mockGetMessageInScope(...a),getMessagesByIdsInScope: (...a: unknown[]) => mockGetMessagesByIdsInScope(...a),listMessages: (...a: unknown[]) => mockListMessages(...a),@@ -140,6 +142,7 @@ describe("POST /api/community/channels/[id]/messages", () => {mockGetUserInternal.mockResolvedValue({ isBot: false, deletedAt: null })mockGetMessage.mockResolvedValue({id: "m1",+ seq: 12,authorId: "u1",authorName: "Alice",authorImage: null,@@ -151,6 +154,7 @@ describe("POST /api/community/channels/[id]/messages", () => {embeds: null,createdAt: "2026-06-30T00:00:00.000Z",})+ mockGetMessageByAuthorAndNonce.mockResolvedValue(null)mockListMembers.mockResolvedValue([])mockListMemberUserIds.mockResolvedValue([])mockGetMessagesByIdsInScope.mockResolvedValue([])@@ -197,6 +201,46 @@ describe("POST /api/community/channels/[id]/messages", () => {expect(mockGetChannelForMember).toHaveBeenCalled()})+ it("returns canonical id, seq, and clientNonce for a fresh accepted send", async () => {+ mockGetMessage.mockResolvedValue({+ id: "m1",+ seq: 12,+ clientNonce: "n1",+ authorId: "u1",+ authorName: "Alice",+ authorImage: null,+ authorEmail: "[email protected]",+ content: "hello",+ type: "default",+ mentionType: null,+ replyToId: null,+ embeds: null,+ createdAt: "2026-06-30T00:00:00.000Z",+ })++ const res = await POST(postReq({ content: "hello", nonce: "n1" }), ctx)+ const body = await res.json() as { message: { id: string; seq: number; clientNonce?: string }; deduped?: boolean }++ expect(res.status).toBe(201)+ expect(body).toEqual({+ message: expect.objectContaining({ id: "m1", seq: 12, clientNonce: "n1" }),+ })+ })++ it("returns the original canonical contract for a same-nonce replay", async () => {+ mockGetMessageByAuthorAndNonce.mockResolvedValue({ id: "m-existing", seq: 8, clientNonce: "n1" })++ const res = await POST(postReq({ content: "hello", nonce: "n1" }), ctx)+ const body = await res.json() as { message: { id: string; seq: number; clientNonce?: string }; deduped: boolean }++ expect(res.status).toBe(201)+ expect(body).toEqual({+ message: expect.objectContaining({ id: "m-existing", seq: 8, clientNonce: "n1" }),+ deduped: true,+ })+ expect(mockCreateMessage).not.toHaveBeenCalled()+ })+it("rejects content longer than MAX_MESSAGE_CONTENT_LENGTH with 400", async () => {const tooLong = "a".repeat(MAX_MESSAGE_CONTENT_LENGTH + 1)const res = await POST(postReq({ content: tooLong }), ctx)diff --git a/src/web/src/app/api/community/dm/[id]/messages/route.test.ts b/src/web/src/app/api/community/dm/[id]/messages/route.test.tsindex 5a46bcd16..0ed180eee 100644--- a/src/web/src/app/api/community/dm/[id]/messages/route.test.ts+++ b/src/web/src/app/api/community/dm/[id]/messages/route.test.ts@@ -10,6 +10,7 @@ const mockGetDMPeer = vi.fn()const mockIsBlocked = vi.fn()const mockCreateMessage = vi.fn()const mockGetMessage = vi.fn()+const mockGetMessageByAuthorAndNonce = vi.fn()const mockGetMessageInScope = vi.fn()const mockGetMessagesByIdsInScope = vi.fn()const mockListMessages = vi.fn()@@ -52,6 +53,7 @@ vi.mock("@alook/shared", async () => {communityMessage: {createMessage: (...a: unknown[]) => mockCreateMessage(...a),getMessage: (...a: unknown[]) => mockGetMessage(...a),+ getMessageByAuthorAndNonce: (...a: unknown[]) => mockGetMessageByAuthorAndNonce(...a),getMessageInScope: (...a: unknown[]) => mockGetMessageInScope(...a),getMessagesByIdsInScope: (...a: unknown[]) => mockGetMessagesByIdsInScope(...a),listMessages: (...a: unknown[]) => mockListMessages(...a),@@ -145,6 +147,7 @@ describe("POST /api/community/dm/[id]/messages", () => {mockFanOutToDM.mockResolvedValue(undefined)mockBroadcastToUser.mockResolvedValue(undefined)mockCheckMessageRateLimit.mockResolvedValue({ allowed: true })+ mockGetMessageByAuthorAndNonce.mockResolvedValue(null)})it("returns 429 with Retry-After when the sender is rate limited", async () => {@@ -193,6 +196,38 @@ describe("POST /api/community/dm/[id]/messages", () => {expect(mockListMembers).not.toHaveBeenCalled()expect(mockListMemberUserIds).not.toHaveBeenCalled()})++ it("returns canonical id, seq, and clientNonce for fresh and replayed sends", async () => {+ mockIsBlocked.mockResolvedValue(false)+ mockCreateMessage.mockResolvedValue({ id: "m1" })+ mockGetMessage.mockResolvedValue({+ id: "m1",+ seq: 12,+ clientNonce: "n1",+ authorId: "u1",+ authorName: "Alice",+ authorImage: null,+ authorEmail: "[email protected]",+ content: "hi",+ type: "default",+ mentionType: null,+ replyToId: null,+ embeds: null,+ createdAt: "2026-06-30T00:00:00.000Z",+ })++ const fresh = await POST(postReq({ content: "hi", nonce: "n1" }), ctx)+ expect(await fresh.json()).toEqual({+ message: expect.objectContaining({ id: "m1", seq: 12, clientNonce: "n1" }),+ })++ mockGetMessageByAuthorAndNonce.mockResolvedValue({ id: "m1", seq: 12, clientNonce: "n1" })+ const replay = await POST(postReq({ content: "hi", nonce: "n1" }), ctx)+ expect(await replay.json()).toEqual({+ message: expect.objectContaining({ id: "m1", seq: 12, clientNonce: "n1" }),+ deduped: true,+ })+ })})describe("GET /api/community/dm/[id]/messages", () => {diff --git a/src/web/src/app/api/community/servers/[id]/bots/route.ts b/src/web/src/app/api/community/servers/[id]/bots/route.tsindex e3714ba2d..985238677 100644--- a/src/web/src/app/api/community/servers/[id]/bots/route.ts+++ b/src/web/src/app/api/community/servers/[id]/bots/route.ts@@ -173,6 +173,7 @@ export const POST = withAuth(async (req: NextRequest, ctx) => {channelId: dm.id,message: {id: msg.id,+ seq: msg.seq,authorId: botId,authorName: botName,content: msg.content,diff --git a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsxindex dda88f5d1..307dc8d71 100644--- a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx+++ b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx@@ -48,6 +48,7 @@ import {} from "@/hooks/community/use-channel-panels"import { useNotificationSettings } from "@/hooks/community/use-notification-settings"import { useOnlineUserIds, useCommunityWsStore } from "@/stores/community/ws"+import { useMessageStreamStore } from "@/stores/community/message-stream"import {useSendMessage,useToggleReactionApi,@@ -63,8 +64,9 @@ import {useSetChannelNotif,useUploadFile,zipUploadResultsWithDimensions,+ toAttachmentVm,sendNonce,- type SendMessageResult,+ tempMessageId,type UploadedAttachment,} from "@/hooks/community/mutations"import {@@ -328,6 +330,7 @@ function ChannelView() {// early). On the bootstrap path the initial page is pre-seeded, so trust it// and don't refetch page 0 on mount.const messagesQuery = useMessages(channelId, {+ serverId,lastReadMessageId: readSnapshotFetching? undefined: (readSnapshot?.lastReadMessageId ?? null),@@ -454,7 +457,7 @@ function ChannelView() {const setMemberRoleMut = useSetMemberRole()const kickMemberMut = useKickMember()const setChannelNotifMut = useSetChannelNotif()- const uploadFileMut = useUploadFile()+ const { mutateAsync: uploadFileAsync } = useUploadFile()const goBack = useCallback(() => { uiHandlers.goBackMobile?.() }, [uiHandlers])@@ -511,7 +514,7 @@ function ChannelView() {return () => {communityWsUnsubscribe()}- }, [channelId, isChildChannel, params.serverId, router])+ }, [channelId, isChildChannel, params.serverId, router, serverId])// ── Local UI state ──────────────────────────────────────────────────────const [rightPanel, setRightPanel] = useState<RightPanel>(null)@@ -714,19 +717,62 @@ function ChannelView() {// error overlay (rate-limit path was the reproducer). Returning `null`// instead lets thread-create + retry callers detect failure without a// try/catch each.- const doSend = useCallback(- async (content: string, opts?: { replyToId?: string; mentionType?: MentionType; attachments?: UploadedAttachment[]; nonce?: string }): Promise<SendMessageResult | null> => {+ const messageScope = useMemo(+ () => ({ kind: "channel" as const, id: channelId, serverId }),+ [channelId, serverId],+ )++ const runAcceptedIntent = useCallback(+ async (nonce: string) => {+ const streamStore = useMessageStreamStore.getState()+ const payload = streamStore.getRetryPayload(messageScope, nonce)+ if (!payload) return+ let uploadedAttachments: UploadedAttachment[] | undefined+ if (payload.localUploads.length > 0 && payload.uploadStatus === "settled") {+ const projected = payload.message.attachments+ if (projected?.length === payload.localUploads.length) {+ uploadedAttachments = projected.map((attachment, index) => {+ const local = payload.localUploads[index]+ return {+ url: attachment.url,+ filename: local.file.name,+ contentType: local.file.type,+ size: local.file.size,+ width: local.width,+ height: local.height,+ }+ })+ }+ }+ if (payload.localUploads.length > 0 && !uploadedAttachments) {+ const results = await Promise.all(+ payload.localUploads.map((upload) =>+ uploadFileAsync({ target: { channelId }, file: upload.file }).catch((error) => {+ toastApiError(error, "Failed to attach file")+ return null+ }),+ ),+ )+ if (results.some((result) => result === null)) {+ streamStore.dispatch(messageScope, { type: "uploadFailed", nonce })+ return+ }+ uploadedAttachments = zipUploadResultsWithDimensions(results, [...payload.localUploads])+ streamStore.dispatch(messageScope, {+ type: "uploadSettled",+ nonce,+ attachments: uploadedAttachments.map(toAttachmentVm),+ })+ }try {- return await sendMessageAsync({+ await sendMessageAsync({+ serverId,channelId,- content,- replyToId: opts?.replyToId,- mentionType: opts?.mentionType,- attachments: opts?.attachments,- // Idempotency nonce: mint one per fresh send; a retry passes the- // failed row's nonce back (see `onRetry`) so the resend dedupes- // server-side instead of double-posting.- nonce: opts?.nonce ?? sendNonce(),+ content: payload.message.content ?? "",+ replyToId: payload.message.replyTo?.id,+ mentionType: payload.mentionType,+ attachments: uploadedAttachments,+ nonce,author: {id: currentUser.id,name: currentUser.name,@@ -734,10 +780,10 @@ function ChannelView() {},})} catch {- return null+ return}},- [sendMessageAsync, channelId, currentUser.id, currentUser.name, currentUser.avatar],+ [messageScope, uploadFileAsync, channelId, sendMessageAsync, serverId, currentUser.id, currentUser.name, currentUser.avatar],)// Latest-ref for the values the message actions read at call time. Keeping@@ -759,9 +805,9 @@ function ChannelView() {const messageActions = useMemo(() => ({onToggleReaction: (id: string, emoji: string) =>- toggleReactionApi({ channelId, messageId: id, emoji, userId: currentUser.id }),+ toggleReactionApi({ serverId, channelId, messageId: id, emoji, userId: currentUser.id }),onReact: (id: string, emoji: string) =>- toggleReactionApi({ channelId, messageId: id, emoji, userId: currentUser.id }),+ toggleReactionApi({ serverId, channelId, messageId: id, emoji, userId: currentUser.id }),onReply: (id: string) => {const m = actionsCtxRef.current.messages.find((x) => x.id === id)if (m) setReplyTo({ id: m.id, authorName: m.authorName ?? "", text: m.content ?? "" })@@ -786,7 +832,7 @@ function ChannelView() {const m = actionsCtxRef.current.messages.find((x) => x.id === id)const name = deriveThreadName(m?.content, actionsCtxRef.current.channelName)try {- const data = await createThreadAsync({ channelId, messageId: id, name })+ const data = await createThreadAsync({ serverId, channelId, messageId: id, name })router.push(`/c/channels/${params.serverId}/${data.id}`)} catch (e) {toastApiError(e, "Failed to create thread")@@ -798,13 +844,17 @@ function ChannelView() {},onRetry: (id: string) => {const m = actionsCtxRef.current.messages.find((x) => x.id === id)- // Reuse the failed row's nonce so the resend dedupes server-side if the- // original actually committed (500-after-commit). Remove the stale failed- // row first — `doSend` inserts a fresh optimistic row (reusing the nonce),- // and a WS/dedupe reconcile then converges them by nonce/id.- if (m?.content) {- void doSend(m.content, { nonce: m.clientNonce, replyToId: m.replyTo?.id })- }+ if (!m?.clientNonce) return+ useMessageStreamStore.getState().dispatch(messageScope, { type: "retry", nonce: m.clientNonce })+ void runAcceptedIntent(m.clientNonce)+ },+ onDismiss: (id: string) => {+ const m = actionsCtxRef.current.messages.find((x) => x.id === id)+ if (!m?.clientNonce) return+ useMessageStreamStore.getState().dispatch(messageScope, {+ type: "dismissFailed",+ nonce: m.clientNonce,+ })},onPreviewImage: (url: string) => {actionsCtxRef.current.uiHandlers.previewImage?.(url)@@ -822,7 +872,7 @@ function ChannelView() {// reads go through actionsCtxRef. This stability is load-bearing: an unstable// messageActions busts MessageRow/Message's memo and re-renders every visible// row on every commit (see message.tsx messagePropsEqual).- }), [channelId, currentUser.id, toggleReactionApi, unpinMessageMutate, pinMessageMutate, toggleMark, createThreadAsync, doSend, router, params.serverId])+ }), [serverId, channelId, currentUser.id, toggleReactionApi, unpinMessageMutate, pinMessageMutate, toggleMark, createThreadAsync, messageScope, runAcceptedIntent, router, params.serverId])const threadActions = useMemo(() => ({ ...messageActions, onCreateThread: undefined }),@@ -843,29 +893,42 @@ function ChannelView() {)// ── Send messages ───────────────────────────────────────────────────────- const sendMessage = async (markdown: string, attachments?: SendAttachment[], mentionType?: MentionType) => {- if (!markdown && !attachments?.length) return-- let uploadedAttachments: UploadedAttachment[] = []- if (attachments?.length) {- const results = await Promise.all(- attachments.map((a) =>- uploadFileMut.mutateAsync({ target: { channelId }, file: a.file }).catch((e) => {- toastApiError(e, "Failed to attach file")- return null- }),- ),- )- uploadedAttachments = zipUploadResultsWithDimensions(results, attachments)- }-- void doSend(markdown || "", {- replyToId: replyTo?.id,+ const acceptMessage = (markdown: string, attachments?: SendAttachment[], mentionType?: MentionType): boolean => {+ if (!markdown && !attachments?.length) return false+ const nonce = sendNonce()+ const createdPreviewUrls: string[] = []+ const accepted = useMessageStreamStore.getState().accept(messageScope, {+ nonce,+ tempId: tempMessageId(),+ message: {+ type: "chat",+ authorId: currentUser.id,+ authorName: currentUser.name,+ authorAvatar: currentUser.avatar,+ content: markdown,+ createdAt: new Date().toISOString(),+ ...(replyTo ? { replyTo: { id: replyTo.id, authorName: replyTo.authorName, text: replyTo.text.slice(0, 100) } } : {}),+ },+ localUploads: attachments?.map((attachment) => {+ const previewObjectUrl = attachment.previewObjectUrl ?? URL.createObjectURL(attachment.file)+ if (!attachment.previewObjectUrl) createdPreviewUrls.push(previewObjectUrl)+ return {+ file: attachment.file,+ previewObjectUrl,+ width: attachment.width,+ height: attachment.height,+ }+ }) ?? [],mentionType,- attachments: uploadedAttachments.length > 0 ? uploadedAttachments : undefined,})+ if (!accepted) {+ for (const url of createdPreviewUrls) URL.revokeObjectURL(url)+ return false+ }+ void runAcceptedIntent(nonce)communityWsResetTypingThrottle({ channelId })setReplyTo(null)+ return true}const handleTyping = () => {@@ -1130,7 +1193,8 @@ function ChannelView() {members={composerMembers}onSearchMembers={membersHook.searchMembers}channelRefCandidates={channelRefCandidates}- onSend={sendMessage}+ sendContract="accepted"+ onAcceptSend={acceptMessage}onTyping={handleTyping}replyingTo={replyTo?.authorName}onCancelReply={() => setReplyTo(null)}@@ -1280,7 +1344,8 @@ function ChannelView() {members={composerMembers}onSearchMembers={membersHook.searchMembers}channelRefCandidates={channelRefCandidates}- onSend={sendMessage}+ sendContract="accepted"+ onAcceptSend={acceptMessage}onTyping={handleTyping}replyingTo={replyTo?.authorName}onCancelReply={() => setReplyTo(null)}diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsxindex 2e6d75dd9..c031bd0db 100644--- a/src/web/src/app/c/me/[dmId]/page.tsx+++ b/src/web/src/app/c/me/[dmId]/page.tsx@@ -437,6 +437,7 @@ function DmView() {) : (<div data-onboarding-target="dm-composer" data-onboarding-name={dm.name} className="shrink-0"><Composer+ sendContract="legacy"channel={dm.name}context="dm"// DM context short-circuits `rankMentionItems` to `[]` — no popup,diff --git a/src/web/src/components/community/composer.tsx b/src/web/src/components/community/composer.tsxindex 8bb2f8bcf..8ebc3b597 100644--- a/src/web/src/components/community/composer.tsx+++ b/src/web/src/components/community/composer.tsx@@ -38,14 +38,19 @@ import {type ChannelRefPopupState,} from "@/lib/community/channel-ref-extension"-export type SendAttachment = { file: File; width?: number; height?: number }+export type SendAttachment = { file: File; previewObjectUrl?: string; width?: number; height?: number }// Pure mapping from `useFileAttachments`'s pending-file state to `onSend`'s// attachments argument. Extracted so the width/height threading through// `Composer.send()` is unit-testable without mounting the tiptap editor.export function pendingFilesToSendAttachments(pendingFiles: PendingFile[]): SendAttachment[] | undefined {if (pendingFiles.length === 0) return undefined- return pendingFiles.map((pf) => ({ file: pf.file, width: pf.width, height: pf.height }))+ return pendingFiles.map((pf) => ({+ file: pf.file,+ previewObjectUrl: pf.thumbnailUrl ?? undefined,+ width: pf.width,+ height: pf.height,+ }))}// Pure extraction of the paste → File[] collection used by `handlePaste`:@@ -77,7 +82,7 @@ export type ComposerHandle = {openFilePicker: () => void}-export type ComposerProps = {+type ComposerBaseProps = {channel: stringcontext: MentionContextmembers: Member[]@@ -91,7 +96,6 @@ export type ComposerProps = {// for DM composers. Always provided by the caller — empty array is fine,// the popup just shows nothing on `/`.channelRefCandidates?: ChannelRefCandidate[]- onSend?: (markdown: string, attachments?: SendAttachment[], mentionType?: MentionType) => voidonTyping?: () => void// when set, shows a "Replying to X" bar above the inputreplyingTo?: string@@ -125,6 +129,20 @@ export type ComposerProps = {draftKey?: string}+type ComposerLegacySend = {+ sendContract?: "legacy"+ onSend?: (markdown: string, attachments?: SendAttachment[], mentionType?: MentionType) => void | Promise<void>+ onAcceptSend?: never+}++type ComposerAcceptedSend = {+ sendContract: "accepted"+ onAcceptSend: (markdown: string, attachments?: SendAttachment[], mentionType?: MentionType) => boolean+ onSend?: never+}++export type ComposerProps = ComposerBaseProps & (ComposerLegacySend | ComposerAcceptedSend)+// 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@@ -139,7 +157,9 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compomembers,onSearchMembers,channelRefCandidates = [],+ sendContract = "legacy",onSend,+ onAcceptSend,onTyping,replyingTo,onCancelReply,@@ -155,6 +175,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compoconst {pendingFiles,setPendingFiles,+ transferPendingFiles,addPendingFiles,fileInputRef,handleFileSelect,@@ -427,14 +448,20 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo// the compose → send → render round-trip preserves both newline levels.const markdown = editor.isEmpty ? "" : editor.getText({ blockSeparator: "\n\n" }).trim()const mentionType = detectMentionType(markdown)- onSend?.(markdown, pendingFilesToSendAttachments(pendingFiles), mentionType)+ const attachments = pendingFilesToSendAttachments(pendingFiles)+ if (sendContract === "accepted") {+ if (!onAcceptSend?.(markdown, attachments, mentionType)) return+ } else {+ void onSend?.(markdown, attachments, 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()if (draftKeyRef.current) clearComposerDraft(draftKeyRef.current)- setPendingFiles([])+ if (sendContract === "accepted") transferPendingFiles()+ else setPendingFiles([])setMentionPopup(EMPTY_MENTION_STATE)setChannelRefPopup(EMPTY_CHANNEL_REF_STATE)}diff --git a/src/web/src/components/community/create-forum-post.tsx b/src/web/src/components/community/create-forum-post.tsxindex 35caddd8a..4a4c098ed 100644--- a/src/web/src/components/community/create-forum-post.tsx+++ b/src/web/src/components/community/create-forum-post.tsx@@ -158,6 +158,7 @@ export function CreateForumPost({</button></div><Composer+ sendContract="legacy"ref={bodyComposerRef}mode="forumPostBody"hideEmojidiff --git a/src/web/src/components/community/message-context-sheet.tsx b/src/web/src/components/community/message-context-sheet.tsxindex 926257c9e..1e17d2488 100644--- a/src/web/src/components/community/message-context-sheet.tsx+++ b/src/web/src/components/community/message-context-sheet.tsx@@ -278,10 +278,12 @@ export function MessageContextSheet({const onCreateThreadId = useCallback(async (id: string) => {if (type === "dm") return+ const serverId = routeParams?.serverId+ if (!serverId) returnconst m = findMessage(id)const name = deriveThreadName(m?.content, "channel")try {- const data = await createThreadMut.mutateAsync({ channelId, messageId: id, name })+ const data = await createThreadMut.mutateAsync({ serverId, channelId, messageId: id, name })// Match the main-channel UX: after creating a thread the row shows// the thread indicator, click it to enter. Don't auto-navigate — we're// inside a sidecar preview, silently teleporting the user to the thread@@ -304,7 +306,7 @@ export function MessageContextSheet({} catch (e) {toastApiError(e, "Failed to create thread")}- }, [type, channelId, findMessage, createThreadMut, queryClient, queryKey])+ }, [type, routeParams, channelId, findMessage, createThreadMut, queryClient, queryKey])const onOpenThreadId = useCallback((threadId: string) => {// Sheet's Reply-style handoff: navigate the main window to the thread anddiff --git a/src/web/src/components/community/message-list.tsx b/src/web/src/components/community/message-list.tsxindex 1a7107d7b..d53dcdfa3 100644--- a/src/web/src/components/community/message-list.tsx+++ b/src/web/src/components/community/message-list.tsx@@ -21,7 +21,7 @@ import type { Msg, OpenProfile } from "./_types"export function MessageList({channel, messages, loading, pinnedIds, newDividerBefore, typingUsers, onOpenThread, onOpenProfile,onToggleReaction, onReact,- onReply, onPin, onMark, onCreateThread, onCopy, onRetry, onPreviewImage, onDownloadFile,+ onReply, onPin, onMark, onCreateThread, onCopy, onRetry, onDismiss, onPreviewImage, onDownloadFile,resolveUserName, scrollToMessageId, hero, variant = "channel", onScrollRoot, viewerUserId, initialScrollReady = true,hasMore, isFetchingOlder, onLoadOlder,hasMoreNewer, isFetchingNewer, onLoadNewer, onJumpToPresent, unreadCount, onOpenContextSheet,@@ -42,6 +42,7 @@ export function MessageList({onCreateThread?: (id: string) => voidonCopy?: (id: string) => voidonRetry?: (id: string) => void+ onDismiss?: (id: string) => voidonPreviewImage?: (name: string) => voidonDownloadFile?: (name: string) => voidresolveUserName?: (userId: string) => string@@ -457,6 +458,7 @@ export function MessageList({onCreateThreadId={onCreateThread}onCopyId={onCopy}onRetryId={onRetry}+ onDismissId={onDismiss}onJumpToId={jumpTo}onPreviewImage={onPreviewImage}onDownloadFile={onDownloadFile}diff --git a/src/web/src/components/community/message-row.tsx b/src/web/src/components/community/message-row.tsxindex e97264d32..e33c2a3e5 100644--- a/src/web/src/components/community/message-row.tsx+++ b/src/web/src/components/community/message-row.tsx@@ -29,6 +29,7 @@ export interface MessageRowProps {onCreateThreadId?: (id: string) => voidonCopyId?: (id: string) => voidonRetryId?: (id: string) => void+ onDismissId?: (id: string) => voidonJumpToId?: (id: string) => voidonPreviewImage?: (name: string) => voidonDownloadFile?: (name: string) => void@@ -50,7 +51,7 @@ function MessageRowImpl(props: MessageRowProps) {const {m, pinned, highlighted, onOpenThread, onOpenProfile,onToggleReactionId, onReactId, onReplyId, onPinId, onMarkId, onCreateThreadId,- onCopyId, onRetryId, onJumpToId, onPreviewImage, onDownloadFile,+ onCopyId, onRetryId, onDismissId, onJumpToId, onPreviewImage, onDownloadFile,resolveUserName, onImageLoad,selectMode, selected, onToggleSelectId, onEnterSelectId, onShareSingleId,} = props@@ -71,6 +72,7 @@ function MessageRowImpl(props: MessageRowProps) {const onCreateThread = useCallback(() => onCreateThreadId?.(id), [onCreateThreadId, id])const onCopy = useCallback(() => onCopyId?.(id), [onCopyId, id])const onRetry = useCallback(() => onRetryId?.(id), [onRetryId, id])+ const onDismiss = useCallback(() => onDismissId?.(id), [onDismissId, id])const onJumpReply = useCallback(() => { if (replyToId) onJumpToId?.(replyToId) }, [onJumpToId, replyToId])const onToggleSelect = useCallback(() => onToggleSelectId?.(id), [onToggleSelectId, id])const onEnterSelect = useCallback(() => onEnterSelectId?.(id), [onEnterSelectId, id])@@ -97,6 +99,7 @@ function MessageRowImpl(props: MessageRowProps) {onCreateThread={onCreateThreadId ? onCreateThread : undefined}onCopy={onCopyId ? onCopy : undefined}onRetry={onRetryId ? onRetry : undefined}+ onDismiss={onDismissId ? onDismiss : undefined}onPreviewImage={onPreviewImage}onDownloadFile={onDownloadFile}resolveUserName={resolveUserName}diff --git a/src/web/src/components/community/message.render.test.ts b/src/web/src/components/community/message.render.test.tsindex 4ae9cc717..3414793e2 100644--- a/src/web/src/components/community/message.render.test.ts+++ b/src/web/src/components/community/message.render.test.ts@@ -143,4 +143,24 @@ describe("Message lazy overlays", () => {// The reaction-add testid only renders inside the activated toolbar.expect(tree).not.toContain("reaction-add")})++ it("keeps failed-message dismiss independent from retry", () => {+ const onRetry = vi.fn()+ const onDismiss = vi.fn()+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ makeTree({ m: baseMsg({ failed: true }), onOpenThread: vi.fn(), onRetry, onDismiss }),+ { createNodeMock: () => genericMock },+ )+ })++ const dismiss = renderer!.root.findAllByType("button")+ .find((button) => button.children.includes("Dismiss"))+ expect(dismiss).toBeDefined()+ act(() => dismiss!.props.onClick())++ expect(onDismiss).toHaveBeenCalledOnce()+ expect(onRetry).not.toHaveBeenCalled()+ })})diff --git a/src/web/src/components/community/message.tsx b/src/web/src/components/community/message.tsxindex 3022c4234..9ae64c80a 100644--- a/src/web/src/components/community/message.tsx+++ b/src/web/src/components/community/message.tsx@@ -48,7 +48,7 @@ export function messageCanShare(m: RenderMsg, compact?: boolean): boolean {function MessageImpl({m, compact, pinned, onOpenThread, onOpenProfile, onJumpReply,- onToggleReaction, onReact, onReply, onPin, onMark, onCreateThread, onCopy, onRetry,+ onToggleReaction, onReact, onReply, onPin, onMark, onCreateThread, onCopy, onRetry, onDismiss,onPreviewImage, onDownloadFile, highlighted, resolveUserName, onImageLoad,selectMode, selected, onToggleSelect, onEnterSelect, onShareSingle,}: {@@ -69,6 +69,7 @@ function MessageImpl({onCreateThread?: () => voidonCopy?: () => voidonRetry?: () => void+ onDismiss?: () => voidonPreviewImage?: (name: string) => voidonDownloadFile?: (name: string) => voidhighlighted?: boolean@@ -414,9 +415,16 @@ function MessageImpl({)}{m.failed && (- <button onClick={onRetry} className="mt-1 flex items-center gap-2 text-xs text-destructive hover:underline">- <X className="size-3.5" /> Message failed to send. Click to retry.- </button>+ <div className="mt-1 flex items-center gap-3 text-xs text-destructive">+ <button onClick={onRetry} className="flex items-center gap-2 hover:underline">+ <X className="size-3.5" /> Message failed to send. Click to retry.+ </button>+ {onDismiss && (+ <button onClick={onDismiss} className="text-muted-foreground hover:text-foreground hover:underline">+ Dismiss+ </button>+ )}+ </div>)}</div></div>@@ -492,6 +500,7 @@ function messagePropsEqual(prev: MessageProps, next: MessageProps): boolean {prev.onCreateThread === next.onCreateThread &&prev.onCopy === next.onCopy &&prev.onRetry === next.onRetry &&+ prev.onDismiss === next.onDismiss &&prev.onPreviewImage === next.onPreviewImage &&prev.onDownloadFile === next.onDownloadFile &&prev.resolveUserName === next.resolveUserName &&diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsxindex 6750942fd..e4a45f24b 100644--- a/src/web/src/components/community/shell-frame.tsx+++ b/src/web/src/components/community/shell-frame.tsx@@ -35,6 +35,7 @@ import { signOut } from "@/lib/auth-client"import { clearPersistedCache } from "@/lib/query-persister"import { useCommunityStore } from "@/stores/community"import { useCommunityWsStore, useOnlineUserIds } from "@/stores/community/ws"+import { useMessageStreamStore } from "@/stores/community/message-stream"import { useCurrentUser, useSetCurrentUser } from "@/contexts/community/current-user"import { useServers } from "@/hooks/community/use-servers"import { useFolders } from "@/hooks/community/use-folders"@@ -613,6 +614,7 @@ export function ShellFrame({// the debounce window — covers every sign-out path uniformly.useCommunityStore.getState().reset()useCommunityWsStore.getState().reset()+ useMessageStreamStore.getState().resetAll()// Drop the persisted IDB blob so the next user on this machine// doesn't see the previous session's cached message rows.await clearPersistedCache(currentUser.id).catch(() => { })diff --git a/src/web/src/components/nav-user.tsx b/src/web/src/components/nav-user.tsxindex 34f6cc7c8..0ad289286 100644--- a/src/web/src/components/nav-user.tsx+++ b/src/web/src/components/nav-user.tsx@@ -7,6 +7,7 @@ import { clearAllCache } from "@/lib/chat-cache";import { clearPersistedCache } from "@/lib/query-persister";import { useCommunityStore } from "@/stores/community";import { useCommunityWsStore } from "@/stores/community/ws";+import { useMessageStreamStore } from "@/stores/community/message-stream";import {DropdownMenu,DropdownMenuContent,@@ -80,6 +81,7 @@ export function NavUser() {// WS handler timers survive past sign-out.useCommunityStore.getState().reset();useCommunityWsStore.getState().reset();+ useMessageStreamStore.getState().resetAll();await clearAllCache();// Drop the persisted IDB blob so the next user on this machine// doesn't inherit the previous session's cached message rows.diff --git a/src/web/src/hooks/community/insert-message-into-cache.test.ts b/src/web/src/hooks/community/insert-message-into-cache.test.tsindex bee8381d5..27d2d87da 100644--- a/src/web/src/hooks/community/insert-message-into-cache.test.ts+++ b/src/web/src/hooks/community/insert-message-into-cache.test.ts@@ -1,6 +1,11 @@import { describe, it, expect } from "vitest"-import { insertMessageIntoCache } from "./use-community-ws"+import { insertMessageIntoCache as placeMessageInCache } from "./use-community-ws"import type { CommunityMessageCreate } from "@alook/shared"+import { projectCommunityMessageCreate } from "@/lib/community/message-wire"++function insertMessageIntoCache(cache: unknown, message: CommunityMessageCreate["message"]) {+ return placeMessageInCache(cache as never, projectCommunityMessageCreate(message))+}// `insertMessageIntoCache` is a pure cache-patch function (no React), so it// can be imported and tested directly — no need for the file's heavy React@@ -12,6 +17,7 @@ describe("insertMessageIntoCache — attachment width/height", () => {function baseMessage(overrides: Partial<CommunityMessageCreate["message"]> = {}): CommunityMessageCreate["message"] {return {id: "msg_1",+ seq: 1,type: "chat",authorId: "author_1",authorName: "Author",@@ -100,6 +106,7 @@ describe("insertMessageIntoCache — optimistic-row reconcile by clientNonce (refunction echo(overrides: Partial<CommunityMessageCreate["message"]> = {}): CommunityMessageCreate["message"] {return {id: "msg_server_1",+ seq: 2,type: "chat",authorId: "author_1",authorName: "Author",diff --git a/src/web/src/hooks/community/mutations/messages.test.ts b/src/web/src/hooks/community/mutations/messages.test.tsindex 64ff55bb2..e1db07227 100644--- a/src/web/src/hooks/community/mutations/messages.test.ts+++ b/src/web/src/hooks/community/mutations/messages.test.ts@@ -118,22 +118,32 @@ beforeEach(() => {// ── useSendMessage ────────────────────────────────────────────────────────describe("useSendMessage — happy path", () => {- it("optimistic insert then reconciles server id on success", async () => {+ it("keeps Query base-only and acknowledges the accepted overlay intent", async () => {capturedQc.setQueryData(communityKeys.channelMessages("ch_1"), makeCache([]))- apiFetchMock.mockResolvedValueOnce({ message: { id: "server_id_1" } })+ apiFetchMock.mockResolvedValueOnce({ message: { id: "server_id_1", seq: 9 } })const mod = await loadMod()+ const stream = await import("@/stores/community/message-stream")+ stream.useMessageStreamStore.getState().accept(+ { kind: "channel", id: "ch_1", serverId: "s1" },+ { nonce: "n1", tempId: "temp_n1", message: { type: "chat", content: "hi" }, localUploads: [] },+ )mod.useSendMessage() // populate capturedConfigawait runMutation({+ serverId: "s1",channelId: "ch_1",content: "hi",+ nonce: "n1",author: { id: "u_me", name: "me", avatar: "M" },})const cache = capturedQc.getQueryData<{ pages: { messages: { id: string }[] }[] }>(communityKeys.channelMessages("ch_1"),)- expect(cache?.pages[0].messages.map((m) => m.id)).toEqual(["server_id_1"])+ expect(cache?.pages[0].messages).toEqual([])+ expect(stream.getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).outboxByNonce.get("n1")).toEqual(+ expect.objectContaining({ status: "acked", serverMessageId: "server_id_1", serverSeq: 9 }),+ )})})@@ -142,17 +152,24 @@ describe("useSendMessage — rollback", () => {capturedQc.setQueryData(communityKeys.channelMessages("ch_1"), makeCache([]))apiFetchMock.mockRejectedValueOnce(new Error("boom"))const mod = await loadMod()+ const stream = await import("@/stores/community/message-stream")+ stream.useMessageStreamStore.getState().accept(+ { kind: "channel", id: "ch_1", serverId: "s1" },+ { nonce: "n1", tempId: "temp_n1", message: { type: "chat", content: "hi" }, localUploads: [] },+ )mod.useSendMessage()await runMutation({+ serverId: "s1",channelId: "ch_1",content: "hi",+ nonce: "n1",author: { id: "u_me", name: "me", avatar: "M" },}).catch(() => { })const cache = capturedQc.getQueryData<{ pages: { messages: { id: string; failed?: boolean }[] }[] }>(communityKeys.channelMessages("ch_1"),)- expect(cache?.pages[0].messages).toHaveLength(1)- expect(cache?.pages[0].messages[0].failed).toBe(true)+ expect(cache?.pages[0].messages).toEqual([])+ expect(stream.getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).outboxByNonce.get("n1")?.status).toBe("failed")})})@@ -163,21 +180,19 @@ describe("useSendMessage — rollback", () => {describe("useSendMessage — stamps authorId on optimistic row", () => {it("optimistic row carries the sender's authorId", async () => {capturedQc.setQueryData(communityKeys.channelMessages("ch_1"), makeCache([]))- // Never resolves — we only care about the optimistic write from onMutate.- apiFetchMock.mockImplementation(() => new Promise(() => { }))const mod = await loadMod()- mod.useSendMessage()- const cfg = capturedConfig!- await cfg.onMutate!({- channelId: "ch_1",- content: "hi",- author: { id: "u_me", name: "me", avatar: "M" },- })- const cache = capturedQc.getQueryData<{ pages: { messages: { authorId?: string }[] }[] }>(- communityKeys.channelMessages("ch_1"),+ const stream = await import("@/stores/community/message-stream")+ stream.useMessageStreamStore.getState().accept(+ { kind: "channel", id: "ch_1", serverId: "s1" },+ {+ nonce: "n1",+ tempId: "temp_n1",+ message: { type: "chat", content: "hi", authorId: "u_me" },+ localUploads: [],+ },)- expect(cache?.pages[0].messages).toHaveLength(1)- expect(cache?.pages[0].messages[0].authorId).toBe("u_me")+ expect(stream.getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).outboxByNonce.get("n1")?.message.authorId).toBe("u_me")+ expect(mod.useSendMessage).toBeTypeOf("function")})})@@ -278,15 +293,23 @@ describe("useSendMessage — 429 rate limit fires a toast + marks failed", () =>const { ApiError } = await import("@/lib/errors")apiFetchMock.mockRejectedValueOnce(new ApiError("rate_limited", 429))mod.useSendMessage()+ const stream = await import("@/stores/community/message-stream")+ stream.useMessageStreamStore.getState().accept(+ { kind: "channel", id: "ch_1", serverId: "s1" },+ { nonce: "n1", tempId: "temp_n1", message: { type: "chat", content: "hi" }, localUploads: [] },+ )await runMutation({+ serverId: "s1",channelId: "ch_1",content: "hi",+ nonce: "n1",author: { id: "u_me", name: "me", avatar: "M" },}).catch(() => { })const cache = capturedQc.getQueryData<{ pages: { messages: { failed?: boolean }[] }[] }>(communityKeys.channelMessages("ch_1"),)- expect(cache?.pages[0].messages[0].failed).toBe(true)+ expect(cache?.pages[0].messages).toEqual([])+ expect(stream.getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).outboxByNonce.get("n1")?.status).toBe("failed")expect(toastMock).toHaveBeenCalledWith(expect.stringContaining("Rate limited"))})})@@ -324,16 +347,23 @@ describe("useSendMessage — no blocked branch on channel path", () => {const { ApiError } = await import("@/lib/errors")apiFetchMock.mockRejectedValueOnce(new ApiError("blocked", 403))mod.useSendMessage()+ const stream = await import("@/stores/community/message-stream")+ stream.useMessageStreamStore.getState().accept(+ { kind: "channel", id: "ch_1", serverId: "s1" },+ { nonce: "n1", tempId: "temp_n1", message: { type: "chat", content: "hi" }, localUploads: [] },+ )await runMutation({+ serverId: "s1",channelId: "ch_1",content: "hi",+ nonce: "n1",author: { id: "u_me", name: "me", avatar: "M" },}).catch(() => { })const cache = capturedQc.getQueryData<{ pages: { messages: { failed?: boolean }[] }[] }>(communityKeys.channelMessages("ch_1"),)- expect(cache?.pages[0].messages).toHaveLength(1)- expect(cache?.pages[0].messages[0].failed).toBe(true)+ expect(cache?.pages[0].messages).toEqual([])+ expect(stream.getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).outboxByNonce.get("n1")?.status).toBe("failed")expect(toastMock).not.toHaveBeenCalledWith("You cannot send messages to this user")expect(toastMock).toHaveBeenCalledWith("blocked")})@@ -391,6 +421,61 @@ describe("useToggleReaction — optimistic flip + rollback", () => {// timer on subsequent clicks. Step 3's hook dropped the coalescing; this// restores it via useCommunityStore.reactionTimers.describe("useToggleReactionApi — 300ms debounce coalescing", () => {+ it("updates and rolls back a fallback-only channel row without creating a second row", async () => {+ vi.useFakeTimers()+ try {+ capturedQc.setQueryData(communityKeys.channelMessages("ch_1"), makeCache([]))+ apiFetchMock.mockRejectedValueOnce(new Error("boom"))+ const mod = await loadMod()+ const stream = await import("@/stores/community/message-stream")+ const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }+ stream.useMessageStreamStore.getState().dispatch(scope, {+ type: "wsMessage",+ message: {+ id: "m_1",+ seq: 1,+ type: "chat",+ authorId: "u_other",+ authorName: "Other",+ content: "hello",+ createdAt: "2026-08-06T00:00:00.000Z",+ reactions: [{ emoji: "👍", count: 1, me: true, userIds: ["u_me"] }],+ },+ })++ const toggle = mod.useToggleReactionApi()+ toggle({+ serverId: "s1",+ channelId: "ch_1",+ messageId: "m_1",+ emoji: "👍",+ userId: "u_me",+ })++ let overlay = stream.getMessageOverlay(scope)+ expect(overlay.liveById).toHaveLength(1)+ expect(overlay.liveById.get("m_1")?.reactions).toEqual([])++ await vi.advanceTimersByTimeAsync(300)+ await Promise.resolve()++ overlay = stream.getMessageOverlay(scope)+ expect(apiFetchMock).toHaveBeenCalledWith(+ expect.stringContaining("/api/community/messages/m_1/reactions/"),+ { method: "DELETE" },+ )+ expect(overlay.liveById).toHaveLength(1)+ expect(overlay.liveById.get("m_1")?.reactions).toEqual([+ expect.objectContaining({ emoji: "👍", me: true, count: 1 }),+ ])+ expect(capturedQc.getQueryData<{ pages: { messages: unknown[] }[] }>(+ communityKeys.channelMessages("ch_1"),+ )?.pages[0].messages).toEqual([])+ } finally {+ vi.useRealTimers()+ }+ })+it("5 rapid clicks with alternating me→!me→me settle to a SINGLE API call at end of window", async () => {vi.useFakeTimers()try {diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.tsindex dca9ab1b3..393bcb108 100644--- a/src/web/src/hooks/community/mutations/messages.ts+++ b/src/web/src/hooks/community/mutations/messages.ts@@ -12,6 +12,13 @@ import { ApiError } from "@/lib/errors"import { communityKeys } from "@/lib/query-keys"import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"import { useCommunityStore } from "@/stores/community"+import { useMessageStreamStore } from "@/stores/community/message-stream"+import { getMessageOverlay } from "@/stores/community/message-stream"+import {+ materializeMessageStream,+ type CanonicalMessage,+ type MessageScope,+} from "@/lib/community/message-stream"import type { Msg, Attachment } from "@/components/community/_types"import type { MessagesPage } from "@/hooks/community/use-messages"import type { PinsResponse } from "@/hooks/community/use-channel-panels"@@ -194,6 +201,7 @@ export function sendNonce(): string {// ── Send message (channel/thread) ──────────────────────────────────────────export type SendMessageArgs = {+ serverId: stringchannelId: stringcontent: stringreplyToId?: string@@ -210,7 +218,7 @@ export type SendMessageArgs = {// the same nonce — `message` is the canonical (original) row, nothing new was// inserted. The caller treats it as success (reconcile the optimistic row,// clear the failed pill), never as a failure to resend.-export type SendMessageResult = { message: { id: string }; deduped?: boolean }+export type SendMessageResult = { message: { id: string; seq: number }; deduped?: boolean }/*** Channel/thread send. The server infers thread-vs-channel routing from the@@ -218,12 +226,10 @@ export type SendMessageResult = { message: { id: string }; deduped?: boolean }* `/channels/:id/messages`.*/export function useSendMessage() {- const queryClient = useQueryClient()return useMutation<SendMessageResult,Error,- SendMessageArgs,- { tempId: string; key: readonly unknown[] }+ SendMessageArgs>({mutationFn: async ({ channelId, content, replyToId, mentionType, attachments, nonce }) => {return apiFetch<SendMessageResult>(@@ -234,61 +240,13 @@ export function useSendMessage() {},)},- onMutate: async (args) => {- const key = communityKeys.channelMessages(args.channelId)- await queryClient.cancelQueries({ queryKey: key })- const tempId = tempMessageId()- // Caller supplies the nonce (fresh send mints one, retry reuses the- // failed row's). Stamped on the optimistic row so a WS message-create- // echoing the same nonce can reconcile this row by nonce — this heals the- // no-click phantom (500-after-commit the user never retried).- const nonce = args.nonce- // Retry reuses the failed row's nonce — drop that stale row first so- // exactly one row carries this nonce (else the WS by-nonce reconcile- // would match two).- if (nonce) {- queryClient.setQueryData<PageCache>(key, (c) => removeByNonce(c, nonce))- }- const cache = queryClient.getQueryData<PageCache>(key)- let replyTo: Msg["replyTo"] | undefined- if (args.replyToId && cache) {- for (const page of cache.pages) {- const original = page.messages.find((m) => m.id === args.replyToId)- if (original) {- replyTo = {- id: args.replyToId,- authorName: original.authorName ?? "Unknown",- text: (original.content ?? "").slice(0, 100),- }- break- }- }- if (!replyTo) {- replyTo = { id: args.replyToId, authorName: "Unknown", text: "" }- }- }- const optimisticAttachments = args.attachments?.map(toAttachmentVm)- const msg: Msg = {- id: tempId,- type: "chat",- // #3: stamp the sender's userId onto optimistic rows so- // `useChannelWatermark` recognizes them as self-authored (skip- // client PUT — server-side write path already writes the sender's- // watermark on POST, see #1).- authorId: args.author.id,- authorName: args.author.name,- authorAvatar: args.author.avatar,- content: args.content,- createdAt: new Date().toISOString(),- ...(nonce ? { clientNonce: nonce } : {}),- ...(replyTo ? { replyTo } : {}),- ...(optimisticAttachments?.length ? { attachments: optimisticAttachments } : {}),+ onError: (err, args) => {+ if (args.nonce) {+ useMessageStreamStore.getState().dispatch(+ { kind: "channel", id: args.channelId, serverId: args.serverId },+ { type: "postFail", nonce: args.nonce },+ )}- queryClient.setQueryData<PageCache>(key, (c) => prependOptimistic(c, msg))- return { tempId, key }- },- onError: (err, _args, ctx) => {- if (!ctx) return// 429: server-side rate limit. Fire an explicit toast so the user// knows why the send failed — otherwise the only signal is a// `failed: true` pill, which reads like a generic error. The row@@ -302,14 +260,17 @@ export function useSendMessage() {// failures outside the 429 case.toastApiError(err, "Failed to send message")}- queryClient.setQueryData<PageCache>(ctx.key as ReturnType<typeof communityKeys.channelMessages>, (c) =>- markFailedById(c, ctx.tempId),- )},- onSuccess: (data, _args, ctx) => {- if (!ctx) return- queryClient.setQueryData<PageCache>(ctx.key as ReturnType<typeof communityKeys.channelMessages>, (c) =>- reconcileServerId(c, ctx.tempId, data.message.id),+ onSuccess: (data, args) => {+ if (!args.nonce) return+ useMessageStreamStore.getState().dispatch(+ { kind: "channel", id: args.channelId, serverId: args.serverId },+ {+ type: "postAck",+ nonce: args.nonce,+ serverMessageId: data.message.id,+ serverSeq: data.message.seq,+ },)},})@@ -413,6 +374,7 @@ export function useSendDmMessage() {// ── Toggle reaction ────────────────────────────────────────────────────────export type ToggleReactionArgs = {+ serverId?: stringchannelId?: stringdmId?: stringmessageId: string@@ -439,34 +401,77 @@ function togglePageCacheReaction(const pages = cache.pages.map((p) => {if (!p.messages.some((m) => m.id === messageId)) return ptouched = true- const nextMessages = p.messages.map((m) => {- if (m.id !== messageId) return m- const reactions = (m.reactions ?? []).map((r) => ({ ...r, userIds: [...(r.userIds ?? [])] }))- const existing = reactions.find((r) => r.emoji === emoji)- if (add) {- if (existing) {- if (!existing.userIds.includes(userId)) {- existing.userIds.push(userId)- existing.count = existing.userIds.length- }- existing.me = true- } else {- reactions.push({ emoji, count: 1, me: true, userIds: [userId] })- }- } else if (existing) {- existing.userIds = existing.userIds.filter((id) => id !== userId)- existing.count = existing.userIds.length- existing.me = false- if (existing.count <= 0) reactions.splice(reactions.indexOf(existing), 1)- }- return { ...m, reactions }- })+ const nextMessages = p.messages.map((m) =>+ m.id === messageId ? toggleMessageReaction(m, emoji, userId, add) : m)return { ...p, messages: nextMessages }})if (!touched) return cachereturn { ...cache, pages }}+function toggleMessageReaction(+ message: Msg,+ emoji: string,+ userId: string,+ add: boolean,+): Msg {+ const reactions = (message.reactions ?? []).map((reaction) => ({+ ...reaction,+ userIds: [...(reaction.userIds ?? [])],+ }))+ const existing = reactions.find((reaction) => reaction.emoji === emoji)+ if (add) {+ if (existing) {+ if (!existing.userIds.includes(userId)) existing.userIds.push(userId)+ existing.count = existing.userIds.length+ existing.me = true+ } else {+ reactions.push({ emoji, count: 1, me: true, userIds: [userId] })+ }+ } else if (existing) {+ existing.userIds = existing.userIds.filter((id) => id !== userId)+ existing.count = existing.userIds.length+ existing.me = false+ if (existing.count <= 0) reactions.splice(reactions.indexOf(existing), 1)+ }+ return { ...message, reactions }+}++function channelScope(args: ToggleReactionArgs): MessageScope | undefined {+ return args.channelId && args.serverId+ ? { kind: "channel", id: args.channelId, serverId: args.serverId }+ : undefined+}++function currentMaterializedMessage(+ cache: PageCache | undefined,+ scope: MessageScope,+ messageId: string,+): Msg | undefined {+ const base = cache?.pages.flatMap((page) => page.messages)+ .filter((message): message is CanonicalMessage => message.seq !== undefined) ?? []+ return materializeMessageStream(base, getMessageOverlay(scope))+ .find((message) => message.id === messageId)+}++function refreshExistingReactionFallback(+ cache: PageCache | undefined,+ args: ToggleReactionArgs,+ add: boolean,+): void {+ const scope = channelScope(args)+ if (!scope) return+ const overlay = getMessageOverlay(scope)+ const existing = [...overlay.liveById.values()].find((message) => message.id === args.messageId)+ if (!existing) return+ const source = currentMaterializedMessage(cache, scope, args.messageId) ?? existing+ if (source.seq === undefined) return+ useMessageStreamStore.getState().dispatch(scope, {+ type: "liveRefreshed",+ message: toggleMessageReaction(source, args.emoji, args.userId, add) as CanonicalMessage,+ })+}+function currentMeStatus(cache: PageCache | undefined,messageId: string,@@ -573,13 +578,20 @@ export function useToggleReactionApi(): (args: ToggleReactionArgs) => void {? communityKeys.dmMessages(args.dmId): communityKeys.channelMessages("__none__")const cache = queryClient.getQueryData<PageCache>(key)- const wasMe = currentMeStatus(cache, args.messageId, args.emoji)+ const scope = channelScope(args)+ const source = scope+ ? currentMaterializedMessage(cache, scope, args.messageId)+ : undefined+ const wasMe = source+ ? source.reactions?.find((reaction) => reaction.emoji === args.emoji)?.me ?? false+ : currentMeStatus(cache, args.messageId, args.emoji)const nextMe = !wasMe// Optimistic write is always synchronous — the debounce only defers the// API call, not the visible UI.queryClient.setQueryData<PageCache>(key, (c) =>togglePageCacheReaction(c, args.messageId, args.emoji, args.userId, nextMe),)+ refreshExistingReactionFallback(queryClient.getQueryData<PageCache>(key), args, nextMe)const timerKey = `${args.messageId}:${args.emoji}`const reactionTimers = useCommunityStore.getState().reactionTimers@@ -607,6 +619,7 @@ export function useToggleReactionApi(): (args: ToggleReactionArgs) => void {queryClient.setQueryData<PageCache>(key, (c) =>togglePageCacheReaction(c, args.messageId, args.emoji, args.userId, originalMe),)+ refreshExistingReactionFallback(queryClient.getQueryData<PageCache>(key), args, originalMe)})}, REACTION_DEBOUNCE_MS)reactionTimers.set(timerKey, { timer, originalMe })@@ -769,6 +782,7 @@ export function useToggleMark() {// ── Create thread ──────────────────────────────────────────────────────────export type CreateThreadArgs = {+ serverId: stringchannelId: string // parent channel — used to invalidate the threads listmessageId: stringname: string@@ -809,6 +823,23 @@ export function useCreateThread() {return { ...cache, pages }},)+ const scope: MessageScope = { kind: "channel", id: args.channelId, serverId: args.serverId }+ const fallback = [...getMessageOverlay(scope).liveById.values()]+ .find((message) => message.id === args.messageId)+ if (fallback) {+ const cached = queryClient.getQueryData<PageCache>(communityKeys.channelMessages(args.channelId))+ const source = currentMaterializedMessage(cached, scope, args.messageId) ?? fallback+ if (source.seq !== undefined) {+ useMessageStreamStore.getState().dispatch(scope, {+ type: "liveRefreshed",+ message: {+ ...source,+ seq: source.seq,+ thread: { id: data.id, name: args.name, messageCount: 0 },+ },+ })+ }+ }void queryClient.invalidateQueries({ queryKey: communityKeys.threads(args.channelId) })},})diff --git a/src/web/src/hooks/community/use-community-ws.test.ts b/src/web/src/hooks/community/use-community-ws.test.tsindex f72475558..f9f6bc067 100644--- a/src/web/src/hooks/community/use-community-ws.test.ts+++ b/src/web/src/hooks/community/use-community-ws.test.ts@@ -28,6 +28,7 @@ import type {CommunityFriendRequest,CommunityTypingStart,} from "@alook/shared"+import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"import { communityKeys } from "@/lib/query-keys"// ── React shim ───────────────────────────────────────────────────────────@@ -126,8 +127,10 @@ async function mountHook(options?: { viewerUserId?: string | null } & Record<strasync function resetStore() {const { useCommunityStore } = await import("@/stores/community")useCommunityStore.getState().reset()+ useCommunityStore.getState().setCurrentServerId("s1")const { useCommunityWsStore } = await import("@/stores/community/ws")useCommunityWsStore.getState().reset()+ useMessageStreamStore.getState().resetAll()const mod = await import("./use-community-ws")mod._resetActiveSend_forTesting()}@@ -145,6 +148,8 @@ function messageCreate(channelId: string, msgId = "m_1"): CommunityMessageCreatechannelId,message: {id: msgId,+ seq: Number(msgId.match(/\d+$/)?.[0] ?? 1),+ type: "chat",authorId: "u_author",authorName: "author",content: "hi",@@ -162,7 +167,7 @@ function unreadBump(}describe("useCommunityWs — message.create", () => {- it("patches channelMessages cache when the event matches the focused channel", async () => {+ it("writes the channel overlay and leaves the base cache untouched when focused", async () => {await mountHook()const { useCommunityStore } = await import("@/stores/community")useCommunityStore.getState().subscribe({ channelId: "ch_1" })@@ -184,7 +189,27 @@ describe("useCommunityWs — message.create", () => {const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(communityKeys.channelMessages("ch_1"),)- expect(cache?.pages[0].messages.map((m) => m.id)).toEqual(["m_1"])+ expect(cache?.pages[0].messages).toEqual([])+ expect([...getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).liveById]).toHaveLength(1)+ })++ it("heals a first-seen event replay once the focused serverId becomes available", async () => {+ await mountHook()+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().setCurrentServerId(null)+ useCommunityStore.getState().subscribe({ channelId: "ch_1" })+ refCounter = 0+ stateCounter = 0+ callbackCounter = 0+ await mountHook()++ const event = messageCreate("ch_1")+ capturedOnMessage!(event)+ expect(getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).liveById).toHaveLength(0)++ useCommunityStore.getState().setCurrentServerId("s1")+ capturedOnMessage!(event)+ expect(getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).liveById).toHaveLength(1)})it("does NOT patch a channel we aren't focused on", async () => {@@ -244,10 +269,7 @@ describe("useCommunityWs — message.create", () => {capturedOnMessage!(messageCreate("ch_1"))capturedOnMessage!(messageCreate("ch_1"))capturedOnMessage!(messageCreate("ch_1"))- const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(- communityKeys.channelMessages("ch_1"),- )- expect(cache?.pages[0].messages).toHaveLength(1)+ expect(getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).liveById.size).toBe(1)})it("caps the live page at MAX_LIVE_PAGE_MESSAGES, dropping the oldest entry", async () => {@@ -277,11 +299,9 @@ describe("useCommunityWs — message.create", () => {)const ids = cache?.pages[0].messages.map((m) => m.id) ?? []expect(ids).toHaveLength(MAX_LIVE_PAGE_MESSAGES)- // Oldest entry (seed_0) was dropped; the newest inserted message is present.- expect(ids).not.toContain("seed_0")- expect(ids[ids.length - 1]).toBe("new_message")- // Second-oldest survivor shifts to the front.- expect(ids[0]).toBe("seed_1")+ expect(ids[0]).toBe("seed_0")+ expect(ids).not.toContain("new_message")+ expect(getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).liveById.has("new_message")).toBe(true)})it("flips hasMore/hasMoreOlder to true when the head-slice discards history (legacy shape)", async () => {@@ -313,7 +333,7 @@ describe("useCommunityWs — message.create", () => {// Head-slice discarded seed_0; the "Load older" affordance must re-arm// via `hasMore: true` (legacy shape had no `hasMoreOlder` so we don't// synthesize it).- expect(cache?.pages[0].hasMore).toBe(true)+ expect(cache?.pages[0].hasMore).toBe(false)expect(cache?.pages[0].hasMoreOlder).toBeUndefined()})@@ -343,7 +363,7 @@ describe("useCommunityWs — message.create", () => {const cache = capturedQueryClient.getQueryData<{pages: { messages: { id: string }[]; hasMore?: boolean; hasMoreOlder?: boolean; hasMoreNewer?: boolean }[]}>(communityKeys.channelMessages("ch_1"))- expect(cache?.pages[0].hasMoreOlder).toBe(true)+ expect(cache?.pages[0].hasMoreOlder).toBe(false)// We must NOT invent a legacy `hasMore` flag on an anchor envelope —// the two shapes are mutually exclusive.expect(cache?.pages[0].hasMore).toBeUndefined()@@ -396,7 +416,8 @@ describe("useCommunityWs — message.create", () => {const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(communityKeys.channelMessages("ch_1"),)- expect(cache?.pages[0].messages.map((m) => m.id)).toEqual(["seed_0", "m_new"])+ expect(cache?.pages[0].messages.map((m) => m.id)).toEqual(["seed_0"])+ expect(getMessageOverlay({ kind: "channel", id: "ch_1", serverId: "s1" }).liveById.has("m_new")).toBe(true)})it("does not schedule an inbox invalidate for viewer's own messages", async () => {@@ -628,7 +649,8 @@ describe("useCommunityWs — message.create patches channel unread in the open sconst messagesCache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(communityKeys.channelMessages("ch_focused"),)- expect(messagesCache?.pages[0].messages.map((m) => m.id)).toEqual(["m_1"])+ expect(messagesCache?.pages[0].messages).toEqual([])+ expect(getMessageOverlay({ kind: "channel", id: "ch_focused", serverId: "s1" }).liveById.has("m_1")).toBe(true)const inboxCalls = invalidateSpy.mock.calls.filter((c) => {const key = c[0]?.queryKeyreturn Array.isArray(key) && key.includes("inbox")@@ -1105,6 +1127,7 @@ describe("useCommunityWs — DM message.create", () => {channelId: "dm_1",message: {id: "dm_m_1",+ seq: 1,authorId: "u_a",authorName: "a",content: "hi",@@ -1236,6 +1259,66 @@ describe("useCommunityWs — child_create patches parent thread badge with count}>(communityKeys.channelMessages("ch_parent"))expect(cache?.pages[0].messages[0].thread?.messageCount).toBe(5)})++ it("child_update keeps newer thread fields from the current base row when refreshing fallback", async () => {+ await mountHook()+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().setCurrentServerId("s1")+ const scope = { kind: "channel" as const, id: "ch_parent", serverId: "s1" }+ useMessageStreamStore.getState().dispatch(scope, {+ type: "wsMessage",+ message: {+ id: "m_parent",+ seq: 1,+ type: "chat",+ authorId: "u1",+ authorName: "Alice",+ content: "hello",+ createdAt: "2026-08-06T00:00:00.000Z",+ thread: {+ id: "ch_thread",+ name: "fallback",+ messageCount: 1,+ lastReplyAt: "2026-08-06T00:00:01.000Z",+ },+ },+ })+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_parent"), {+ pages: [{+ messages: [{+ id: "m_parent",+ seq: 1,+ type: "chat",+ authorId: "u1",+ authorName: "Alice",+ content: "hello",+ createdAt: "2026-08-06T00:00:00.000Z",+ thread: {+ id: "ch_thread",+ name: "base",+ messageCount: 2,+ lastReplyAt: "2026-08-06T00:00:02.000Z",+ },+ }],+ hasMore: false,+ }],+ pageParams: [null],+ })++ capturedOnMessage!({+ type: "community:channel.child_update",+ parentChannelId: "ch_parent",+ channelId: "ch_thread",+ changes: { messageCount: 5 },+ } satisfies CommunityChildChannelUpdate)++ expect(getMessageOverlay(scope).liveById.get("m_parent")?.thread).toEqual({+ id: "ch_thread",+ name: "base",+ messageCount: 5,+ lastReplyAt: "2026-08-06T00:00:02.000Z",+ })+ })})// ── Regression #5 — typing.start focus guard (DM leak) ──────────────────diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.tsindex aaf74a13b..468ebf3cb 100644--- a/src/web/src/hooks/community/use-community-ws.ts+++ b/src/web/src/hooks/community/use-community-ws.ts@@ -4,9 +4,9 @@ import { useCallback, useEffect, useRef } from "react"import { useQueryClient, type InfiniteData } from "@tanstack/react-query"import { useUserWs } from "@/lib/use-user-ws"import { useCommunityStore } from "@/stores/community"+import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"import { useCommunityWsStore } from "@/stores/community/ws"import { communityKeys } from "@/lib/query-keys"-import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"import {patchCacheJoin,patchCacheLeave,@@ -51,8 +51,10 @@ import type {CommunityMachineRemoved,} from "@alook/shared"import { isCommunityEvent, TYPING_INDICATOR_TIMEOUT_MS, TYPING_INDICATOR_THROTTLE_MS } from "@alook/shared"-import type { Msg, Attachment } from "@/components/community/_types"+import type { Msg } from "@/components/community/_types"import { avatarInitial } from "@/lib/community/avatar"+import { projectCommunityMessageCreate } from "@/lib/community/message-wire"+import type { CanonicalMessage } from "@/lib/community/message-stream"import type { MachinesResponse } from "@/hooks/community/use-machines"import type { ServersResponse, ServerDetail } from "@/hooks/community/use-servers"import { patchChannelUnread } from "@/hooks/community/server-detail-cache"@@ -143,7 +145,7 @@ type PageCache = InfiniteData<MessagesPage>*/export function insertMessageIntoCache(cache: PageCache | undefined,- msg: CommunityMessageCreate["message"],+ msg: CanonicalMessage,): PageCache | undefined {if (!cache) return cacheif (cache.pages.length === 0) return cache@@ -161,7 +163,7 @@ export function insertMessageIntoCache(// `srv:`-fallback nonces are never echoed (WS step-1), so this only ever// matches the sender's own client-provided nonce; others' messages (no// matching optimistic row) fall through to the normal append below.- const nonce = "clientNonce" in msg ? (msg as { clientNonce?: string }).clientNonce : undefined+ const nonce = msg.clientNonceif (nonce) {for (let pi = 0; pi < cache.pages.length; pi++) {const p = cache.pages[pi]@@ -169,52 +171,19 @@ export function insertMessageIntoCache(if (mi !== -1) {const pages = cache.pages.slice()const msgs = p.messages.slice()- // Rename in place (temp id → server id), clear `failed`, keep position.- msgs[mi] = { ...msgs[mi], id: msg.id, failed: false }+ msgs[mi] = {+ ...msgs[mi],+ id: msg.id,+ seq: msg.seq,+ ...(msg.clientNonce ? { clientNonce: msg.clientNonce } : {}),+ failed: false,+ }pages[pi] = { ...p, messages: msgs }return { ...cache, pages }}}}- const attachments: Attachment[] | undefined = msg.attachments?.map((a) => {- const isImage = isInlineAttachmentContentType(a.contentType)- return isImage- ? { kind: "image", name: a.filename, url: a.url, width: a.width ?? undefined, height: a.height ?? undefined }- : {- kind: "file",- name: a.filename,- url: a.url,- size: a.size ? `${Math.round(a.size / 1024)} KB` : "",- }- })- const isSystem = "type" in msg && (msg as { type?: string }).type === "system"- const systemKind = "systemKind" in msg ? (msg as { systemKind?: "thread" }).systemKind : undefined- const authorName = "authorName" in msg ? msg.authorName : "Unknown"- const authorAvatar = "authorAvatar" in msg ? msg.authorAvatar : undefined- const authorId = "authorId" in msg ? msg.authorId : undefined- const replyTo = "replyTo" in msg ? (msg.replyTo as Msg["replyTo"]) : undefined- const approval = "approval" in msg ? (msg.approval as Msg["approval"]) : undefined- const rendered: Msg = {- id: msg.id,- authorName,- authorAvatar: authorAvatar || avatarInitial(authorName ?? ""),- content: msg.content,- createdAt: msg.createdAt,- ...(approval ? { approval } : {}),- // Non-system branch is explicit ("chat", not omitted) — `Msg.type` is a- // required, exhaustive discriminator (#12); a DM message (the other- // union member here) never carries `type` at all, and also renders as- // an ordinary chat row, so it gets the same explicit fallback.- ...(isSystem ? { type: "system" as const, ...(systemKind ? { systemKind } : {}) } : { type: "chat" as const }),- ...(replyTo ? { replyTo } : {}),- ...(attachments?.length ? { attachments } : {}),- // #3: preserve authorId so `useChannelWatermark` can skip self-authored- // messages when advancing the read pointer (avoids a redundant PUT — the- // server-side write path already sets the sender's `lastReadMessageId`- // on send, see #1).- ...(authorId ? { authorId } : {}),- }- const merged = [...first.messages, rendered]+ const merged = [...first.messages, msg]// Drop from the head (oldest end of this page) once the live tail grows// past the cap — keeps the newest messages, sheds the oldest.const trimmed = merged.length > MAX_LIVE_PAGE_MESSAGES@@ -304,42 +273,59 @@ function applyReactionToCache(touched = truereturn {...p,- messages: p.messages.map((m) => {- if (m.id !== event.messageId) return m- const reactions = (m.reactions ?? []).map((r) => ({ ...r, userIds: [...(r.userIds ?? [])] }))- if (event.type === "community:reaction.add") {- const existing = reactions.find((r) => r.emoji === event.emoji)- if (existing) {- if (!existing.userIds.includes(event.userId)) {- existing.userIds.push(event.userId)- existing.count = existing.userIds.length- }- if (viewerUserId && event.userId === viewerUserId) existing.me = true- } else {- reactions.push({- emoji: event.emoji,- count: 1,- me: !!viewerUserId && event.userId === viewerUserId,- userIds: [event.userId],- })- }- } else {- const idx = reactions.findIndex((r) => r.emoji === event.emoji)- if (idx !== -1) {- reactions[idx].userIds = reactions[idx].userIds.filter((id) => id !== event.userId)- reactions[idx].count = reactions[idx].userIds.length- if (viewerUserId && event.userId === viewerUserId) reactions[idx].me = false- if (reactions[idx].count <= 0) reactions.splice(idx, 1)- }- }- return { ...m, reactions }- }),+ messages: p.messages.map((message) =>+ message.id === event.messageId+ ? applyReactionToMessage(message, event, viewerUserId)+ : message),}})if (!touched) return cachereturn { ...cache, pages }}+function applyReactionToMessage(+ message: Msg,+ event: CommunityReactionAdd | CommunityReactionRemove,+ viewerUserId: string | null,+): Msg {+ const reactions = (message.reactions ?? []).map((reaction) => ({+ ...reaction,+ userIds: [...(reaction.userIds ?? [])],+ }))+ if (event.type === "community:reaction.add") {+ const existing = reactions.find((reaction) => reaction.emoji === event.emoji)+ if (existing) {+ if (!existing.userIds.includes(event.userId)) existing.userIds.push(event.userId)+ existing.count = existing.userIds.length+ if (viewerUserId && event.userId === viewerUserId) existing.me = true+ } else {+ reactions.push({+ emoji: event.emoji,+ count: 1,+ me: !!viewerUserId && event.userId === viewerUserId,+ userIds: [event.userId],+ })+ }+ } else {+ const index = reactions.findIndex((reaction) => reaction.emoji === event.emoji)+ if (index !== -1) {+ reactions[index].userIds = reactions[index].userIds.filter((id) => id !== event.userId)+ reactions[index].count = reactions[index].userIds.length+ if (viewerUserId && event.userId === viewerUserId) reactions[index].me = false+ if (reactions[index].count <= 0) reactions.splice(index, 1)+ }+ }+ return { ...message, reactions }+}++function findCachedMessage(cache: PageCache | undefined, messageId: string): Msg | undefined {+ for (const page of cache?.pages ?? []) {+ const message = page.messages.find((row) => row.id === messageId)+ if (message) return message+ }+ return undefined+}+// ── Public hook ────────────────────────────────────────────────────────────/**@@ -466,6 +452,16 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {switch (event.type) {// ── Message create ──────────────────────────────────────────────case "community:message.create": {+ const projected = projectCommunityMessageCreate(event.message)+ if (event.channelId === sub.channelId) {+ const serverId = useCommunityStore.getState().currentServerId+ if (serverId) {+ useMessageStreamStore.getState().dispatch(+ { kind: "channel", id: event.channelId, serverId },+ { type: "wsMessage", message: projected },+ )+ }+ }if (wsStore.hasSeenMessage(event.message.id)) returnwsStore.markSeenMessage(event.message.id)// Sending a message is an implicit typing.stop for its author —@@ -482,13 +478,9 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {if (event.channelId === sub.dmConversationId) {queryClient.setQueryData<PageCache>(communityKeys.dmMessages(event.channelId),- (c) => insertMessageIntoCache(c, event.message),+ (c) => insertMessageIntoCache(c, projected),)} else if (event.channelId === sub.channelId) {- queryClient.setQueryData<PageCache>(- communityKeys.channelMessages(event.channelId),- (c) => insertMessageIntoCache(c, event.message),- )// A thread/forum_post enrolls its sender + mentioned users as// participants server-side on send. That set IS its Members panel,// so refetch it live — otherwise a new speaker/mention only appears@@ -601,6 +593,25 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {communityKeys.dmMessages(event.channelId),(c) => applyReactionToCache(c, event, viewerId),)+ if (event.channelId === sub.channelId) {+ const serverId = useCommunityStore.getState().currentServerId+ if (serverId) {+ const scope = { kind: "channel" as const, id: event.channelId, serverId }+ const fallback = [...getMessageOverlay(scope).liveById.values()]+ .find((message) => message.id === event.messageId)+ if (fallback) {+ const cached = findCachedMessage(+ queryClient.getQueryData<PageCache>(communityKeys.channelMessages(event.channelId)),+ event.messageId,+ )+ const source = cached?.seq !== undefined ? cached as CanonicalMessage : fallback+ useMessageStreamStore.getState().dispatch(scope, {+ type: "liveRefreshed",+ message: applyReactionToMessage(source, event, viewerId) as CanonicalMessage,+ })+ }+ }+ }if (matchesFocus(event)) cbs.onReaction?.(event)return}@@ -684,6 +695,26 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {return { ...cache, pages }},)+ const serverId = useCommunityStore.getState().currentServerId+ if (serverId) {+ const scope = { kind: "channel" as const, id: event.parentChannelId, serverId }+ const fallback = [...getMessageOverlay(scope).liveById.values()]+ .find((message) => message.id === event.parentMessageId)+ if (fallback) {+ const cached = findCachedMessage(+ queryClient.getQueryData<PageCache>(communityKeys.channelMessages(event.parentChannelId)),+ event.parentMessageId,+ )+ const source = cached?.seq !== undefined ? cached as CanonicalMessage : fallback+ useMessageStreamStore.getState().dispatch(scope, {+ type: "liveRefreshed",+ message: {+ ...source,+ thread: { id: event.channel.id, name: event.channel.name, messageCount: 0 },+ },+ })+ }+ }}} else {// child_update — sync counts/name on the parent message's thread@@ -720,6 +751,30 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {return { ...cache, pages }},)+ const serverId = useCommunityStore.getState().currentServerId+ if (serverId) {+ const scope = { kind: "channel" as const, id: event.parentChannelId, serverId }+ const fallback = [...getMessageOverlay(scope).liveById.values()]+ .find((message) => message.thread?.id === event.channelId)+ if (fallback?.thread) {+ const cached = findCachedMessage(+ queryClient.getQueryData<PageCache>(communityKeys.channelMessages(event.parentChannelId)),+ fallback.id,+ )+ const source = cached?.seq !== undefined ? cached as CanonicalMessage : fallback+ useMessageStreamStore.getState().dispatch(scope, {+ type: "liveRefreshed",+ message: {+ ...source,+ thread: {+ ...(source.thread ?? fallback.thread),+ ...(changes.name !== undefined ? { name: changes.name } : {}),+ ...(changes.messageCount !== undefined ? { messageCount: changes.messageCount } : {}),+ },+ },+ })+ }+ }}}cbs.onChildChannel?.(event)@@ -777,6 +832,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {// the store pointers now dangle — reset them so the UI drops back// to a safe default instead of rendering a ghost server/channel.const store = useCommunityStore.getState()+ useMessageStreamStore.getState().removeServer(event.serverId)if (store.currentServerId === event.serverId) {store.setCurrentServerId(null)store.setCurrentChannelId(null)@@ -801,6 +857,11 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {// subsequent same-id revive (rare, but the server can reuse ids)// would surface stale rows.if (event.type === "community:channel.delete") {+ useMessageStreamStore.getState().removeScope({+ kind: "channel",+ id: event.channelId,+ serverId: event.serverId,+ })queryClient.removeQueries({queryKey: communityKeys.channelMessages(event.channelId),})@@ -847,6 +908,11 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {event.type === "community:channel.member_remove" &&event.userId === viewerUserIdRef.current) {+ useMessageStreamStore.getState().removeScope({+ kind: "channel",+ id: event.channelId,+ serverId: event.serverId,+ })queryClient.removeQueries({ queryKey: communityKeys.channelMessages(event.channelId) })queryClient.removeQueries({ queryKey: communityKeys.pins(event.channelId) })queryClient.removeQueries({ queryKey: communityKeys.threads(event.channelId) })@@ -887,6 +953,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {// so the layout's eject effect can detect the drop and route// the user away from the now-forbidden URL.if (event.userId === viewerUserIdRef.current) {+ useMessageStreamStore.getState().removeServer(event.serverId)// Rail LIST only (the layout's eject effect reads it to route the// kicked viewer away). `exact` so a kick doesn't cascade-refetch// every server's nested detail subtree.@@ -915,6 +982,17 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {(cache) => patchAuthorNameInCache(cache, userId, newName),)}+ const streamState = useMessageStreamStore.getState()+ for (const entry of streamState.entries.values()) {+ if (entry.scope.kind !== "channel" || entry.scope.serverId !== event.serverId) continue+ for (const message of entry.state.liveById.values()) {+ if (message.authorId !== userId) continue+ useMessageStreamStore.getState().dispatch(entry.scope, {+ type: "liveRefreshed",+ message: { ...message, authorName: newName },+ })+ }+ }}}// Membership just changed → the invite dialog's "friends who aren'tdiff --git a/src/web/src/hooks/community/use-messages.anchor-revalidation.test.ts b/src/web/src/hooks/community/use-messages.anchor-revalidation.test.tsindex e0426cb66..0b805c922 100644--- a/src/web/src/hooks/community/use-messages.anchor-revalidation.test.ts+++ b/src/web/src/hooks/community/use-messages.anchor-revalidation.test.ts@@ -19,7 +19,7 @@ function Capture({ onRender, channelId, lastReadMessageId }: {channelId: string | nulllastReadMessageId?: string | null}) {- const result = useMessages(channelId, { lastReadMessageId })+ const result = useMessages(channelId, { serverId: "s1", lastReadMessageId })onRender(result.messages.map((m) => m.id))return null}@@ -66,8 +66,8 @@ describe("useMessages — Fix 3 anchor re-validation", () => {queryClient.setQueryData(key, {pages: [{messages: [- { id: "m_old_1", createdAt: "2026-06-30T23:59:58.000Z" },- { id: "m_old_2", createdAt: "2026-06-30T23:59:59.000Z" },+ { id: "m_old_1", seq: 1, createdAt: "2026-06-30T23:59:58.000Z" },+ { id: "m_old_2", seq: 2, createdAt: "2026-06-30T23:59:59.000Z" },],hasMoreOlder: false,hasMoreNewer: false,@@ -86,9 +86,9 @@ describe("useMessages — Fix 3 anchor re-validation", () => {apiFetchMock.mockImplementation(() => new Promise((resolve) => setTimeout(() => resolve({messages: [- { id: "m_new_1", createdAt: "2026-07-01T00:00:01.000Z" },- { id: "m_new_anchor", createdAt: "2026-07-01T00:00:02.000Z" },- { id: "m_new_2", createdAt: "2026-07-01T00:00:03.000Z" },+ { id: "m_new_1", seq: 3, createdAt: "2026-07-01T00:00:01.000Z" },+ { id: "m_new_anchor", seq: 4, createdAt: "2026-07-01T00:00:02.000Z" },+ { id: "m_new_2", seq: 5, createdAt: "2026-07-01T00:00:03.000Z" },],hasMoreOlder: true,hasMoreNewer: true,@@ -146,9 +146,9 @@ describe("useMessages — Fix 3 anchor re-validation", () => {// (`pages[0]` = anchor/newest, later pages = progressively older).queryClient.setQueryData(key, {pages: [- { messages: [{ id: "m_anchor_old", createdAt: "2026-07-01T00:00:05.000Z" }], hasMoreOlder: true, hasMoreNewer: false },- { messages: [{ id: "m_older_1", createdAt: "2026-07-01T00:00:03.000Z" }], hasMoreOlder: true, hasMoreNewer: false },- { messages: [{ id: "m_older_2", createdAt: "2026-07-01T00:00:01.000Z" }], hasMoreOlder: false, hasMoreNewer: false },+ { messages: [{ id: "m_anchor_old", seq: 3, createdAt: "2026-07-01T00:00:05.000Z" }], hasMoreOlder: true, hasMoreNewer: false },+ { messages: [{ id: "m_older_1", seq: 2, createdAt: "2026-07-01T00:00:03.000Z" }], hasMoreOlder: true, hasMoreNewer: false },+ { messages: [{ id: "m_older_2", seq: 1, createdAt: "2026-07-01T00:00:01.000Z" }], hasMoreOlder: false, hasMoreNewer: false },],pageParams: [{ mode: "anchor", anchor: "m_anchor_old" },@@ -159,7 +159,7 @@ describe("useMessages — Fix 3 anchor re-validation", () => {apiFetchMock.mockImplementation(() => new Promise((resolve) => setTimeout(() => resolve({- messages: [{ id: "m_new_anchor", createdAt: "2026-07-01T00:00:10.000Z" }],+ messages: [{ id: "m_new_anchor", seq: 4, createdAt: "2026-07-01T00:00:10.000Z" }],hasMoreOlder: true,hasMoreNewer: true,}), 20)),@@ -210,7 +210,7 @@ describe("useMessages — Fix 3 anchor re-validation", () => {const key = communityKeys.channelMessages("ch_2")queryClient.setQueryData(key, {- pages: [{ messages: [{ id: "m_old_1", createdAt: "2026-06-30T00:00:00.000Z" }], hasMoreOlder: false, hasMoreNewer: false }],+ pages: [{ messages: [{ id: "m_old_1", seq: 1, createdAt: "2026-06-30T00:00:00.000Z" }], hasMoreOlder: false, hasMoreNewer: false }],pageParams: [{ mode: "anchor", anchor: "m_old_anchor" }],})// Force `dataUpdatedAt` far in the past — well beyond STALE_HYDRATED_CACHE_MS@@ -225,7 +225,7 @@ describe("useMessages — Fix 3 anchor re-validation", () => {// test above for the same rationale.apiFetchMock.mockImplementation(() => new Promise((resolve) => setTimeout(() => resolve({- messages: [{ id: "m_fresh_anchor", createdAt: "2026-07-01T00:00:00.000Z" }],+ messages: [{ id: "m_fresh_anchor", seq: 2, createdAt: "2026-07-01T00:00:00.000Z" }],hasMoreOlder: true,hasMoreNewer: false,}), 20)),diff --git a/src/web/src/hooks/community/use-messages.loading-state.test.ts b/src/web/src/hooks/community/use-messages.loading-state.test.tsindex f1a368674..065c99219 100644--- a/src/web/src/hooks/community/use-messages.loading-state.test.ts+++ b/src/web/src/hooks/community/use-messages.loading-state.test.ts@@ -4,6 +4,7 @@ import TestRenderer, { act } from "react-test-renderer"import { QueryClient, QueryClientProvider } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"import { useMessages } from "./use-messages"+import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"const apiFetchMock = vi.fn()vi.mock("@/lib/api/client", () => ({@@ -12,6 +13,7 @@ vi.mock("@/lib/api/client", () => ({beforeEach(() => {apiFetchMock.mockReset()+ useMessageStreamStore.getState().resetAll()})// Regression test for the "brand-new channel flashes a frame of fake-empty@@ -23,17 +25,17 @@ beforeEach(() => {// (this repo's existing pattern — see message-list.mount-identity.test.ts)// and captures the hook's return value.function Capture({ onResult, channelId, lastReadMessageId }: {- onResult: (r: { isLoading: boolean; messages: unknown[] }) => void+ onResult: (r: { isLoading: boolean; messages: unknown[]; latestSeq: number }) => voidchannelId: string | nulllastReadMessageId?: string | null}) {- const result = useMessages(channelId, { lastReadMessageId })- onResult({ isLoading: result.isLoading, messages: result.messages })+ const result = useMessages(channelId, { serverId: "s1", lastReadMessageId })+ onResult({ isLoading: result.isLoading, messages: result.messages, latestSeq: result.latestSeq })return null}function renderCapture(- onResult: (r: { isLoading: boolean; messages: unknown[] }) => void,+ onResult: (r: { isLoading: boolean; messages: unknown[]; latestSeq: number }) => void,lastReadMessageId: string | null | undefined,seedTail?: { id: string; seq: number }[],) {@@ -60,7 +62,7 @@ function renderCapture(describe("useMessages — isLoading while the anchor snapshot is unresolved", () => {it("reports isLoading: true even though the underlying query is disabled (enabled: false forces isFetching: false)", () => {- let latest: { isLoading: boolean; messages: unknown[] } | undefined+ let latest: { isLoading: boolean; messages: unknown[]; latestSeq: number } | undefined// `lastReadMessageId: undefined` — the anchor snapshot resolving case// (see MessagesOpts' doc comment in use-messages.ts): `enabled` is false.renderCapture((r) => { latest = r }, undefined)@@ -72,7 +74,7 @@ describe("useMessages — isLoading while the anchor snapshot is unresolved", ()it("reports isLoading: true while the now-enabled query's first fetch is in flight", () => {apiFetchMock.mockImplementation(() => new Promise(() => {})) // never resolves- let latest: { isLoading: boolean; messages: unknown[] } | undefined+ let latest: { isLoading: boolean; messages: unknown[]; latestSeq: number } | undefined// `lastReadMessageId: null` — anchor resolved (no anchor), query enabled// and genuinely fetching.renderCapture((r) => { latest = r }, null)@@ -83,7 +85,7 @@ describe("useMessages — isLoading while the anchor snapshot is unresolved", ()describe("useMessages — instant channel switch: warm cache paints without waiting on the anchor", () => {it("reports isLoading: false when the anchor is unresolved but the channelMessages cache is already hydrated", () => {- let latest: { isLoading: boolean; messages: unknown[] } | undefined+ let latest: { isLoading: boolean; messages: unknown[]; latestSeq: number } | undefined// Warm switch: anchor snapshot still resolving (`lastReadMessageId:// undefined`, query disabled) BUT the persisted newest-tail is already in// cache. The rows must paint now — no skeleton, no network wait.@@ -99,7 +101,7 @@ describe("useMessages — instant channel switch: warm cache paints without wait})it("still reports isLoading: true (skeleton) on a cold cache with the anchor unresolved", () => {- let latest: { isLoading: boolean; messages: unknown[] } | undefined+ let latest: { isLoading: boolean; messages: unknown[]; latestSeq: number } | undefined// Cold channel: anchor unresolved AND no hydrated tail → skeleton, exactly// as before, so the decoupling never turns a genuine cold load into a flash// of empty content.@@ -108,4 +110,50 @@ describe("useMessages — instant channel switch: warm cache paints without waitexpect(latest?.isLoading).toBe(true)expect(latest?.messages).toEqual([])})++ it("keeps latestSeq owned by the base snapshot when the overlay has a higher seq", () => {+ useMessageStreamStore.getState().dispatch(+ { kind: "channel", id: "ch_new", serverId: "s1" },+ {+ type: "wsMessage",+ message: {+ id: "m_live",+ seq: 99,+ type: "chat",+ authorId: "u1",+ authorName: "Alice",+ content: "live",+ createdAt: "2026-08-06T00:00:00.000Z",+ },+ },+ )+ let latest: { isLoading: boolean; messages: unknown[]; latestSeq: number } | undefined+ renderCapture((result) => { latest = result }, undefined, [{ id: "m_base", seq: 5 }])++ expect(latest?.messages).toHaveLength(2)+ expect(latest?.latestSeq).toBe(5)+ })++ it("keeps the real server scope through baseChanged so removeServer clears it", () => {+ const messageScope = { kind: "channel" as const, id: "ch_new", serverId: "s1" }+ useMessageStreamStore.getState().dispatch(messageScope, {+ type: "wsMessage",+ message: {+ id: "m_live",+ seq: 9,+ type: "chat",+ authorId: "u1",+ authorName: "Alice",+ content: "live",+ createdAt: "2026-08-06T00:00:00.000Z",+ },+ })++ renderCapture(() => {}, undefined, [{ id: "m_base", seq: 5 }])+ expect([...useMessageStreamStore.getState().entries.values()][0]?.scope.serverId).toBe("s1")++ act(() => useMessageStreamStore.getState().removeServer("s1"))+ expect(useMessageStreamStore.getState().entries.size).toBe(0)+ expect(getMessageOverlay(messageScope).liveById.size).toBe(0)+ })})diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.tsindex e65afe9c1..62684589f 100644--- a/src/web/src/hooks/community/use-messages.ts+++ b/src/web/src/hooks/community/use-messages.ts@@ -11,6 +11,12 @@ import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import type { Msg } from "@/components/community/_types"import { flushPendingReads } from "@/hooks/community/mutations/messages"+import {+ materializeMessageStream,+ type CanonicalMessage,+ type MessageScope,+} from "@/lib/community/message-stream"+import { useMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"/*** Fetches paginated messages for a community channel.@@ -180,6 +186,10 @@ type MessagesOpts = {trustSeededInitialPage?: boolean}+type ChannelMessagesOpts = MessagesOpts & {+ serverId: string+}+// Shared pagination + reducer used by both channel and DM hooks. Kept inline// as a hook because both variants need the same TanStack setup — factoring// out a plain function would leak query internals; a hook stays clean.@@ -538,15 +548,39 @@ function useMessagesInner(*/export function useMessages(channelId: string | null,- opts?: MessagesOpts,+ opts: ChannelMessagesOpts,): MessagesReturn {const queryKey = communityKeys.channelMessages(channelId ?? "__none__")- return useMessagesInner(+ const base = useMessagesInner(channelId,queryKey,channelMessagesQueryFn(channelId ?? "__none__"),opts,)+ const scope = useMemo<MessageScope>(() => ({+ kind: "channel",+ id: channelId ?? "__none__",+ serverId: opts.serverId,+ }), [channelId, opts.serverId])+ const overlay = useMessageOverlay(scope)+ const canonicalBase = useMemo(+ () => base.messages.filter(+ (message): message is CanonicalMessage => typeof message.seq === "number",+ ),+ [base.messages],+ )+ useEffect(() => {+ if (!channelId) return+ useMessageStreamStore.getState().dispatch(scope, {+ type: "baseChanged",+ messages: canonicalBase,+ })+ }, [canonicalBase, channelId, scope])+ const messages = useMemo(+ () => materializeMessageStream(canonicalBase, overlay),+ [canonicalBase, overlay],+ )+ return { ...base, messages }}/**diff --git a/src/web/src/hooks/use-file-attachments.test.ts b/src/web/src/hooks/use-file-attachments.test.tsindex 571644f4c..bac547293 100644--- a/src/web/src/hooks/use-file-attachments.test.ts+++ b/src/web/src/hooks/use-file-attachments.test.ts@@ -76,4 +76,22 @@ describe("useFileAttachments — PendingFile width/height", () => {expect(pending[0].width).toBeUndefined()expect(pending[0].height).toBeUndefined()})++ it("transfers accepted files without revoking their preview URLs", async () => {+ generateThumbnailMock.mockResolvedValue({ blob: { size: 1 } as Blob, width: 640, height: 480 })+ const hook = await renderCapture()+ const file = new File([new Uint8Array([1])], "photo.png", { type: "image/png" })+ await hook.addFiles([file])++ let transferred: PendingFile[] = []+ await act(async () => {+ transferred = hook.current.transferPendingFiles()+ })++ expect(transferred).toEqual([+ expect.objectContaining({ file, thumbnailUrl: "blob:fake", width: 640, height: 480 }),+ ])+ expect(hook.current.pendingFiles).toEqual([])+ expect(URL.revokeObjectURL).not.toHaveBeenCalled()+ })})diff --git a/src/web/src/hooks/use-file-attachments.ts b/src/web/src/hooks/use-file-attachments.tsindex 0efb61237..c003597e9 100644--- a/src/web/src/hooks/use-file-attachments.ts+++ b/src/web/src/hooks/use-file-attachments.ts@@ -47,6 +47,13 @@ export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {});}, []);+ const transferPendingFiles = useCallback(() => {+ const transferred = pendingFilesRef.current;+ pendingFilesRef.current = [];+ _setPendingFiles([]);+ return transferred;+ }, []);+useEffect(() => {return () => revokeThumbnailUrls(pendingFilesRef.current);}, []);@@ -141,6 +148,7 @@ export function useFileAttachments(opts: UseFileAttachmentsOptions = {}) {return {pendingFiles,setPendingFiles,+ transferPendingFiles,fileInputRef,addPendingFiles,handleFileSelect,diff --git a/src/web/src/lib/community/message-payload.test.ts b/src/web/src/lib/community/message-payload.test.tsindex 8a4f9578a..e3bdb6aa6 100644--- a/src/web/src/lib/community/message-payload.test.ts+++ b/src/web/src/lib/community/message-payload.test.ts@@ -11,6 +11,7 @@ const baseRow: MessageRow = {mentionType: null,replyToId: null,embeds: null,+ seq: 42,createdAt: "2026-07-03T12:00:00.000Z",}@@ -108,6 +109,10 @@ describe("mapMessageForApi", () => {})describe("mapMessageForWs", () => {+ it("preserves the required server seq", () => {+ expect(mapMessageForWs(baseRow, emptyWsCtx).seq).toBe(42)+ })+it("maps ordinary rows to type: \"chat\" (was \"default\" before #12's exhaustive discriminator)", () => {expect(mapMessageForWs({ ...baseRow, type: null }, emptyWsCtx).type).toBe("chat")expect(mapMessageForWs({ ...baseRow, type: "default" }, emptyWsCtx).type).toBe("chat")diff --git a/src/web/src/lib/community/message-stream.test.ts b/src/web/src/lib/community/message-stream.test.tsnew file mode 100644index 000000000..1d768a3c6--- /dev/null+++ b/src/web/src/lib/community/message-stream.test.ts@@ -0,0 +1,411 @@+import { describe, expect, it } from "vitest"+import type { Msg } from "@/components/community/_types"+import {+ MAX_LIVE_MESSAGE_DELTAS,+ emptyMessageOverlay,+ getOutboxRetryPayload,+ materializeMessageStream,+ reduceMessageOverlay,+ type CanonicalMessage,+ type MessageOverlayEvent,+ type MessageOverlayState,+ type NewOutboxIntent,+} from "./message-stream"++function message(id: string, seq: number, extra: Partial<Msg> = {}): CanonicalMessage {+ return {+ id,+ seq,+ type: "chat",+ authorId: "u1",+ authorName: "Gus",+ content: id,+ createdAt: `2026-08-06T00:00:${String(seq).padStart(2, "0")}.000Z`,+ ...extra,+ }+}++function localMessage(content: string): NewOutboxIntent["message"] {+ return {+ type: "chat",+ authorId: "u1",+ authorName: "Gus",+ content,+ createdAt: "2026-08-06T00:00:00.000Z",+ }+}++function intent(+ nonce: string,+ localOrdinal: number,+ extra: Partial<NewOutboxIntent> = {},+): NewOutboxIntent {+ const tempId = `temp_${nonce}`+ return {+ nonce,+ tempId,+ localOrdinal,+ message: localMessage(nonce),+ localUploads: [],+ ...extra,+ }+}++function apply(state: MessageOverlayState, event: MessageOverlayEvent) {+ return reduceMessageOverlay(state, event)+}++function ids(base: CanonicalMessage[], state: MessageOverlayState): string[] {+ return materializeMessageStream(base, state).map((row) => row.id)+}++function submit(state: MessageOverlayState, value = intent("n1", 1)) {+ return apply(state, { type: "submit", intent: value }).state+}++function canonical(+ id = "m1",+ seq = 11,+ nonce = "n1",+ extra: Partial<Msg> = {},+): CanonicalMessage {+ return message(id, seq, { clientNonce: nonce, authorName: "Canonical", ...extra })+}++describe("message stream monotonic visibility", () => {+ it("keeps a pending row when an anchor snapshot started first and resolves without it", () => {+ let state = submit(emptyMessageOverlay())+ state = apply(state, {+ type: "baseChanged",+ messages: [message("anchor", 5)],+ latestSeq: 99,+ }).state++ expect(ids([message("anchor", 5)], state)).toEqual(["anchor", "temp_n1"])+ })++ it.each([+ ["ack → WS → stale snapshot", [+ { type: "postAck", nonce: "n1", serverMessageId: "m1", serverSeq: 11 },+ { type: "wsMessage", message: canonical() },+ { type: "baseChanged", messages: [message("older", 5)], latestSeq: 10 },+ ]],+ ["WS → ack → stale snapshot", [+ { type: "wsMessage", message: canonical() },+ { type: "postAck", nonce: "n1", serverMessageId: "m1", serverSeq: 11 },+ { type: "baseChanged", messages: [message("older", 5)], latestSeq: 10 },+ ]],+ ["stale snapshot → ack → delayed WS", [+ { type: "baseChanged", messages: [message("older", 5)], latestSeq: 10 },+ { type: "postAck", nonce: "n1", serverMessageId: "m1", serverSeq: 11 },+ { type: "wsMessage", message: canonical() },+ ]],+ ["WS → stale snapshot → ack", [+ { type: "wsMessage", message: canonical() },+ { type: "baseChanged", messages: [message("older", 5)], latestSeq: 10 },+ { type: "postAck", nonce: "n1", serverMessageId: "m1", serverSeq: 11 },+ ]],+ ] satisfies Array<[string, MessageOverlayEvent[]]>) (+ "%s always materializes exactly one canonical row",+ (_label, events) => {+ let state = submit(emptyMessageOverlay())+ for (const event of events) state = apply(state, event).state+ expect(ids([message("older", 5)], state)).toEqual(["older", "m1"])+ expect(materializeMessageStream([message("older", 5)], state)[1].authorName).toBe("Canonical")+ },+ )++ it("replaying a first-seen WS event after a snapshot overwrite attempt is idempotent", () => {+ const row = canonical()+ let state = apply(emptyMessageOverlay(), { type: "wsMessage", message: row }).state+ state = apply(state, { type: "baseChanged", messages: [], latestSeq: 12 }).state+ state = apply(state, { type: "wsMessage", message: row }).state++ expect(ids([], state)).toEqual(["m1"])+ expect(state.liveById.size).toBe(1)+ })++ it("materializes an outbox row synchronously when base/pages are absent", () => {+ const state = submit(emptyMessageOverlay())+ expect(ids([], state)).toEqual(["temp_n1"])+ })++ it("initializes submit state without accepting caller-supplied server identity", () => {+ const injected = {+ ...intent("n1", 1),+ status: "acked",+ uploadStatus: "settled",+ serverMessageId: "injected",+ serverSeq: 999,+ message: { ...localMessage("n1"), id: "injected", seq: 999, clientNonce: "other" },+ } as unknown as NewOutboxIntent++ const state = submit(emptyMessageOverlay(), injected)+ const stored = state.outboxByNonce.get("n1")+ expect(stored).toEqual(expect.objectContaining({+ status: "pending",+ uploadStatus: "none",+ }))+ expect(stored?.serverMessageId).toBeUndefined()+ expect(stored?.serverSeq).toBeUndefined()+ const materialized = materializeMessageStream([], state)[0]+ expect(materialized).toEqual(expect.objectContaining({+ id: "temp_n1",+ clientNonce: "n1",+ }))+ expect(materialized.seq).toBeUndefined()+ })++ it("retains mentionType in the retry payload", () => {+ let state = submit(emptyMessageOverlay(), intent("n1", 1, { mentionType: "everyone" }))+ expect(getOutboxRetryPayload(state, "n1")?.mentionType).toBe("everyone")+ state = apply(state, { type: "postFail", nonce: "n1" }).state+ state = apply(state, { type: "retry", nonce: "n1" }).state+ expect(getOutboxRetryPayload(state, "n1")?.mentionType).toBe("everyone")+ })++ it("failed retry reuses one nonce and converges through deduped ack + WS", () => {+ let state = submit(emptyMessageOverlay())+ state = apply(state, { type: "postFail", nonce: "n1" }).state+ expect(materializeMessageStream([], state)[0].failed).toBe(true)++ state = apply(state, { type: "retry", nonce: "n1" }).state+ expect(state.outboxByNonce.size).toBe(1)+ expect(state.outboxByNonce.get("n1")?.status).toBe("pending")++ state = apply(state, {+ type: "postAck",+ nonce: "n1",+ serverMessageId: "m1",+ serverSeq: 11,+ }).state+ state = apply(state, { type: "wsMessage", message: canonical() }).state+ expect(ids([], state)).toEqual(["m1"])+ expect(state.outboxByNonce.size).toBe(0)+ })++ it("does not treat latestSeq as proof that an anchor window contains the row", () => {+ let state = submit(emptyMessageOverlay())+ state = apply(state, {+ type: "postAck",+ nonce: "n1",+ serverMessageId: "m1",+ serverSeq: 11,+ }).state+ state = apply(state, {+ type: "baseChanged",+ messages: [message("anchor", 50)],+ latestSeq: 100,+ }).state++ expect(ids([message("anchor", 50)], state)).toEqual(["m1", "anchor"])+ expect(state.outboxByNonce.has("n1")).toBe(true)+ })++ it("settles an exact base hit into a bounded fallback that survives later window omission", () => {+ let state = submit(emptyMessageOverlay())+ state = apply(state, {+ type: "postAck",+ nonce: "n1",+ serverMessageId: "m1",+ serverSeq: 11,+ }).state+ state = apply(state, {+ type: "baseChanged",+ messages: [canonical("m1", 11, "n1", { content: "from base" })],+ }).state++ expect(state.outboxByNonce.size).toBe(0)+ expect(state.liveById.get("m1")?.content).toBe("from base")+ expect(ids([canonical()], state)).toEqual(["m1"])++ state = apply(state, {+ type: "baseChanged",+ messages: [message("older", 5)],+ latestSeq: 50,+ }).state+ expect(ids([message("older", 5)], state)).toEqual(["older", "m1"])+ expect(materializeMessageStream([message("older", 5)], state)[1].content).toBe("from base")+ })++ it("keeps a realtime row as fallback after base contains it and later omits it", () => {+ let state = apply(emptyMessageOverlay(), {+ type: "wsMessage",+ message: canonical("m1", 11, "n1", { content: "from ws" }),+ }).state+ state = apply(state, {+ type: "baseChanged",+ messages: [canonical("m1", 11, "n1", { content: "from base" })],+ }).state+ state = apply(state, { type: "baseChanged", messages: [], latestSeq: 50 }).state++ expect(materializeMessageStream([], state)).toEqual([+ expect.objectContaining({ id: "m1", seq: 11, content: "from base" }),+ ])+ })++ it("uses complete WS presentation for a same-nonce optimistic intent", () => {+ let state = submit(emptyMessageOverlay())+ state = apply(state, {+ type: "wsMessage",+ message: canonical("m1", 11, "n1", { content: "enriched", authorAvatar: "avatar" }),+ }).state++ expect(materializeMessageStream([], state)).toEqual([+ expect.objectContaining({ id: "m1", content: "enriched", authorAvatar: "avatar", failed: false }),+ ])+ })++ it("sorts canonical rows by seq and pending rows by explicit localOrdinal", () => {+ let state = submit(emptyMessageOverlay(), intent("n2", 2))+ state = submit(state, intent("n1", 1))++ expect(ids([message("m20", 20), message("m10", 10)], state)).toEqual([+ "m10", "m20", "temp_n1", "temp_n2",+ ])++ state = apply(state, {+ type: "postAck",+ nonce: "n2",+ serverMessageId: "m15",+ serverSeq: 15,+ }).state+ expect(ids([message("m20", 20), message("m10", 10)], state)).toEqual([+ "m10", "m15", "m20", "temp_n1",+ ])+ })++ it("refreshes only an existing live fallback and never absorbs outbox", () => {+ const initial = emptyMessageOverlay()+ const absent = apply(initial, {+ type: "liveRefreshed",+ message: canonical("m1", 11, "n1", { content: "ignored" }),+ })+ expect(absent.state).toBe(initial)+ expect(absent.state.liveById.size).toBe(0)++ let state = submit(emptyMessageOverlay())+ state = apply(state, { type: "wsMessage", message: canonical() }).state+ state = submit(state, intent("n2", 2))+ state = apply(state, {+ type: "liveRefreshed",+ message: canonical("m1", 11, "n1", { content: "refreshed" }),+ }).state+ expect(state.liveById.get("m1")?.content).toBe("refreshed")+ expect(state.outboxByNonce.has("n2")).toBe(true)+ })++ it("bounds canonical live deltas to the existing 500-row live-tail scale", () => {+ let state = emptyMessageOverlay()+ for (let seq = 1; seq <= MAX_LIVE_MESSAGE_DELTAS + 2; seq++) {+ state = apply(state, { type: "wsMessage", message: message(`m${seq}`, seq) }).state+ }++ expect(state.liveById.size).toBe(MAX_LIVE_MESSAGE_DELTAS)+ expect(state.liveById.has("m1")).toBe(false)+ expect(state.liveById.has("m2")).toBe(false)+ expect(state.liveById.has(`m${MAX_LIVE_MESSAGE_DELTAS + 2}`)).toBe(true)+ })+})++describe("attachment ownership effects", () => {+ const retryFile = { name: "notes.txt", size: 1024, type: "text/plain" } as File+ const attachedIntent = () => intent("files", 1, {+ localUploads: [+ { file: retryFile, previewObjectUrl: "blob:a", width: 640, height: 480 },+ { file: { name: "photo.png", size: 2048, type: "image/png" } as File, previewObjectUrl: "blob:b", width: 320, height: 240 },+ { file: { name: "copy.txt", size: 1024, type: "text/plain" } as File, previewObjectUrl: "blob:a" },+ ],+ })++ it("initializes lifecycle and retains immutable upload inputs through retry", () => {+ let state = submit(emptyMessageOverlay(), attachedIntent())+ expect(state.outboxByNonce.get("files")).toEqual(expect.objectContaining({+ status: "pending",+ uploadStatus: "pending",+ }))++ state = apply(state, { type: "uploadFailed", nonce: "files" }).state+ state = apply(state, { type: "retry", nonce: "files" }).state++ const retried = state.outboxByNonce.get("files")+ expect(retried?.localUploads[0].file).toBe(retryFile)+ expect(retried?.localUploads[0].previewObjectUrl).toBe("blob:a")+ expect(retried?.localUploads[0].width).toBe(640)+ 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" },+ ])+ })++ it("keeps one attachment intent across upload + ack and revokes URLs once on WS reconciliation", () => {+ let state = submit(emptyMessageOverlay(), attachedIntent())+ state = apply(state, {+ type: "uploadSettled",+ nonce: "files",+ attachments: [{ kind: "file", name: "notes.txt", url: "/media/notes", size: "1 KB" }],+ }).state+ state = apply(state, {+ type: "postAck",+ nonce: "files",+ serverMessageId: "mf",+ serverSeq: 20,+ }).state++ const first = apply(state, { type: "wsMessage", message: canonical("mf", 20, "files") })+ expect(first.effects).toEqual([+ { type: "revokeObjectUrl", url: "blob:a" },+ { type: "revokeObjectUrl", url: "blob:b" },+ ])+ expect(first.state.outboxByNonce.size).toBe(0)++ const replay = apply(first.state, { type: "wsMessage", message: canonical("mf", 20, "files") })+ expect(replay.effects).toEqual([])+ expect(ids([], replay.state)).toEqual(["mf"])+ })++ it("retains upload failure across retry and only dismisses explicitly", () => {+ let state = submit(emptyMessageOverlay(), attachedIntent())+ state = apply(state, { type: "uploadFailed", nonce: "files" }).state+ expect(state.outboxByNonce.get("files")).toEqual(expect.objectContaining({+ status: "failed",+ uploadStatus: "failed",+ }))++ state = apply(state, { type: "retry", nonce: "files" }).state+ expect(state.outboxByNonce.get("files")).toEqual(expect.objectContaining({+ status: "pending",+ uploadStatus: "pending",+ }))++ state = apply(state, { type: "uploadFailed", nonce: "files" }).state+ const dismissed = apply(state, { type: "dismissFailed", nonce: "files" })+ expect(dismissed.effects).toHaveLength(2)+ expect(dismissed.state.outboxByNonce.size).toBe(0)+ })++ it("emits cleanup exactly once for canonical base absorption and clear", () => {+ let state = submit(emptyMessageOverlay(), attachedIntent())+ state = apply(state, {+ type: "postAck",+ nonce: "files",+ serverMessageId: "mf",+ serverSeq: 20,+ }).state+ const absorbed = apply(state, { type: "baseChanged", messages: [canonical("mf", 20, "files")] })+ expect(absorbed.effects).toHaveLength(2)++ const absorbedAgain = apply(absorbed.state, { type: "baseChanged", messages: [canonical("mf", 20, "files")] })+ expect(absorbedAgain.effects).toEqual([])++ const withSecond = submit(absorbedAgain.state, intent("second", 2, {+ localUploads: [{ file: { name: "second.txt" } as File, previewObjectUrl: "blob:c" }],+ }))+ const cleared = apply(withSecond, { type: "clear" })+ expect(cleared.effects).toEqual([{ type: "revokeObjectUrl", url: "blob:c" }])+ expect(cleared.state).toEqual(emptyMessageOverlay())+ })+})diff --git a/src/web/src/lib/community/message-stream.ts b/src/web/src/lib/community/message-stream.tsnew file mode 100644index 000000000..7ad33f2d5--- /dev/null+++ b/src/web/src/lib/community/message-stream.ts@@ -0,0 +1,408 @@+import type { Msg } from "@/components/community/_types"+import type { MentionType } from "@alook/shared"+import { isInlineAttachmentContentType } from "@/lib/community/attachment-content-type"++export const MAX_LIVE_MESSAGE_DELTAS = 500++export type CanonicalMessage = Msg & { seq: number }++export type MessageScope =+ | { kind: "channel"; id: string; serverId: string }+ | { kind: "dm"; id: string }++type LocalUploadInput = Readonly<{+ file: File+ previewObjectUrl?: string+ width?: number+ height?: number+}>++type LocalOutboxMessage = Omit<Msg, "id" | "seq" | "clientNonce" | "failed">++export type NewOutboxIntent = Readonly<{+ nonce: string+ tempId: string+ localOrdinal: number+ message: LocalOutboxMessage+ localUploads: readonly LocalUploadInput[]+ mentionType?: MentionType+}>++export type OutboxRetryPayload = Readonly<{+ nonce: string+ message: Msg+ localUploads: NewOutboxIntent["localUploads"]+ uploadStatus: "none" | "pending" | "settled" | "failed"+ mentionType?: MentionType+}>++type OutboxIntent = Omit<NewOutboxIntent, "message"> & {+ message: Msg+ status: "pending" | "failed" | "acked"+ uploadStatus: "none" | "pending" | "settled" | "failed"+ serverMessageId?: string+ serverSeq?: number+}++export type MessageOverlayState = {+ liveById: ReadonlyMap<string, CanonicalMessage>+ outboxByNonce: ReadonlyMap<string, OutboxIntent>+}++type MessageOverlayEffect = {+ type: "revokeObjectUrl"+ url: string+}++export type MessageOverlayTransition = {+ state: MessageOverlayState+ effects: MessageOverlayEffect[]+}++export type MessageOverlayEvent =+ | { type: "submit"; intent: NewOutboxIntent }+ | { type: "uploadSettled"; nonce: string; attachments: Msg["attachments"] }+ | { type: "uploadFailed"; nonce: string }+ | { type: "postAck"; nonce: string; serverMessageId: string; serverSeq: number }+ | { type: "postFail"; nonce: string }+ | { type: "retry"; nonce: string }+ | { type: "wsMessage"; message: CanonicalMessage }+ | { type: "liveRefreshed"; message: CanonicalMessage }+ | { type: "baseChanged"; messages: CanonicalMessage[]; latestSeq?: number }+ | { type: "dismissFailed"; nonce: string }+ | { type: "clear" }++type MaterializedEntry = {+ message: Msg+ localOrdinal?: number+}++export function emptyMessageOverlay(): MessageOverlayState {+ return {+ liveById: new Map(),+ outboxByNonce: new Map(),+ }+}++function unchanged(state: MessageOverlayState): MessageOverlayTransition {+ return { state, effects: [] }+}++function revokeEffects(intent: OutboxIntent): MessageOverlayEffect[] {+ const urls = intent.localUploads.flatMap(({ previewObjectUrl }) =>+ previewObjectUrl === undefined ? [] : [previewObjectUrl])+ return [...new Set(urls)].map((url) => ({+ type: "revokeObjectUrl" as const,+ url,+ }))+}++function updateIntent(+ state: MessageOverlayState,+ nonce: string,+ update: (intent: OutboxIntent) => OutboxIntent,+): MessageOverlayTransition {+ const current = state.outboxByNonce.get(nonce)+ if (!current) return unchanged(state)+ const outboxByNonce = new Map(state.outboxByNonce)+ outboxByNonce.set(nonce, update(current))+ return { state: { ...state, outboxByNonce }, effects: [] }+}++function canonicalDeltaOrder(a: CanonicalMessage, b: CanonicalMessage): number {+ return a.seq - b.seq+}++function trimLiveDeltas(liveById: Map<string, CanonicalMessage>): void {+ const overflow = liveById.size - MAX_LIVE_MESSAGE_DELTAS+ if (overflow <= 0) return+ const oldest = [...liveById.values()].sort(canonicalDeltaOrder).slice(0, overflow)+ for (const message of oldest) liveById.delete(message.id)+}++function upsertLiveCanonical(+ liveById: Map<string, CanonicalMessage>,+ message: CanonicalMessage,+): void {+ const nonce = message.clientNonce+ if (nonce) {+ for (const [id, current] of liveById) {+ if (id !== message.id && current.clientNonce === nonce) liveById.delete(id)+ }+ }+ liveById.set(message.id, { ...message, failed: false })+}++function materializeIntent(intent: OutboxIntent): Msg {+ return {+ ...intent.message,+ id: intent.serverMessageId ?? intent.tempId,+ ...(intent.serverSeq !== undefined ? { seq: intent.serverSeq } : {}),+ clientNonce: intent.nonce,+ failed: intent.status === "failed" || intent.uploadStatus === "failed",+ }+}++function localUploadAttachments(+ uploads: readonly LocalUploadInput[],+): Msg["attachments"] {+ const attachments: NonNullable<Msg["attachments"]> = []+ for (const upload of uploads) {+ if (!upload.previewObjectUrl) continue+ if (isInlineAttachmentContentType(upload.file.type)) {+ attachments.push({+ kind: "image",+ name: upload.file.name,+ url: upload.previewObjectUrl,+ width: upload.width,+ height: upload.height,+ })+ continue+ }+ attachments.push({+ kind: "file",+ name: upload.file.name,+ url: upload.previewObjectUrl,+ size: upload.file.size ? `${Math.round(upload.file.size / 1024)} KB` : "",+ })+ }+ return attachments.length > 0 ? attachments : undefined+}++function upsertMaterialized(+ byId: Map<string, MaterializedEntry>,+ idByNonce: Map<string, string>,+ entry: MaterializedEntry,+): void {+ const { message } = entry+ const nonce = message.clientNonce+ if (nonce) {+ const priorId = idByNonce.get(nonce)+ if (priorId && priorId !== message.id) byId.delete(priorId)+ idByNonce.set(nonce, message.id)+ }+ byId.set(message.id, entry)+}++function materializedOrder(a: MaterializedEntry, b: MaterializedEntry): number {+ const aSeq = a.message.seq+ const bSeq = b.message.seq+ if (aSeq !== undefined && bSeq !== undefined && aSeq !== bSeq) return aSeq - bSeq+ if (aSeq !== undefined && bSeq === undefined) return -1+ if (aSeq === undefined && bSeq !== undefined) return 1++ const aOrdinal = a.localOrdinal+ const bOrdinal = b.localOrdinal+ if (aOrdinal !== undefined && bOrdinal !== undefined && aOrdinal !== bOrdinal) {+ return aOrdinal - bOrdinal+ }+ if (aOrdinal !== undefined && bOrdinal === undefined) return 1+ if (aOrdinal === undefined && bOrdinal !== undefined) return -1++ return 0+}++export function materializeMessageStream(+ baseMessages: CanonicalMessage[],+ overlay: MessageOverlayState,+): Msg[] {+ const byId = new Map<string, MaterializedEntry>()+ const idByNonce = new Map<string, string>()++ // Later sources replace earlier presentation for the same id/nonce:+ // optimistic outbox < complete WS row < complete base row.+ for (const intent of overlay.outboxByNonce.values()) {+ upsertMaterialized(byId, idByNonce, {+ message: materializeIntent(intent),+ localOrdinal: intent.status === "acked" ? undefined : intent.localOrdinal,+ })+ }+ for (const message of overlay.liveById.values()) {+ upsertMaterialized(byId, idByNonce, { message })+ }+ for (const message of baseMessages) {+ upsertMaterialized(byId, idByNonce, { message })+ }++ return [...byId.values()].sort(materializedOrder).map((entry) => entry.message)+}++export function getOutboxRetryPayload(+ state: MessageOverlayState,+ nonce: string,+): OutboxRetryPayload | undefined {+ const intent = state.outboxByNonce.get(nonce)+ if (!intent) return undefined+ return {+ nonce,+ message: intent.message,+ localUploads: intent.localUploads,+ uploadStatus: intent.uploadStatus,+ mentionType: intent.mentionType,+ }+}++export function reduceMessageOverlay(+ state: MessageOverlayState,+ event: MessageOverlayEvent,+): MessageOverlayTransition {+ switch (event.type) {+ case "submit": {+ if (state.outboxByNonce.has(event.intent.nonce)) return unchanged(state)+ const outboxByNonce = new Map(state.outboxByNonce)+ const optimisticAttachments = localUploadAttachments(event.intent.localUploads)+ const message: Msg = {+ ...event.intent.message,+ id: event.intent.tempId,+ clientNonce: event.intent.nonce,+ failed: false,+ ...(optimisticAttachments !== undefined+ ? { attachments: optimisticAttachments }+ : {}),+ }+ delete message.seq+ outboxByNonce.set(event.intent.nonce, {+ nonce: event.intent.nonce,+ tempId: event.intent.tempId,+ localOrdinal: event.intent.localOrdinal,+ localUploads: event.intent.localUploads.map((upload) => ({ ...upload })),+ status: "pending",+ uploadStatus: event.intent.localUploads.length === 0 ? "none" : "pending",+ message,+ mentionType: event.intent.mentionType,+ })+ return { state: { ...state, outboxByNonce }, effects: [] }+ }++ case "uploadSettled":+ return updateIntent(state, event.nonce, (intent) => ({+ ...intent,+ uploadStatus: "settled",+ message: { ...intent.message, attachments: event.attachments },+ }))++ case "uploadFailed":+ return updateIntent(state, event.nonce, (intent) => ({+ ...intent,+ status: "failed",+ uploadStatus: "failed",+ message: { ...intent.message, failed: true },+ }))++ case "postAck":+ return updateIntent(state, event.nonce, (intent) => ({+ ...intent,+ status: "acked",+ serverMessageId: event.serverMessageId,+ serverSeq: event.serverSeq,+ message: { ...intent.message, failed: false },+ }))++ case "postFail":+ return updateIntent(state, event.nonce, (intent) => ({+ ...intent,+ status: "failed",+ message: { ...intent.message, failed: true },+ }))++ case "retry":+ return updateIntent(state, event.nonce, (intent) => ({+ ...intent,+ status: "pending",+ uploadStatus: intent.uploadStatus === "failed" ? "pending" : intent.uploadStatus,+ message: { ...intent.message, failed: false },+ }))++ case "wsMessage": {+ const liveById = new Map(state.liveById)+ const outboxByNonce = new Map(state.outboxByNonce)+ const effects: MessageOverlayEffect[] = []+ const nonce = event.message.clientNonce++ for (const [intentNonce, intent] of outboxByNonce) {+ const matchesNonce = nonce !== undefined && intentNonce === nonce+ const matchesServerId = intent.serverMessageId !== undefined+ && intent.serverMessageId === event.message.id+ if (!matchesNonce && !matchesServerId) continue+ outboxByNonce.delete(intentNonce)+ effects.push(...revokeEffects(intent))+ }++ // The complete enriched WS row is canonical presentation.+ upsertLiveCanonical(liveById, event.message)+ trimLiveDeltas(liveById)+ return { state: { liveById, outboxByNonce }, effects }+ }++ case "liveRefreshed": {+ let existingId: string | undefined+ if (state.liveById.has(event.message.id)) {+ existingId = event.message.id+ } else if (event.message.clientNonce) {+ for (const [id, message] of state.liveById) {+ if (message.clientNonce === event.message.clientNonce) {+ existingId = id+ break+ }+ }+ }+ if (!existingId) return unchanged(state)+ const liveById = new Map(state.liveById)+ if (existingId !== event.message.id) liveById.delete(existingId)+ upsertLiveCanonical(liveById, event.message)+ trimLiveDeltas(liveById)+ return { state: { ...state, liveById }, effects: [] }+ }++ case "baseChanged": {+ const baseById = new Map(event.messages.map((message) => [message.id, message]))+ const baseByNonce = new Map(+ event.messages.flatMap((message) =>+ message.clientNonce ? [[message.clientNonce, message] as const] : []),+ )+ const liveById = new Map(state.liveById)+ const outboxByNonce = new Map(state.outboxByNonce)+ const effects: MessageOverlayEffect[] = []++ for (const message of state.liveById.values()) {+ const canonical = baseById.get(message.id)+ ?? (message.clientNonce ? baseByNonce.get(message.clientNonce) : undefined)+ if (canonical) upsertLiveCanonical(liveById, canonical)+ }+ for (const [nonce, intent] of outboxByNonce) {+ const canonical = intent.serverMessageId+ ? baseById.get(intent.serverMessageId) ?? baseByNonce.get(nonce)+ : baseByNonce.get(nonce)+ if (!canonical) continue+ outboxByNonce.delete(nonce)+ upsertLiveCanonical(liveById, canonical)+ effects.push(...revokeEffects(intent))+ }+ trimLiveDeltas(liveById)++ // `latestSeq` is deliberately not a deletion predicate: an anchor page+ // can report a high stream seq while omitting this visible tail row. A+ // base hit refreshes the bounded fallback but does not delete it, because+ // a later window may omit the row again.+ return { state: { liveById, outboxByNonce }, effects }+ }++ case "dismissFailed": {+ const intent = state.outboxByNonce.get(event.nonce)+ if (!intent || (intent.status !== "failed" && intent.uploadStatus !== "failed")) {+ return unchanged(state)+ }+ const outboxByNonce = new Map(state.outboxByNonce)+ outboxByNonce.delete(event.nonce)+ return {+ state: { ...state, outboxByNonce },+ effects: revokeEffects(intent),+ }+ }++ case "clear": {+ const effects = [...state.outboxByNonce.values()].flatMap(revokeEffects)+ return { state: emptyMessageOverlay(), effects }+ }+ }+}diff --git a/src/web/src/lib/community/message-wire.test.ts b/src/web/src/lib/community/message-wire.test.tsnew file mode 100644index 000000000..61fc1a414--- /dev/null+++ b/src/web/src/lib/community/message-wire.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it } from "vitest"+import type { CommunityMessageCreate } from "@alook/shared"+import { projectCommunityMessageCreate } from "./message-wire"++function wire(+ overrides: Partial<CommunityMessageCreate["message"]> = {},+): CommunityMessageCreate["message"] {+ return {+ id: "m1",+ seq: 42,+ authorId: "u1",+ authorName: "Gus",+ content: "hello",+ type: "chat",+ createdAt: "2026-08-06T00:00:00.000Z",+ ...overrides,+ }+}++describe("projectCommunityMessageCreate", () => {+ it("preserves canonical identity and presentation fields", () => {+ const replyTo = { id: "m0", authorName: "A", text: "prior" }+ const approval = {+ friendshipId: "f1",+ status: "pending" as const,+ waitingOn: "you" as const,+ otherProfile: { id: "u2", name: "Other", discriminator: "0002", image: null },+ botProfile: { id: "b1", name: "Bot", discriminator: "0003", image: null },+ }+ const projected = projectCommunityMessageCreate(wire({+ clientNonce: "nonce",+ type: "system",+ systemKind: "thread",+ authorAvatar: "avatar",+ replyTo,+ approval,+ }))+ expect(projected).toEqual(expect.objectContaining({+ id: "m1",+ seq: 42,+ clientNonce: "nonce",+ type: "system",+ systemKind: "thread",+ authorId: "u1",+ authorName: "Gus",+ authorAvatar: "avatar",+ content: "hello",+ createdAt: "2026-08-06T00:00:00.000Z",+ replyTo,+ approval,+ }))+ })++ it("narrows embeds and maps safe image/file attachments", () => {+ const projected = projectCommunityMessageCreate(wire({+ embeds: [{ title: "Card", url: "https://example.com" }, { url: "missing-title" }, null],+ attachments: [+ { id: "a1", filename: "photo.png", url: "/photo", contentType: "image/png", size: 2048, width: 640, height: 480 },+ { id: "a2", filename: "doc.pdf", url: "/doc", contentType: "application/pdf", size: 2048 },+ { id: "a3", filename: "unsafe.svg", url: "/unsafe", contentType: "image/svg+xml", size: 1024 },+ ],+ }))+ 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" },+ ])+ })+})diff --git a/src/web/src/lib/community/message-wire.ts b/src/web/src/lib/community/message-wire.tsnew file mode 100644index 000000000..04f6e017e--- /dev/null+++ b/src/web/src/lib/community/message-wire.ts@@ -0,0 +1,119 @@+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 type { CanonicalMessage } from "@/lib/community/message-stream"++type UiEmbed = NonNullable<Msg["embeds"]>[number]++function stringValue(value: unknown): string | undefined {+ return typeof value === "string" ? value : undefined+}++function numberValue(value: unknown): number | undefined {+ return typeof value === "number" && Number.isFinite(value) ? value : undefined+}++function objectValue(value: unknown): Record<string, unknown> | undefined {+ return typeof value === "object" && value !== null && !Array.isArray(value)+ ? value as Record<string, unknown>+ : undefined+}++function projectEmbed(value: unknown): UiEmbed | undefined {+ const input = objectValue(value)+ const title = stringValue(input?.title)+ if (!input || title === undefined) return undefined+ const imageInput = objectValue(input.image)+ const imageUrl = stringValue(imageInput?.url)+ const thumbnailInput = objectValue(input.thumbnail)+ const thumbnailUrl = stringValue(thumbnailInput?.url)+ const footerInput = objectValue(input.footer)+ const footerText = stringValue(footerInput?.text)+ const authorInput = objectValue(input.author)+ const authorName = stringValue(authorInput?.name)+ const fields = Array.isArray(input.fields)+ ? input.fields.flatMap((field) => {+ const row = objectValue(field)+ const name = stringValue(row?.name)+ const fieldValue = stringValue(row?.value)+ if (name === undefined || fieldValue === undefined) return []+ return [{+ name,+ value: fieldValue,+ ...(typeof row?.inline === "boolean" ? { inline: row.inline } : {}),+ }]+ })+ : undefined+ return {+ title,+ ...(stringValue(input.provider) !== undefined ? { provider: stringValue(input.provider) } : {}),+ ...(stringValue(input.url) !== undefined ? { url: stringValue(input.url) } : {}),+ ...(stringValue(input.desc) !== undefined ? { desc: stringValue(input.desc) } : {}),+ ...(stringValue(input.color) !== undefined ? { color: stringValue(input.color) } : {}),+ ...(imageUrl !== undefined ? {+ image: {+ url: imageUrl,+ ...(numberValue(imageInput?.width) !== undefined ? { width: numberValue(imageInput?.width) } : {}),+ ...(numberValue(imageInput?.height) !== undefined ? { height: numberValue(imageInput?.height) } : {}),+ },+ } : {}),+ ...(thumbnailUrl !== undefined ? { thumbnail: { url: thumbnailUrl } } : {}),+ ...(fields?.length ? { fields } : {}),+ ...(footerText !== undefined ? {+ footer: {+ text: footerText,+ ...(stringValue(footerInput?.iconUrl) !== undefined ? { iconUrl: stringValue(footerInput?.iconUrl) } : {}),+ },+ } : {}),+ ...(authorName !== undefined ? {+ author: {+ name: authorName,+ ...(stringValue(authorInput?.url) !== undefined ? { url: stringValue(authorInput?.url) } : {}),+ ...(stringValue(authorInput?.iconUrl) !== undefined ? { iconUrl: stringValue(authorInput?.iconUrl) } : {}),+ },+ } : {}),+ }+}++export function projectCommunityMessageCreate(+ message: CommunityMessageCreate["message"],+): CanonicalMessage {+ const attachments = message.attachments?.map((attachment) => {+ if (isInlineAttachmentContentType(attachment.contentType)) {+ return {+ kind: "image" as const,+ name: attachment.filename,+ url: attachment.url,+ width: attachment.width ?? undefined,+ height: attachment.height ?? undefined,+ }+ }+ return {+ kind: "file" as const,+ name: attachment.filename,+ url: attachment.url,+ size: attachment.size ? `${Math.round(attachment.size / 1024)} KB` : "",+ }+ })+ const embeds = message.embeds?.flatMap((embed) => {+ const projected = projectEmbed(embed)+ return projected ? [projected] : []+ })+ return {+ id: message.id,+ seq: message.seq,+ type: message.type,+ ...(message.systemKind ? { systemKind: message.systemKind } : {}),+ authorId: message.authorId,+ authorName: message.authorName,+ authorAvatar: message.authorAvatar || avatarInitial(message.authorName),+ content: message.content,+ createdAt: message.createdAt,+ ...(message.clientNonce ? { clientNonce: message.clientNonce } : {}),+ ...(message.replyTo ? { replyTo: message.replyTo } : {}),+ ...(message.approval ? { approval: message.approval } : {}),+ ...(embeds?.length ? { embeds } : {}),+ ...(attachments?.length ? { attachments } : {}),+ }+}diff --git a/src/web/src/stores/community/message-stream.test.ts b/src/web/src/stores/community/message-stream.test.tsnew file mode 100644index 000000000..549f2f1c9--- /dev/null+++ b/src/web/src/stores/community/message-stream.test.ts@@ -0,0 +1,64 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import type { MessageScope } from "@/lib/community/message-stream"+import { getMessageOverlay, useMessageStreamStore } from "./message-stream"++const channel = (id: string, serverId = "s1"): MessageScope => ({ kind: "channel", id, serverId })++function acceptedIntent(nonce: string, previewObjectUrl?: string) {+ return {+ nonce,+ tempId: `temp_${nonce}`,+ message: { type: "chat" as const, content: nonce },+ localUploads: previewObjectUrl+ ? [{ file: { name: `${nonce}.txt` } as File, previewObjectUrl }]+ : [],+ }+}++describe("message stream store", () => {+ beforeEach(() => {+ vi.stubGlobal("URL", { revokeObjectURL: vi.fn() })+ useMessageStreamStore.getState().resetAll()+ })++ it("allocates ordinals atomically and rejects a duplicate nonce", () => {+ const store = useMessageStreamStore.getState()+ expect(store.accept(channel("c1"), acceptedIntent("n1"))).toBe(true)+ expect(useMessageStreamStore.getState().accept(channel("c1"), acceptedIntent("n1"))).toBe(false)+ expect(useMessageStreamStore.getState().accept(channel("c1"), acceptedIntent("n2"))).toBe(true)+ expect([...getMessageOverlay(channel("c1")).outboxByNonce.values()].map((intent) => intent.localOrdinal)).toEqual([1, 2])+ })++ it("cleans one scope, every server scope, and all scopes with one revoke per owned URL", () => {+ const store = useMessageStreamStore.getState()+ store.accept(channel("c1"), acceptedIntent("n1", "blob:1"))+ store.accept(channel("c2"), acceptedIntent("n2", "blob:2"))+ store.accept(channel("c3", "s2"), acceptedIntent("n3", "blob:3"))+ store.removeScope(channel("c1"))+ expect(URL.revokeObjectURL).toHaveBeenCalledWith("blob:1")+ expect(getMessageOverlay(channel("c2")).outboxByNonce.size).toBe(1)+ useMessageStreamStore.getState().removeServer("s1")+ expect(URL.revokeObjectURL).toHaveBeenCalledWith("blob:2")+ expect(getMessageOverlay(channel("c3", "s2")).outboxByNonce.size).toBe(1)+ useMessageStreamStore.getState().resetAll()+ expect(URL.revokeObjectURL).toHaveBeenCalledWith("blob:3")+ expect(URL.revokeObjectURL).toHaveBeenCalledTimes(3)+ })++ it("dismisses one failed attachment row by nonce and revokes its owned preview once", () => {+ const store = useMessageStreamStore.getState()+ const messageScope = channel("c1")+ store.accept(messageScope, acceptedIntent("failed", "blob:failed"))+ store.dispatch(messageScope, {+ type: "postFail",+ nonce: "failed",+ })++ expect(getMessageOverlay(messageScope).outboxByNonce.has("failed")).toBe(true)+ store.dispatch(messageScope, { type: "dismissFailed", nonce: "failed" })++ expect(getMessageOverlay(messageScope).outboxByNonce.has("failed")).toBe(false)+ expect(URL.revokeObjectURL).toHaveBeenCalledWith("blob:failed")+ expect(URL.revokeObjectURL).toHaveBeenCalledTimes(1)+ })+})diff --git a/src/web/src/stores/community/message-stream.ts b/src/web/src/stores/community/message-stream.tsnew file mode 100644index 000000000..0208096de--- /dev/null+++ b/src/web/src/stores/community/message-stream.ts@@ -0,0 +1,119 @@+"use client"++import { create } from "zustand"+import {+ emptyMessageOverlay,+ getOutboxRetryPayload,+ reduceMessageOverlay,+ type MessageOverlayEvent,+ type MessageOverlayState,+ type MessageScope,+ type NewOutboxIntent,+ type OutboxRetryPayload,+} from "@/lib/community/message-stream"++type ScopeEntry = { scope: MessageScope; state: MessageOverlayState }++type MessageStreamStoreState = {+ entries: ReadonlyMap<string, ScopeEntry>+ nextOrdinal: number+ accept: (scope: MessageScope, intent: Omit<NewOutboxIntent, "localOrdinal">) => boolean+ dispatch: (scope: MessageScope, event: MessageOverlayEvent) => void+ getRetryPayload: (scope: MessageScope, nonce: string) => OutboxRetryPayload | undefined+ removeScope: (scope: MessageScope) => void+ removeServer: (serverId: string) => void+ resetAll: () => void+}++const EMPTY_OVERLAY = emptyMessageOverlay()++function messageScopeKey(scope: Pick<MessageScope, "kind" | "id">): string {+ return `${scope.kind}:${scope.id}`+}++function executeEffects(effects: ReturnType<typeof reduceMessageOverlay>["effects"]): void {+ for (const effect of effects) URL.revokeObjectURL(effect.url)+}++export const useMessageStreamStore = create<MessageStreamStoreState>((set, get) => ({+ entries: new Map(),+ nextOrdinal: 1,++ accept: (scope, intent) => {+ const key = messageScopeKey(scope)+ const current = get()+ const overlay = current.entries.get(key)?.state ?? EMPTY_OVERLAY+ if (overlay.outboxByNonce.has(intent.nonce)) return false+ const transition = reduceMessageOverlay(overlay, {+ type: "submit",+ intent: { ...intent, localOrdinal: current.nextOrdinal },+ })+ const entries = new Map(current.entries)+ entries.set(key, { scope, state: transition.state })+ set({ entries, nextOrdinal: current.nextOrdinal + 1 })+ executeEffects(transition.effects)+ return true+ },++ dispatch: (scope, event) => {+ const key = messageScopeKey(scope)+ const current = get()+ const overlay = current.entries.get(key)?.state ?? EMPTY_OVERLAY+ const transition = reduceMessageOverlay(overlay, event)+ if (transition.state !== overlay) {+ const entries = new Map(current.entries)+ entries.set(key, { scope, state: transition.state })+ set({ entries })+ }+ executeEffects(transition.effects)+ },++ getRetryPayload: (scope, nonce) => {+ const entry = get().entries.get(messageScopeKey(scope))+ return entry ? getOutboxRetryPayload(entry.state, nonce) : undefined+ },++ removeScope: (scope) => {+ const key = messageScopeKey(scope)+ const current = get()+ const entry = current.entries.get(key)+ if (!entry) return+ const transition = reduceMessageOverlay(entry.state, { type: "clear" })+ const entries = new Map(current.entries)+ entries.delete(key)+ set({ entries })+ executeEffects(transition.effects)+ },++ removeServer: (serverId) => {+ const current = get()+ const entries = new Map(current.entries)+ const effects: ReturnType<typeof reduceMessageOverlay>["effects"] = []+ let changed = false+ for (const [key, entry] of current.entries) {+ if (entry.scope.kind !== "channel" || entry.scope.serverId !== serverId) continue+ effects.push(...reduceMessageOverlay(entry.state, { type: "clear" }).effects)+ entries.delete(key)+ changed = true+ }+ if (changed) set({ entries })+ executeEffects(effects)+ },++ resetAll: () => {+ const current = get()+ const effects = [...current.entries.values()].flatMap((entry) =>+ reduceMessageOverlay(entry.state, { type: "clear" }).effects)+ set({ entries: new Map(), nextOrdinal: 1 })+ executeEffects(effects)+ },+}))++export function getMessageOverlay(scope: MessageScope): MessageOverlayState {+ return useMessageStreamStore.getState().entries.get(messageScopeKey(scope))?.state ?? EMPTY_OVERLAY+}++export function useMessageOverlay(scope: MessageScope): MessageOverlayState {+ const key = messageScopeKey(scope)+ return useMessageStreamStore((state) => state.entries.get(key)?.state ?? EMPTY_OVERLAY)+}diff --git a/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts b/src/web/src/test/e2e-ui/02-server-channel-message.spec.tsindex 84e0a886a..dc0ceff83 100644--- a/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts+++ b/src/web/src/test/e2e-ui/02-server-channel-message.spec.ts@@ -1,50 +1,176 @@import { test, expect } from "./_fixtures/community-fixture"import { tid } from "./_fixtures/testids"-import { createServer, sendMessage, expectMessageVisible } from "./_fixtures/actions"+import { composerEditable, createServer, sendMessage, expectMessageVisible } from "./_fixtures/actions"-// Journey 2 — the core path: create a server, send messages, and exercise the-// message-level edge + regression cases inline. Serial: each step builds on-// the server created in the first test.-test.describe.serial("server → channel → message", () => {- let serverId: string+test("server → channel → message", async ({ asUser }) => {+ test.setTimeout(120_000)+ const { page } = await asUser("alice")+ await page.goto("/c")+ await page.waitForURL(/\/c/, { timeout: 20_000, waitUntil: "commit" })+ await createServer(page, `E2E Server ${Date.now()}`)+ const channelUrl = page.url()+ expect(channelUrl).toMatch(/\/c\/channels\/[^/]+\/[^/]+/)- test("create a server from the rail", async ({ asUser }) => {- const { page } = await asUser("alice")- await page.goto("/c")- await page.waitForURL(/\/c/, { timeout: 20_000 , waitUntil: "commit" })- serverId = await createServer(page, `E2E Server ${Date.now()}`)- expect(serverId).toBeTruthy()+ const firstBody = `hello world ${Date.now()}`+ const firstResponsePromise = page.waitForResponse((response) => {+ const pathname = new URL(response.url()).pathname+ return response.request().method() === "POST"+ && /^\/api\/community\/channels\/[^/]+\/messages$/.test(pathname)})+ await sendMessage(page, firstBody)+ const firstResponse = await firstResponsePromise+ expect(firstResponse.status()).toBe(201)+ const firstPayload = await firstResponse.json() as { message: { id: string; seq: number } }+ expect(firstPayload.message.seq).toBeGreaterThan(0)+ await expectMessageVisible(page, firstBody)+ await expect(page.getByTestId(tid.message(firstPayload.message.id))).toHaveCount(1)+ await expect(page.getByTestId(tid.composerInput)).toHaveText("")- test("send a message; it appears and the composer clears", async ({ asUser }) => {- const { page } = await asUser("alice")- await page.goto(`/c/channels/${serverId}`)- await page.waitForURL(/\/c\/channels\/[^/]+\/[^/]+/, { timeout: 20_000 , waitUntil: "commit" })+ let sends = 0+ page.on("request", (request) => {+ const pathname = new URL(request.url()).pathname+ if (request.method() === "POST" && /^\/api\/community\/channels\/[^/]+\/messages$/.test(pathname)) sends+++ })- const body = `hello world ${Date.now()}`- await sendMessage(page, body)- await expectMessageVisible(page, body)+ const editable = composerEditable(page)+ const imeBody = `ime probe ${Date.now()}`+ await editable.click()+ await editable.pressSequentially(imeBody)+ await editable.evaluate((element) => {+ element.dispatchEvent(new CompositionEvent("compositionstart", { bubbles: true, data: "候" }))+ element.dispatchEvent(new KeyboardEvent("keydown", {+ key: "Enter",+ code: "Enter",+ keyCode: 13,+ which: 13,+ isComposing: true,+ bubbles: true,+ cancelable: true,+ }))+ element.dispatchEvent(new CompositionEvent("compositionend", { bubbles: true, data: "候" }))+ })+ await expect(editable).toContainText(imeBody)+ await expect.poll(() => sends).toBe(0)+ const imeResponsePromise = page.waitForResponse((response) => {+ const pathname = new URL(response.url()).pathname+ return response.request().method() === "POST"+ && /^\/api\/community\/channels\/[^/]+\/messages$/.test(pathname)+ })+ await page.keyboard.press("Enter")+ const imeResponse = await imeResponsePromise+ expect(imeResponse.status()).toBe(201)+ const imePayload = await imeResponse.json() as { message: { id: string; seq: number } }+ expect(imePayload.message.seq).toBeGreaterThan(firstPayload.message.seq)+ await expectMessageVisible(page, imeBody)+ await expect(page.getByTestId(tid.message(imePayload.message.id))).toHaveCount(1)+ await expect.poll(() => sends).toBe(1)- // Regression/edge: composer clears after send.- await expect(page.getByTestId(tid.composerInput)).toHaveText("")+ const draft = `draft probe ${Date.now()}`+ await editable.click()+ await editable.pressSequentially(draft)+ await expect(editable).toContainText(draft)+ await page.goto("/c/me", { waitUntil: "commit" })+ await page.goto(channelUrl, { waitUntil: "commit" })+ await expect(composerEditable(page)).toContainText(draft)+ await expect(page.getByTestId(tid.message(firstPayload.message.id))).toHaveCount(1)+ await expect(page.getByTestId(tid.message(imePayload.message.id))).toHaveCount(1)++ let releaseMessages!: () => void+ const messagesGate = new Promise<void>((resolve) => { releaseMessages = resolve })+ let intercepted = false+ await page.route("**/api/community/channels/*/bootstrap*", async (route) => {+ if (route.request().method() !== "GET") {+ await route.continue()+ return+ }+ intercepted = true+ await messagesGate+ await route.continue()})+ await page.reload({ waitUntil: "commit" })+ await expect.poll(() => intercepted).toBe(true)+ releaseMessages()+ await expect(composerEditable(page)).toContainText(draft)+ await expect(page.getByTestId(tid.message(firstPayload.message.id))).toHaveCount(1)+ await expect(page.getByTestId(tid.message(imePayload.message.id))).toHaveCount(1)+ await page.unroute("**/api/community/channels/*/bootstrap*")- test("empty message does not send; Shift+Enter inserts a newline", async ({ asUser }) => {- const { page } = await asUser("alice")- await page.goto(`/c/channels/${serverId}`)- await page.waitForURL(/\/c\/channels\/[^/]+\/[^/]+/, { timeout: 20_000 , waitUntil: "commit" })+ const restored = composerEditable(page)+ await restored.click()+ await page.keyboard.press("ControlOrMeta+A")+ await page.keyboard.press("Backspace")+ await page.keyboard.press("Enter")+ await expect(restored).toHaveText("")+ await restored.pressSequentially("line one")+ await page.keyboard.press("Shift+Enter")+ await restored.pressSequentially("line two")+ await expect(restored).toContainText("line one")+ await expect(restored).toContainText("line two")- const input = page.getByTestId(tid.composerInput)- await input.click()- // Enter on empty input: nothing sent, input stays empty.- await page.keyboard.press("Enter")- await expect(input).toHaveText("")+ await restored.click()+ await page.keyboard.press("ControlOrMeta+A")+ await page.keyboard.press("Backspace")+ await page.evaluate(() => {+ Object.defineProperty(window.crypto, "randomUUID", {+ configurable: true,+ value: () => "00000000-0000-4000-8000-000000000001",+ })+ })+ let releasePendingSend!: () => void+ const pendingSendGate = new Promise<void>((resolve) => { releasePendingSend = resolve })+ let pendingSendIntercepted = false+ let pendingSendCompleted = false+ await page.route("**/api/community/channels/*/messages", async (route) => {+ if (route.request().method() !== "POST") {+ await route.continue()+ return+ }+ pendingSendIntercepted = true+ await pendingSendGate+ await route.fulfill({+ status: 500,+ contentType: "application/json",+ body: JSON.stringify({ error: "forced staging rejection probe" }),+ })+ pendingSendCompleted = true+ })++ await restored.pressSequentially(`pending ${Date.now()}`)+ await page.keyboard.press("Enter")+ await expect(restored).toHaveText("")+ await expect.poll(() => pendingSendIntercepted).toBe(true)- // Shift+Enter inserts a newline instead of sending.- await page.keyboard.type("line one")- await page.keyboard.press("Shift+Enter")- await page.keyboard.type("line two")- await expect(input).toContainText("line one")- await expect(input).toContainText("line two")+ const rejectedDraft = `rejected draft ${Date.now()}`+ await restored.pressSequentially(rejectedDraft)+ await page.evaluate(() => {+ const revokedUrls: string[] = []+ const revokeObjectUrl = URL.revokeObjectURL.bind(URL)+ Object.defineProperty(window, "__messageStreamRevokedUrls", {+ configurable: true,+ value: revokedUrls,+ })+ URL.revokeObjectURL = (url) => {+ revokedUrls.push(url)+ revokeObjectUrl(url)+ }})+ await page.locator('input[type="file"]').last().setInputFiles({+ name: "rejected.txt",+ mimeType: "text/plain",+ buffer: Buffer.from("keep me"),+ })+ await expect(page.getByText("rejected.txt", { exact: true })).toBeVisible()+ await page.keyboard.press("Enter")+ await expect(restored).toContainText(rejectedDraft)+ await expect(page.getByText("rejected.txt", { exact: true })).toBeVisible()+ await expect.poll(() => page.evaluate(() =>+ (window as unknown as { __messageStreamRevokedUrls: string[] }).__messageStreamRevokedUrls.length,+ )).toBe(1)++ releasePendingSend()+ await expect.poll(() => pendingSendCompleted).toBe(true)+ await page.unroute("**/api/community/channels/*/messages")+ await page.goto("/c/me", { waitUntil: "commit" })+ await page.goto(channelUrl, { waitUntil: "commit" })+ await expect(composerEditable(page)).toContainText(rejectedDraft)})