Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
refactor(web): add community WS projection transactions (#518)
Generd7475d388212
diff --git a/src/web/src/hooks/community/community-ws/channel-scope-projection.ts b/src/web/src/hooks/community/community-ws/channel-scope-projection.tsnew file mode 100644index 000000000..10789a408--- /dev/null+++ b/src/web/src/hooks/community/community-ws/channel-scope-projection.ts@@ -0,0 +1,58 @@+import type { QueryClient } from "@tanstack/react-query"+import { communityKeys } from "@/lib/query-keys"+import type { ServerDetail } from "@/hooks/community/use-servers"+import { useCommunityStore } from "@/stores/community"+import { useMessageStreamStore } from "@/stores/community/message-stream"+import {+ isKnownNonForumSidebarChannel,+ removeForumSidebarChildrenForParent,+ removeForumSidebarThreadExact,+ removeForumSidebarUnreadChild,+} from "@/hooks/community/use-forum-sidebar-threads"+import type { CommunityWsProjectionTransaction } from "./projection-transaction"++export function projectChannelScopeEviction(+ projection: CommunityWsProjectionTransaction,+ queryClient: QueryClient,+ serverId: string,+ channelId: string,+) {+ projection.project(() => {+ const nonForum = isKnownNonForumSidebarChannel(queryClient, serverId, channelId)+ if (!nonForum) {+ removeForumSidebarUnreadChild(queryClient, serverId, channelId)+ removeForumSidebarChildrenForParent(queryClient, serverId, channelId)+ removeForumSidebarThreadExact(queryClient, serverId, channelId)+ } else {+ queryClient.removeQueries({+ queryKey: communityKeys.channelMeta(serverId, channelId),+ exact: true,+ })+ }+ queryClient.setQueryData<ServerDetail | undefined>(+ communityKeys.server(serverId),+ (server) => {+ if (!server) return server+ let changed = false+ const categories = server.categories.map((category) => {+ const channels = category.channels.filter((channel) => channel.id !== channelId)+ if (channels.length === category.channels.length) return category+ changed = true+ return { ...category, channels }+ })+ return changed ? { ...server, categories } : server+ },+ )+ if (useCommunityStore.getState().currentChannelId === channelId) {+ useCommunityStore.getState().setCurrentChannelMeta(null)+ }+ useMessageStreamStore.getState().removeScope({+ kind: "channel",+ id: channelId,+ serverId,+ })+ queryClient.removeQueries({ queryKey: communityKeys.channelMessages(channelId) })+ queryClient.removeQueries({ queryKey: communityKeys.pins(channelId) })+ queryClient.removeQueries({ queryKey: communityKeys.threads(channelId) })+ })+}diff --git a/src/web/src/hooks/community/community-ws/handler-context.ts b/src/web/src/hooks/community/community-ws/handler-context.tsindex c1256dff3..57bc818a4 100644--- a/src/web/src/hooks/community/community-ws/handler-context.ts+++ b/src/web/src/hooks/community/community-ws/handler-context.ts@@ -1,6 +1,7 @@import type { QueryClient } from "@tanstack/react-query"import type { useCommunityStore } from "@/stores/community"import type { useCommunityWsStore } from "@/stores/community/ws"+import type { CommunityWsProjectionTransaction } from "@/hooks/community/community-ws/projection-transaction"export type Subscription = {// The focused regular channel/thread.@@ -20,7 +21,7 @@ export type UseCommunityWsOptions = {viewerUserId?: string | null}-export type CommunityWsHandlerContext = {+export type CommunityWsDispatchContext = {queryClient: QueryClientcommunityStore: ReturnType<typeof useCommunityStore.getState>wsStore: ReturnType<typeof useCommunityWsStore.getState>@@ -30,6 +31,10 @@ export type CommunityWsHandlerContext = {scheduleInboxInvalidate: () => void}+export type CommunityWsHandlerContext = CommunityWsDispatchContext & {+ projection: CommunityWsProjectionTransaction+}+export type MessageEventContext = CommunityWsHandlerContextexport type TypingEventContext = Pick<CommunityWsHandlerContext,@@ -37,15 +42,15 @@ export type TypingEventContext = Pick<>export type StructureTreeEventContext = Pick<CommunityWsHandlerContext,- "queryClient"+ "queryClient" | "projection">export type MembershipEventContext = Pick<CommunityWsHandlerContext,- "queryClient" | "viewerUserIdRef"+ "queryClient" | "viewerUserIdRef" | "projection">export type SocialEventContext = Pick<CommunityWsHandlerContext,- "queryClient" | "sub" | "viewerUserIdRef"+ "queryClient" | "sub" | "viewerUserIdRef" | "projection">export type PresenceMachineEventContext = Pick<CommunityWsHandlerContext,diff --git a/src/web/src/hooks/community/community-ws/invalidation-projections.ts b/src/web/src/hooks/community/community-ws/invalidation-projections.tsnew file mode 100644index 000000000..db32fbc38--- /dev/null+++ b/src/web/src/hooks/community/community-ws/invalidation-projections.ts@@ -0,0 +1,127 @@+import { communityKeys } from "@/lib/query-keys"+import type { CommunityWsProjectionTransaction } from "./projection-transaction"++export function invalidateChannelRefDirectory(+ projection: CommunityWsProjectionTransaction,+) {+ projection.invalidate("channel-ref-directory", {+ queryKey: communityKeys.channelRefDirectory(),+ exact: true,+ })+}++export function invalidateServerDetail(+ projection: CommunityWsProjectionTransaction,+ serverId: string,+) {+ projection.invalidate("server-detail", {+ queryKey: communityKeys.server(serverId),+ exact: true,+ })+}++export function invalidateServersList(+ projection: CommunityWsProjectionTransaction,+) {+ projection.invalidate("servers-list", {+ queryKey: communityKeys.servers(),+ exact: true,+ })+}++export function invalidateChannelMembers(+ projection: CommunityWsProjectionTransaction,+ channelId: string,+) {+ projection.invalidate("channel-members", {+ queryKey: communityKeys.channelMembers(channelId),+ })+}++export function invalidateChannelRoster(+ projection: CommunityWsProjectionTransaction,+ channelId: string,+) {+ invalidateChannelMembers(projection, channelId)+ projection.invalidate("channel-addable-members", {+ queryKey: communityKeys.channelAddableMembers(channelId),+ })+ projection.invalidate("thread-participants", {+ queryKey: communityKeys.threadParticipants(channelId),+ })+}++export function invalidateThreads(+ projection: CommunityWsProjectionTransaction,+ channelId: string,+) {+ projection.invalidate("threads", {+ queryKey: communityKeys.threads(channelId),+ })+}++export function invalidateChannelMessages(+ projection: CommunityWsProjectionTransaction,+ channelId: string,+) {+ projection.invalidate("channel-messages", {+ queryKey: communityKeys.channelMessages(channelId),+ })+}++export function invalidatePins(+ projection: CommunityWsProjectionTransaction,+ channelId: string,+) {+ projection.invalidate("pins", {+ queryKey: communityKeys.pins(channelId),+ })+}++export function invalidateFriends(+ projection: CommunityWsProjectionTransaction,+) {+ projection.invalidate("friends", { queryKey: communityKeys.friends() })+}++export function invalidateInbox(+ projection: CommunityWsProjectionTransaction,+) {+ projection.invalidate("inbox", { queryKey: communityKeys.inbox() })+}++export function invalidateDms(+ projection: CommunityWsProjectionTransaction,+) {+ projection.invalidate("dms", { queryKey: communityKeys.dms() })+}++export function invalidatePresence(+ projection: CommunityWsProjectionTransaction,+ serverId: string,+) {+ projection.invalidate("presence", {+ queryKey: communityKeys.presence(serverId),+ exact: true,+ refetchType: "active",+ })+}++export function invalidateInvitableFriends(+ projection: CommunityWsProjectionTransaction,+ serverId: string,+) {+ projection.invalidate("invitable-friends", {+ queryKey: communityKeys.invitableFriends(serverId),+ })+}++export function invalidateInvites(+ projection: CommunityWsProjectionTransaction,+ serverId: string,+) {+ projection.invalidate("invites", {+ queryKey: communityKeys.invites(serverId),+ exact: true,+ })+}diff --git a/src/web/src/hooks/community/community-ws/membership-events.test.ts b/src/web/src/hooks/community/community-ws/membership-events.test.tsindex 9db655552..d730c02d5 100644--- a/src/web/src/hooks/community/community-ws/membership-events.test.ts+++ b/src/web/src/hooks/community/community-ws/membership-events.test.ts@@ -338,6 +338,55 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",).toBe(true)})+ it("does not evict channel scope when another user is removed", async () => {+ await mountHook({ viewerUserId: "u_me" })+ const serverKey = communityKeys.server("srv_1")+ const messagesKey = communityKeys.channelMessages("ch_1")+ const pinsKey = communityKeys.pins("ch_1")+ const threadsKey = communityKeys.threads("ch_1")+ capturedQueryClient.setQueryData(messagesKey, { pages: [], pageParams: [] })+ capturedQueryClient.setQueryData(pinsKey, { pins: [] })+ capturedQueryClient.setQueryData(threadsKey, { threads: [] })+ capturedQueryClient.setQueryData(serverKey, {+ id: "srv_1",+ categories: [{ id: "cat_1", channels: [{ id: "ch_1", type: "text" }] }],+ })++ capturedOnMessage!({+ type: "community:channel.member_remove",+ serverId: "srv_1",+ channelId: "ch_1",+ userId: "u_other",+ })++ expect(capturedQueryClient.getQueryState(messagesKey)).toBeDefined()+ expect(capturedQueryClient.getQueryState(pinsKey)).toBeDefined()+ expect(capturedQueryClient.getQueryState(threadsKey)).toBeDefined()+ expect(capturedQueryClient.getQueryData<{+ categories: { channels: { id: string }[] }[]+ }>(serverKey)?.categories[0].channels).toEqual([{ id: "ch_1", type: "text" }])+ })++ it("removes a private channel from the viewer's server tree on access loss", async () => {+ await mountHook({ viewerUserId: "u_me" })+ const serverKey = communityKeys.server("srv_1")+ capturedQueryClient.setQueryData(serverKey, {+ id: "srv_1",+ categories: [{ id: "cat_1", channels: [{ id: "ch_1", type: "text" }] }],+ })++ capturedOnMessage!({+ type: "community:channel.member_remove",+ serverId: "srv_1",+ channelId: "ch_1",+ userId: "u_me",+ })++ expect(capturedQueryClient.getQueryData<{+ categories: { channels: { id: string }[] }[]+ }>(serverKey)?.categories[0].channels).toEqual([])+ })+it("adds/removes the viewer's participating child in the forum sidebar", async () => {await mountHook({ viewerUserId: "u_me" })const { useCommunityStore } = await import("@/stores/community")diff --git a/src/web/src/hooks/community/community-ws/membership-events.ts b/src/web/src/hooks/community/community-ws/membership-events.tsindex 09ee9bd3c..6de0f2633 100644--- a/src/web/src/hooks/community/community-ws/membership-events.ts+++ b/src/web/src/hooks/community/community-ws/membership-events.ts@@ -18,12 +18,18 @@ import {import {grantForumSidebarChild,isKnownNonForumSidebarChannel,- removeForumSidebarChildrenForParent,- removeForumSidebarThreadExact,- removeForumSidebarUnreadChild,} from "@/hooks/community/use-forum-sidebar-threads"import { patchAuthorNameInCache, type PageCache } from "@/hooks/community/community-ws/cache"import type { MembershipEventContext } from "@/hooks/community/community-ws/handler-context"+import { projectChannelScopeEviction } from "./channel-scope-projection"+import {+ invalidateChannelRefDirectory,+ invalidateChannelRoster,+ invalidateInvitableFriends,+ invalidatePresence,+ invalidateServerDetail,+ invalidateServersList,+} from "./invalidation-projections"type ChannelMemberEvent = Extract<CommunityWsEvent,@@ -32,7 +38,7 @@ type ChannelMemberEvent = Extract<export function handleChannelMemberEvent(event: ChannelMemberEvent,- { queryClient, viewerUserIdRef }: MembershipEventContext,+ { queryClient, viewerUserIdRef, projection }: MembershipEventContext,) {// Re-run the viewer-scoped server tree so the sidebar gains/loses the// private channel. On REMOVE for the viewer, evict that channel's@@ -42,32 +48,12 @@ export function handleChannelMemberEvent(event.type === "community:channel.member_remove" &&event.userId === viewerUserIdRef.current) {- const nonForum = isKnownNonForumSidebarChannel(+ projectChannelScopeEviction(+ projection,queryClient,event.serverId,event.channelId,)- if (!nonForum) {- removeForumSidebarUnreadChild(queryClient, event.serverId, event.channelId)- removeForumSidebarChildrenForParent(queryClient, event.serverId, event.channelId)- removeForumSidebarThreadExact(queryClient, event.serverId, event.channelId)- } else {- queryClient.removeQueries({- queryKey: communityKeys.channelMeta(event.serverId, event.channelId),- exact: true,- })- }- if (useCommunityStore.getState().currentChannelId === event.channelId) {- useCommunityStore.getState().setCurrentChannelMeta(null)- }- useMessageStreamStore.getState().removeScope({- kind: "channel",- id: event.channelId,- serverId: event.serverId,- })- queryClient.removeQueries({ queryKey: communityKeys.channelMessages(event.channelId) })- queryClient.removeQueries({ queryKey: communityKeys.pins(event.channelId) })- queryClient.removeQueries({ queryKey: communityKeys.threads(event.channelId) })} else if (event.type === "community:channel.member_add" &&event.userId === viewerUserIdRef.current@@ -76,38 +62,28 @@ export function handleChannelMemberEvent(void grantForumSidebarChild(queryClient, event.serverId, event.channelId)}}- void queryClient.invalidateQueries({- queryKey: communityKeys.server(event.serverId),- exact: true,- })- void queryClient.invalidateQueries({- queryKey: communityKeys.channelRefDirectory(),- exact: true,- })+ invalidateServerDetail(projection, event.serverId)+ invalidateChannelRefDirectory(projection)// Refetch the channel roster so an open private-channel Members drawer// (and the manage-members dialog) reflect the add/remove live.- void queryClient.invalidateQueries({ queryKey: communityKeys.channelMembers(event.channelId) })// The addable-members candidate pool is the complement of the roster —// a peer's add/remove changes it too, so an open add dialog doesn't// offer a just-added member (whose Add would 400) or hide a removed one.- void queryClient.invalidateQueries({ queryKey: communityKeys.channelAddableMembers(event.channelId) })// A forum thread's "Add participant" emits this same MEMBER_ADD event —// its Members panel is the participant set, so refetch it too. No-op// for a plain channel (participants query disabled there).- void queryClient.invalidateQueries({ queryKey: communityKeys.threadParticipants(event.channelId) })+ invalidateChannelRoster(projection, event.channelId)}function finishMemberEvent(event: CommunityMemberJoin | CommunityMemberLeave | CommunityMemberUpdate,- { queryClient }: MembershipEventContext,+ { projection }: MembershipEventContext,) {// Membership just changed → the invite dialog's "friends who aren't// in this server" list is stale. Cheap invalidation because the// query is disabled unless the dialog is actually open.if (event.type !== "community:member.update") {- void queryClient.invalidateQueries({- queryKey: communityKeys.invitableFriends(event.serverId),- })+ invalidateInvitableFriends(projection, event.serverId)}}@@ -115,7 +91,7 @@ export function handleMemberJoin(event: CommunityMemberJoin,context: MembershipEventContext,) {- const { queryClient, viewerUserIdRef } = context+ const { queryClient, viewerUserIdRef, projection } = contextconst key = communityKeys.members(event.serverId)queryClient.setQueryData<InfiniteData<MembersEnvelope> | undefined>(key,@@ -125,24 +101,11 @@ export function handleMemberJoin(// MEMBER_JOIN intentionally carries identity, not presence. Refresh the// affected server's authoritative presence seed so a newly rendered member// does not inherit the offline fallback until the next presence frame.- void queryClient.invalidateQueries({- queryKey: communityKeys.presence(event.serverId),- exact: true,- refetchType: "active",- })+ invalidatePresence(projection, event.serverId)if (event.member.userId === viewerUserIdRef.current) {- void queryClient.invalidateQueries({- queryKey: communityKeys.channelRefDirectory(),- exact: true,- })- void queryClient.invalidateQueries({- queryKey: communityKeys.servers(),- exact: true,- })- void queryClient.invalidateQueries({- queryKey: communityKeys.server(event.serverId),- exact: true,- })+ invalidateChannelRefDirectory(projection)+ invalidateServersList(projection)+ invalidateServerDetail(projection, event.serverId)}finishMemberEvent(event, context)}@@ -151,7 +114,7 @@ export function handleMemberLeave(event: CommunityMemberLeave,context: MembershipEventContext,) {- const { queryClient, viewerUserIdRef } = context+ const { queryClient, viewerUserIdRef, projection } = contextconst key = communityKeys.members(event.serverId)queryClient.setQueryData<InfiniteData<MembersEnvelope> | undefined>(key,@@ -167,10 +130,7 @@ export function handleMemberLeave(// so the layout's eject effect can detect the drop and route// the user away from the now-forbidden URL.if (event.userId === viewerUserIdRef.current) {- void queryClient.invalidateQueries({- queryKey: communityKeys.channelRefDirectory(),- exact: true,- })+ invalidateChannelRefDirectory(projection)useMessageStreamStore.getState().removeServer(event.serverId)queryClient.removeQueries({ queryKey: communityKeys.server(event.serverId) })const store = useCommunityStore.getState()@@ -182,7 +142,7 @@ export function handleMemberLeave(// Rail LIST only (the layout's eject effect reads it to route the// kicked viewer away). `exact` so a kick doesn't cascade-refetch// every server's nested detail subtree.- void queryClient.invalidateQueries({ queryKey: communityKeys.servers(), exact: true })+ invalidateServersList(projection)}finishMemberEvent(event, context)}diff --git a/src/web/src/hooks/community/community-ws/message-events.test.ts b/src/web/src/hooks/community/community-ws/message-events.test.tsindex 4b0eff522..184b50741 100644--- a/src/web/src/hooks/community/community-ws/message-events.test.ts+++ b/src/web/src/hooks/community/community-ws/message-events.test.ts@@ -599,6 +599,37 @@ describe("useCommunityWs — reactions", () => {{ emoji: "👍", count: 1, me: true, userIds: ["u_me"] },])})++ it("refreshes a focused channel row that exists only in the overlay", async () => {+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().subscribe({ channelId: "ch_1" })+ await mountHook({ viewerUserId: "u_me" })+ const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }+ useMessageStreamStore.getState().dispatch(scope, {+ type: "wsMessage",+ message: {+ id: "m_channel",+ seq: 4,+ type: "chat",+ authorId: "u_other",+ authorName: "Other",+ content: "hi",+ reactions: [],+ },+ })++ capturedOnMessage!({+ type: "community:reaction.add",+ channelId: "ch_1",+ messageId: "m_channel",+ userId: "u_me",+ emoji: "👍",+ })++ expect(getMessageOverlay(scope).liveById.get("m_channel")?.reactions).toEqual([+ { emoji: "👍", count: 1, me: true, userIds: ["u_me"] },+ ])+ })})describe("useCommunityWs — message.updated", () => {@@ -631,6 +662,34 @@ describe("useCommunityWs — message.updated", () => {expect(getMessageOverlay({ kind: "dm", id: "dm_1" }).liveById.get("m_dm")?.approval).toEqual(approval)})++ it("refreshes approval fields on a focused channel row that exists only in the overlay", async () => {+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().subscribe({ channelId: "ch_1" })+ await mountHook()+ const scope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }+ useMessageStreamStore.getState().dispatch(scope, {+ type: "wsMessage",+ message: { id: "m_channel", 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: "ch_1",+ messageId: "m_channel",+ approval,+ })++ expect(getMessageOverlay(scope).liveById.get("m_channel")?.approval).toEqual(approval)+ })})describe("useCommunityWs — pin.add", () => {@@ -767,6 +826,9 @@ describe("useCommunityWs — message edit refreshes forum opener summary", () =>threads: [{ id: "post_1", name: "old title", openerMessageId: "opener-post_1" }],})capturedOnMessage!(opener)+ expect(capturedQueryClient.getQueryData<{ content: string }>(+ communityKeys.message("opener-post_1"),+ )?.content).toBe("old title")await vi.waitFor(() => expect(invalidateSpy).toHaveBeenCalledWith({queryKey: communityKeys.threads("forum_1"), exact: true,}))@@ -787,6 +849,43 @@ describe("useCommunityWs — message edit refreshes forum opener summary", () =>} satisfies CommunityMessageEdited)expect(invalidateSpy).not.toHaveBeenCalled()})++ it("patches loaded ordinary channel copies and only the matching stream scope", async () => {+ await mountHook()+ const matchingScope = { kind: "channel" as const, id: "ch_1", serverId: "s1" }+ const otherScope = { kind: "channel" as const, id: "ch_2", serverId: "s1" }+ const message = {+ id: "m_1",+ seq: 4,+ type: "chat" as const,+ content: "old",+ }+ capturedQueryClient.setQueryData(communityKeys.channelMessages("ch_1"), {+ pages: [{ messages: [message], hasMore: false }],+ pageParams: [null],+ })+ useMessageStreamStore.getState().dispatch(matchingScope, {+ type: "wsMessage",+ message,+ })+ useMessageStreamStore.getState().dispatch(otherScope, {+ type: "wsMessage",+ message,+ })++ capturedOnMessage!({+ type: "community:message.edited",+ channelId: "ch_1",+ messageId: "m_1",+ content: "new",+ } satisfies CommunityMessageEdited)++ expect(capturedQueryClient.getQueryData<{+ pages: { messages: { content: string }[] }[]+ }>(communityKeys.channelMessages("ch_1"))?.pages[0].messages[0].content).toBe("new")+ expect(getMessageOverlay(matchingScope).liveById.get("m_1")?.content).toBe("new")+ expect(getMessageOverlay(otherScope).liveById.get("m_1")?.content).toBe("old")+ })})describe("useCommunityWs — does NOT auto-mark-read on WS message.create", () => {diff --git a/src/web/src/hooks/community/community-ws/message-events.ts b/src/web/src/hooks/community/community-ws/message-events.tsindex 885251190..e791e84df 100644--- a/src/web/src/hooks/community/community-ws/message-events.ts+++ b/src/web/src/hooks/community/community-ws/message-events.ts@@ -7,12 +7,9 @@ import type {CommunityReactionRemove,CommunityWsEvent,} from "@alook/shared"-import { communityKeys } from "@/lib/query-keys"import { projectCommunityMessageCreate } from "@/lib/community/message-wire"-import type { CanonicalMessage } from "@/lib/community/message-stream"-import type { Msg } from "@/lib/community/models/message"import { useCommunityStore } from "@/stores/community"-import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"+import { useMessageStreamStore } from "@/stores/community/message-stream"import {getForumSidebarBase,hasForumSidebarThread,@@ -21,17 +18,19 @@ import {patchForumSidebarActivityExact,} from "@/hooks/community/use-forum-sidebar-threads"import { reconcileForumOpenerTitle } from "@/hooks/community/forum-opener-title-reconciliation"-import {- applyReactionToCache,- applyReactionToMessage,- findCachedMessage,- patchApprovalInCache,- patchMessageContentInCache,- type PageCache,-} from "@/hooks/community/community-ws/cache"import { clearTypingIndicator, typingScopeKey } from "@/hooks/community/community-ws/typing"import type { MessageEventContext } from "@/hooks/community/community-ws/handler-context"import { scheduleFocusedMessageGapRepair } from "@/hooks/community/community-ws/reconnect-messages"+import {+ projectApprovalCopies,+ projectEditedCopies,+ projectReactionCopies,+} from "@/hooks/community/community-ws/message-projections"+import {+ invalidateChannelMembers,+ invalidateFriends,+ invalidatePins,+} from "@/hooks/community/community-ws/invalidation-projections"type CommunityMessageEdited = Extract<CommunityWsEvent,@@ -47,6 +46,7 @@ export function handleMessageCreate(sub,viewerUserIdRef,scheduleInboxInvalidate,+ projection,}: MessageEventContext,) {const projected = projectCommunityMessageCreate(event.message)@@ -117,9 +117,7 @@ export function handleMessageCreate(communityStore.currentChannelId === event.channelId &&communityStore.currentChannelMeta?.parentChannelId) {- void queryClient.invalidateQueries({- queryKey: communityKeys.channelMembers(event.channelId),- })+ invalidateChannelMembers(projection, event.channelId)}// 2) Every message.create — regardless of focus — schedules a@@ -146,131 +144,39 @@ export function handleMessageCreate(}-type ReactionEvent = CommunityReactionAdd | CommunityReactionRemove-export function handleReactionEvent(- event: ReactionEvent,- { queryClient, viewerUserIdRef, sub }: MessageEventContext,+ event: CommunityReactionAdd | CommunityReactionRemove,+ context: MessageEventContext,) {- const viewerId = viewerUserIdRef.current- // A reaction event carries only `channelId` with no channel-vs-DM- // discriminator. A regular channel's cache lives under- // `channelMessages(id)`, a DM channel's under `dmMessages(id)` — patch- // both keys; the one that doesn't exist receives `undefined` and the- // updater returns it, a harmless no-op.- queryClient.setQueriesData<PageCache>(- { queryKey: communityKeys.channelMessages(event.channelId) },- (c) => applyReactionToCache(c, event, viewerId),- )- queryClient.setQueryData<PageCache>(- communityKeys.dmMessages(event.channelId),- (c) => applyReactionToCache(c, event, viewerId),- )- queryClient.setQueryData<Msg | undefined>(- communityKeys.message(event.messageId),- (message) => message ? applyReactionToMessage(message, event, viewerId) : message,- )- if (event.channelId === sub.channelId) {- const serverId = useCommunityStore.getState().currentServerId- if (serverId) {- const scope = { kind: "channel" as const, id: event.channelId, serverId }- const fallback = [...getMessageOverlay(scope).liveById.values()]- .find((message) => message.id === event.messageId)- if (fallback) {- const cached = findCachedMessage(- queryClient.getQueryData<PageCache>(communityKeys.channelMessages(event.channelId)),- event.messageId,- )- const source = cached?.seq !== undefined ? cached as CanonicalMessage : fallback- useMessageStreamStore.getState().dispatch(scope, {- type: "liveRefreshed",- message: applyReactionToMessage(source, event, viewerId) as CanonicalMessage,- })- }- }- }- if (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,- })- }- }+ projectReactionCopies(event, context)}export function handlePinEvent(event: CommunityPinAdd | CommunityPinRemove,- { queryClient }: MessageEventContext,+ { projection }: MessageEventContext,) {- void queryClient.invalidateQueries({ queryKey: communityKeys.pins(event.channelId) })+ invalidatePins(projection, event.channelId)}export function handleMessageUpdated(event: CommunityMessageUpdated,- { queryClient, sub }: MessageEventContext,+ context: MessageEventContext,) {- // Folded from the old `dm.message_updated` — keyed by `channelId` (the- // DM's channel id). Patch the card's approval payload in the focused- // DM cache so it re-renders in its new state without a refetch.- if (event.channelId === sub.dmConversationId || event.channelId === sub.channelId) {- queryClient.setQueryData<PageCache>(- communityKeys.dmMessages(event.channelId),- (c) => patchApprovalInCache(c, event.messageId, event.approval),- )- queryClient.setQueryData<PageCache>(- communityKeys.channelMessages(event.channelId),- (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 },- })- }+ projectApprovalCopies(event, context)// 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// dead-letters FRIEND_ACCEPT to the bot).if (event.approval.status !== "pending" || event.approval.waitingOn !== "you") {- void queryClient.invalidateQueries({ queryKey: communityKeys.friends() })+ invalidateFriends(context.projection)}}export function handleMessageEdited(event: CommunityMessageEdited,- { queryClient }: MessageEventContext,+ context: MessageEventContext,) {+ const { queryClient } = contextif (event.parentChannelId) {if (!event.serverId) returnvoid reconcileForumOpenerTitle(queryClient, {@@ -282,25 +188,5 @@ export function handleMessageEdited(})return}- queryClient.setQueryData<{ content: string }>(- communityKeys.message(event.messageId),- (message) => message ? { ...message, content: event.content } : message,- )- queryClient.setQueriesData<PageCache>(- { queryKey: communityKeys.channelMessages(event.channelId) },- (cache) => patchMessageContentInCache(cache, event.messageId, event.content),- )- queryClient.setQueryData<PageCache>(- communityKeys.dmMessages(event.channelId),- (cache) => patchMessageContentInCache(cache, event.messageId, event.content),- )- const streamStore = useMessageStreamStore.getState()- for (const entry of streamStore.entries.values()) {- if (entry.scope.id !== event.channelId) continue- streamStore.dispatch(entry.scope, {- type: "messageEdited",- messageId: event.messageId,- content: event.content,- })- }+ projectEditedCopies(event, context)}diff --git a/src/web/src/hooks/community/community-ws/message-projections.ts b/src/web/src/hooks/community/community-ws/message-projections.tsnew file mode 100644index 000000000..dba13c425--- /dev/null+++ b/src/web/src/hooks/community/community-ws/message-projections.ts@@ -0,0 +1,159 @@+import type { QueryKey } from "@tanstack/react-query"+import type {+ CommunityMessageUpdated,+ CommunityReactionAdd,+ CommunityReactionRemove,+} from "@alook/shared"+import { communityKeys } from "@/lib/query-keys"+import type { CanonicalMessage, MessageScope } from "@/lib/community/message-stream"+import type { Msg } from "@/lib/community/models/message"+import { useCommunityStore } from "@/stores/community"+import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"+import {+ applyReactionToCache,+ applyReactionToMessage,+ findCachedMessage,+ patchApprovalInCache,+ patchMessageContentInCache,+ type PageCache,+} from "./cache"+import type { MessageEventContext } from "./handler-context"++type ReactionEvent = CommunityReactionAdd | CommunityReactionRemove+type MessageProjectionContext = Pick<+ MessageEventContext,+ "projection" | "queryClient" | "sub" | "viewerUserIdRef"+>++function refreshOverlayCopy(+ context: MessageProjectionContext,+ scope: MessageScope,+ cacheKey: QueryKey,+ messageId: string,+ update: (message: CanonicalMessage) => CanonicalMessage,+) {+ const fallback = [...getMessageOverlay(scope).liveById.values()]+ .find((message) => message.id === messageId)+ if (!fallback) return+ const cached = findCachedMessage(+ context.queryClient.getQueryData<PageCache>(cacheKey),+ messageId,+ )+ const source = cached?.seq !== undefined ? cached as CanonicalMessage : fallback+ useMessageStreamStore.getState().dispatch(scope, {+ type: "liveRefreshed",+ message: update(source),+ })+}++export function projectReactionCopies(+ event: ReactionEvent,+ context: MessageProjectionContext,+) {+ const { projection, queryClient, sub, viewerUserIdRef } = context+ projection.project(() => {+ const viewerId = viewerUserIdRef.current+ queryClient.setQueriesData<PageCache>(+ { queryKey: communityKeys.channelMessages(event.channelId) },+ (cache) => applyReactionToCache(cache, event, viewerId),+ )+ queryClient.setQueryData<PageCache>(+ communityKeys.dmMessages(event.channelId),+ (cache) => applyReactionToCache(cache, event, viewerId),+ )+ queryClient.setQueryData<Msg | undefined>(+ communityKeys.message(event.messageId),+ (message) => message ? applyReactionToMessage(message, event, viewerId) : message,+ )+ if (event.channelId === sub.channelId) {+ const serverId = useCommunityStore.getState().currentServerId+ if (serverId) {+ refreshOverlayCopy(+ context,+ { kind: "channel", id: event.channelId, serverId },+ communityKeys.channelMessages(event.channelId),+ event.messageId,+ (message) => applyReactionToMessage(message, event, viewerId) as CanonicalMessage,+ )+ }+ }+ if (event.channelId === sub.dmConversationId) {+ refreshOverlayCopy(+ context,+ { kind: "dm", id: event.channelId },+ communityKeys.dmMessages(event.channelId),+ event.messageId,+ (message) => applyReactionToMessage(message, event, viewerId) as CanonicalMessage,+ )+ }+ })+}++export function projectApprovalCopies(+ event: CommunityMessageUpdated,+ context: MessageProjectionContext,+) {+ const { projection, queryClient, sub } = context+ projection.project(() => {+ if (event.channelId === sub.dmConversationId || event.channelId === sub.channelId) {+ queryClient.setQueryData<PageCache>(+ communityKeys.dmMessages(event.channelId),+ (cache) => patchApprovalInCache(cache, event.messageId, event.approval),+ )+ queryClient.setQueryData<PageCache>(+ communityKeys.channelMessages(event.channelId),+ (cache) => patchApprovalInCache(cache, event.messageId, event.approval),+ )+ }+ if (event.channelId === sub.dmConversationId) {+ refreshOverlayCopy(+ context,+ { kind: "dm", id: event.channelId },+ communityKeys.dmMessages(event.channelId),+ event.messageId,+ (message) => ({ ...message, approval: event.approval }),+ )+ } else if (event.channelId === sub.channelId) {+ const serverId = useCommunityStore.getState().currentServerId+ if (serverId) {+ refreshOverlayCopy(+ context,+ { kind: "channel", id: event.channelId, serverId },+ communityKeys.channelMessages(event.channelId),+ event.messageId,+ (message) => ({ ...message, approval: event.approval }),+ )+ }+ }+ })+}++export function projectEditedCopies(+ event: { channelId: string; messageId: string; content: string },+ context: Pick<MessageEventContext, "projection" | "queryClient">,+) {+ const { projection, queryClient } = context+ projection.project(() => {+ queryClient.setQueryData<{ content: string }>(+ communityKeys.message(event.messageId),+ (message) => message ? { ...message, content: event.content } : message,+ )+ queryClient.setQueriesData<PageCache>(+ { queryKey: communityKeys.channelMessages(event.channelId) },+ (cache) => patchMessageContentInCache(cache, event.messageId, event.content),+ )+ queryClient.setQueryData<PageCache>(+ communityKeys.dmMessages(event.channelId),+ (cache) => patchMessageContentInCache(cache, event.messageId, event.content),+ )+ const streamStore = useMessageStreamStore.getState()+ for (const entry of streamStore.entries.values()) {+ if (entry.scope.id !== event.channelId) continue+ streamStore.dispatch(entry.scope, {+ type: "messageEdited",+ messageId: event.messageId,+ content: event.content,+ })+ }+ })+}diff --git a/src/web/src/hooks/community/community-ws/projection-transaction.test.ts b/src/web/src/hooks/community/community-ws/projection-transaction.test.tsnew file mode 100644index 000000000..d35416a44--- /dev/null+++ b/src/web/src/hooks/community/community-ws/projection-transaction.test.ts@@ -0,0 +1,95 @@+import { describe, expect, it, vi } from "vitest"+import { notifyManager, QueryClient } from "@tanstack/react-query"+import {+ getCommunityWsProjectionFlushError,+ runCommunityWsProjectionTransaction,+} from "./projection-transaction"+import { invalidateInbox } from "./invalidation-projections"++describe("community WS projection transaction", () => {+ it("has no flush error metadata for primitive or null errors", () => {+ expect(getCommunityWsProjectionFlushError(null)).toBeUndefined()+ expect(getCommunityWsProjectionFlushError("project failed")).toBeUndefined()+ })++ it("executes projections synchronously inside one notification batch", () => {+ const queryClient = new QueryClient()+ const batch = vi.spyOn(notifyManager, "batch")++ try {+ runCommunityWsProjectionTransaction(queryClient, (transaction) => {+ transaction.project(() => queryClient.setQueryData(["entity"], { value: 1 }))+ expect(queryClient.getQueryData(["entity"])).toEqual({ value: 1 })+ transaction.project(() => queryClient.setQueryData<{ value: number }>(+ ["entity"],+ (current) => ({ value: (current?.value ?? 0) + 1 }),+ ))+ expect(queryClient.getQueryData(["entity"])).toEqual({ value: 2 })+ })+ expect(batch).toHaveBeenCalled()+ } finally {+ batch.mockRestore()+ }+ })++ it("deduplicates only identical owner and filter pairs in first-seen order", () => {+ const queryClient = new QueryClient()+ const invalidate = vi.spyOn(queryClient, "invalidateQueries").mockResolvedValue()+ const first = { queryKey: ["community", "inbox"] as const }+ const conflict = { queryKey: ["community", "inbox"] as const, exact: true }+ const second = { queryKey: ["community", "servers"] as const, exact: true }++ runCommunityWsProjectionTransaction(queryClient, (transaction) => {+ invalidateInbox(transaction)+ invalidateInbox(transaction)+ transaction.invalidate("inbox", conflict)+ transaction.invalidate("servers", second)+ })++ expect(invalidate.mock.calls.map(([filters]) => filters)).toEqual([+ first,+ conflict,+ second,+ ])+ })++ it("flushes queued invalidations when projection fails", () => {+ const queryClient = new QueryClient()+ const invalidate = vi.spyOn(queryClient, "invalidateQueries").mockResolvedValue()+ const projectError = new Error("project failed")++ expect(() => runCommunityWsProjectionTransaction(queryClient, (transaction) => {+ transaction.invalidate("inbox", { queryKey: ["community", "inbox"] })+ throw projectError+ })).toThrow(projectError)++ expect(invalidate).toHaveBeenCalledTimes(1)+ })++ it("preserves the projection error when the invalidation flush also throws", () => {+ const queryClient = new QueryClient()+ const projectError = new Error("project failed")+ const flushError = new Error("flush failed")+ vi.spyOn(queryClient, "invalidateQueries").mockImplementation(() => {+ throw flushError+ })++ expect(() => runCommunityWsProjectionTransaction(queryClient, (transaction) => {+ transaction.invalidate("inbox", { queryKey: ["community", "inbox"] })+ throw projectError+ })).toThrow(projectError)+ expect(getCommunityWsProjectionFlushError(projectError)).toBe(flushError)+ })++ it("throws a flush error when projection succeeds", () => {+ const queryClient = new QueryClient()+ const flushError = new Error("flush failed")+ vi.spyOn(queryClient, "invalidateQueries").mockImplementation(() => {+ throw flushError+ })++ expect(() => runCommunityWsProjectionTransaction(queryClient, (transaction) => {+ transaction.invalidate("inbox", { queryKey: ["community", "inbox"] })+ })).toThrow(flushError)+ })+})diff --git a/src/web/src/hooks/community/community-ws/projection-transaction.ts b/src/web/src/hooks/community/community-ws/projection-transaction.tsnew file mode 100644index 000000000..fc4bab2a0--- /dev/null+++ b/src/web/src/hooks/community/community-ws/projection-transaction.ts@@ -0,0 +1,89 @@+import {+ hashKey,+ notifyManager,+ type InvalidateQueryFilters,+ type QueryClient,+} from "@tanstack/react-query"++const projectionFlushErrors = new WeakMap<object, unknown>()++export function getCommunityWsProjectionFlushError(error: unknown) {+ if (+ error === null ||+ (typeof error !== "object" && typeof error !== "function")+ ) return undefined+ return projectionFlushErrors.get(error)+}++export type CommunityWsProjectionTransaction = {+ project: <T>(effect: () => T) => T+ invalidate: (owner: string, filters: InvalidateQueryFilters) => void+}++type PendingInvalidation = {+ filters: InvalidateQueryFilters+}++function createProjectionTransaction(+ queryClient: QueryClient,+): CommunityWsProjectionTransaction & { flushInvalidations: () => void } {+ const pending = new Map<string, PendingInvalidation>()+ let flushed = false++ return {+ project: (effect) => effect(),+ invalidate: (owner, filters) => {+ if (flushed) throw new Error("community WS projection transaction already flushed")+ const identity = hashKey([owner, filters])+ if (!pending.has(identity)) pending.set(identity, { filters })+ },+ flushInvalidations: () => {+ if (flushed) return+ flushed = true+ for (const { filters } of pending.values()) {+ void queryClient.invalidateQueries(filters)+ }+ },+ }+}++export function runCommunityWsProjectionTransaction<T>(+ queryClient: QueryClient,+ project: (transaction: CommunityWsProjectionTransaction) => T,+): T {+ return notifyManager.batch(() => {+ const transaction = createProjectionTransaction(queryClient)+ let result: T | undefined+ let projectFailed = false+ let projectError: unknown+ let flushFailed = false+ let flushError: unknown++ try {+ result = project(transaction)+ } catch (error) {+ projectFailed = true+ projectError = error+ } finally {+ try {+ transaction.flushInvalidations()+ } catch (error) {+ flushFailed = true+ flushError = error+ }+ }++ if (projectFailed) {+ if (+ flushFailed &&+ projectError !== null &&+ (typeof projectError === "object" || typeof projectError === "function")+ ) {+ projectionFlushErrors.set(projectError, flushError)+ }+ throw projectError+ }+ if (flushFailed) throw flushError+ return result as T+ })+}diff --git a/src/web/src/hooks/community/community-ws/registry.test.ts b/src/web/src/hooks/community/community-ws/registry.test.tsindex 16d2c226e..9ab6ee829 100644--- a/src/web/src/hooks/community/community-ws/registry.test.ts+++ b/src/web/src/hooks/community/community-ws/registry.test.ts@@ -1,10 +1,16 @@import { describe, expect, it, vi } from "vitest"+import { notifyManager, QueryClient } from "@tanstack/react-query"import { WS_EVENTS } from "@alook/shared"import { communityWsEventFixtures } from "../../../../../shared/test/community-ws-events.fixtures"+import type {+ CommunityWsDispatchContext,+ CommunityWsHandlerContext,+} from "./handler-context"import {communityWsReconnectPolicies,communityWsRegistry,dispatchCommunityWsEvent,+ dispatchCommunityWsEvents,} from "./registry"const handlers = vi.hoisted(() => new Proxy({} as Record<string, ReturnType<typeof vi.fn>>, {@@ -55,6 +61,18 @@ vi.mock("./presence-machine-events", () => ({handleStatusUpdate: handlers.handleStatusUpdate,}))+function dispatchContext(queryClient = new QueryClient()): CommunityWsDispatchContext {+ return {+ queryClient,+ communityStore: {} as CommunityWsDispatchContext["communityStore"],+ wsStore: {} as CommunityWsDispatchContext["wsStore"],+ sub: {},+ viewerUserIdRef: { current: null },+ matchesFocus: () => false,+ scheduleInboxInvalidate: vi.fn(),+ }+}+describe("community WebSocket registry", () => {it("has exactly one entry for each of the 41 runtime event types", () => {const eventTypes = Object.values(WS_EVENTS).sort()@@ -98,8 +116,60 @@ describe("community WebSocket registry", () => {["community:machine.created", "handleMachineCreated"],["community:bot.audit_event", "handleBotAuditEvent"],] as const)("dispatches %s through its existing handler group", (type, handlerName) => {- const context = { marker: "context" } as never+ const context = dispatchContext()dispatchCommunityWsEvent(communityWsEventFixtures[type], context)expect(handlers[handlerName]).toHaveBeenCalled()})++ it("provides projection transactions to context-owning handlers", () => {+ dispatchCommunityWsEvent(+ communityWsEventFixtures["community:message.create"],+ dispatchContext(),+ )++ expect(handlers.handleMessageCreate).toHaveBeenCalledWith(+ communityWsEventFixtures["community:message.create"],+ expect.objectContaining({+ projection: expect.objectContaining({+ project: expect.any(Function),+ invalidate: expect.any(Function),+ }),+ }),+ )+ })++ it("wraps public single-event dispatch in one projection batch", () => {+ const batch = vi.spyOn(notifyManager, "batch")++ try {+ dispatchCommunityWsEvent(+ communityWsEventFixtures["community:typing.stop"],+ dispatchContext(),+ )+ expect(batch).toHaveBeenCalledTimes(1)+ } finally {+ batch.mockRestore()+ }+ })++ it("lets later events observe synchronous projections from earlier events", () => {+ const queryClient = new QueryClient()+ const observed: number[] = []+ handlers.handleMessageCreate.mockImplementationOnce((+ _event: unknown,+ context: CommunityWsHandlerContext,+ ) => {+ context.projection.project(() => queryClient.setQueryData(["ordered"], 1))+ })+ handlers.handleTypingStart.mockImplementationOnce(() => {+ observed.push(queryClient.getQueryData<number>(["ordered"]) ?? 0)+ })++ dispatchCommunityWsEvents([+ communityWsEventFixtures["community:message.create"],+ communityWsEventFixtures["community:typing.start"],+ ], dispatchContext(queryClient))++ expect(observed).toEqual([1])+ })})diff --git a/src/web/src/hooks/community/community-ws/registry.ts b/src/web/src/hooks/community/community-ws/registry.tsindex f48de41bb..40a342dac 100644--- a/src/web/src/hooks/community/community-ws/registry.ts+++ b/src/web/src/hooks/community/community-ws/registry.ts@@ -1,6 +1,10 @@import type { CommunityWsEvent } from "@alook/shared"import type { CommunityWsReconcilePolicy } from "@/lib/analytics"-import type { CommunityWsHandlerContext } from "@/hooks/community/community-ws/handler-context"+import type {+ CommunityWsDispatchContext,+ CommunityWsHandlerContext,+} from "@/hooks/community/community-ws/handler-context"+import { runCommunityWsProjectionTransaction } from "@/hooks/community/community-ws/projection-transaction"import {handleMessageCreate,handleMessageEdited,@@ -93,10 +97,22 @@ export const communityWsRegistry = {export function dispatchCommunityWsEvent(event: CommunityWsEvent,- context: CommunityWsHandlerContext,+ context: CommunityWsDispatchContext,) {- const entry = communityWsRegistry[event.type] as RegistryEntry<typeof event.type>- entry.handler(event, context)+ dispatchCommunityWsEvents([event], context)+}++export function dispatchCommunityWsEvents(+ events: readonly CommunityWsEvent[],+ context: CommunityWsDispatchContext,+) {+ runCommunityWsProjectionTransaction(context.queryClient, (projection) => {+ const handlerContext: CommunityWsHandlerContext = { ...context, projection }+ for (const event of events) {+ const entry = communityWsRegistry[event.type] as RegistryEntry<typeof event.type>+ entry.handler(event, handlerContext)+ }+ })}export const communityWsReconnectPolicies = Array.from(new Set(diff --git a/src/web/src/hooks/community/community-ws/social-events.ts b/src/web/src/hooks/community/community-ws/social-events.tsindex 3f3c0e703..88afbe0b0 100644--- a/src/web/src/hooks/community/community-ws/social-events.ts+++ b/src/web/src/hooks/community/community-ws/social-events.ts@@ -18,6 +18,11 @@ import {setForumSidebarParentUnreadBase,} from "@/hooks/community/use-forum-sidebar-threads"import type { SocialEventContext } from "@/hooks/community/community-ws/handler-context"+import {+ invalidateFriends,+ invalidateInbox,+ invalidateServersList,+} from "./invalidation-projections"type CommunityUnreadBump = Extract<CommunityWsEvent,@@ -124,16 +129,16 @@ type FriendEvent =export function handleFriendEvent(_event: FriendEvent,- { queryClient }: SocialEventContext,+ { projection }: SocialEventContext,) {- void queryClient.invalidateQueries({ queryKey: communityKeys.friends() })+ invalidateFriends(projection)}export function handleMentionCreate(_event: CommunityMentionCreate,- { queryClient }: SocialEventContext,+ { projection }: SocialEventContext,) {- void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })+ invalidateInbox(projection)// The server rail badge counts unread mentions per server; refresh// it on every new mention. `exact: true` is essential: the mention// count lives in the `servers()` LIST query, but members/presence/@@ -142,5 +147,5 @@ export function handleMentionCreate(// force-refetches that whole subtree (and invalidate overrides the// staleTime: Infinity those carry). With an active bot in the server,// every mention.create would otherwise storm-refetch all of them.- void queryClient.invalidateQueries({ queryKey: communityKeys.servers(), exact: true })+ invalidateServersList(projection)}diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.test.tsindex 431083629..b051bc7c3 100644--- a/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts@@ -1,5 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { QueryObserver } from "@tanstack/react-query"import type {+ CommunityCategoryCreate,CommunityChannelCreate,CommunityChannelDelete,CommunityChildChannelCreate,@@ -115,6 +117,33 @@ describe("useCommunityWs — channel.* invalidates server(id)", () => {})})+describe("useCommunityWs — category.* invalidates tree projections", () => {+ it("category.create invalidates the channel directory and matching server", async () => {+ await mountHook()+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")++ capturedOnMessage!({+ type: "community:category.create",+ serverId: "srv_1",+ category: {+ id: "cat_new",+ name: "Category",+ position: 0,+ private: false,+ },+ } satisfies CommunityCategoryCreate)++ expect(spy).toHaveBeenCalledWith({+ queryKey: communityKeys.channelRefDirectory(),+ exact: true,+ })+ expect(spy).toHaveBeenCalledWith({+ queryKey: communityKeys.server("srv_1"),+ exact: true,+ })+ })+})+describe("useCommunityWs — invite.create", () => {it("invalidates only the matching server invite query", async () => {await mountHook()@@ -163,6 +192,61 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>expect(capturedQueryClient.getQueryData(communityKeys.threads("ch_dead"))).toBeUndefined()expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(sidebarKey)?.threads).toEqual([])})++ it("evicts the deleted row while an active server-tree refetch is pending", async () => {+ await mountHook()+ const serverKey = communityKeys.server("srv_1")+ const deletedChannel = {+ id: "ch_dead",+ name: "Deleted",+ type: "text" as const,+ position: 0,+ createdAt: "2026-07-03T00:00:00.000Z",+ }+ const freshServer = {+ id: "srv_1",+ name: "Server",+ discriminator: "0001",+ description: "",+ icon: null,+ ownerId: "u_owner",+ categories: [{ id: "cat_1", name: "Category", private: 0, channels: [] }],+ }+ capturedQueryClient.setQueryData(serverKey, {+ ...freshServer,+ categories: [{+ ...freshServer.categories[0],+ channels: [deletedChannel],+ }],+ })+ let resolveServer!: (server: typeof freshServer) => void+ const fetchServer = vi.fn(() => new Promise<typeof freshServer>((resolve) => {+ resolveServer = resolve+ }))+ const observer = new QueryObserver(capturedQueryClient, {+ queryKey: serverKey,+ queryFn: fetchServer,+ staleTime: Infinity,+ })+ const unsubscribe = observer.subscribe(() => {})++ try {+ capturedOnMessage!({+ type: "community:channel.delete",+ serverId: "srv_1",+ channelId: "ch_dead",+ } satisfies CommunityChannelDelete)++ expect(fetchServer).toHaveBeenCalledTimes(1)+ expect(+ capturedQueryClient.getQueryData<typeof freshServer>(serverKey)?.categories[0].channels,+ ).toEqual([])+ resolveServer(freshServer)+ await vi.waitFor(() => expect(observer.getCurrentResult().isFetching).toBe(false))+ } finally {+ unsubscribe()+ }+ })})describe("useCommunityWs — child_create patches parent thread badge with count 0", () => {diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.tsindex 524e04d4b..1a9aea6fc 100644--- a/src/web/src/hooks/community/community-ws/structure-tree-events.ts+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.ts@@ -22,9 +22,7 @@ import type { ServersResponse, ServerDetail } from "@/hooks/community/use-serverimport {grantForumSidebarChild,isForumSidebarParent,- isKnownNonForumSidebarChannel,patchForumSidebarActivityExact,- removeForumSidebarChildrenForParent,removeForumSidebarThreadExact,removeForumSidebarUnreadChild,} from "@/hooks/community/use-forum-sidebar-threads"@@ -34,27 +32,25 @@ import {type PageCache,} from "@/hooks/community/community-ws/cache"import type { StructureTreeEventContext } from "@/hooks/community/community-ws/handler-context"--function invalidateChannelRefDirectory(- queryClient: StructureTreeEventContext["queryClient"],-) {- void queryClient.invalidateQueries({- queryKey: communityKeys.channelRefDirectory(),- exact: true,- })-}+import { projectChannelScopeEviction } from "./channel-scope-projection"+import {+ invalidateChannelMessages,+ invalidateChannelRefDirectory,+ invalidateInvites,+ invalidateServerDetail,+ invalidateServersList,+ invalidateThreads,+} from "./invalidation-projections"export function handleChildChannelCreate(event: CommunityChildChannelCreate,- { queryClient }: StructureTreeEventContext,+ { queryClient, projection }: StructureTreeEventContext,) {// Cheap invalidate for the child-thread lists. The parent// messages list also needs an update because the parent message's// thread indicator (`msg.thread`) changes — do a targeted// setQueryData patch when we know parentMessageId.- void queryClient.invalidateQueries({- queryKey: communityKeys.threads(event.parentChannelId),- })+ invalidateThreads(projection, event.parentChannelId)const parentMessagesKey = communityKeys.channelMessages(event.parentChannelId)const parentMessages = queryClient.getQueryData<PageCache>(parentMessagesKey)const openerCached = !!event.parentMessageId && parentMessages?.pages.some((page) =>@@ -115,21 +111,19 @@ export function handleChildChannelCreate(}}if (event.parentMessageId && !openerCached) {- void queryClient.invalidateQueries({ queryKey: parentMessagesKey })+ invalidateChannelMessages(projection, event.parentChannelId)}}export function handleChildChannelUpdate(event: CommunityChildChannelUpdate,- { queryClient }: StructureTreeEventContext,+ { queryClient, projection }: StructureTreeEventContext,) {// Cheap invalidate for the child-thread lists. The parent// messages list also needs an update because the parent message's// thread indicator (`msg.thread`) changes — do a targeted// setQueryData patch when we know parentMessageId.- void queryClient.invalidateQueries({- queryKey: communityKeys.threads(event.parentChannelId),- })+ invalidateThreads(projection, event.parentChannelId)// child_update — sync counts/name on the parent message's thread// indicator if the update carries them.const changes = event.changes@@ -239,9 +233,9 @@ export function handleChildChannelUpdate(export function handleServerUpdate(event: CommunityServerUpdate,- { queryClient }: StructureTreeEventContext,+ { queryClient, projection }: StructureTreeEventContext,) {- invalidateChannelRefDirectory(queryClient)+ invalidateChannelRefDirectory(projection)queryClient.setQueryData<ServerDetail | undefined>(communityKeys.server(event.serverId),(prev) =>@@ -283,14 +277,14 @@ export function handleServerUpdate(export function handleServerDelete(event: CommunityServerDelete,- { queryClient }: StructureTreeEventContext,+ { queryClient, projection }: StructureTreeEventContext,) {- invalidateChannelRefDirectory(queryClient)+ invalidateChannelRefDirectory(projection)// Refresh the rail LIST only (drop the deleted server). `exact`// so this doesn't cascade-refetch every other server's nested// detail subtree; the deleted server's own subtree is cleared by// the removeQueries below.- void queryClient.invalidateQueries({ queryKey: communityKeys.servers(), exact: true })+ invalidateServersList(projection)queryClient.removeQueries({ queryKey: communityKeys.server(event.serverId) })// #10: if the deleted server is the one the viewer is looking at,// the store pointers now dangle — reset them so the UI drops back@@ -312,47 +306,21 @@ type ChannelEvent =export function handleChannelEvent(event: ChannelEvent,- { queryClient }: StructureTreeEventContext,+ { queryClient, projection }: StructureTreeEventContext,) {- invalidateChannelRefDirectory(queryClient)+ invalidateChannelRefDirectory(projection)// #3: on channel.delete, evict every channel-scoped cache before// invalidating the server. Without this the messages/pins/threads/// child-thread caches for the dead channel linger forever — a// subsequent same-id revive (rare, but the server can reuse ids)// would surface stale rows.if (event.type === "community:channel.delete") {- const nonForum = isKnownNonForumSidebarChannel(+ projectChannelScopeEviction(+ projection,queryClient,event.serverId,event.channelId,)- if (!nonForum) {- removeForumSidebarUnreadChild(queryClient, event.serverId, event.channelId)- removeForumSidebarChildrenForParent(queryClient, event.serverId, event.channelId)- removeForumSidebarThreadExact(queryClient, event.serverId, event.channelId)- } else {- queryClient.removeQueries({- queryKey: communityKeys.channelMeta(event.serverId, event.channelId),- exact: true,- })- }- if (useCommunityStore.getState().currentChannelId === event.channelId) {- useCommunityStore.getState().setCurrentChannelMeta(null)- }- useMessageStreamStore.getState().removeScope({- kind: "channel",- id: event.channelId,- serverId: event.serverId,- })- queryClient.removeQueries({- queryKey: communityKeys.channelMessages(event.channelId),- })- queryClient.removeQueries({- queryKey: communityKeys.pins(event.channelId),- })- queryClient.removeQueries({- queryKey: communityKeys.threads(event.channelId),- })// When a child thread is deleted, refresh the// PARENT's list so the deleted card disappears from the feed on// every client. Absent on older events / top-level channels.@@ -361,18 +329,11 @@ export function handleChannelEvent({ queryKey: communityKeys.channelMessages(event.parentChannelId) },(cache) => removeThreadFromCache(cache, event.channelId),)- void queryClient.invalidateQueries({- queryKey: communityKeys.channelMessages(event.parentChannelId),- })- void queryClient.invalidateQueries({- queryKey: communityKeys.threads(event.parentChannelId),- })+ invalidateChannelMessages(projection, event.parentChannelId)+ invalidateThreads(projection, event.parentChannelId)}}- void queryClient.invalidateQueries({- queryKey: communityKeys.server(event.serverId),- exact: true,- })+ invalidateServerDetail(projection, event.serverId)}type CategoryEvent =@@ -383,21 +344,15 @@ type CategoryEvent =export function handleCategoryEvent(event: CategoryEvent,- { queryClient }: StructureTreeEventContext,+ { projection }: StructureTreeEventContext,) {- invalidateChannelRefDirectory(queryClient)- void queryClient.invalidateQueries({- queryKey: communityKeys.server(event.serverId),- exact: true,- })+ invalidateChannelRefDirectory(projection)+ invalidateServerDetail(projection, event.serverId)}export function handleInviteCreate(event: CommunityInviteCreate,- { queryClient }: StructureTreeEventContext,+ { projection }: StructureTreeEventContext,) {- void queryClient.invalidateQueries({- queryKey: communityKeys.invites(event.serverId),- exact: true,- })+ invalidateInvites(projection, event.serverId)}diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.tsindex 03872b4cb..366fa5f93 100644--- a/src/web/src/hooks/community/use-community-ws.ts+++ b/src/web/src/hooks/community/use-community-ws.ts@@ -5,11 +5,15 @@ import { useQueryClient } from "@tanstack/react-query"import { useUserWs } from "@/lib/use-user-ws"import { useCommunityStore } from "@/stores/community"import { useCommunityWsStore } from "@/stores/community/ws"-import { communityKeys } from "@/lib/query-keys"import { reconcileCommunityWsReconnect } from "@/hooks/community/community-ws/reconnect"import { dispatchCommunityWsEvent } from "@/hooks/community/community-ws/registry"+import { runCommunityWsProjectionTransaction } from "@/hooks/community/community-ws/projection-transaction"+import {+ invalidateDms,+ invalidateInbox,+} from "@/hooks/community/community-ws/invalidation-projections"import type {- CommunityWsHandlerContext,+ CommunityWsDispatchContext,Subscription,UseCommunityWsOptions,} from "@/hooks/community/community-ws/handler-context"@@ -130,15 +134,17 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {if (inboxDebounce.current) returninboxDebounce.current = setTimeout(() => {inboxDebounce.current = null- void queryClient.invalidateQueries({ queryKey: communityKeys.inbox() })- // A DM is a channel now, so a DM message arrives as `message.create`- // with no discriminator distinguishing it from a channel message. Fold- // the old `dm.new_message` DM-sidebar refresh in here: invalidate the- // DM list too so an unread DM's preview/unread flag updates live. Cheap- // — `communityKeys.dms()` is only observed under the `/c/me` layout, so- // this is a no-op (marks stale, no refetch) while viewing a server- // channel where the DM sidebar isn't mounted.- void queryClient.invalidateQueries({ queryKey: communityKeys.dms() })+ runCommunityWsProjectionTransaction(queryClient, (projection) => {+ invalidateInbox(projection)+ // A DM is a channel now, so a DM message arrives as `message.create`+ // with no discriminator distinguishing it from a channel message. Fold+ // the old `dm.new_message` DM-sidebar refresh in here: invalidate the+ // DM list too so an unread DM's preview/unread flag updates live. Cheap+ // — `communityKeys.dms()` is only observed under the `/c/me` layout, so+ // this is a no-op (marks stale, no refetch) while viewing a server+ // channel where the DM sidebar isn't mounted.+ invalidateDms(projection)+ })}, INBOX_INVALIDATE_DEBOUNCE_MS)}, [queryClient])@@ -176,7 +182,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {if (!e.channelId) return falsereturn e.channelId === sub.channelId || e.channelId === sub.dmConversationId}- const context: CommunityWsHandlerContext = {+ const context: CommunityWsDispatchContext = {queryClient,communityStore,wsStore,