Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): keep picker reactions add-only (#770)

Gener4a1188f674f4
diff --git a/src/web/src/app/c/me/[dmId]/page.test.ts b/src/web/src/app/c/me/[dmId]/page.test.ts
index a61376784..887121df5 100644
--- a/src/web/src/app/c/me/[dmId]/page.test.ts
+++ b/src/web/src/app/c/me/[dmId]/page.test.ts
@@ -29,4 +29,12 @@ describe("DM page loading ownership", () => {
expect(source).toContain("channelRefCandidateSource={channelRefCandidateSource}")
expect(source).toContain("onChannelRefIntent={handleChannelRefIntent}")
})
+
+ it("keeps chip toggle and picker add on separate reaction intents", () => {
+ const source = readFileSync(new URL("./page.tsx", import.meta.url), "utf8")
+ expect(source).toContain("const toggleReaction = useToggleReactionApi()")
+ expect(source).toContain("const addReaction = useAddReactionApi()")
+ expect(source).toContain("onToggleReaction: (id: string, emoji: string) =>\n toggleReaction(")
+ expect(source).toContain("onReact: (id: string, emoji: string) =>\n addReaction(")
+ })
})
diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsx
index b1c0907a7..06eff4b61 100644
--- a/src/web/src/app/c/me/[dmId]/page.tsx
+++ b/src/web/src/app/c/me/[dmId]/page.tsx
@@ -31,6 +31,7 @@ import { useDmWatermark } from "@/hooks/community/use-dm-watermark"
import { useChannelRefDirectory } from "@/hooks/community/use-channel-ref-directory"
import { toChannelRefCandidate } from "@/lib/community/channel-ref-extension"
import {
+ useAddReactionApi,
useToggleReactionApi,
useToggleMark,
} from "@/hooks/community/mutations"
@@ -289,6 +290,7 @@ function DmView() {
const typingNames = useTypingNamesForScope(`dm:${dmId}`)
const { accept: acceptDmMessage, retry: retryDmMessage } = useDmMessageSender()
const toggleReaction = useToggleReactionApi()
+ const addReaction = useAddReactionApi()
const toggleMark = useToggleMark()
const goBack = useCallback(() => { uiHandlers.goBackMobile?.() }, [uiHandlers])
@@ -367,7 +369,7 @@ function DmView() {
onToggleReaction: (id: string, emoji: string) =>
toggleReaction({ dmId, messageId: id, emoji, userId: currentUser.id }),
onReact: (id: string, emoji: string) =>
- toggleReaction({ dmId, messageId: id, emoji, userId: currentUser.id }),
+ addReaction({ dmId, messageId: id, emoji, userId: currentUser.id }),
onReply: (id: string) => {
const m = messages.find((x) => x.id === id)
if (m) {
@@ -406,7 +408,7 @@ function DmView() {
onPreviewAttachment: (attachment: FileAttachment) => {
uiHandlers.previewAttachment?.(attachment)
},
- }), [toggleReaction, toggleMark, dmId, currentUser.id, messages, retryDmMessage, uiHandlers, advanceOnboardingAfterSend])
+ }), [toggleReaction, addReaction, toggleMark, dmId, currentUser.id, messages, retryDmMessage, uiHandlers, advanceOnboardingAfterSend])
// DM endpoint ignores mentionType. Replies are supported β€” the backend
// persists replyToId for DMs too.
diff --git a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts
index 974165adc..8d0912122 100644
--- a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts
+++ b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts
@@ -251,6 +251,7 @@ vi.mock("@/stores/community/ws", () => ({
vi.mock("@/hooks/community/mutations", () => ({
useSendMessage: () => ({ mutateAsync: vi.fn() }),
useToggleReactionApi: () => vi.fn(),
+ useAddReactionApi: () => vi.fn(),
usePinMessage: () => ({ mutate: vi.fn() }),
useUnpinMessage: () => ({ mutate: vi.fn() }),
useToggleMark: () => vi.fn(),
diff --git a/src/web/src/components/community/channels/text-channel-surface.dom.test.ts b/src/web/src/components/community/channels/text-channel-surface.dom.test.ts
index 571606971..dbd5cb909 100644
--- a/src/web/src/components/community/channels/text-channel-surface.dom.test.ts
+++ b/src/web/src/components/community/channels/text-channel-surface.dom.test.ts
@@ -14,6 +14,7 @@ import { useMessageStreamStore } from "@/stores/community/message-stream"
const mutationMocks = vi.hoisted(() => ({
sendMessage: vi.fn(),
toggleReaction: vi.fn(),
+ addReaction: vi.fn(),
pinMessage: vi.fn(),
unpinMessage: vi.fn(),
toggleMark: vi.fn(),
@@ -79,6 +80,7 @@ vi.mock("@/stores/community", () => {
vi.mock("@/hooks/community/mutations", () => ({
useSendMessage: () => ({ mutateAsync: mutationMocks.sendMessage }),
useToggleReactionApi: () => mutationMocks.toggleReaction,
+ useAddReactionApi: () => mutationMocks.addReaction,
usePinMessage: () => ({ mutate: mutationMocks.pinMessage }),
useUnpinMessage: () => ({ mutate: mutationMocks.unpinMessage }),
useToggleMark: () => mutationMocks.toggleMark,
diff --git a/src/web/src/components/community/messages/message-channel-controller-actions.test.ts b/src/web/src/components/community/messages/message-channel-controller-actions.test.ts
index 22cf0e914..41b9f525e 100644
--- a/src/web/src/components/community/messages/message-channel-controller-actions.test.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-actions.test.ts
@@ -18,6 +18,7 @@ vi.mock("@alook/shared", () => ({ deriveThreadName: mocks.deriveThreadName }))
function setup() {
const setReplyTo = vi.fn()
const toggleReactionApi = vi.fn()
+ const addReactionApi = vi.fn()
const unpinMessageMutate = vi.fn()
const pinMessageMutate = vi.fn()
const toggleMark = vi.fn()
@@ -52,6 +53,7 @@ function setup() {
viewerUserId: "viewer_1",
setReplyTo,
toggleReactionApi,
+ addReactionApi,
unpinMessageMutate,
pinMessageMutate,
toggleMark,
@@ -65,6 +67,7 @@ function setup() {
actionContext,
setReplyTo,
toggleReactionApi,
+ addReactionApi,
unpinMessageMutate,
pinMessageMutate,
toggleMark,
@@ -94,9 +97,10 @@ describe("createMessageActions", () => {
expect(harness.toggleReactionApi).toHaveBeenNthCalledWith(1, {
serverId: "server_1", channelId: "channel_1", messageId: "m1", emoji: "πŸ‘", userId: "viewer_1",
})
- expect(harness.toggleReactionApi).toHaveBeenNthCalledWith(2, {
+ expect(harness.addReactionApi).toHaveBeenCalledWith({
serverId: "server_1", channelId: "channel_1", messageId: "m1", emoji: "πŸ”₯", userId: "viewer_1",
})
+ expect(harness.toggleReactionApi).toHaveBeenCalledOnce()
harness.actions.onMark("m1")
expect(harness.toggleMark).toHaveBeenCalledWith("channel_1", "m1")
harness.actions.onPreviewImage({ url: "image" })
diff --git a/src/web/src/components/community/messages/message-channel-controller-actions.ts b/src/web/src/components/community/messages/message-channel-controller-actions.ts
index 3759fd1a2..9d689cd72 100644
--- a/src/web/src/components/community/messages/message-channel-controller-actions.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-actions.ts
@@ -38,6 +38,7 @@ export function createMessageActions({
viewerUserId,
setReplyTo,
toggleReactionApi,
+ addReactionApi,
unpinMessageMutate,
pinMessageMutate,
toggleMark,
@@ -58,6 +59,13 @@ export function createMessageActions({
emoji: string
userId: string
}) => void
+ addReactionApi: (input: {
+ serverId: string
+ channelId: string
+ messageId: string
+ emoji: string
+ userId: string
+ }) => void
unpinMessageMutate: (
input: { channelId: string; messageId: string },
options?: MutationOptions,
@@ -84,7 +92,7 @@ export function createMessageActions({
onToggleReaction: (id, emoji) =>
toggleReactionApi({ serverId, channelId, messageId: id, emoji, userId: viewerUserId }),
onReact: (id, emoji) =>
- toggleReactionApi({ serverId, channelId, messageId: id, emoji, userId: viewerUserId }),
+ addReactionApi({ serverId, channelId, messageId: id, emoji, userId: viewerUserId }),
onReply: (id) => {
const message = actionContext.current.messages.find((item) => item.id === id)
if (message) {
diff --git a/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts b/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts
index 5463cf61a..28432c766 100644
--- a/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts
@@ -130,6 +130,7 @@ describe("MessageChannelController facade contract", () => {
"const [contextTarget, setContextTarget] = useState<MessageContextTarget | null>(null)",
"useSendMessage()",
"useToggleReactionApi()",
+ "useAddReactionApi()",
"usePinMessage()",
"useUnpinMessage()",
"useToggleMark()",
diff --git a/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts b/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts
index 19a692be2..8e68a0a68 100644
--- a/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts
@@ -37,6 +37,7 @@ const mocks = vi.hoisted(() => {
seq: null as string | null,
sendMutation: vi.fn(),
reactionMutation: vi.fn(),
+ addReactionMutation: vi.fn(),
pinMutation: vi.fn(),
unpinMutation: vi.fn(),
markMutation: vi.fn(),
@@ -85,6 +86,7 @@ vi.mock("@/stores/community", () => {
vi.mock("@/hooks/community/mutations", () => ({
useSendMessage: () => { mocks.order.push("send"); return { mutateAsync: mocks.sendMutation } },
useToggleReactionApi: () => { mocks.order.push("reaction"); return mocks.reactionMutation },
+ useAddReactionApi: () => { mocks.order.push("reaction-add"); return mocks.addReactionMutation },
usePinMessage: () => { mocks.order.push("pin"); return { mutate: mocks.pinMutation } },
useUnpinMessage: () => { mocks.order.push("unpin"); return { mutate: mocks.unpinMutation } },
useToggleMark: () => { mocks.order.push("mark"); return mocks.markMutation },
@@ -164,8 +166,8 @@ describe("useMessageChannelController", () => {
const valueProps = props()
let renderer: ReturnType<typeof rtlRender>
act(() => { renderer = rtlRender(React.createElement(Probe, { value: valueProps })) })
- expect(mocks.order.slice(0, 11)).toEqual([
- "send", "reaction", "pin", "unpin", "mark", "edit", "thread", "upload",
+ expect(mocks.order.slice(0, 12)).toEqual([
+ "send", "reaction", "reaction-add", "pin", "unpin", "mark", "edit", "thread", "upload",
"typing-users", "typing-names", "pending-store",
])
expect(mocks.typingScopes.users.length).toBeGreaterThan(0)
diff --git a/src/web/src/components/community/messages/message-channel-controller-state.ts b/src/web/src/components/community/messages/message-channel-controller-state.ts
index 060466237..1fd056697 100644
--- a/src/web/src/components/community/messages/message-channel-controller-state.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-state.ts
@@ -14,6 +14,7 @@ import {
useTypingUsersForScope,
} from "@/stores/community"
import {
+ useAddReactionApi,
useCreateThread,
useEditMessage,
usePinMessage,
@@ -63,6 +64,7 @@ export function useMessageChannelController({
const [contextTarget, setContextTarget] = useState<MessageContextTarget | null>(null)
const { mutateAsync: sendMessageAsync } = useSendMessage()
const toggleReactionApi = useToggleReactionApi()
+ const addReactionApi = useAddReactionApi()
const { mutate: pinMessageMutate } = usePinMessage()
const { mutate: unpinMessageMutate } = useUnpinMessage()
const toggleMark = useToggleMark()
@@ -230,6 +232,7 @@ export function useMessageChannelController({
viewerUserId: viewer.id,
setReplyTo,
toggleReactionApi,
+ addReactionApi,
unpinMessageMutate,
pinMessageMutate,
toggleMark,
@@ -242,6 +245,7 @@ export function useMessageChannelController({
serverId,
viewer.id,
toggleReactionApi,
+ addReactionApi,
unpinMessageMutate,
pinMessageMutate,
toggleMark,
diff --git a/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.ts b/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.ts
index af2d8eeec..1a55156f5 100644
--- a/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.ts
+++ b/src/web/src/components/community/messages/message-context-sheet.navigation.dom.test.ts
@@ -7,6 +7,11 @@ const mocks = vi.hoisted(() => ({
close: vi.fn(),
openThread: undefined as undefined | ((threadId: string) => void),
pin: undefined as undefined | ((messageId: string) => void),
+ toggleReaction: undefined as undefined | ((messageId: string, emoji: string) => void),
+ addReaction: undefined as undefined | ((messageId: string, emoji: string) => void),
+ toggleReactionApi: vi.fn(),
+ addReactionApi: vi.fn(),
+ setQueryData: vi.fn(),
pinMutate: vi.fn(),
unpinMutate: vi.fn(),
toastApiError: vi.fn(),
@@ -35,7 +40,19 @@ vi.mock("@tanstack/react-query", () => ({
isLoading: false,
isError: false,
}),
- useQueryClient: () => ({ setQueryData: vi.fn() }),
+ useQueryClient: () => ({
+ getQueryData: () => ({
+ notFound: false,
+ anchorId: "message_1",
+ messages: [{
+ id: "message_1",
+ seq: 1,
+ type: "chat",
+ reactions: [],
+ }],
+ }),
+ setQueryData: mocks.setQueryData,
+ }),
}))
vi.mock("@/components/community/shell/community-sheet", () => ({
CommunitySheet: ({ children }: { children: React.ReactNode }) => children,
@@ -53,12 +70,18 @@ vi.mock("./message-row", () => ({
MessageRow: ({
onOpenThread,
onPinId,
+ onToggleReactionId,
+ onReactId,
}: {
onOpenThread: (threadId: string) => void
onPinId?: (messageId: string) => void
+ onToggleReactionId?: (messageId: string, emoji: string) => void
+ onReactId?: (messageId: string, emoji: string) => void
}) => {
mocks.openThread = onOpenThread
mocks.pin = onPinId
+ mocks.toggleReaction = onToggleReactionId
+ mocks.addReaction = onReactId
return null
},
}))
@@ -76,6 +99,8 @@ vi.mock("@/hooks/community/mutations", () => ({
useUnpinMessage: () => ({ mutate: mocks.unpinMutate }),
useCreateThread: () => ({ mutateAsync: vi.fn() }),
useToggleMark: () => vi.fn(),
+ useToggleReactionApi: () => mocks.toggleReactionApi,
+ useAddReactionApi: () => mocks.addReactionApi,
}))
vi.mock("sonner", () => ({ toast: vi.fn() }))
vi.mock("@/lib/api/client", () => ({ apiFetch: vi.fn(), toastApiError: mocks.toastApiError }))
@@ -90,6 +115,8 @@ describe("MessageContextSheet thread navigation", () => {
vi.clearAllMocks()
mocks.openThread = undefined
mocks.pin = undefined
+ mocks.toggleReaction = undefined
+ mocks.addReaction = undefined
})
it("opens a rendered channel thread by its flat child id and closes the sheet", () => {
@@ -126,6 +153,39 @@ describe("MessageContextSheet thread navigation", () => {
expect(close).not.toHaveBeenCalled()
})
+ it("routes chips to toggle and picker choices to add through the sheet cache", () => {
+ render(React.createElement(MessageContextSheet, {
+ open: true,
+ onOpenChange: mocks.close,
+ channelId: "parent_1",
+ targetSeq: 1,
+ }))
+
+ act(() => mocks.toggleReaction?.("message_1", "πŸ‘"))
+ act(() => mocks.addReaction?.("message_1", "πŸ”₯"))
+
+ expect(mocks.toggleReactionApi).toHaveBeenCalledWith(expect.objectContaining({
+ channelId: "parent_1",
+ messageId: "message_1",
+ emoji: "πŸ‘",
+ currentMe: false,
+ skipDefaultCache: true,
+ syncReactionState: expect.any(Function),
+ }))
+ expect(mocks.addReactionApi).toHaveBeenCalledWith(expect.objectContaining({
+ channelId: "parent_1",
+ messageId: "message_1",
+ emoji: "πŸ”₯",
+ currentMe: false,
+ skipDefaultCache: true,
+ syncReactionState: expect.any(Function),
+ }))
+
+ const syncReactionState = mocks.addReactionApi.mock.calls[0]?.[0].syncReactionState
+ act(() => syncReactionState(true))
+ expect(mocks.setQueryData).toHaveBeenCalledWith(expect.anything(), expect.any(Function))
+ })
+
it("exposes preview Pin only to managers and opens pinned only after success", () => {
const onOpenPinned = vi.fn()
const member = render(React.createElement(MessageContextSheet, {
diff --git a/src/web/src/components/community/messages/message-context-sheet.reaction-coordinator.dom.test.ts b/src/web/src/components/community/messages/message-context-sheet.reaction-coordinator.dom.test.ts
new file mode 100644
index 000000000..5b36d7730
--- /dev/null
+++ b/src/web/src/components/community/messages/message-context-sheet.reaction-coordinator.dom.test.ts
@@ -0,0 +1,210 @@
+import React from "react"
+import { act, render } from "@/test/react-dom-harness"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+
+const mocks = vi.hoisted(() => {
+ const state = {
+ cache: undefined as undefined | {
+ notFound: boolean
+ anchorId: string
+ messages: Array<Record<string, unknown>>
+ },
+ renderSnapshot: undefined as undefined | {
+ notFound: boolean
+ anchorId: string
+ messages: Array<Record<string, unknown>>
+ },
+ }
+ const queryClient = {
+ getQueryData: vi.fn(() => state.cache),
+ setQueryData: vi.fn((_key: unknown, updater: unknown) => {
+ state.cache = typeof updater === "function"
+ ? updater(state.cache)
+ : updater as typeof state.cache
+ return state.cache
+ }),
+ }
+ return {
+ state,
+ queryClient,
+ apiFetch: vi.fn(),
+ toastApiError: vi.fn(),
+ onToggle: undefined as undefined | ((messageId: string, emoji: string) => void),
+ onAdd: undefined as undefined | ((messageId: string, emoji: string) => void),
+ }
+})
+
+vi.mock("next/navigation", () => ({
+ useParams: () => ({ serverId: "server_1" }),
+ useRouter: () => ({ push: vi.fn() }),
+}))
+vi.mock("@tanstack/react-query", async () => {
+ const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query")
+ return {
+ ...actual,
+ useQuery: () => ({
+ data: mocks.state.renderSnapshot,
+ isLoading: false,
+ isError: false,
+ }),
+ useQueryClient: () => mocks.queryClient,
+ }
+})
+vi.mock("@/components/community/shell/community-sheet", () => ({
+ CommunitySheet: ({ children }: { children: React.ReactNode }) => children,
+}))
+vi.mock("./message-row", () => ({
+ MessageRow: ({
+ onToggleReactionId,
+ onReactId,
+ }: {
+ onToggleReactionId?: (messageId: string, emoji: string) => void
+ onReactId?: (messageId: string, emoji: string) => void
+ }) => {
+ mocks.onToggle = onToggleReactionId
+ mocks.onAdd = onReactId
+ return null
+ },
+}))
+vi.mock("./message-share-dialog", () => ({ MessageShareDialog: () => null }))
+vi.mock("../channels/channel-icon", () => ({ ChannelIcon: () => null }))
+vi.mock("@/components/ui/skeleton", () => ({ Skeleton: () => null }))
+vi.mock("../dividers", () => ({ DateDivider: () => null }))
+vi.mock("@/contexts/community/current-user", () => ({
+ useCurrentUser: () => ({ id: "viewer_1" }),
+}))
+vi.mock("@/stores/community", async () => {
+ const actual = await vi.importActual<typeof import("@/stores/community")>("@/stores/community")
+ return { ...actual, useUiHandlers: () => ({}) }
+})
+vi.mock("@/hooks/use-hover-capable", () => ({ useHoverCapable: () => true }))
+vi.mock("@/hooks/community/mutations", async () => {
+ const reactions = await vi.importActual<typeof import("@/hooks/community/mutations/messages")>(
+ "@/hooks/community/mutations/messages",
+ )
+ return {
+ useToggleReactionApi: reactions.useToggleReactionApi,
+ useAddReactionApi: reactions.useAddReactionApi,
+ usePinMessage: () => ({ mutate: vi.fn() }),
+ useUnpinMessage: () => ({ mutate: vi.fn() }),
+ useCreateThread: () => ({ mutateAsync: vi.fn() }),
+ useToggleMark: () => vi.fn(),
+ }
+})
+vi.mock("sonner", () => ({ toast: vi.fn() }))
+vi.mock("@/lib/api/client", () => ({
+ apiFetch: (...args: unknown[]) => mocks.apiFetch(...args),
+ toastApiError: (...args: unknown[]) => mocks.toastApiError(...args),
+}))
+
+import { useCommunityStore } from "@/stores/community"
+import { MessageContextSheet } from "./message-context-sheet"
+
+function sheetCache(me: boolean) {
+ return {
+ notFound: false,
+ anchorId: "message_1",
+ messages: [{
+ id: "message_1",
+ seq: 1,
+ type: "chat",
+ authorId: "author_1",
+ authorName: "Author",
+ content: "Message",
+ createdAt: "2026-09-11T00:00:00.000Z",
+ reactions: me
+ ? [{ emoji: "πŸ‘", count: 1, me: true, userIds: ["viewer_1"] }]
+ : [],
+ }],
+ }
+}
+
+function renderSheet(me: boolean) {
+ const initial = sheetCache(me)
+ mocks.state.cache = initial
+ mocks.state.renderSnapshot = initial
+ return render(React.createElement(MessageContextSheet, {
+ open: true,
+ onOpenChange: vi.fn(),
+ channelId: "channel_1",
+ targetSeq: 1,
+ }))
+}
+
+function currentMe() {
+ const reactions = mocks.state.cache?.messages[0]?.reactions as Array<{ emoji: string; me: boolean }>
+ return reactions.find((reaction) => reaction.emoji === "πŸ‘")?.me ?? false
+}
+
+describe("MessageContextSheet reaction coordinator", () => {
+ beforeEach(() => {
+ vi.useFakeTimers()
+ vi.clearAllMocks()
+ mocks.onToggle = undefined
+ mocks.onAdd = undefined
+ const timers = useCommunityStore.getState().reactionTimers
+ for (const { timer } of timers.values()) clearTimeout(timer)
+ timers.clear()
+ })
+
+ afterEach(() => {
+ const timers = useCommunityStore.getState().reactionTimers
+ for (const { timer } of timers.values()) clearTimeout(timer)
+ timers.clear()
+ vi.useRealTimers()
+ })
+
+ it("repeats picker add without a rerender and preserves the first timer deadline", async () => {
+ mocks.apiFetch.mockResolvedValue(undefined)
+ renderSheet(false)
+
+ act(() => mocks.onAdd?.("message_1", "πŸ‘"))
+ const timerKey = "message_1:πŸ‘"
+ const firstPending = useCommunityStore.getState().reactionTimers.get(timerKey)
+ const firstWriteCount = mocks.queryClient.setQueryData.mock.calls.length
+ expect(currentMe()).toBe(true)
+ expect(firstPending).toBeDefined()
+
+ await act(async () => { await vi.advanceTimersByTimeAsync(150) })
+ act(() => mocks.onAdd?.("message_1", "πŸ‘"))
+ expect(mocks.queryClient.setQueryData).toHaveBeenCalledTimes(firstWriteCount)
+ expect(useCommunityStore.getState().reactionTimers.get(timerKey)).toBe(firstPending)
+
+ await act(async () => { await vi.advanceTimersByTimeAsync(150) })
+ expect(mocks.apiFetch).toHaveBeenCalledTimes(1)
+ expect(mocks.apiFetch).toHaveBeenCalledWith(
+ expect.stringContaining("/api/community/messages/message_1/reactions/"),
+ { method: "PUT" },
+ )
+ })
+
+ it("coalesces chip remove then picker add without a rerender to zero requests", async () => {
+ renderSheet(true)
+
+ act(() => mocks.onToggle?.("message_1", "πŸ‘"))
+ expect(currentMe()).toBe(false)
+ act(() => mocks.onAdd?.("message_1", "πŸ‘"))
+
+ expect(currentMe()).toBe(true)
+ expect(useCommunityStore.getState().reactionTimers.size).toBe(0)
+ await act(async () => { await vi.advanceTimersByTimeAsync(500) })
+ expect(mocks.apiFetch).not.toHaveBeenCalled()
+ })
+
+ it("rolls a failed add back and emits one error toast", async () => {
+ const error = new Error("boom")
+ mocks.apiFetch.mockRejectedValueOnce(error)
+ renderSheet(false)
+
+ act(() => mocks.onAdd?.("message_1", "πŸ‘"))
+ expect(currentMe()).toBe(true)
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(300)
+ await Promise.resolve()
+ })
+
+ expect(currentMe()).toBe(false)
+ expect(mocks.toastApiError).toHaveBeenCalledOnce()
+ expect(mocks.toastApiError).toHaveBeenCalledWith(error, "Failed to update reaction")
+ })
+})
diff --git a/src/web/src/components/community/messages/message-context-sheet.tsx b/src/web/src/components/community/messages/message-context-sheet.tsx
index f074f1243..b1ab02c04 100644
--- a/src/web/src/components/community/messages/message-context-sheet.tsx
+++ b/src/web/src/components/community/messages/message-context-sheet.tsx
@@ -18,7 +18,15 @@ import { formatDateLabel } from "@/lib/community/format-time"
import { DateDivider } from "../dividers"
import { useCurrentUser } from "@/contexts/community/current-user"
import { useUiHandlers } from "@/stores/community"
-import { usePinMessage, useUnpinMessage, useCreateThread, useToggleMark } from "@/hooks/community/mutations"
+import {
+ useAddReactionApi,
+ useCreateThread,
+ usePinMessage,
+ useToggleMark,
+ useToggleReactionApi,
+ useUnpinMessage,
+ type ReactionArgs,
+} from "@/hooks/community/mutations"
import type { FileAttachment, ImagePreview, MessagesPage, Msg, Reaction, RenderMsg } from "@/lib/community/models/message"
import type { OpenProfile } from "@/components/community/social/profile-types"
import { useHoverCapable } from "@/hooks/use-hover-capable"
@@ -177,6 +185,8 @@ export function MessageContextSheet({
const unpinMessageMut = useUnpinMessage()
const createThreadMut = useCreateThread()
const toggleMark = useToggleMark()
+ const toggleReactionApi = useToggleReactionApi()
+ const addReactionApi = useAddReactionApi()
const queryKey = useMemo(
() => communityKeys.messageContext(type, channelId, targetSeq),
@@ -238,24 +248,38 @@ export function MessageContextSheet({
[query.data],
)
- const toggleReaction = useCallback((messageId: string, emoji: string) => {
- const msg = findMessage(messageId)
+ const runReactionIntent = useCallback((
+ intent: (args: ReactionArgs) => void,
+ messageId: string,
+ emoji: string,
+ ) => {
+ const msg = queryClient.getQueryData<SheetCache>(queryKey)
+ ?.messages?.find((message) => message.id === messageId)
if (!msg) return
- const wasMe = msg.reactions?.find((r) => r.emoji === emoji)?.me ?? false
- const nextMe = !wasMe
- // Optimistic β€” flip immediately on the sheet's own cache.
- queryClient.setQueryData<SheetCache>(queryKey, (c) =>
- toggleSheetReaction(c, messageId, emoji, currentUser.id, nextMe),
- )
- const method = wasMe ? "DELETE" : "PUT"
- const url = `/api/community/messages/${messageId}/reactions/${encodeURIComponent(emoji)}`
- apiFetch(url, { method }).catch((e) => {
- queryClient.setQueryData<SheetCache>(queryKey, (c) =>
- toggleSheetReaction(c, messageId, emoji, currentUser.id, wasMe),
- )
- toastApiError(e, "Failed to update reaction")
+ const currentMe = msg.reactions?.find((r) => r.emoji === emoji)?.me ?? false
+ intent({
+ ...(type === "dm" ? { dmId: channelId } : { channelId }),
+ messageId,
+ emoji,
+ userId: currentUser.id,
+ currentMe,
+ skipDefaultCache: true,
+ syncReactionState: (me) => {
+ queryClient.setQueryData<SheetCache>(queryKey, (c) =>
+ toggleSheetReaction(c, messageId, emoji, currentUser.id, me),
+ )
+ },
+ onError: (error) => toastApiError(error, "Failed to update reaction"),
})
- }, [queryKey, queryClient, currentUser.id, findMessage])
+ }, [channelId, currentUser.id, queryClient, queryKey, type])
+
+ const toggleReaction = useCallback((messageId: string, emoji: string) => {
+ runReactionIntent(toggleReactionApi, messageId, emoji)
+ }, [runReactionIntent, toggleReactionApi])
+
+ const addReaction = useCallback((messageId: string, emoji: string) => {
+ runReactionIntent(addReactionApi, messageId, emoji)
+ }, [addReactionApi, runReactionIntent])
const onCopyId = useCallback((id: string) => {
const m = findMessage(id)
@@ -442,7 +466,7 @@ export function MessageContextSheet({
onOpenThread={type === "channel" ? onOpenThreadId : undefined}
resolveUserName={resolveUserName}
onToggleReaction={toggleReaction}
- onReact={toggleReaction}
+ onReact={addReaction}
onReply={onReply ? onReplyId : undefined}
onCopy={onCopyId}
onPin={type === "channel" && canManagePins ? onPinId : undefined}
diff --git a/src/web/src/hooks/community/mutations/messages.test.ts b/src/web/src/hooks/community/mutations/messages.test.ts
index 52285b5ca..ab792483d 100644
--- a/src/web/src/hooks/community/mutations/messages.test.ts
+++ b/src/web/src/hooks/community/mutations/messages.test.ts
@@ -598,13 +598,155 @@ describe("useSendMessage β€” no blocked branch on channel path", () => {
})
})
-// ── useToggleReactionApi β€” the #9 300ms debounce ────────────────────────
+// ── Reaction intent coordinator β€” the #9 300ms debounce ────────────────
//
// Old context (context.tsx:1061-1130) captured `originalMe` at first click,
// scheduled the API in a 300ms timer, and either replaced or cancelled the
// timer on subsequent clicks. Step 3's hook dropped the coalescing; this
// restores it via useCommunityStore.reactionTimers.
-describe("useToggleReactionApi β€” 300ms debounce coalescing", () => {
+describe("reaction intents β€” 300ms debounce coalescing", () => {
+ it("keeps the add-only action stable across renders with a stable query client", async () => {
+ const mod = await loadMod()
+ callbackCounter = 0
+ const first = mod.useAddReactionApi()
+ callbackCounter = 0
+ const second = mod.useAddReactionApi()
+ expect(second).toBe(first)
+ })
+
+ it("treats add on me=true as a strict cache, timer, and network no-op", async () => {
+ vi.useFakeTimers()
+ try {
+ capturedQc.setQueryData(communityKeys.channelMessages("ch_1"), {
+ pages: [{ messages: [{
+ id: "m_1",
+ reactions: [{ emoji: "πŸ‘", count: 1, me: true, userIds: ["u_me"] }],
+ }], hasMore: false }],
+ pageParams: [null],
+ })
+ const mod = await loadMod()
+ mod._resetReactionTimers_forTesting()
+ const cacheWrite = vi.spyOn(capturedQc, "setQueryData")
+ const schedule = vi.spyOn(globalThis, "setTimeout")
+ const syncReactionState = vi.fn()
+
+ mod.useAddReactionApi()({
+ channelId: "ch_1",
+ messageId: "m_1",
+ emoji: "πŸ‘",
+ userId: "u_me",
+ syncReactionState,
+ })
+
+ const { useCommunityStore } = await import("@/stores/community")
+ expect(cacheWrite).not.toHaveBeenCalled()
+ expect(schedule).not.toHaveBeenCalled()
+ expect(syncReactionState).not.toHaveBeenCalled()
+ expect(useCommunityStore.getState().reactionTimers.size).toBe(0)
+ await vi.advanceTimersByTimeAsync(500)
+ expect(apiFetchMock).not.toHaveBeenCalled()
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it("does not rewrite cache or postpone the first PUT when add is repeated", async () => {
+ vi.useFakeTimers()
+ try {
+ capturedQc.setQueryData(communityKeys.channelMessages("ch_1"), {
+ pages: [{ messages: [{ id: "m_1", reactions: [] }], hasMore: false }],
+ pageParams: [null],
+ })
+ apiFetchMock.mockResolvedValue(undefined)
+ const mod = await loadMod()
+ mod._resetReactionTimers_forTesting()
+ const add = mod.useAddReactionApi()
+ const cacheWrite = vi.spyOn(capturedQc, "setQueryData")
+
+ add({ channelId: "ch_1", messageId: "m_1", emoji: "πŸ‘", userId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ const firstPending = useCommunityStore.getState().reactionTimers.get("m_1:πŸ‘")
+ const firstWriteCount = cacheWrite.mock.calls.length
+ expect(firstPending).toBeDefined()
+
+ await vi.advanceTimersByTimeAsync(150)
+ add({ channelId: "ch_1", messageId: "m_1", emoji: "πŸ‘", userId: "u_me" })
+ expect(cacheWrite).toHaveBeenCalledTimes(firstWriteCount)
+ expect(useCommunityStore.getState().reactionTimers.get("m_1:πŸ‘")).toBe(firstPending)
+
+ await vi.advanceTimersByTimeAsync(150)
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ expect.stringContaining("/api/community/messages/m_1/reactions/"),
+ { method: "PUT" },
+ )
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it("coalesces chip remove followed by picker add to the original state and zero requests", async () => {
+ vi.useFakeTimers()
+ try {
+ capturedQc.setQueryData(communityKeys.channelMessages("ch_1"), {
+ pages: [{ messages: [{
+ id: "m_1",
+ reactions: [{ emoji: "πŸ‘", count: 1, me: true, userIds: ["u_me"] }],
+ }], hasMore: false }],
+ pageParams: [null],
+ })
+ const mod = await loadMod()
+ mod._resetReactionTimers_forTesting()
+ const toggle = mod.useToggleReactionApi()
+ const add = mod.useAddReactionApi()
+
+ toggle({ channelId: "ch_1", messageId: "m_1", emoji: "πŸ‘", userId: "u_me" })
+ add({ channelId: "ch_1", messageId: "m_1", emoji: "πŸ‘", userId: "u_me" })
+
+ const cache = capturedQc.getQueryData<{ pages: { messages: Msg[] }[] }>(
+ communityKeys.channelMessages("ch_1"),
+ )
+ const { useCommunityStore } = await import("@/stores/community")
+ expect(cache?.pages[0].messages[0].reactions).toEqual([
+ { emoji: "πŸ‘", count: 1, me: true, userIds: ["u_me"] },
+ ])
+ expect(useCommunityStore.getState().reactionTimers.size).toBe(0)
+ await vi.advanceTimersByTimeAsync(500)
+ expect(apiFetchMock).not.toHaveBeenCalled()
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it("drives an additional cache through optimistic add and rollback", async () => {
+ vi.useFakeTimers()
+ try {
+ apiFetchMock.mockRejectedValueOnce(new Error("boom"))
+ const mod = await loadMod()
+ mod._resetReactionTimers_forTesting()
+ const syncReactionState = vi.fn()
+ const onError = vi.fn()
+
+ mod.useAddReactionApi()({
+ dmId: "dm_1",
+ messageId: "m_dm",
+ emoji: "πŸ”₯",
+ userId: "u_me",
+ currentMe: false,
+ syncReactionState,
+ onError,
+ })
+ expect(syncReactionState).toHaveBeenCalledWith(true)
+
+ await vi.advanceTimersByTimeAsync(300)
+ await Promise.resolve()
+ expect(syncReactionState).toHaveBeenLastCalledWith(false)
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: "boom" }))
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
it("optimistically patches and rolls back a thread opener's single-message cache", 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 8ce386d39..04e231c9d 100644
--- a/src/web/src/hooks/community/mutations/messages.ts
+++ b/src/web/src/hooks/community/mutations/messages.ts
@@ -392,18 +392,24 @@ export function useSendDmMessage() {
})
}
-// ── Toggle reaction ────────────────────────────────────────────────────────
+// ── Reaction intents ──────────────────────────────────────────────────────
-export type ToggleReactionArgs = {
+export type ReactionArgs = {
serverId?: string
channelId?: string
dmId?: string
messageId: string
emoji: string
userId: string
+ currentMe?: boolean
+ skipDefaultCache?: boolean
+ syncReactionState?: (me: boolean) => void
+ onError?: (error: unknown) => void
}
-// Apply an optimistic reaction toggle to any page cache that contains the
+type ReactionIntent = "toggle" | "add"
+
+// Apply an optimistic reaction state to any page cache that contains the
// message. This mirrors the reducer in the God-context.
function togglePageCacheReaction(
cache: PageCache | undefined,
@@ -473,7 +479,7 @@ function toggleSingleMessageReaction<T extends { reactions?: Msg["reactions"] }>
: message
}
-function messageScope(args: ToggleReactionArgs): MessageScope | undefined {
+function messageScope(args: ReactionArgs): MessageScope | undefined {
if (args.channelId && args.serverId) {
return { kind: "channel", id: args.channelId, serverId: args.serverId }
}
@@ -493,7 +499,7 @@ function currentMaterializedMessage(
function refreshExistingReactionFallback(
cache: PageCache | undefined,
- args: ToggleReactionArgs,
+ args: ReactionArgs,
add: boolean,
): void {
const scope = messageScope(args)
@@ -538,8 +544,8 @@ export function _resetReactionTimers_forTesting() {
}
/**
- * Practical toggle-reaction callback. Because the fetch verb (`PUT`/`DELETE`)
- * depends on the pre-toggle `me` state, we express the pattern here as a
+ * Coordinated reaction-intent callback. Because the fetch verb (`PUT`/`DELETE`)
+ * depends on the original `me` state, we express the pattern here as a
* stable closure that (a) writes the optimistic toggle synchronously, (b)
* schedules the fetch behind a 300ms debounce keyed by `${messageId}:${emoji}`
* so rapid re-clicks collapse to one request measured against the *original*
@@ -549,9 +555,9 @@ export function _resetReactionTimers_forTesting() {
* `reset()` (fired on sign-out) clears any outstanding timers before they can
* hit an already-torn-down cache.
*/
-export function useToggleReactionApi(): (args: ToggleReactionArgs) => void {
+function useReactionApi(intent: ReactionIntent): (args: ReactionArgs) => void {
const queryClient = useQueryClient()
- return useCallback((args: ToggleReactionArgs) => {
+ return useCallback((args: ReactionArgs) => {
const key = args.channelId
? communityKeys.channelMessages(args.channelId)
: args.dmId
@@ -564,21 +570,25 @@ export function useToggleReactionApi(): (args: ToggleReactionArgs) => void {
const source = scope
? currentMaterializedMessage(cache, scope, args.messageId)
: undefined
- const wasMe = source
+ const wasMe = args.currentMe ?? (source
? source.reactions?.find((reaction) => reaction.emoji === args.emoji)?.me ?? false
: singleMessage
? singleMessage.reactions?.find((reaction) => reaction.emoji === args.emoji)?.me ?? false
- : currentMeStatus(cache, args.messageId, args.emoji)
- const nextMe = !wasMe
+ : currentMeStatus(cache, args.messageId, args.emoji))
+ if (intent === "add" && wasMe) return
+ const nextMe = intent === "add" ? true : !wasMe
// Optimistic write is always synchronous β€” the debounce only defers the
// API call, not the visible UI.
- queryClient.setQueryData<PageCache>(key, (c) =>
- togglePageCacheReaction(c, args.messageId, args.emoji, args.userId, nextMe),
- )
- queryClient.setQueryData(messageKey, (message: typeof singleMessage) =>
- toggleSingleMessageReaction(message, args.emoji, args.userId, nextMe),
- )
- refreshExistingReactionFallback(queryClient.getQueryData<PageCache>(key), args, nextMe)
+ if (!args.skipDefaultCache) {
+ queryClient.setQueryData<PageCache>(key, (c) =>
+ togglePageCacheReaction(c, args.messageId, args.emoji, args.userId, nextMe),
+ )
+ queryClient.setQueryData(messageKey, (message: typeof singleMessage) =>
+ toggleSingleMessageReaction(message, args.emoji, args.userId, nextMe),
+ )
+ refreshExistingReactionFallback(queryClient.getQueryData<PageCache>(key), args, nextMe)
+ }
+ args.syncReactionState?.(nextMe)
const timerKey = `${args.messageId}:${args.emoji}`
const reactionTimers = useCommunityStore.getState().reactionTimers
@@ -601,19 +611,31 @@ export function useToggleReactionApi(): (args: ToggleReactionArgs) => void {
reactionTimers.delete(timerKey)
const method = originalMe ? "DELETE" : "PUT"
const url = `/api/community/messages/${args.messageId}/reactions/${encodeURIComponent(args.emoji)}`
- apiFetch(url, { method }).catch(() => {
+ apiFetch(url, { method }).catch((error) => {
// Roll back to the original server state on failure.
- queryClient.setQueryData<PageCache>(key, (c) =>
- togglePageCacheReaction(c, args.messageId, args.emoji, args.userId, originalMe),
- )
- queryClient.setQueryData(messageKey, (message: typeof singleMessage) =>
- toggleSingleMessageReaction(message, args.emoji, args.userId, originalMe),
- )
- refreshExistingReactionFallback(queryClient.getQueryData<PageCache>(key), args, originalMe)
+ if (!args.skipDefaultCache) {
+ queryClient.setQueryData<PageCache>(key, (c) =>
+ togglePageCacheReaction(c, args.messageId, args.emoji, args.userId, originalMe),
+ )
+ queryClient.setQueryData(messageKey, (message: typeof singleMessage) =>
+ toggleSingleMessageReaction(message, args.emoji, args.userId, originalMe),
+ )
+ refreshExistingReactionFallback(queryClient.getQueryData<PageCache>(key), args, originalMe)
+ }
+ args.syncReactionState?.(originalMe)
+ args.onError?.(error)
})
}, REACTION_DEBOUNCE_MS)
reactionTimers.set(timerKey, { timer, originalMe })
- }, [queryClient])
+ }, [intent, queryClient])
+}
+
+export function useToggleReactionApi(): (args: ReactionArgs) => void {
+ return useReactionApi("toggle")
+}
+
+export function useAddReactionApi(): (args: ReactionArgs) => void {
+ return useReactionApi("add")
}
// ── Pin / unpin ────────────────────────────────────────────────────────────