Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

refactor(community): unify DM message ownership

Gus819f473af293
diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsx
index c031bd0db..b06650a9f 100644
--- a/src/web/src/app/c/me/[dmId]/page.tsx
+++ b/src/web/src/app/c/me/[dmId]/page.tsx
@@ -3,7 +3,6 @@
import { useCallback, useEffect, useMemo, useState } from "react"
import { useParams, useSearchParams } from "next/navigation"
import { toast } from "sonner"
-import { toastApiError } from "@/lib/api/client"
import { useBreakpoint } from "@/hooks/use-mobile"
import { DmHeader, DmHeaderSkeleton } from "@/components/community/dm-header"
import { Avatar } from "@/components/community/avatar"
@@ -30,13 +29,11 @@ import { useDmWatermark } from "@/hooks/community/use-dm-watermark"
import { useEagerDmRead } from "@/hooks/community/use-eager-dm-read"
import { useChannelRefDirectory } from "@/hooks/community/use-channel-ref-directory"
import {
- useSendDmMessage,
useToggleReactionApi,
- useUploadFile,
useToggleMark,
- zipUploadResultsWithDimensions,
- sendNonce,
} from "@/hooks/community/mutations"
+import { useDmMessageSender } from "@/hooks/community/use-dm-message-sender"
+import { useMessageStreamStore } from "@/stores/community/message-stream"
import { useCurrentUser } from "@/contexts/community/current-user"
import {
communityWsSubscribe,
@@ -196,9 +193,8 @@ function DmView() {
const typingUsers = useTypingUsersForScope(`dm:${dmId}`)
const typingNames = useTypingNamesForScope(`dm:${dmId}`)
- const sendDmMessage = useSendDmMessage()
+ const { accept: acceptDmMessage, retry: retryDmMessage } = useDmMessageSender()
const toggleReaction = useToggleReactionApi()
- const uploadFile = useUploadFile()
const toggleMark = useToggleMark()
const goBack = useCallback(() => { uiHandlers.goBackMobile?.() }, [uiHandlers])
@@ -282,24 +278,18 @@ function DmView() {
onMark: (id: string) => toggleMark(dmId, id),
onRetry: (id: string) => {
const m = messages.find((x) => x.id === id)
- if (m?.content) {
- sendDmMessage.mutate(
- {
- dmId,
- content: m.content,
- replyToId: m.replyTo?.id,
- // Reuse the failed row's nonce so the resend dedupes server-side if
- // the original committed (`onMutate` drops the stale row first).
- nonce: m.clientNonce,
- author: {
- id: currentUser.id,
- name: currentUser.name,
- avatar: currentUser.avatar,
- },
- },
- { onSuccess: advanceOnboardingAfterSend },
- )
- }
+ if (!m?.clientNonce) return
+ void retryDmMessage(dmId, m.clientNonce).then((result) => {
+ if (result.ok) advanceOnboardingAfterSend()
+ })
+ },
+ onDismiss: (id: string) => {
+ const m = messages.find((x) => x.id === id)
+ if (!m?.clientNonce) return
+ useMessageStreamStore.getState().dispatch(
+ { kind: "dm", id: dmId },
+ { type: "dismissFailed", nonce: m.clientNonce },
+ )
},
onPreviewImage: (url: string) => {
uiHandlers.previewImage?.(url)
@@ -310,42 +300,31 @@ function DmView() {
a.download = url.split("/").pop() ?? "file"
a.click()
},
- }), [toggleReaction, toggleMark, dmId, currentUser.id, currentUser.name, currentUser.avatar, messages, sendDmMessage, uiHandlers, advanceOnboardingAfterSend])
+ }), [toggleReaction, toggleMark, dmId, currentUser.id, messages, retryDmMessage, uiHandlers, advanceOnboardingAfterSend])
// DM endpoint ignores mentionType. Replies are supported — the backend
// persists replyToId for DMs too.
- const sendDmMsg = async (markdown: string, attachments?: SendAttachment[]) => {
- if (!markdown && !attachments?.length) return
- if (!dmId) return
- let uploadedAttachments: ReturnType<typeof zipUploadResultsWithDimensions> = []
- if (attachments?.length) {
- const results = await Promise.all(
- attachments.map((a) =>
- uploadFile.mutateAsync({ target: { dmId }, file: a.file }).catch((e) => {
- toastApiError(e, "Failed to attach file")
- return null
- }),
- ),
- )
- uploadedAttachments = zipUploadResultsWithDimensions(results, attachments)
- }
- sendDmMessage.mutate(
- {
- dmId,
- content: markdown || "",
- replyToId: replyTo?.id,
- attachments: uploadedAttachments.length > 0 ? uploadedAttachments : undefined,
- nonce: sendNonce(),
- author: {
- id: currentUser.id,
- name: currentUser.name,
- avatar: currentUser.avatar,
- },
+ const acceptDmSend = (markdown: string, attachments?: SendAttachment[]): boolean => {
+ const receipt = acceptDmMessage({
+ dmId,
+ content: markdown,
+ replyTo: replyTo
+ ? { id: replyTo.id, authorName: replyTo.authorName, text: replyTo.text.slice(0, 100) }
+ : undefined,
+ attachments,
+ author: {
+ id: currentUser.id,
+ name: currentUser.name,
+ avatar: currentUser.avatar,
},
- )
- advanceOnboardingAfterSend()
+ })
+ if (!receipt.accepted) return false
+ void receipt.committed.then((result) => {
+ if (result.ok) advanceOnboardingAfterSend()
+ })
communityWsResetTypingThrottle({ channelId: dmId })
setReplyTo(null)
+ return true
}
const handleTyping = () => { communityWsSendTyping({ channelId: dmId }) }
@@ -403,6 +382,7 @@ function DmView() {
onCopy={messageActions.onCopy}
onMark={dmBlocked ? undefined : messageActions.onMark}
onRetry={dmBlocked ? undefined : messageActions.onRetry}
+ onDismiss={dmBlocked ? undefined : messageActions.onDismiss}
onPreviewImage={messageActions.onPreviewImage}
onDownloadFile={messageActions.onDownloadFile}
onOpenProfile={openProfile}
@@ -437,7 +417,7 @@ function DmView() {
) : (
<div data-onboarding-target="dm-composer" data-onboarding-name={dm.name} className="shrink-0">
<Composer
- sendContract="legacy"
+ sendContract="accepted"
channel={dm.name}
context="dm"
// DM context short-circuits `rankMentionItems` to `[]` — no popup,
@@ -445,7 +425,7 @@ function DmView() {
// honest without shimming friends into a member shape.
members={[]}
channelRefCandidates={channelRefCandidates}
- onSend={sendDmMsg}
+ onAcceptSend={acceptDmSend}
onTyping={handleTyping}
replyingTo={replyTo?.authorName}
onCancelReply={() => setReplyTo(null)}
diff --git a/src/web/src/components/community/composer.test.ts b/src/web/src/components/community/composer.test.ts
index 2ba1ea12f..344f148a7 100644
--- a/src/web/src/components/community/composer.test.ts
+++ b/src/web/src/components/community/composer.test.ts
@@ -1,7 +1,33 @@
import { describe, it, expect } from "vitest"
import { clipboardFiles, pendingFilesToSendAttachments, popoverStyle } from "./composer"
+import type { ComposerProps } from "./composer"
import type { PendingFile } from "@/hooks/use-file-attachments"
+describe("Composer send contract", () => {
+ it("keeps accepted chat and deferred forum modes mutually exclusive", () => {
+ const accepted = {
+ channel: "dm",
+ context: "dm" as const,
+ members: [],
+ sendContract: "accepted" as const,
+ mode: "chat" as const,
+ onAcceptSend: () => true,
+ } satisfies ComposerProps
+ expect(accepted.sendContract).toBe("accepted")
+
+ // @ts-expect-error accepted sends must clear/transfer and therefore cannot use the deferred forum mode
+ const invalid: ComposerProps = {
+ channel: "forum",
+ context: "channel",
+ members: [],
+ sendContract: "accepted",
+ mode: "forumPostBody",
+ onAcceptSend: () => true,
+ }
+ expect(invalid.mode).toBe("forumPostBody")
+ })
+})
+
// Minimal DataTransferItemList stand-in: each entry declares its `kind` and the
// File its `getAsFile()` yields (null models the browser returning nothing for
// a "file" item). Indexed access + `.length` is all `clipboardFiles` touches.
diff --git a/src/web/src/components/community/composer.tsx b/src/web/src/components/community/composer.tsx
index 8ebc3b597..324395e17 100644
--- a/src/web/src/components/community/composer.tsx
+++ b/src/web/src/components/community/composer.tsx
@@ -70,8 +70,6 @@ export function clipboardFiles(items: DataTransferItemList | undefined): File[]
return files
}
-type ComposerMode = "chat" | "forumPostBody"
-
export type ComposerHandle = {
focusEditor: () => void
submitNow: () => void
@@ -103,10 +101,6 @@ type ComposerBaseProps = {
// Auto-focus the editor on mount and on channel change. Desktop only —
// callers pass `bp !== "mobile"` to avoid unexpected soft-keyboard pop-up.
autoFocus?: boolean
- // `"chat"` (default) — Enter sends, Shift+Enter newline, `send()` clears.
- // `"forumPostBody"` — inverted: Enter newline, Shift+Enter submits; `send()`
- // does NOT clear so the parent can await mutation success before resetting.
- mode?: ComposerMode
// Placeholder override — used by `forumPostBody` to swap the chat-composer
// relic string. Falls back to the mode-derived default when absent.
placeholder?: string
@@ -129,19 +123,21 @@ type ComposerBaseProps = {
draftKey?: string
}
-type ComposerLegacySend = {
- sendContract?: "legacy"
- onSend?: (markdown: string, attachments?: SendAttachment[], mentionType?: MentionType) => void | Promise<void>
- onAcceptSend?: never
-}
-
type ComposerAcceptedSend = {
sendContract: "accepted"
+ mode?: "chat"
onAcceptSend: (markdown: string, attachments?: SendAttachment[], mentionType?: MentionType) => boolean
- onSend?: never
+ onDeferredSubmit?: never
+}
+
+type ComposerDeferredSend = {
+ sendContract: "deferred"
+ mode: "forumPostBody"
+ onDeferredSubmit: (markdown: string, attachments?: SendAttachment[], mentionType?: MentionType) => void | Promise<void>
+ onAcceptSend?: never
}
-export type ComposerProps = ComposerBaseProps & (ComposerLegacySend | ComposerAcceptedSend)
+export type ComposerProps = ComposerBaseProps & (ComposerAcceptedSend | ComposerDeferredSend)
// Composer — plain-text TipTap editor with a chat-style @-mention popover.
// Users type raw markdown which MessageBody/Streamdown renders on display.
@@ -157,9 +153,9 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
members,
onSearchMembers,
channelRefCandidates = [],
- sendContract = "legacy",
- onSend,
+ sendContract,
onAcceptSend,
+ onDeferredSubmit,
onTyping,
replyingTo,
onCancelReply,
@@ -452,7 +448,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
if (sendContract === "accepted") {
if (!onAcceptSend?.(markdown, attachments, mentionType)) return
} else {
- void onSend?.(markdown, attachments, mentionType)
+ void onDeferredSubmit?.(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.
@@ -460,8 +456,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
if (isForumPostBody) return
editor.commands.clearContent()
if (draftKeyRef.current) clearComposerDraft(draftKeyRef.current)
- if (sendContract === "accepted") transferPendingFiles()
- else setPendingFiles([])
+ transferPendingFiles()
setMentionPopup(EMPTY_MENTION_STATE)
setChannelRefPopup(EMPTY_CHANNEL_REF_STATE)
}
diff --git a/src/web/src/components/community/create-forum-post.test.ts b/src/web/src/components/community/create-forum-post.test.ts
index a81da8470..ba1d16414 100644
--- a/src/web/src/components/community/create-forum-post.test.ts
+++ b/src/web/src/components/community/create-forum-post.test.ts
@@ -12,6 +12,8 @@ vi.mock("./composer", () => ({
createElement("div", {
"data-testid": "mock-composer",
"data-mode": (props.mode as string) ?? "chat",
+ "data-send-contract": props.sendContract as string,
+ "data-has-deferred-submit": String(typeof props.onDeferredSubmit === "function"),
"data-hide-emoji": String(!!props.hideEmoji),
"data-placeholder": (props.placeholder as string) ?? "",
}),
@@ -53,6 +55,8 @@ describe("CreateForumPost — copy + structure", () => {
const html = render()
expect(html).toContain('data-testid="mock-composer"')
expect(html).toContain('data-mode="forumPostBody"')
+ expect(html).toContain('data-send-contract="deferred"')
+ expect(html).toContain('data-has-deferred-submit="true"')
expect(html).toContain('data-hide-emoji="true"')
expect(html).toContain('data-placeholder="What do you want to discuss?"')
})
diff --git a/src/web/src/components/community/create-forum-post.tsx b/src/web/src/components/community/create-forum-post.tsx
index 4a4c098ed..4cc31b215 100644
--- a/src/web/src/components/community/create-forum-post.tsx
+++ b/src/web/src/components/community/create-forum-post.tsx
@@ -158,7 +158,7 @@ export function CreateForumPost({
</button>
</div>
<Composer
- sendContract="legacy"
+ sendContract="deferred"
ref={bodyComposerRef}
mode="forumPostBody"
hideEmoji
@@ -169,7 +169,7 @@ export function CreateForumPost({
onSearchMembers={onSearchMembers}
channelRefCandidates={[]}
placeholder="What do you want to discuss?"
- onSend={handleBodySubmit}
+ onDeferredSubmit={handleBodySubmit}
onDirty={setBodyHasContent}
/>
<div className="mt-2 flex items-center gap-3">
diff --git a/src/web/src/components/community/invite-dialog.tsx b/src/web/src/components/community/invite-dialog.tsx
index 56c361510..47ede8c21 100644
--- a/src/web/src/components/community/invite-dialog.tsx
+++ b/src/web/src/components/community/invite-dialog.tsx
@@ -13,8 +13,8 @@ import { useInvitableFriends } from "@/hooks/community/use-invitable-friends"
import {
useResolveOrCreateInvite,
useCreateOrGetDm,
- useSendDmMessage,
} from "@/hooks/community/mutations"
+import { useDmMessageSender } from "@/hooks/community/use-dm-message-sender"
import { useCurrentUser } from "@/contexts/community/current-user"
import type { Friend } from "./_types"
@@ -52,7 +52,7 @@ export function InviteDialog({
const { friends, isLoading: friendsLoading } = useInvitableFriends(serverId, open)
const resolveOrCreate = useResolveOrCreateInvite(serverId)
const createOrGetDm = useCreateOrGetDm()
- const sendDm = useSendDmMessage()
+ const { accept: acceptDmMessage } = useDmMessageSender()
const [token, setToken] = useState<string | null>(null)
const [resolveError, setResolveError] = useState<string | null>(null)
@@ -108,7 +108,7 @@ export function InviteDialog({
if (!token || !friend.userId) return
try {
const { conversation } = await createOrGetDm.mutateAsync({ userId: friend.userId })
- await sendDm.mutateAsync({
+ const receipt = acceptDmMessage({
dmId: conversation.id,
content: inviteUrl(token),
author: {
@@ -117,6 +117,9 @@ export function InviteDialog({
avatar: currentUser.avatar,
},
})
+ if (!receipt.accepted) throw new Error("Couldn't send invite")
+ const committed = await receipt.committed
+ if (!committed.ok) throw committed.error
setInvitedUserIds((prev) => {
const next = new Set(prev)
next.add(friend.userId!)
diff --git a/src/web/src/components/community/message.render.test.ts b/src/web/src/components/community/message.render.test.ts
index 3414793e2..f9041415c 100644
--- a/src/web/src/components/community/message.render.test.ts
+++ b/src/web/src/components/community/message.render.test.ts
@@ -144,23 +144,46 @@ describe("Message lazy overlays", () => {
expect(tree).not.toContain("reaction-add")
})
- it("keeps failed-message dismiss independent from retry", () => {
+ it.each([
+ ["Retry", (onRetry: ReturnType<typeof vi.fn>, _onDismiss: ReturnType<typeof vi.fn>) => onRetry],
+ ["Dismiss", (_onRetry: ReturnType<typeof vi.fn>, onDismiss: ReturnType<typeof vi.fn>) => onDismiss],
+ ])("keeps a failed row out of lazy overlays so pointerenter → first %s click fires once", (label, expectedCallback) => {
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 }),
+ makeTree({
+ m: baseMsg({ failed: true }),
+ onOpenThread: vi.fn(),
+ onCopy: 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())
+ const row = renderer!.root.find(
+ (node) => typeof node.props.className === "string"
+ && node.props.className.includes("group relative -mx-2"),
+ )
+ expect(row.props.onPointerEnter).toBeUndefined()
+ act(() => row.props.onPointerEnter?.())
+ expect(renderer!.root.findAll(
+ (node) => node.props["data-slot"] === "context-menu-trigger",
+ )).toHaveLength(0)
- expect(onDismiss).toHaveBeenCalledOnce()
- expect(onRetry).not.toHaveBeenCalled()
+ const action = renderer!.root.findAllByType("button").find((button) =>
+ label === "Dismiss"
+ ? button.children.includes("Dismiss")
+ : button.children.some((child) => typeof child === "string" && child.includes("Message failed to send")),
+ )
+ expect(action).toBeDefined()
+ act(() => action!.props.onClick())
+
+ expect(expectedCallback(onRetry, onDismiss)).toHaveBeenCalledOnce()
+ const otherCallback = label === "Dismiss" ? onRetry : onDismiss
+ expect(otherCallback).not.toHaveBeenCalled()
})
})
diff --git a/src/web/src/components/community/message.tsx b/src/web/src/components/community/message.tsx
index 9ae64c80a..0e7a55de0 100644
--- a/src/web/src/components/community/message.tsx
+++ b/src/web/src/components/community/message.tsx
@@ -136,7 +136,7 @@ function MessageImpl({
onShare: canShare ? (onEnterSelect ?? onShareSingle) : undefined,
}
const showMenu = hasMessageMenu(menuHandlers)
- const interactive = !compact && showMenu
+ const interactive = !compact && !m.failed && showMenu
const activate = interactive && !activated ? () => setActivated(true) : undefined
// In select mode (multi-share), the whole row is a big toggle target and gets
// a leading checkbox overlay + a tint when picked. `canShare` rows only —
diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsx
index e4a45f24b..d7c7c62c0 100644
--- a/src/web/src/components/community/shell-frame.tsx
+++ b/src/web/src/components/community/shell-frame.tsx
@@ -58,9 +58,9 @@ import {
useDeleteMention,
useUnmarkMessage,
useUpdateProfile,
- useSendDmMessage,
useUploadUserAvatar,
} from "@/hooks/community/mutations"
+import { useDmMessageSender } from "@/hooks/community/use-dm-message-sender"
/**
* Shared community shell — ServerRail on the left, sidebar column with the
@@ -154,7 +154,7 @@ export function ShellFrame({
const { mutate: updateFolderItemsMutate } = useUpdateFolderItems()
const { mutate: createFolderWithMutate } = useCreateServerFolderWith()
const createOrGetDm = useCreateOrGetDm()
- const sendDmMessage = useSendDmMessage()
+ const { accept: acceptDmMessage } = useDmMessageSender()
const markAllInboxRead = useMarkAllInboxRead()
const deleteMention = useDeleteMention()
const updateProfile = useUpdateProfile()
@@ -454,27 +454,22 @@ export function ShellFrame({
toastApiError(e, "Failed to open DM")
return
}
- // Await the send BEFORE navigating so the server row exists by the time
- // the DM page mounts and fires its initial `GET /messages`. Otherwise
- // the fresh-mount fetch races the send: it returns [], overwrites the
- // optimistic cache, and the first message silently vanishes. Failure
- // surfaces as a toast + `failed: true` pill; we still navigate so the
- // user has the composer to retry.
const trimmed = text.trim()
if (trimmed) {
- try {
- await sendDmMessage.mutateAsync({
- dmId,
- content: trimmed,
- author: {
- id: currentUser.id,
- name: currentUser.name,
- avatar: currentUser.avatar,
- },
- })
- } catch (e) {
- toastApiError(e, "Failed to send message")
+ const receipt = acceptDmMessage({
+ dmId,
+ content: trimmed,
+ author: {
+ id: currentUser.id,
+ name: currentUser.name,
+ avatar: currentUser.avatar,
+ },
+ })
+ if (!receipt.accepted) {
+ toast("Failed to send message")
+ return
}
+ void receipt.committed
}
router.push(`/c/me/${dmId}`)
}
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.ts
deleted file mode 100644
index 27d2d87da..000000000
--- a/src/web/src/hooks/community/insert-message-into-cache.test.ts
+++ /dev/null
@@ -1,161 +0,0 @@
-import { describe, it, expect } from "vitest"
-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
-// shim. The image-attachment branch is one of the silent-drop sites flagged
-// in plans/attachment-image-dimensions.md's plan review.
-describe("insertMessageIntoCache — attachment width/height", () => {
- const emptyCache = { pages: [{ messages: [] }], pageParams: [null] }
-
- function baseMessage(overrides: Partial<CommunityMessageCreate["message"]> = {}): CommunityMessageCreate["message"] {
- return {
- id: "msg_1",
- seq: 1,
- type: "chat",
- authorId: "author_1",
- authorName: "Author",
- authorAvatar: "A",
- content: "hello",
- createdAt: "2026-01-01T00:00:00.000Z",
- ...overrides,
- }
- }
-
- it("carries width/height through onto an image attachment", () => {
- const msg = baseMessage({
- attachments: [
- { id: "a1", filename: "a.png", url: "/a.png", contentType: "image/png", size: 1000, width: 1920, height: 1080 },
- ],
- })
- const result = insertMessageIntoCache(emptyCache as never, msg)
- const inserted = result?.pages[0].messages[0]
- expect(inserted?.attachments).toEqual([
- { kind: "image", name: "a.png", url: "/a.png", width: 1920, height: 1080 },
- ])
- })
-
- it("leaves width/height undefined for an image attachment with no dimensions on the payload", () => {
- const msg = baseMessage({
- attachments: [
- { id: "a1", filename: "a.png", url: "/a.png", contentType: "image/png", size: 1000 },
- ],
- })
- const result = insertMessageIntoCache(emptyCache as never, msg)
- const inserted = result?.pages[0].messages[0]
- expect(inserted?.attachments).toEqual([
- { kind: "image", name: "a.png", url: "/a.png", width: undefined, height: undefined },
- ])
- })
-
- it("never adds width/height to a file-kind attachment", () => {
- const msg = baseMessage({
- attachments: [
- { id: "a1", filename: "a.pdf", url: "/a.pdf", contentType: "application/pdf", size: 2048, width: 1920, height: 1080 },
- ],
- })
- const result = insertMessageIntoCache(emptyCache as never, msg)
- const inserted = result?.pages[0].messages[0]
- expect(inserted?.attachments).toEqual([
- { kind: "file", name: "a.pdf", url: "/a.pdf", size: "2 KB" },
- ])
- })
-
- it.each(["image/svg+xml", "image/x-forged"])(
- "materializes unsafe %s attachments as file-kind",
- (contentType) => {
- const msg = baseMessage({
- attachments: [
- { id: "a1", filename: "unsafe.img", url: "/unsafe.img", contentType, size: 2048, width: 1920, height: 1080 },
- ],
- })
- const result = insertMessageIntoCache(emptyCache as never, msg)
- const inserted = result?.pages[0].messages[0]
- expect(inserted?.attachments).toEqual([
- { kind: "file", name: "unsafe.img", url: "/unsafe.img", size: "2 KB" },
- ])
- },
- )
-})
-
-// reply-disappear root-cause fix (step 2): a message.create echo of the
-// SENDER's own send carries the same clientNonce the optimistic row was stamped
-// with (WS step 1), so `insertMessageIntoCache` reconciles that row IN PLACE
-// (temp id → server id) instead of appending a duplicate. The duplicate was the
-// 2-row transient that, collapsed under an unlucky POST-vs-WS ordering, made a
-// just-sent reply vanish. These lock "one row, no double-insert" — the machine
-// oracle for the fix (Ingaborg's dt=0 ADD,ADD → single ADD).
-describe("insertMessageIntoCache — optimistic-row reconcile by clientNonce (reply-disappear step 2)", () => {
- const optimisticRow = {
- id: "temp_abc",
- type: "chat" as const,
- authorId: "author_1",
- authorName: "Author",
- content: "hello",
- createdAt: "2026-01-01T00:00:00.000Z",
- clientNonce: "nonce-xyz",
- }
- const cacheWithOptimistic = () => ({ pages: [{ messages: [{ ...optimisticRow }] }], pageParams: [null] })
-
- function echo(overrides: Partial<CommunityMessageCreate["message"]> = {}): CommunityMessageCreate["message"] {
- return {
- id: "msg_server_1",
- seq: 2,
- type: "chat",
- authorId: "author_1",
- authorName: "Author",
- authorAvatar: "A",
- content: "hello",
- createdAt: "2026-01-01T00:00:00.000Z",
- clientNonce: "nonce-xyz",
- ...overrides,
- } as CommunityMessageCreate["message"]
- }
-
- it("same-nonce echo renames the optimistic row in place (temp→server id) — ONE row, no duplicate", () => {
- const result = insertMessageIntoCache(cacheWithOptimistic() as never, echo())
- const rows = result?.pages[0].messages
- expect(rows).toHaveLength(1)
- expect(rows?.[0].id).toBe("msg_server_1")
- expect(rows?.[0].clientNonce).toBe("nonce-xyz")
- expect(rows?.[0].failed).toBe(false)
- })
-
- it("preserves the optimistic row's position (reconcile in place, not append)", () => {
- const older = { id: "m_old", type: "chat" as const, authorId: "a", authorName: "X", content: "prev", createdAt: "2025-12-31T00:00:00.000Z" }
- const cache = { pages: [{ messages: [older, { ...optimisticRow }] }], pageParams: [null] }
- const result = insertMessageIntoCache(cache as never, echo())
- const rows = result?.pages[0].messages
- expect(rows).toHaveLength(2)
- expect(rows?.map((m) => m.id)).toEqual(["m_old", "msg_server_1"])
- })
-
- it("an echo with a DIFFERENT nonce (someone else's message) is appended normally — no false reconcile", () => {
- const result = insertMessageIntoCache(cacheWithOptimistic() as never, echo({ id: "msg_other", clientNonce: "other-nonce" }))
- const rows = result?.pages[0].messages
- expect(rows).toHaveLength(2)
- expect(rows?.map((m) => m.id)).toEqual(["temp_abc", "msg_other"])
- })
-
- it("an echo with NO clientNonce (srv-fallback, never echoed anyway) is appended — no reconcile", () => {
- const result = insertMessageIntoCache(cacheWithOptimistic() as never, echo({ id: "msg_nononce", clientNonce: undefined }))
- const rows = result?.pages[0].messages
- expect(rows).toHaveLength(2)
- expect(rows?.map((m) => m.id)).toEqual(["temp_abc", "msg_nononce"])
- })
-
- it("the server-id dedup still wins first: a re-delivered echo (server id already present) is a no-op", () => {
- // After a prior reconcile the row already carries the server id; a duplicate
- // echo must not touch the cache (id check precedes the nonce reconcile).
- const cache = { pages: [{ messages: [{ ...optimisticRow, id: "msg_server_1" }] }], pageParams: [null] }
- const result = insertMessageIntoCache(cache as never, echo())
- expect(result?.pages[0].messages).toHaveLength(1)
- expect(result?.pages[0].messages[0].id).toBe("msg_server_1")
- })
-})
diff --git a/src/web/src/hooks/community/mutations/messages.test.ts b/src/web/src/hooks/community/mutations/messages.test.ts
index e1db07227..5423a3a50 100644
--- a/src/web/src/hooks/community/mutations/messages.test.ts
+++ b/src/web/src/hooks/community/mutations/messages.test.ts
@@ -174,9 +174,7 @@ describe("useSendMessage — rollback", () => {
})
// Regression pin — the mount-time effect in <MessageList> gates self-send
-// auto-scroll on `tail.authorId === viewerUserId`. A missing `authorId` on
-// the optimistic row silently disables that scroll, so pin the field on
-// BOTH the channel and DM optimistic paths.
+// auto-scroll on `tail.authorId === viewerUserId`.
describe("useSendMessage — stamps authorId on optimistic row", () => {
it("optimistic row carries the sender's authorId", async () => {
capturedQc.setQueryData(communityKeys.channelMessages("ch_1"), makeCache([]))
@@ -198,43 +196,54 @@ describe("useSendMessage — stamps authorId on optimistic row", () => {
// ── useSendDmMessage ──────────────────────────────────────────────────────
-describe("useSendDmMessage — stamps authorId on optimistic row", () => {
- // Companion regression: without authorId the self-send auto-scroll bails
- // in <MessageList> because `undefined !== viewerUserId`. Pin the field.
- it("optimistic DM row carries the sender's authorId", async () => {
+async function acceptDmIntent(nonce = "n1") {
+ const stream = await import("@/stores/community/message-stream")
+ stream.useMessageStreamStore.getState().accept(
+ { kind: "dm", id: "dm_1" },
+ {
+ nonce,
+ tempId: `temp_${nonce}`,
+ message: { type: "chat", content: "hi", authorId: "u_me" },
+ localUploads: [],
+ },
+ )
+ return stream
+}
+
+describe("useSendDmMessage — overlay terminal emitter", () => {
+ it("keeps Query base-only and emits exactly one postAck", async () => {
capturedQc.setQueryData(communityKeys.dmMessages("dm_1"), makeCache([]))
- apiFetchMock.mockImplementation(() => new Promise(() => { }))
+ apiFetchMock.mockResolvedValueOnce({ message: { id: "server_1", seq: 8 } })
const mod = await loadMod()
+ const stream = await acceptDmIntent()
+ const dispatch = vi.spyOn(stream.useMessageStreamStore.getState(), "dispatch")
mod.useSendDmMessage()
- const cfg = capturedConfig!
- await cfg.onMutate!({
- dmId: "dm_1",
- content: "hi",
- author: { id: "u_me", name: "me", avatar: "M" },
- })
- const cache = capturedQc.getQueryData<{ pages: { messages: { authorId?: string }[] }[] }>(
- communityKeys.dmMessages("dm_1"),
+ await runMutation({ dmId: "dm_1", content: "hi", nonce: "n1" })
+
+ expect(capturedQc.getQueryData(communityKeys.dmMessages("dm_1"))).toEqual(makeCache([]))
+ expect(dispatch).toHaveBeenCalledTimes(1)
+ expect(dispatch).toHaveBeenCalledWith(
+ { kind: "dm", id: "dm_1" },
+ { type: "postAck", nonce: "n1", serverMessageId: "server_1", serverSeq: 8 },
)
- expect(cache?.pages[0].messages).toHaveLength(1)
- expect(cache?.pages[0].messages[0].authorId).toBe("u_me")
})
-})
-describe("useSendDmMessage — rollback", () => {
- it("marks the temp DM row failed on server failure", async () => {
+ it("emits postFail for a generic network failure and leaves Query untouched", async () => {
capturedQc.setQueryData(communityKeys.dmMessages("dm_1"), makeCache([]))
apiFetchMock.mockRejectedValueOnce(new Error("boom"))
const mod = await loadMod()
+ const stream = await acceptDmIntent()
+ const dispatch = vi.spyOn(stream.useMessageStreamStore.getState(), "dispatch")
mod.useSendDmMessage()
- await runMutation({
- dmId: "dm_1",
- content: "hi",
- author: { id: "u_me", name: "me", avatar: "M" },
- }).catch(() => { })
- const cache = capturedQc.getQueryData<{ pages: { messages: { failed?: boolean }[] }[] }>(
- communityKeys.dmMessages("dm_1"),
+ await runMutation({ dmId: "dm_1", content: "hi", nonce: "n1" }).catch(() => { })
+
+ expect(capturedQc.getQueryData(communityKeys.dmMessages("dm_1"))).toEqual(makeCache([]))
+ expect(stream.getMessageOverlay({ kind: "dm", id: "dm_1" }).outboxByNonce.get("n1")?.status).toBe("failed")
+ expect(dispatch).toHaveBeenCalledTimes(1)
+ expect(dispatch).toHaveBeenCalledWith(
+ { kind: "dm", id: "dm_1" },
+ { type: "postFail", nonce: "n1" },
)
- expect(cache?.pages[0].messages[0].failed).toBe(true)
})
})
@@ -246,17 +255,21 @@ describe("useSendDmMessage — 403 blocked special-case", () => {
// instance the hook's `err instanceof ApiError` check will see.
const { ApiError } = await import("@/lib/errors")
apiFetchMock.mockRejectedValueOnce(new ApiError("blocked", 403))
+ const stream = await acceptDmIntent()
+ const dispatch = vi.spyOn(stream.useMessageStreamStore.getState(), "dispatch")
mod.useSendDmMessage()
await runMutation({
dmId: "dm_1",
content: "hi",
- author: { id: "u_me", name: "me", avatar: "M" },
+ nonce: "n1",
}).catch(() => { })
- const cache = capturedQc.getQueryData<{ pages: { messages: unknown[] }[] }>(
- communityKeys.dmMessages("dm_1"),
+ expect(stream.getMessageOverlay({ kind: "dm", id: "dm_1" }).outboxByNonce.size).toBe(0)
+ expect(dispatch).toHaveBeenCalledTimes(1)
+ expect(dispatch).toHaveBeenCalledWith(
+ { kind: "dm", id: "dm_1" },
+ { type: "terminalReject", nonce: "n1" },
)
- // Temp row scrubbed — no bubble, no failed:true.
- expect(cache?.pages[0].messages).toHaveLength(0)
+ expect(capturedQc.getQueryData(communityKeys.dmMessages("dm_1"))).toEqual(makeCache([]))
expect(toastMock).toHaveBeenCalledWith("You cannot send messages to this user")
})
@@ -265,17 +278,15 @@ describe("useSendDmMessage — 403 blocked special-case", () => {
const mod = await loadMod()
const { ApiError } = await import("@/lib/errors")
apiFetchMock.mockRejectedValueOnce(new ApiError("boom", 500))
+ const stream = await acceptDmIntent()
mod.useSendDmMessage()
await runMutation({
dmId: "dm_1",
content: "hi",
- author: { id: "u_me", name: "me", avatar: "M" },
+ nonce: "n1",
}).catch(() => { })
- const cache = capturedQc.getQueryData<{ pages: { messages: { failed?: boolean }[] }[] }>(
- communityKeys.dmMessages("dm_1"),
- )
- expect(cache?.pages[0].messages).toHaveLength(1)
- expect(cache?.pages[0].messages[0].failed).toBe(true)
+ expect(stream.getMessageOverlay({ kind: "dm", id: "dm_1" }).outboxByNonce.get("n1")?.status).toBe("failed")
+ expect(capturedQc.getQueryData(communityKeys.dmMessages("dm_1"))).toEqual(makeCache([]))
// Not the blocked-specific copy — any other error falls through to the
// generic send-failed toast (see `useSendDmMessage`'s `onError` fallback).
expect(toastMock).not.toHaveBeenCalledWith("You cannot send messages to this user")
@@ -320,17 +331,15 @@ describe("useSendDmMessage — 429 rate limit fires a toast + marks failed", ()
const mod = await loadMod()
const { ApiError } = await import("@/lib/errors")
apiFetchMock.mockRejectedValueOnce(new ApiError("rate_limited", 429))
+ const stream = await acceptDmIntent()
mod.useSendDmMessage()
await runMutation({
dmId: "dm_1",
content: "hi",
- author: { id: "u_me", name: "me", avatar: "M" },
+ nonce: "n1",
}).catch(() => { })
- const cache = capturedQc.getQueryData<{ pages: { messages: { failed?: boolean }[] }[] }>(
- communityKeys.dmMessages("dm_1"),
- )
- expect(cache?.pages[0].messages).toHaveLength(1)
- expect(cache?.pages[0].messages[0].failed).toBe(true)
+ expect(stream.getMessageOverlay({ kind: "dm", id: "dm_1" }).outboxByNonce.get("n1")?.status).toBe("failed")
+ expect(capturedQc.getQueryData(communityKeys.dmMessages("dm_1"))).toEqual(makeCache([]))
expect(toastMock).toHaveBeenCalledWith(expect.stringContaining("Rate limited"))
})
})
@@ -369,51 +378,6 @@ describe("useSendMessage — no blocked branch on channel path", () => {
})
})
-// ── useToggleReaction ─────────────────────────────────────────────────────
-
-describe("useToggleReaction — optimistic flip + rollback", () => {
- it("optimistically adds a reaction with me=true and issues PUT", async () => {
- capturedQc.setQueryData(communityKeys.channelMessages("ch_1"), {
- pages: [{ messages: [{ id: "m_1", reactions: [] }], hasMore: false }],
- pageParams: [null],
- })
- apiFetchMock.mockResolvedValueOnce(undefined)
- const mod = await loadMod()
- mod.useToggleReaction()
- await runMutation({
- channelId: "ch_1",
- messageId: "m_1",
- emoji: "👍",
- userId: "u_me",
- })
- const cache = capturedQc.getQueryData<{
- pages: { messages: { reactions: { emoji: string; me: boolean }[] }[] }[]
- }>(communityKeys.channelMessages("ch_1"))
- expect(cache?.pages[0].messages[0].reactions).toMatchObject([{ emoji: "👍", me: true }])
- expect(apiFetchMock).toHaveBeenCalledWith(expect.any(String), { method: "PUT" })
- })
-
- it("rolls back on failure — reactions return to []", async () => {
- capturedQc.setQueryData(communityKeys.channelMessages("ch_1"), {
- pages: [{ messages: [{ id: "m_1", reactions: [] }], hasMore: false }],
- pageParams: [null],
- })
- apiFetchMock.mockRejectedValueOnce(new Error("boom"))
- const mod = await loadMod()
- mod.useToggleReaction()
- await runMutation({
- channelId: "ch_1",
- messageId: "m_1",
- emoji: "👍",
- userId: "u_me",
- }).catch(() => { })
- const cache = capturedQc.getQueryData<{ pages: { messages: { reactions: unknown[] }[] }[] }>(
- communityKeys.channelMessages("ch_1"),
- )
- expect(cache?.pages[0].messages[0].reactions).toEqual([])
- })
-})
-
// ── useToggleReactionApi — the #9 300ms debounce ────────────────────────
//
// Old context (context.tsx:1061-1130) captured `originalMe` at first click,
@@ -476,6 +440,75 @@ describe("useToggleReactionApi — 300ms debounce coalescing", () => {
}
})
+ it("updates and rolls back a fallback-only DM row, starting from me=true", async () => {
+ vi.useFakeTimers()
+ try {
+ capturedQc.setQueryData(communityKeys.dmMessages("dm_1"), makeCache([]))
+ apiFetchMock.mockRejectedValueOnce(new Error("boom"))
+ const mod = await loadMod()
+ const stream = await import("@/stores/community/message-stream")
+ const scope = { kind: "dm" as const, id: "dm_1" }
+ stream.useMessageStreamStore.getState().dispatch(scope, {
+ type: "wsMessage",
+ message: {
+ id: "m_dm",
+ seq: 2,
+ type: "chat",
+ content: "hello",
+ reactions: [{ emoji: "👍", count: 1, me: true, userIds: ["u_me"] }],
+ },
+ })
+
+ mod.useToggleReactionApi()({
+ dmId: "dm_1",
+ messageId: "m_dm",
+ emoji: "👍",
+ userId: "u_me",
+ })
+ expect(stream.getMessageOverlay(scope).liveById.get("m_dm")?.reactions).toEqual([])
+
+ await vi.advanceTimersByTimeAsync(300)
+ await Promise.resolve()
+
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ expect.stringContaining("/api/community/messages/m_dm/reactions/"),
+ { method: "DELETE" },
+ )
+ expect(stream.getMessageOverlay(scope).liveById.get("m_dm")?.reactions).toEqual([
+ expect.objectContaining({ emoji: "👍", me: true, count: 1 }),
+ ])
+ expect(capturedQc.getQueryData<{ pages: { messages: unknown[] }[] }>(
+ communityKeys.dmMessages("dm_1"),
+ )?.pages[0].messages).toEqual([])
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it("does not invent a DM fallback when the message exists in neither base nor overlay", async () => {
+ vi.useFakeTimers()
+ try {
+ capturedQc.setQueryData(communityKeys.dmMessages("dm_1"), makeCache([]))
+ apiFetchMock.mockRejectedValueOnce(new Error("boom"))
+ const mod = await loadMod()
+ const stream = await import("@/stores/community/message-stream")
+ const scope = { kind: "dm" as const, id: "dm_1" }
+
+ mod.useToggleReactionApi()({
+ dmId: "dm_1",
+ messageId: "missing",
+ emoji: "👍",
+ userId: "u_me",
+ })
+ await vi.advanceTimersByTimeAsync(300)
+ await Promise.resolve()
+
+ expect(stream.getMessageOverlay(scope).liveById.size).toBe(0)
+ } 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.ts
index 393bcb108..5422b8090 100644
--- a/src/web/src/hooks/community/mutations/messages.ts
+++ b/src/web/src/hooks/community/mutations/messages.ts
@@ -29,11 +29,10 @@ import { isBlocked } from "@alook/shared"
/**
* Message-scoped mutation hooks — the split of the God-context's
* `sendMessage`/`toggleReaction`/`pinMessage`/etc. into standalone
- * `useMutation` hooks. Every hook writes optimistic state into the shared
- * TanStack Query cache (`communityKeys.channelMessages(id)` /
- * `communityKeys.pins(id)` / etc.), performs the fetch inside `mutationFn`,
- * and rolls back via the context returned from `onMutate` when the request
- * fails.
+ * `useMutation` hooks. Message existence is owned by the session overlay;
+ * field-only operations and panel resources may still patch TanStack Query.
+ * Each hook performs its fetch inside `mutationFn` and applies the matching
+ * reducer/cache terminal transition on success or failure.
*
* Rules of engagement:
* - Never invalidate on success unless there's no server-broadcast path — the
@@ -48,121 +47,6 @@ import { isBlocked } from "@alook/shared"
type PageCache = InfiniteData<MessagesPage>
-/**
- * Insert an optimistic message into the newest page. Pages carry ASC rows;
- * "newest" is the FIRST page (pageParam=null). Consumers of `useMessages`
- * concatenate in reverse-page order (oldest page first), so appending to
- * page 0 places the new row at the end of the visible list.
- */
-function prependOptimistic(
- cache: PageCache | undefined,
- msg: Msg,
-): PageCache | undefined {
- if (!cache) return cache
- if (cache.pages.length === 0) return cache
- const [first, ...rest] = cache.pages
- return {
- ...cache,
- pages: [{ ...first, messages: [...first.messages, msg] }, ...rest],
- }
-}
-
-/**
- * Swap an optimistic `temp_` id for the server-assigned id after a successful
- * POST. Walks every page since there's no guarantee which page the row lives
- * in (though the newest is the only realistic one for a fresh insert).
- */
-function reconcileServerId(
- cache: PageCache | undefined,
- tempId: string,
- serverId: string,
-): PageCache | undefined {
- if (!cache) return cache
- // Dedupe guard: if the server row is already in the cache (e.g. a
- // deduped-replay whose WS message-create already landed, or a nonce-based WS
- // reconcile that already healed this send), DROP the temp row instead of
- // renaming it — renaming would leave two rows sharing `serverId`. Only when
- // `serverId` is absent do we rename the optimistic row in place. This also
- // clears the `failed` flag, since a successful reconcile means the send
- // landed.
- const alreadyPresent = cache.pages.some((p) =>
- p.messages.some((m) => m.id === serverId),
- )
- let touched = false
- const pages = cache.pages.map((p) => {
- if (!p.messages.some((m) => m.id === tempId)) return p
- touched = true
- if (alreadyPresent) {
- return { ...p, messages: p.messages.filter((m) => m.id !== tempId) }
- }
- return {
- ...p,
- messages: p.messages.map((m) =>
- m.id === tempId ? { ...m, id: serverId, failed: false } : m,
- ),
- }
- })
- if (!touched) return cache
- return { ...cache, pages }
-}
-
-function removeById(
- cache: PageCache | undefined,
- id: string,
-): PageCache | undefined {
- if (!cache) return cache
- let touched = false
- const pages = cache.pages.map((p) => {
- const filtered = p.messages.filter((m) => m.id !== id)
- if (filtered.length === p.messages.length) return p
- touched = true
- return { ...p, messages: filtered }
- })
- if (!touched) return cache
- return { ...cache, pages }
-}
-
-// Drop any row carrying `nonce` as its `clientNonce`. Called on a retry-pill
-// resend BEFORE inserting the fresh optimistic row: the retry reuses the failed
-// row's nonce, so without this both the stale failed row and the new row would
-// share one nonce and the WS by-nonce reconcile would match two rows. Removing
-// the stale one first keeps exactly one row per nonce.
-function removeByNonce(
- cache: PageCache | undefined,
- nonce: string,
-): PageCache | undefined {
- if (!cache) return cache
- let touched = false
- const pages = cache.pages.map((p) => {
- const filtered = p.messages.filter((m) => m.clientNonce !== nonce)
- if (filtered.length === p.messages.length) return p
- touched = true
- return { ...p, messages: filtered }
- })
- if (!touched) return cache
- return { ...cache, pages }
-}
-
-function markFailedById(
- cache: PageCache | undefined,
- id: string,
-): PageCache | undefined {
- if (!cache) return cache
- let touched = false
- const pages = cache.pages.map((p) => {
- if (!p.messages.some((m) => m.id === id)) return p
- touched = true
- return {
- ...p,
- messages: p.messages.map((m) =>
- m.id === id ? { ...m, failed: true } : m,
- ),
- }
- })
- if (!touched) return cache
- return { ...cache, pages }
-}
-
/**
* Materialize the attachment view-model from the API attachment shape.
* Mirrors the old context's conversion at `postWithOptimisticInsert`.
@@ -283,18 +167,14 @@ export type SendDmMessageArgs = {
content: string
replyToId?: string
attachments?: { url: string; filename: string; contentType: string; size: number; width?: number; height?: number }[]
- author: { id: string; name: string; avatar: string }
- // Idempotency nonce — see `SendMessageArgs.nonce`.
- nonce?: string
+ nonce: string
}
export function useSendDmMessage() {
- const queryClient = useQueryClient()
return useMutation<
SendMessageResult,
Error,
- SendDmMessageArgs,
- { tempId: string; key: readonly unknown[] }
+ SendDmMessageArgs
>({
mutationFn: async ({ dmId, content, replyToId, attachments, nonce }) => {
return apiFetch<SendMessageResult>(
@@ -305,67 +185,35 @@ export function useSendDmMessage() {
},
)
},
- onMutate: async (args) => {
- const key = communityKeys.dmMessages(args.dmId)
- await queryClient.cancelQueries({ queryKey: key })
- const tempId = tempMessageId()
- // Idempotency nonce — mirror the channel path. Caller mints on fresh
- // send / reuses the failed row's on retry; stamp it on the optimistic
- // row for WS-by-nonce reconcile.
- const nonce = args.nonce
- if (nonce) {
- queryClient.setQueryData<PageCache>(key, (c) => removeByNonce(c, nonce))
- }
- const optimisticAttachments = args.attachments?.map(toAttachmentVm)
- const msg: Msg = {
- id: tempId,
- type: "chat",
- // Mirror the channel path: stamp the sender's userId so the
- // self-send auto-scroll effect in <MessageList> (gated on
- // `tail.authorId === viewerUserId`) recognizes the optimistic row
- // as viewer-authored and pins to bottom on send.
- authorId: args.author.id,
- authorName: args.author.name,
- authorAvatar: args.author.avatar,
- content: args.content,
- createdAt: new Date().toISOString(),
- ...(nonce ? { clientNonce: nonce } : {}),
- ...(optimisticAttachments?.length ? { attachments: optimisticAttachments } : {}),
- }
- queryClient.setQueryData<PageCache>(key, (c) => prependOptimistic(c, msg))
- return { tempId, key }
- },
- onError: (err, _args, ctx) => {
- if (!ctx) return
- // 403 "blocked" is a friendly signal (recipient has blocked the sender) —
- // scrub the optimistic row and show a scoped toast rather than leaving a
- // `failed: true` bubble in place. Mirrors the old context's `onBlocked`
- // branch at contexts/community/context.tsx:1021-1027.
+ onError: (err, args) => {
+ const scope = { kind: "dm" as const, id: args.dmId }
if (err instanceof ApiError && err.status === 403 && isBlocked(err.message)) {
- queryClient.setQueryData<PageCache>(ctx.key as ReturnType<typeof communityKeys.dmMessages>, (c) =>
- removeById(c, ctx.tempId),
- )
+ useMessageStreamStore.getState().dispatch(scope, {
+ type: "terminalReject",
+ nonce: args.nonce,
+ })
toast("You cannot send messages to this user")
return
}
- // 429: server-side rate limit. Fire a scoped toast so the user knows
- // the send was throttled; still mark the row `failed: true` so the
- // retry pill is available (mirrors the channel path).
+ useMessageStreamStore.getState().dispatch(scope, {
+ type: "postFail",
+ nonce: args.nonce,
+ })
if (err instanceof ApiError && err.status === 429) {
toast.error("Rate limited — please wait a moment before trying again")
} else {
- // Any other failure besides 429/blocked (handled above) — the
- // `failed: true` pill is a retry affordance, not a reason.
toastApiError(err, "Failed to send message")
}
- queryClient.setQueryData<PageCache>(ctx.key as ReturnType<typeof communityKeys.dmMessages>, (c) =>
- markFailedById(c, ctx.tempId),
- )
},
- onSuccess: (data, _args, ctx) => {
- if (!ctx) return
- queryClient.setQueryData<PageCache>(ctx.key as ReturnType<typeof communityKeys.dmMessages>, (c) =>
- reconcileServerId(c, ctx.tempId, data.message.id),
+ onSuccess: (data, args) => {
+ useMessageStreamStore.getState().dispatch(
+ { kind: "dm", id: args.dmId },
+ {
+ type: "postAck",
+ nonce: args.nonce,
+ serverMessageId: data.message.id,
+ serverSeq: data.message.seq,
+ },
)
},
})
@@ -382,11 +230,6 @@ export type ToggleReactionArgs = {
userId: string
}
-type ToggleReactionCtx = {
- key: readonly unknown[]
- originalMe: boolean
-}
-
// Apply an optimistic reaction toggle to any page cache that contains the
// message. This mirrors the reducer in the God-context.
function togglePageCacheReaction(
@@ -437,10 +280,11 @@ function toggleMessageReaction(
return { ...message, reactions }
}
-function channelScope(args: ToggleReactionArgs): MessageScope | undefined {
- return args.channelId && args.serverId
- ? { kind: "channel", id: args.channelId, serverId: args.serverId }
- : undefined
+function messageScope(args: ToggleReactionArgs): MessageScope | undefined {
+ if (args.channelId && args.serverId) {
+ return { kind: "channel", id: args.channelId, serverId: args.serverId }
+ }
+ return args.dmId ? { kind: "dm", id: args.dmId } : undefined
}
function currentMaterializedMessage(
@@ -459,7 +303,7 @@ function refreshExistingReactionFallback(
args: ToggleReactionArgs,
add: boolean,
): void {
- const scope = channelScope(args)
+ const scope = messageScope(args)
if (!scope) return
const overlay = getMessageOverlay(scope)
const existing = [...overlay.liveById.values()].find((message) => message.id === args.messageId)
@@ -486,63 +330,6 @@ function currentMeStatus(
return false
}
-/**
- * Toggle a reaction on a message. Optimistic: flips `me` immediately, rolls
- * back on server failure. The HTTP method (`PUT` add vs `DELETE` remove) is
- * derived from the cache read at call-time inside `mutationFn` — capturing
- * the original state before the optimistic flip.
- *
- * Note: consumers usually want `useToggleReactionApi()` below — a
- * fire-and-forget callable — because reactions don't need pending UI.
- */
-export function useToggleReaction() {
- const queryClient = useQueryClient()
- return useMutation<void, Error, ToggleReactionArgs, ToggleReactionCtx>({
- mutationFn: async (args, ..._rest) => {
- // Re-read cache at call time to pick the correct verb. The optimistic
- // write in onMutate has already flipped `me` in cache, but we captured
- // `originalMe` in the context — pull it from there via a ref map. In
- // practice mutationFn doesn't receive ctx, so we re-derive from the
- // originalMe stashed by `onMutate` in a shared closure via `queryClient
- // .getMutationCache()`. Simpler: encode the verb into args pre-call.
- void _rest
- const key = args.channelId
- ? communityKeys.channelMessages(args.channelId)
- : args.dmId
- ? communityKeys.dmMessages(args.dmId)
- : communityKeys.channelMessages("__none__")
- // The cache at this point reflects the optimistic flip. Reverse-derive:
- // if the current `me` after flip is TRUE, we're adding; ELSE removing.
- const cache = queryClient.getQueryData<PageCache>(key)
- const meAfterFlip = currentMeStatus(cache, args.messageId, args.emoji)
- const method = meAfterFlip ? "PUT" : "DELETE"
- const url = `/api/community/messages/${args.messageId}/reactions/${encodeURIComponent(args.emoji)}`
- await apiFetch(url, { method })
- },
- onMutate: async (args) => {
- const key = args.channelId
- ? communityKeys.channelMessages(args.channelId)
- : args.dmId
- ? communityKeys.dmMessages(args.dmId)
- : communityKeys.channelMessages("__none__")
- await queryClient.cancelQueries({ queryKey: key })
- const cache = queryClient.getQueryData<PageCache>(key)
- const originalMe = currentMeStatus(cache, args.messageId, args.emoji)
- const nextMe = !originalMe
- queryClient.setQueryData<PageCache>(key, (c) =>
- togglePageCacheReaction(c, args.messageId, args.emoji, args.userId, nextMe),
- )
- return { key, originalMe }
- },
- onError: (_err, args, ctx) => {
- if (!ctx) return
- queryClient.setQueryData<PageCache>(ctx.key as ReturnType<typeof communityKeys.channelMessages>, (c) =>
- togglePageCacheReaction(c, args.messageId, args.emoji, args.userId, ctx.originalMe),
- )
- },
- })
-}
-
// #9: 300ms coalescing window. A user tapping the same reaction pill in rapid
// succession should collapse to one API call whose verb matches the final
// state vs the *original* server state at first click — never a burst of
@@ -578,7 +365,7 @@ export function useToggleReactionApi(): (args: ToggleReactionArgs) => void {
? communityKeys.dmMessages(args.dmId)
: communityKeys.channelMessages("__none__")
const cache = queryClient.getQueryData<PageCache>(key)
- const scope = channelScope(args)
+ const scope = messageScope(args)
const source = scope
? currentMaterializedMessage(cache, scope, args.messageId)
: undefined
diff --git a/src/web/src/hooks/community/use-community-ws.test.ts b/src/web/src/hooks/community/use-community-ws.test.ts
index f9f6bc067..2612aae40 100644
--- a/src/web/src/hooks/community/use-community-ws.test.ts
+++ b/src/web/src/hooks/community/use-community-ws.test.ts
@@ -691,6 +691,71 @@ describe("useCommunityWs — reactions", () => {
{ emoji: "👍", count: 1, me: false, userIds: ["u_other"] },
])
})
+
+ it("refreshes a focused DM row that exists only in the overlay", async () => {
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ dmConversationId: "dm_1" })
+ await mountHook({ viewerUserId: "u_me" })
+ useMessageStreamStore.getState().dispatch(
+ { kind: "dm", id: "dm_1" },
+ {
+ type: "wsMessage",
+ message: {
+ id: "m_dm",
+ seq: 4,
+ type: "chat",
+ authorId: "u_other",
+ authorName: "Other",
+ content: "hi",
+ reactions: [],
+ },
+ },
+ )
+
+ capturedOnMessage!({
+ type: "community:reaction.add",
+ channelId: "dm_1",
+ messageId: "m_dm",
+ userId: "u_me",
+ emoji: "👍",
+ })
+
+ expect(getMessageOverlay({ kind: "dm", id: "dm_1" }).liveById.get("m_dm")?.reactions).toEqual([
+ { emoji: "👍", count: 1, me: true, userIds: ["u_me"] },
+ ])
+ })
+})
+
+describe("useCommunityWs — message.updated", () => {
+ it("refreshes approval fields on a focused DM row that exists only in the overlay", async () => {
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ dmConversationId: "dm_1" })
+ await mountHook()
+ useMessageStreamStore.getState().dispatch(
+ { kind: "dm", id: "dm_1" },
+ {
+ type: "wsMessage",
+ message: { id: "m_dm", seq: 4, type: "chat", content: "approval" },
+ },
+ )
+ const profile = { id: "u_other", name: "Other", discriminator: "0001", image: null }
+ const approval = {
+ friendshipId: "friendship_1",
+ status: "approved" as const,
+ waitingOn: null,
+ otherProfile: profile,
+ botProfile: { ...profile, id: "bot_1", name: "Bot" },
+ }
+
+ capturedOnMessage!({
+ type: "community:message.updated",
+ channelId: "dm_1",
+ messageId: "m_dm",
+ approval,
+ })
+
+ expect(getMessageOverlay({ kind: "dm", id: "dm_1" }).liveById.get("m_dm")?.approval).toEqual(approval)
+ })
})
describe("useCommunityWs — pin.add", () => {
@@ -747,6 +812,20 @@ describe("useCommunityWs — member events", () => {
it("a self-rename (member.update with userId + changes.nickname) patches authorName in every cached channel/DM message list", async () => {
await mountHook()
+ useMessageStreamStore.getState().dispatch(
+ { kind: "dm", id: "dm_overlay" },
+ {
+ type: "wsMessage",
+ message: {
+ id: "m_overlay",
+ seq: 9,
+ type: "chat",
+ authorId: "u_renamed",
+ authorName: "OldName",
+ content: "overlay only",
+ },
+ },
+ )
// Two message caches — one channel, one DM — each with a message
// authored by the renamed user and one by someone else. Both should
@@ -794,6 +873,9 @@ describe("useCommunityWs — member events", () => {
expect(dmCache?.pages[0].messages).toEqual([
{ id: "m_3", authorId: "u_renamed", authorName: "NewName", content: "sup" },
])
+ expect(
+ getMessageOverlay({ kind: "dm", id: "dm_overlay" }).liveById.get("m_overlay")?.authorName,
+ ).toBe("NewName")
})
it("a role-only member.update (no userId/nickname) does not touch any message cache", async () => {
@@ -1104,7 +1186,7 @@ describe("useCommunityWs — channel.* invalidates server(id)", () => {
})
describe("useCommunityWs — DM message.create", () => {
- it("patches dmMessages cache when focused + invalidates dms()", async () => {
+ it("writes the focused DM overlay, leaves Query base-only, and invalidates dms()", async () => {
vi.useFakeTimers()
try {
await mountHook()
@@ -1139,7 +1221,11 @@ describe("useCommunityWs — DM message.create", () => {
const cache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(
communityKeys.dmMessages("dm_1"),
)
- expect(cache?.pages[0].messages).toHaveLength(1)
+ expect(cache?.pages[0].messages).toEqual([])
+ const { getMessageOverlay } = await import("@/stores/community/message-stream")
+ expect(
+ [...getMessageOverlay({ kind: "dm", id: "dm_1" }).liveById.values()].map((message) => message.id),
+ ).toEqual(["dm_m_1"])
// The inbox + `dms()` invalidation is batched behind the inbox debounce.
vi.advanceTimersByTime(600)
expect(
@@ -1152,6 +1238,30 @@ describe("useCommunityWs — DM message.create", () => {
vi.useRealTimers()
}
})
+
+ it("heals an already-seen DM event into the overlay before seen dedupe returns", async () => {
+ const { useCommunityStore } = await import("@/stores/community")
+ const { useCommunityWsStore } = await import("@/stores/community/ws")
+ useCommunityStore.getState().subscribe({ dmConversationId: "dm_1" })
+ useCommunityWsStore.getState().markSeenMessage("dm_replay")
+ await mountHook()
+
+ capturedOnMessage!({
+ type: "community:message.create",
+ channelId: "dm_1",
+ message: {
+ id: "dm_replay",
+ seq: 12,
+ authorId: "u_a",
+ authorName: "a",
+ content: "replay",
+ type: "chat",
+ createdAt: "2026-07-03T00:00:00.000Z",
+ },
+ })
+
+ expect(getMessageOverlay({ kind: "dm", id: "dm_1" }).liveById.has("dm_replay")).toBe(true)
+ })
})
describe("useCommunityWs — non-community events bail", () => {
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index 468ebf3cb..5b485d8c0 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -86,17 +86,6 @@ import { patchChannelUnread } from "@/hooks/community/server-detail-cache"
// message burst.
const INBOX_INVALIDATE_DEBOUNCE_MS = 500
-// Cap on the live (newest) page's message count inside `insertMessageIntoCache`.
-// Without this, a channel that stays open for a long session (or a flood of
-// WS message.create events) grows the first page — and the per-render
-// clustering pass in `message-list.tsx` — without bound. Matches
-// `SEEN_MESSAGE_MAX` (stores/community/ws.ts) for consistency; set generous
-// on purpose — tune down later if memory/render cost is still a problem.
-// Only the live-tail page is capped: pagination-loaded older pages
-// (`fetchOlder`) are left uncapped since they only grow from explicit user
-// "load more" clicks, not an attacker-controlled vector.
-const MAX_LIVE_PAGE_MESSAGES = 500
-
// ── Types (kept for backwards compat with any lingering imports) ─────────
export type Subscription = {
@@ -138,80 +127,6 @@ export type CommunityWsCallbacks = {
type PageCache = InfiniteData<MessagesPage>
-/**
- * Insert a WS-delivered message onto the first (newest) page of the channel
- * or DM stream — the same slot `useSendMessage` writes optimistic rows into,
- * so the two paths converge. Deduplicates by id.
- */
-export function insertMessageIntoCache(
- cache: PageCache | undefined,
- msg: CanonicalMessage,
-): PageCache | undefined {
- if (!cache) return cache
- if (cache.pages.length === 0) return cache
- const first = cache.pages[0]
- if (first.messages.some((m) => m.id === msg.id)) return cache
- // Reconcile the SENDER's own optimistic row instead of inserting a second row.
- // A message.create echo of a send the viewer just made carries the same
- // `clientNonce` the optimistic row was stamped with (WS step-1). Without this,
- // the echo (server id) shares no key with the optimistic row (temp id) and
- // gets appended as a DUPLICATE — the 2-row transient that, collapsed under an
- // unlucky POST-vs-WS ordering, made a just-sent reply vanish (reply-disappear).
- // Rename the optimistic row to the server id in place: exactly one row, so the
- // collapse has nothing to double-delete. `reconcileServerId` (the POST path)
- // then finds no temp id and no-ops — both orderings converge to one row.
- // `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 = msg.clientNonce
- if (nonce) {
- for (let pi = 0; pi < cache.pages.length; pi++) {
- const p = cache.pages[pi]
- const mi = p.messages.findIndex((m) => m.clientNonce === nonce)
- if (mi !== -1) {
- const pages = cache.pages.slice()
- const msgs = p.messages.slice()
- 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 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
- const messages = trimmed
- ? merged.slice(merged.length - MAX_LIVE_PAGE_MESSAGES)
- : merged
- // When we drop rows off the head of the live page we've forgotten history
- // that the server still has. Flip both the anchor-mode and the legacy
- // `hasMore` flags to `true` so the older-pagination affordance re-arms —
- // otherwise `hasMoreOlder ?? hasMore ?? false` collapses to `false` for
- // the trimmed page and the UI stops offering "Load more" even though
- // there's still history to fetch. Only touch the flags that already
- // existed on the page so we don't accidentally invent an anchor-mode
- // envelope on a legacy newest cache (or vice versa).
- const nextFirst = trimmed
- ? {
- ...first,
- messages,
- ...(first.hasMoreOlder !== undefined ? { hasMoreOlder: true } : {}),
- ...(first.hasMore !== undefined ? { hasMore: true } : {}),
- }
- : { ...first, messages }
- return {
- ...cache,
- pages: [nextFirst, ...cache.pages.slice(1)],
- }
-}
-
/**
* Patch every cached message authored by `userId` to the renamed
* `authorName` — `authorName` is a snapshot field written at send time
@@ -462,6 +377,12 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
)
}
}
+ if (event.channelId === sub.dmConversationId) {
+ useMessageStreamStore.getState().dispatch(
+ { kind: "dm", id: event.channelId },
+ { type: "wsMessage", message: projected },
+ )
+ }
if (wsStore.hasSeenMessage(event.message.id)) return
wsStore.markSeenMessage(event.message.id)
// Sending a message is an implicit typing.stop for its author —
@@ -475,12 +396,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
// 1) Patch the focused channel/dm page cache if the event matches.
// A DM is a channel, distinguished only by which subscription slot
// its channelId lands in.
- if (event.channelId === sub.dmConversationId) {
- queryClient.setQueryData<PageCache>(
- communityKeys.dmMessages(event.channelId),
- (c) => insertMessageIntoCache(c, projected),
- )
- } else if (event.channelId === sub.channelId) {
+ if (event.channelId === sub.channelId) {
// 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
@@ -612,6 +528,22 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
}
}
}
+ if (event.channelId === sub.dmConversationId) {
+ const scope = { kind: "dm" as const, id: event.channelId }
+ const fallback = [...getMessageOverlay(scope).liveById.values()]
+ .find((message) => message.id === event.messageId)
+ if (fallback) {
+ const cached = findCachedMessage(
+ queryClient.getQueryData<PageCache>(communityKeys.dmMessages(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
}
@@ -984,7 +916,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
}
const streamState = useMessageStreamStore.getState()
for (const entry of streamState.entries.values()) {
- if (entry.scope.kind !== "channel" || entry.scope.serverId !== event.serverId) continue
+ 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, {
@@ -1033,6 +965,33 @@ export function useCommunityWs(options?: UseCommunityWsOptions) {
(c) => patchApprovalInCache(c, event.messageId, event.approval),
)
}
+ const overlayScopes = event.channelId === sub.dmConversationId
+ ? [{ kind: "dm" as const, id: event.channelId }]
+ : event.channelId === sub.channelId
+ ? (() => {
+ const serverId = useCommunityStore.getState().currentServerId
+ return serverId
+ ? [{ kind: "channel" as const, id: event.channelId, serverId }]
+ : []
+ })()
+ : []
+ for (const scope of overlayScopes) {
+ const fallback = [...getMessageOverlay(scope).liveById.values()]
+ .find((message) => message.id === event.messageId)
+ if (!fallback) continue
+ const key = scope.kind === "dm"
+ ? communityKeys.dmMessages(event.channelId)
+ : communityKeys.channelMessages(event.channelId)
+ const cached = findCachedMessage(
+ queryClient.getQueryData<PageCache>(key),
+ event.messageId,
+ )
+ const source = cached?.seq !== undefined ? cached as CanonicalMessage : fallback
+ useMessageStreamStore.getState().dispatch(scope, {
+ type: "liveRefreshed",
+ message: { ...source, approval: event.approval },
+ })
+ }
// When a card resolves (accepted/denied/superseded), the friend graph
// changed — invalidate friends + pending so the owner's lists reflect
// it. This is the owner's only signal in the J2 tail (Alice's accept
diff --git a/src/web/src/hooks/community/use-dm-message-sender.test.ts b/src/web/src/hooks/community/use-dm-message-sender.test.ts
new file mode 100644
index 000000000..311514c9d
--- /dev/null
+++ b/src/web/src/hooks/community/use-dm-message-sender.test.ts
@@ -0,0 +1,209 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
+import { materializeMessageStream } from "@/lib/community/message-stream"
+
+vi.mock("react", () => ({
+ useCallback: (fn: Function) => fn,
+}))
+
+const uploadMock = vi.fn()
+const postMock = vi.fn()
+
+vi.mock("@/hooks/community/mutations", () => ({
+ sendNonce: () => "fresh_nonce",
+ tempMessageId: () => "temp_fresh",
+ toAttachmentVm: (attachment: { url: string; filename: string }) => ({
+ kind: "file" as const,
+ name: attachment.filename,
+ url: attachment.url,
+ size: "1 KB",
+ }),
+ zipUploadResultsWithDimensions: (results: unknown[]) => results.filter(Boolean),
+ useUploadFile: () => ({ mutateAsync: uploadMock }),
+ useSendDmMessage: () => ({ mutateAsync: postMock }),
+}))
+
+vi.mock("@/lib/api/client", () => ({
+ toastApiError: vi.fn(),
+}))
+
+beforeEach(() => {
+ uploadMock.mockReset()
+ postMock.mockReset()
+ useMessageStreamStore.getState().resetAll()
+})
+
+describe("useDmMessageSender", () => {
+ it("stages a complete intent synchronously before a POST settles, without Query", async () => {
+ let resolvePost!: (value: { message: { id: string; seq: number } }) => void
+ postMock.mockReturnValueOnce(new Promise((resolve) => { resolvePost = resolve }))
+ const { useDmMessageSender } = await import("./use-dm-message-sender")
+ const sender = useDmMessageSender()
+
+ const receipt = sender.accept({
+ dmId: "dm_1",
+ content: "hello",
+ replyTo: { id: "prior", authorName: "Peer", text: "quoted" },
+ author: { id: "u_me", name: "Me", avatar: "M" },
+ })
+
+ expect(receipt.accepted).toBe(true)
+ const intent = getMessageOverlay({ kind: "dm", id: "dm_1" }).outboxByNonce.get("fresh_nonce")
+ expect(intent?.message).toEqual(expect.objectContaining({
+ authorId: "u_me",
+ authorName: "Me",
+ content: "hello",
+ replyTo: { id: "prior", authorName: "Peer", text: "quoted" },
+ }))
+ expect(postMock).toHaveBeenCalledWith({
+ dmId: "dm_1",
+ content: "hello",
+ replyToId: "prior",
+ attachments: undefined,
+ nonce: "fresh_nonce",
+ })
+
+ resolvePost({ message: { id: "server_1", seq: 7 } })
+ if (!receipt.accepted) throw new Error("expected accepted receipt")
+ await expect(receipt.committed).resolves.toEqual({
+ ok: true,
+ message: { id: "server_1", seq: 7 },
+ })
+ })
+
+ it("normalizes upload failure, marks the intent failed, and never POSTs", async () => {
+ uploadMock.mockRejectedValueOnce(new Error("upload failed"))
+ const { useDmMessageSender } = await import("./use-dm-message-sender")
+ const sender = useDmMessageSender()
+ const file = new File(["x"], "x.txt", { type: "text/plain" })
+ const receipt = sender.accept({
+ dmId: "dm_1",
+ content: "",
+ attachments: [{ file, previewObjectUrl: "blob:x" }],
+ author: { id: "u_me", name: "Me", avatar: "M" },
+ })
+
+ if (!receipt.accepted) throw new Error("expected accepted receipt")
+ await expect(receipt.committed).resolves.toEqual({
+ ok: false,
+ error: expect.any(Error),
+ })
+ expect(postMock).not.toHaveBeenCalled()
+ const intent = getMessageOverlay({ kind: "dm", id: "dm_1" }).outboxByNonce.get("fresh_nonce")
+ expect(intent?.uploadStatus).toBe("failed")
+ expect(intent?.status).toBe("failed")
+ })
+
+ it("retries the same nonce and reports network failure without emitting a terminal event itself", async () => {
+ postMock.mockRejectedValueOnce(new Error("offline"))
+ const { useDmMessageSender } = await import("./use-dm-message-sender")
+ useMessageStreamStore.getState().accept(
+ { kind: "dm", id: "dm_1" },
+ {
+ nonce: "retry_nonce",
+ tempId: "temp_retry",
+ message: { type: "chat", content: "again" },
+ localUploads: [],
+ },
+ )
+ useMessageStreamStore.getState().dispatch(
+ { kind: "dm", id: "dm_1" },
+ { type: "postFail", nonce: "retry_nonce" },
+ )
+ const dispatch = vi.spyOn(useMessageStreamStore.getState(), "dispatch")
+
+ const result = await useDmMessageSender().retry("dm_1", "retry_nonce")
+
+ expect(result).toEqual({ ok: false, error: expect.any(Error) })
+ expect(postMock).toHaveBeenCalledWith(expect.objectContaining({ nonce: "retry_nonce" }))
+ expect(dispatch).toHaveBeenCalledTimes(1)
+ expect(dispatch).toHaveBeenCalledWith(
+ { kind: "dm", id: "dm_1" },
+ { type: "retry", nonce: "retry_nonce" },
+ )
+ })
+
+ it("reuses settled remote attachments on retry without uploading twice", async () => {
+ uploadMock.mockResolvedValueOnce({
+ url: "https://files.example/x.txt",
+ filename: "x.txt",
+ contentType: "text/plain",
+ size: 1,
+ })
+ postMock
+ .mockRejectedValueOnce(new Error("offline"))
+ .mockResolvedValueOnce({ message: { id: "server_file", seq: 9 } })
+ const { useDmMessageSender } = await import("./use-dm-message-sender")
+ const sender = useDmMessageSender()
+ const file = new File(["x"], "x.txt", { type: "text/plain" })
+ const receipt = sender.accept({
+ dmId: "dm_1",
+ content: "file",
+ attachments: [{ file, previewObjectUrl: "blob:x" }],
+ author: { id: "u_me", name: "Me", avatar: "M" },
+ })
+
+ if (!receipt.accepted) throw new Error("expected accepted receipt")
+ await expect(receipt.committed).resolves.toEqual({ ok: false, error: expect.any(Error) })
+ expect(getMessageOverlay({ kind: "dm", id: "dm_1" }).outboxByNonce.get("fresh_nonce")?.uploadStatus).toBe("settled")
+
+ await expect(sender.retry("dm_1", "fresh_nonce")).resolves.toEqual({
+ ok: true,
+ message: { id: "server_file", seq: 9 },
+ })
+ expect(uploadMock).toHaveBeenCalledTimes(1)
+ expect(postMock).toHaveBeenCalledTimes(2)
+ expect(postMock).toHaveBeenNthCalledWith(2, {
+ dmId: "dm_1",
+ content: "file",
+ replyToId: undefined,
+ attachments: [{
+ url: "https://files.example/x.txt",
+ filename: "x.txt",
+ contentType: "text/plain",
+ size: 1,
+ width: undefined,
+ height: undefined,
+ }],
+ nonce: "fresh_nonce",
+ })
+ })
+
+ it("materializes one row after an out-of-view ack and later base arrival", async () => {
+ const scope = { kind: "dm" as const, id: "dm_1" }
+ postMock.mockImplementationOnce(async (args: { nonce: string }) => {
+ useMessageStreamStore.getState().dispatch(scope, {
+ type: "postAck",
+ nonce: args.nonce,
+ serverMessageId: "server_1",
+ serverSeq: 11,
+ })
+ return { message: { id: "server_1", seq: 11 } }
+ })
+ const { useDmMessageSender } = await import("./use-dm-message-sender")
+ const receipt = useDmMessageSender().accept({
+ dmId: "dm_1",
+ content: "out of view",
+ author: { id: "u_me", name: "Me", avatar: "M" },
+ })
+
+ if (!receipt.accepted) throw new Error("expected accepted receipt")
+ await expect(receipt.committed).resolves.toEqual({
+ ok: true,
+ message: { id: "server_1", seq: 11 },
+ })
+ expect(materializeMessageStream([], getMessageOverlay(scope)).map((message) => message.id)).toEqual(["server_1"])
+
+ const base = [{
+ id: "server_1",
+ seq: 11,
+ clientNonce: "fresh_nonce",
+ type: "chat" as const,
+ authorId: "u_me",
+ authorName: "Me",
+ content: "out of view",
+ }]
+ useMessageStreamStore.getState().dispatch(scope, { type: "baseChanged", messages: base })
+ expect(materializeMessageStream(base, getMessageOverlay(scope)).map((message) => message.id)).toEqual(["server_1"])
+ })
+})
diff --git a/src/web/src/hooks/community/use-dm-message-sender.ts b/src/web/src/hooks/community/use-dm-message-sender.ts
new file mode 100644
index 000000000..499c6ab10
--- /dev/null
+++ b/src/web/src/hooks/community/use-dm-message-sender.ts
@@ -0,0 +1,157 @@
+"use client"
+
+import { useCallback } from "react"
+import type { Msg } from "@/components/community/_types"
+import type { SendAttachment } from "@/components/community/composer"
+import { toastApiError } from "@/lib/api/client"
+import { useMessageStreamStore } from "@/stores/community/message-stream"
+import {
+ sendNonce,
+ tempMessageId,
+ toAttachmentVm,
+ useSendDmMessage,
+ useUploadFile,
+ zipUploadResultsWithDimensions,
+ type UploadedAttachment,
+} from "@/hooks/community/mutations"
+
+export type DmSendCommit =
+ | { ok: true; message: { id: string; seq: number } }
+ | { ok: false; error: Error }
+
+export type DmSendReceipt =
+ | { accepted: false }
+ | { accepted: true; nonce: string; committed: Promise<DmSendCommit> }
+
+export type AcceptDmMessageArgs = {
+ dmId: string
+ content: string
+ replyTo?: Msg["replyTo"]
+ attachments?: SendAttachment[]
+ author: { id: string; name: string; avatar: string }
+ nonce?: string
+}
+
+function asError(error: unknown): Error {
+ return error instanceof Error ? error : new Error("Failed to send message")
+}
+
+export function useDmMessageSender() {
+ const { mutateAsync: uploadFileAsync } = useUploadFile()
+ const { mutateAsync: sendDmMessageAsync } = useSendDmMessage()
+
+ const runAcceptedIntent = useCallback(async (
+ dmId: string,
+ nonce: string,
+ ): Promise<DmSendCommit> => {
+ const scope = { kind: "dm" as const, id: dmId }
+ const streamStore = useMessageStreamStore.getState()
+ const payload = streamStore.getRetryPayload(scope, nonce)
+ if (!payload) {
+ return { ok: false, error: new Error("Message intent is no longer available") }
+ }
+
+ 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: { dmId }, file: upload.file }).catch((error) => {
+ toastApiError(error, "Failed to attach file")
+ return null
+ }),
+ ),
+ )
+ if (results.some((result) => result === null)) {
+ streamStore.dispatch(scope, { type: "uploadFailed", nonce })
+ return { ok: false, error: new Error("Failed to attach file") }
+ }
+ uploadedAttachments = zipUploadResultsWithDimensions(results, [...payload.localUploads])
+ streamStore.dispatch(scope, {
+ type: "uploadSettled",
+ nonce,
+ attachments: uploadedAttachments.map(toAttachmentVm),
+ })
+ }
+
+ try {
+ const result = await sendDmMessageAsync({
+ dmId,
+ content: payload.message.content ?? "",
+ replyToId: payload.message.replyTo?.id,
+ attachments: uploadedAttachments,
+ nonce,
+ })
+ return { ok: true, message: result.message }
+ } catch (error) {
+ return { ok: false, error: asError(error) }
+ }
+ }, [sendDmMessageAsync, uploadFileAsync])
+
+ const accept = useCallback((args: AcceptDmMessageArgs): DmSendReceipt => {
+ if (!args.content && !args.attachments?.length) return { accepted: false }
+ const nonce = args.nonce ?? sendNonce()
+ const createdPreviewUrls: string[] = []
+ const accepted = useMessageStreamStore.getState().accept(
+ { kind: "dm", id: args.dmId },
+ {
+ nonce,
+ tempId: tempMessageId(),
+ message: {
+ type: "chat",
+ authorId: args.author.id,
+ authorName: args.author.name,
+ authorAvatar: args.author.avatar,
+ content: args.content,
+ createdAt: new Date().toISOString(),
+ ...(args.replyTo ? { replyTo: args.replyTo } : {}),
+ },
+ localUploads: args.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,
+ }
+ }) ?? [],
+ },
+ )
+ if (!accepted) {
+ for (const url of createdPreviewUrls) URL.revokeObjectURL(url)
+ return { accepted: false }
+ }
+ return {
+ accepted: true,
+ nonce,
+ committed: runAcceptedIntent(args.dmId, nonce),
+ }
+ }, [runAcceptedIntent])
+
+ const retry = useCallback((dmId: string, nonce: string): Promise<DmSendCommit> => {
+ useMessageStreamStore.getState().dispatch(
+ { kind: "dm", id: dmId },
+ { type: "retry", nonce },
+ )
+ return runAcceptedIntent(dmId, nonce)
+ }, [runAcceptedIntent])
+
+ return { accept, retry }
+}
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.ts
index 065c99219..ae2d08f22 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
@@ -3,7 +3,7 @@ import React from "react"
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 { useDmMessages, useMessages } from "./use-messages"
import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
const apiFetchMock = vi.fn()
@@ -60,6 +60,34 @@ function renderCapture(
})
}
+function DmCapture({ onResult }: {
+ onResult: (r: { messages: unknown[]; latestSeq: number }) => void
+}) {
+ const result = useDmMessages("dm_new", { lastReadMessageId: undefined })
+ onResult({ messages: result.messages, latestSeq: result.latestSeq })
+ return null
+}
+
+function renderDmCapture(
+ onResult: (r: { messages: unknown[]; latestSeq: number }) => void,
+ seedTail: { id: string; seq: number }[],
+) {
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(communityKeys.dmMessages("dm_new"), {
+ pages: [{ messages: seedTail, hasMore: false, latestSeq: seedTail.at(-1)?.seq ?? 0 }],
+ pageParams: [{ mode: "newest" }],
+ })
+ act(() => {
+ TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(DmCapture, { onResult }),
+ ),
+ )
+ })
+}
+
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[]; latestSeq: number } | undefined
@@ -157,3 +185,30 @@ describe("useMessages — instant channel switch: warm cache paints without wait
expect(getMessageOverlay(messageScope).liveById.size).toBe(0)
})
})
+
+describe("useDmMessages — base plus overlay", () => {
+ it("materializes a higher live fallback while latestSeq remains base-owned", () => {
+ useMessageStreamStore.getState().dispatch(
+ { kind: "dm", id: "dm_new" },
+ {
+ 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: { messages: unknown[]; latestSeq: number } | undefined
+
+ renderDmCapture((result) => { latest = result }, [{ id: "m_base", seq: 5 }])
+
+ expect(latest?.messages).toHaveLength(2)
+ expect(latest?.latestSeq).toBe(5)
+ expect(apiFetchMock).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.ts
index 62684589f..1e3767f57 100644
--- a/src/web/src/hooks/community/use-messages.ts
+++ b/src/web/src/hooks/community/use-messages.ts
@@ -591,10 +591,33 @@ export function useDmMessages(
opts?: MessagesOpts,
): MessagesReturn {
const queryKey = communityKeys.dmMessages(dmId ?? "__none__")
- return useMessagesInner(
+ const base = useMessagesInner(
dmId,
queryKey,
dmMessagesQueryFn(dmId ?? "__none__"),
opts,
)
+ const scope = useMemo<MessageScope>(() => ({
+ kind: "dm",
+ id: dmId ?? "__none__",
+ }), [dmId])
+ const overlay = useMessageOverlay(scope)
+ const canonicalBase = useMemo(
+ () => base.messages.filter(
+ (message): message is CanonicalMessage => typeof message.seq === "number",
+ ),
+ [base.messages],
+ )
+ useEffect(() => {
+ if (!dmId) return
+ useMessageStreamStore.getState().dispatch(scope, {
+ type: "baseChanged",
+ messages: canonicalBase,
+ })
+ }, [canonicalBase, dmId, scope])
+ const messages = useMemo(
+ () => materializeMessageStream(canonicalBase, overlay),
+ [canonicalBase, overlay],
+ )
+ return { ...base, messages }
}
diff --git a/src/web/src/hooks/community/use-scroll-anchor.test.ts b/src/web/src/hooks/community/use-scroll-anchor.test.ts
index 78c959c0f..129184024 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.test.ts
@@ -197,10 +197,10 @@ describe("decideScrollAction — self-send / peer-follow (both hand-rolled — f
expect(action).toEqual({ type: "none" })
})
- it("temp-id → server-id reconcile: tail id changes via reconcileServerId but author/content/position are otherwise unchanged — resolves as an idempotent self-send, not a misclassified no-op", () => {
+ it("temp-id → canonical-id identity reconcile: tail id changes but author/content/position are otherwise unchanged — resolves as an idempotent self-send, not a misclassified no-op", () => {
// Simulates: viewer sent a message (tempId "temp_123"), it's already the
- // tail, then the server responds and `reconcileServerId` swaps the id to
- // the real server id ("srv_abc") — same author, same position, nothing
+ // tail, then postAck advances the id to the canonical server id
+ // ("srv_abc") — same author, same position, nothing
// about scroll position should change, but the tail id STRING changed.
// With getItemKey keyed on message id, this is a bigger structural event
// for the virtualizer than it was for raw DOM (the item's key changes) —
diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.ts
index 69f61b31f..bc1f4b6e8 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.ts
@@ -224,11 +224,10 @@ export function decideScrollAction(input: DecideScrollActionInput): DecideScroll
const tail = messages[messages.length - 1]
const isSelfSend = !!viewerUserId && tail?.authorId === viewerUserId
if (isSelfSend) {
- // Always follow — handles the composer path and, incidentally, the
- // optimistic temp-id → server-id reconcile (the tail id string
- // changes via `reconcileServerId` on send success, but the author is
- // still the viewer, so this branch still catches it as an idempotent
- // self-send snap, not a misclassified no-op).
+ // Always follow — handles the composer path and the overlay identity
+ // advance on postAck (temp id → canonical server id). The author remains
+ // the viewer, so this branch treats that id change as an idempotent
+ // self-send snap rather than a peer append.
return { action: { type: "scrollToEnd" }, nextState: liveState }
}
// Peer send: only follow if the loaded window is tail-attached to the
diff --git a/src/web/src/lib/community/message-stream.test.ts b/src/web/src/lib/community/message-stream.test.ts
index 1d768a3c6..8a2d2e6cd 100644
--- a/src/web/src/lib/community/message-stream.test.ts
+++ b/src/web/src/lib/community/message-stream.test.ts
@@ -341,32 +341,61 @@ describe("attachment ownership effects", () => {
])
})
- it("keeps one attachment intent across upload + ack and revokes URLs once on WS reconciliation", () => {
+ it("transfers attachment preview ownership on ack and never revokes twice on WS/base/clear", () => {
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, {
+ const acked = 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([
+ })
+ expect(acked.effects).toEqual([
{ type: "revokeObjectUrl", url: "blob:a" },
{ type: "revokeObjectUrl", url: "blob:b" },
])
- expect(first.state.outboxByNonce.size).toBe(0)
+ expect(acked.state.outboxByNonce.get("files")?.localUploads).toEqual([])
+ expect(acked.state.outboxByNonce.get("files")?.message.attachments).toEqual([
+ { kind: "file", name: "notes.txt", url: "/media/notes", size: "1 KB" },
+ ])
+
+ const ws = apply(acked.state, { type: "wsMessage", message: canonical("mf", 20, "files") })
+ expect(ws.effects).toEqual([])
+ expect(ws.state.outboxByNonce.size).toBe(0)
+ const base = apply(ws.state, { type: "baseChanged", messages: [canonical("mf", 20, "files")] })
+ expect(base.effects).toEqual([])
+ const cleared = apply(base.state, { type: "clear" })
+ expect(cleared.effects).toEqual([])
- const replay = apply(first.state, { type: "wsMessage", message: canonical("mf", 20, "files") })
+ const replay = apply(cleared.state, { type: "wsMessage", message: canonical("mf", 20, "files") })
expect(replay.effects).toEqual([])
expect(ids([], replay.state)).toEqual(["mf"])
})
+ it("revokes once when WS wins before ack, while postFail keeps previews owned", () => {
+ const submitted = submit(emptyMessageOverlay(), attachedIntent())
+ const failed = apply(submitted, { type: "postFail", nonce: "files" })
+ expect(failed.effects).toEqual([])
+ expect(failed.state.outboxByNonce.get("files")?.localUploads).toHaveLength(3)
+
+ const ws = apply(submitted, { type: "wsMessage", message: canonical("mf", 20, "files") })
+ expect(ws.effects).toEqual([
+ { type: "revokeObjectUrl", url: "blob:a" },
+ { type: "revokeObjectUrl", url: "blob:b" },
+ ])
+ const lateAck = apply(ws.state, {
+ type: "postAck",
+ nonce: "files",
+ serverMessageId: "mf",
+ serverSeq: 20,
+ })
+ expect(lateAck.effects).toEqual([])
+ })
+
it("retains upload failure across retry and only dismisses explicitly", () => {
let state = submit(emptyMessageOverlay(), attachedIntent())
state = apply(state, { type: "uploadFailed", nonce: "files" }).state
@@ -387,16 +416,29 @@ describe("attachment ownership effects", () => {
expect(dismissed.state.outboxByNonce.size).toBe(0)
})
+ it("terminally rejects a confirmed non-commit and revokes owned URLs once", () => {
+ const state = submit(emptyMessageOverlay(), attachedIntent())
+ const rejected = apply(state, { type: "terminalReject", nonce: "files" })
+
+ expect(rejected.state.outboxByNonce.size).toBe(0)
+ expect(rejected.effects).toEqual([
+ { type: "revokeObjectUrl", url: "blob:a" },
+ { type: "revokeObjectUrl", url: "blob:b" },
+ ])
+ expect(apply(rejected.state, { type: "terminalReject", nonce: "files" }).effects).toEqual([])
+ })
+
it("emits cleanup exactly once for canonical base absorption and clear", () => {
- let state = submit(emptyMessageOverlay(), attachedIntent())
- state = apply(state, {
+ const state = submit(emptyMessageOverlay(), attachedIntent())
+ const acked = 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)
+ })
+ expect(acked.effects).toHaveLength(2)
+ const absorbed = apply(acked.state, { type: "baseChanged", messages: [canonical("mf", 20, "files")] })
+ expect(absorbed.effects).toEqual([])
const absorbedAgain = apply(absorbed.state, { type: "baseChanged", messages: [canonical("mf", 20, "files")] })
expect(absorbedAgain.effects).toEqual([])
diff --git a/src/web/src/lib/community/message-stream.ts b/src/web/src/lib/community/message-stream.ts
index 7ad33f2d5..e4ad52af5 100644
--- a/src/web/src/lib/community/message-stream.ts
+++ b/src/web/src/lib/community/message-stream.ts
@@ -65,6 +65,7 @@ export type MessageOverlayEvent =
| { type: "uploadFailed"; nonce: string }
| { type: "postAck"; nonce: string; serverMessageId: string; serverSeq: number }
| { type: "postFail"; nonce: string }
+ | { type: "terminalReject"; nonce: string }
| { type: "retry"; nonce: string }
| { type: "wsMessage"; message: CanonicalMessage }
| { type: "liveRefreshed"; message: CanonicalMessage }
@@ -289,14 +290,23 @@ export function reduceMessageOverlay(
message: { ...intent.message, failed: true },
}))
- case "postAck":
- return updateIntent(state, event.nonce, (intent) => ({
+ case "postAck": {
+ const intent = state.outboxByNonce.get(event.nonce)
+ if (!intent) return unchanged(state)
+ const outboxByNonce = new Map(state.outboxByNonce)
+ outboxByNonce.set(event.nonce, {
...intent,
status: "acked",
serverMessageId: event.serverMessageId,
serverSeq: event.serverSeq,
+ localUploads: [],
message: { ...intent.message, failed: false },
- }))
+ })
+ return {
+ state: { ...state, outboxByNonce },
+ effects: revokeEffects(intent),
+ }
+ }
case "postFail":
return updateIntent(state, event.nonce, (intent) => ({
@@ -305,6 +315,17 @@ export function reduceMessageOverlay(
message: { ...intent.message, failed: true },
}))
+ case "terminalReject": {
+ const intent = state.outboxByNonce.get(event.nonce)
+ if (!intent) return unchanged(state)
+ const outboxByNonce = new Map(state.outboxByNonce)
+ outboxByNonce.delete(event.nonce)
+ return {
+ state: { ...state, outboxByNonce },
+ effects: revokeEffects(intent),
+ }
+ }
+
case "retry":
return updateIntent(state, event.nonce, (intent) => ({
...intent,
diff --git a/src/web/src/test/e2e-ui/04-dm.spec.ts b/src/web/src/test/e2e-ui/04-dm.spec.ts
index 2072d2f02..7612fd90f 100644
--- a/src/web/src/test/e2e-ui/04-dm.spec.ts
+++ b/src/web/src/test/e2e-ui/04-dm.spec.ts
@@ -17,7 +17,24 @@ test.describe.serial("direct messages", () => {
await alice.page.waitForURL(new RegExp(dmId), { timeout: 20_000 , waitUntil: "commit" })
const body = `dm hello ${Date.now()}`
+ const responsePromise = alice.page.waitForResponse((response) => {
+ const pathname = new URL(response.url()).pathname
+ return response.request().method() === "POST"
+ && pathname === `/api/community/dm/${dmId}/messages`
+ })
await sendMessage(alice.page, body)
+ const response = await responsePromise
+ expect(response.status()).toBe(201)
+ const payload = await response.json() as { message: { id: string; seq: number } }
+ expect(payload.message.seq).toBeGreaterThan(0)
+ await expect(alice.page.getByTestId(tid.message(payload.message.id))).toHaveCount(1)
+ await expect(alice.page.getByTestId(tid.composerInput)).toHaveText("")
+
+ // Revisit through the DM index. The accepted row must remain canonical
+ // exactly once while the base query catches up to the session overlay.
+ await alice.page.goto("/c/me", { waitUntil: "commit" })
+ await alice.page.goto(`/c/me/${dmId}`, { waitUntil: "commit" })
+ await expect(alice.page.getByTestId(tid.message(payload.message.id))).toHaveCount(1)
// Bob's DM sidebar row shows the new conversation without a manual reload.
await expect(bob.page.getByTestId(tid.dmRow(dmId))).toBeVisible({ timeout: 15_000 })
@@ -26,6 +43,7 @@ test.describe.serial("direct messages", () => {
// lag, so give the body a generous window rather than the default.
await bob.page.waitForURL(new RegExp(dmId), { timeout: 20_000 , waitUntil: "commit" })
await expect(bob.page.getByText(body, { exact: false }).first()).toBeVisible({ timeout: 20_000 })
+ await expect(bob.page.getByTestId(tid.message(payload.message.id))).toHaveCount(1)
})
test("blocking replaces the composer with a blocked notice", async ({ asUser }) => {