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
perf(web): kill community switch re-render storm + de-serialize channel open (#404)
Gener3fc84fa2ceb2
diff --git a/src/shared/src/db/community-schema.ts b/src/shared/src/db/community-schema.tsindex 2c2b741ec..2778b1a68 100644--- a/src/shared/src/db/community-schema.ts+++ b/src/shared/src/db/community-schema.ts@@ -224,6 +224,8 @@ export const communityServerMember = sqliteTable(unique("uq_server_member_server_user").on(t.serverId, t.userId),index("idx_server_member_user").on(t.userId),index("idx_server_member_user_rail_order").on(t.userId, t.railOrder),+ // Serves listMembersPaginated's WHERE server_id ORDER BY (joined_at, id).+ index("idx_server_member_server_joined").on(t.serverId, t.joinedAt),]);@@ -260,21 +262,26 @@ export const communityServerFolderItem = sqliteTable();// 10. community_server_invite-export const communityServerInvite = sqliteTable("community_server_invite", {- id: text("id").primaryKey().$defaultFn(() => nanoid()),- serverId: text("server_id")- .notNull()- .references(() => communityServer.id, { onDelete: "cascade" }),- createdBy: text("created_by").references(() => user.id, { onDelete: "set null" }),- token: text("token")- .unique()- .notNull()- .$defaultFn(() => nanoid(10)),- maxUses: integer("max_uses"),- uses: integer("uses").default(0),- expiresAt: text("expires_at"),- createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),-});+export const communityServerInvite = sqliteTable(+ "community_server_invite",+ {+ id: text("id").primaryKey().$defaultFn(() => nanoid()),+ serverId: text("server_id")+ .notNull()+ .references(() => communityServer.id, { onDelete: "cascade" }),+ createdBy: text("created_by").references(() => user.id, { onDelete: "set null" }),+ token: text("token")+ .unique()+ .notNull()+ .$defaultFn(() => nanoid(10)),+ maxUses: integer("max_uses"),+ uses: integer("uses").default(0),+ expiresAt: text("expires_at"),+ createdAt: text("created_at").notNull().$defaultFn(() => new Date().toISOString()),+ },+ // listServerInvites filters WHERE server_id — without this it full-scans.+ (t) => [index("idx_server_invite_server").on(t.serverId)]+);// 11. community_friendshipexport const communityFriendship = sqliteTable(diff --git a/src/web/migrations/0062_community_switch_perf_indexes.sql b/src/web/migrations/0062_community_switch_perf_indexes.sqlnew file mode 100644index 000000000..f706c28b0--- /dev/null+++ b/src/web/migrations/0062_community_switch_perf_indexes.sql@@ -0,0 +1,16 @@+-- Perf: two indexes on the community server-switch path.+-- See plans/community-switch-perf-optimization.md (WS4).+--+-- Both tables are small today, so the immediate win is marginal — this is+-- correctness insurance as membership/invite counts grow. Idempotent.++-- 1. `listServerInvites` (invite.ts) filters WHERE server_id with only a PK and+-- the token UNIQUE, so it currently full-scans the invite table.+CREATE INDEX IF NOT EXISTS idx_server_invite_server+ ON community_server_invite(server_id);++-- 2. `listMembersPaginated` (member.ts) does WHERE server_id ORDER BY (joined_at,+-- id). The (server_id, user_id) unique serves the equality filter but not the+-- sort, so the members page is a filesort. This composite serves both.+CREATE INDEX IF NOT EXISTS idx_server_member_server_joined+ ON community_server_member(server_id, joined_at);diff --git a/src/web/src/app/api/community/channels/[id]/bootstrap/route.ts b/src/web/src/app/api/community/channels/[id]/bootstrap/route.tsnew file mode 100644index 000000000..f5a0e126f--- /dev/null+++ b/src/web/src/app/api/community/channels/[id]/bootstrap/route.ts@@ -0,0 +1,114 @@+import { NextRequest } from "next/server"+import { withAuth } from "@/lib/middleware/auth"+import { writeJSON, writeError } from "@/lib/middleware/helpers"+import { getDb } from "@/lib/db"+import { queries, withD1Retry } from "@alook/shared"+import {+ parsePageSize,+ buildPaginatedResponse,+ buildAnchorResponse,+} from "@/lib/community/messages"+import { enrichMessages } from "@/lib/community/enrich-messages"+import { requireChannelMember } from "@/lib/community/permissions"++/**+ * GET /api/community/channels/:id/bootstrap+ *+ * The de-serialized channel-open payload. See+ * plans/community-switch-perf-optimization.md (WS2). Instead of the client+ * firing `read-state`, waiting for it, then firing `messages?anchor=` (two+ * serial network round-trips gated client-side), this route does BOTH server+ * side behind ONE `requireChannelMember` preflight and returns them together:+ *+ * { readState, messages, hasMoreOlder, hasMoreNewer, olderCursor,+ * newerCursor, latestSeq }+ *+ * The `messages` payload is byte-identical to what the `messages` route's+ * anchor/legacy branch returns (same `enrichMessages`, same anchor-mode+ * envelope with `hasMoreOlder`/`hasMoreNewer`), so the client can seed its+ * existing message cache and let `useMessages` paginate + WS-patch unchanged.+ *+ * Only the INITIAL window lives here; pagination stays on the `messages` route.+ */+export const GET = withAuth(async (_req: NextRequest, ctx) => {+ const channelId = ctx.params?.id+ if (!channelId) return writeError("missing channel id", 400)++ const db = getDb(ctx.env.DB)++ // Preserve the read-state route's 404-vs-403 ordering (unknown channel →+ // 404, known-but-not-a-member → 403).+ const channel = await queries.communityChannel.getChannel(db, channelId)+ if (!channel) return writeError("channel not found", 404)+ const auth = await requireChannelMember(db, channelId, ctx.userId)+ if (!auth.ok) return writeError(auth.error, auth.status)++ const pageSize = parsePageSize(null)++ const readRow = await withD1Retry(+ () => queries.communityReadState.getReadState(db, { userId: ctx.userId, channelId }),+ { route: "community/channels/bootstrap:read-state" },+ )+ const readState = {+ lastReadMessageId: readRow?.lastReadMessageId ?? null,+ lastReadAt: readRow?.lastReadAt ?? null,+ lastReadSeq: readRow?.lastReadSeq ?? 0,+ }++ // Anchor on the read pointer when present AND still resolvable in scope.+ // A stored pointer at a since-deleted / purged message must fall back to the+ // newest page — NOT 404 (that would break channel-open entirely). This is the+ // one behavior the standalone messages route can't safely centralize.+ const anchorId = readState.lastReadMessageId+ const anchor = anchorId+ ? await queries.communityMessage.getMessageInScope(db, anchorId, { channelId })+ : null++ if (anchor) {+ const around = await queries.communityMessage.listMessagesAround(db, {+ channelId,+ anchor: { createdAt: anchor.createdAt, id: anchor.id },+ limit: pageSize,+ })+ const { items, hasMoreOlder, hasMoreNewer, olderCursor, newerCursor } = buildAnchorResponse(+ around.older,+ around.newer,+ { hasMoreOlder: around.hasMoreOlder, hasMoreNewer: around.hasMoreNewer },+ )+ const { messages, latestSeq } = await enrichMessages(db, ctx.userId, { channelId }, items)+ return writeJSON({+ readState,+ anchorMode: "anchor" as const,+ anchorMessageId: anchorId,+ messages,+ hasMoreOlder,+ hasMoreNewer,+ olderCursor,+ newerCursor,+ latestSeq,+ })+ }++ // Newest-page fallback: no read pointer, or the pointer's message is gone.+ // Mirrors the messages route's legacy branch (DESC + one-extra-row probe,+ // reversed to ASC) so the seeded page is a trusted newest-tail window.+ const rows = await queries.communityMessage.listMessages(db, {+ channelId,+ limit: pageSize + 1,+ })+ const { items, hasMore, cursor: nextCursor } = buildPaginatedResponse(rows, pageSize)+ const { messages, latestSeq } = await enrichMessages(db, ctx.userId, { channelId }, items.slice().reverse())+ return writeJSON({+ readState,+ anchorMode: "newest" as const,+ anchorMessageId: null,+ messages,+ // Normalize to the anchor-mode envelope so the client seed is uniform:+ // a newest page has no newer side, and `hasMore` is the older side.+ hasMoreOlder: hasMore,+ hasMoreNewer: false,+ olderCursor: nextCursor,+ newerCursor: null,+ latestSeq,+ })+})diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.ts b/src/web/src/app/api/community/channels/[id]/messages/route.tsindex 8b769f525..48e0c09ea 100644--- a/src/web/src/app/api/community/channels/[id]/messages/route.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/route.ts@@ -10,13 +10,11 @@ import {buildPaginatedResponse,buildAnchorResponse,buildSinceResponse,- groupAttachments,- groupReactions,} from "@/lib/community/messages"+import { enrichMessages } from "@/lib/community/enrich-messages"import { requireChannelMember } from "@/lib/community/permissions"import { checkRateLimit } from "@/lib/rate-limit"import { createCommunityMessage } from "@/lib/community/message-handler"-import { mapMessageForApi } from "@/lib/community/message-payload"export const GET = withAuth(async (req: NextRequest, ctx) => {const channelId = ctx.params?.id@@ -52,7 +50,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {{ hasMoreOlder: around.hasMoreOlder, hasMoreNewer: around.hasMoreNewer },)- const { messages, latestSeq } = await enrichAndFinalize(db, ctx.userId, channelId, items)+ const { messages, latestSeq } = await enrichMessages(db, ctx.userId, { channelId }, items)return writeJSON({ messages, hasMoreOlder, hasMoreNewer, olderCursor, newerCursor, latestSeq })}@@ -65,7 +63,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {limit: pageSize,})const { items, hasMoreNewer, newerCursor } = buildSinceResponse(rows, pageSize)- const { messages, latestSeq } = await enrichAndFinalize(db, ctx.userId, channelId, items)+ const { messages, latestSeq } = await enrichMessages(db, ctx.userId, { channelId }, items)return writeJSON({ messages, hasMoreNewer, newerCursor, latestSeq })}@@ -78,54 +76,10 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {})const { items, hasMore, cursor: nextCursor } = buildPaginatedResponse(rows, pageSize)- const { messages, latestSeq } = await enrichAndFinalize(db, ctx.userId, channelId, items.slice().reverse())+ const { messages, latestSeq } = await enrichMessages(db, ctx.userId, { channelId }, items.slice().reverse())return writeJSON({ messages, hasMore, cursor: nextCursor, latestSeq })})-// Enrichment shared by all three GET branches — attachments, reactions,-// reply-target previews, child-channel thread indicators, and `latestSeq`.-// `items` is expected in chronological ASC (the wire order). Kept in this-// file (not extracted) so the branching above stays a five-line switch.-async function enrichAndFinalize(- db: ReturnType<typeof getDb>,- userId: string,- channelId: string,- items: Array<{ id: string; replyToId: string | null } & Record<string, unknown>>,-): Promise<{ messages: unknown[]; latestSeq: number }> {- const messageIds = items.map((m) => m.id)- const replyToIds = items.map((r) => r.replyToId).filter(Boolean) as string[]-- const [allAttachments, allReactions, replyMessages, childChannels, latestSeq] = await Promise.all([- messageIds.length > 0- ? queries.communityAttachment.listByMessageIds(db, messageIds)- : Promise.resolve([]),- messageIds.length > 0- ? queries.communityReaction.listReactionsByMessageIds(db, messageIds, userId)- : Promise.resolve([]),- replyToIds.length > 0- ? queries.communityMessage.getMessagesByIdsInScope(db, replyToIds, { channelId })- : Promise.resolve([]),- queries.communityChannel.listChildChannels(db, channelId),- queries.communityMessage.getLatestMessageSeq(db, { channelId }),- ])-- const attachmentsByMessage = groupAttachments(allAttachments)- const reactionsByMessage = groupReactions(allReactions, userId)-- const replyMap = new Map(replyMessages.map((m) => [m.id, m]))-- const threadByMessageId = new Map(- childChannels- .filter((c) => c.parentMessageId)- .map((c) => [c.parentMessageId!, { id: c.id, name: c.name, messageCount: c.messageCount ?? 0 }] as const),- )-- const messages = items.map((r) =>- mapMessageForApi(r as never, { replyMap, attachmentsByMessage, reactionsByMessage, threadByMessageId }),- )- return { messages, latestSeq }-}-export const POST = withAuth(async (req: NextRequest, ctx) => {const channelId = ctx.params?.idif (!channelId) return writeError("missing channel id", 400)diff --git a/src/web/src/app/api/community/dm/[id]/messages/route.ts b/src/web/src/app/api/community/dm/[id]/messages/route.tsindex 45dbc6cda..c20fa3981 100644--- a/src/web/src/app/api/community/dm/[id]/messages/route.ts+++ b/src/web/src/app/api/community/dm/[id]/messages/route.ts@@ -10,13 +10,11 @@ import {buildPaginatedResponse,buildAnchorResponse,buildSinceResponse,- groupAttachments,- groupReactions,} from "@/lib/community/messages"+import { enrichMessages } from "@/lib/community/enrich-messages"import { requireDMParticipant } from "@/lib/community/permissions"import { checkRateLimit } from "@/lib/rate-limit"import { createCommunityMessage } from "@/lib/community/message-handler"-import { mapMessageForApi } from "@/lib/community/message-payload"export const GET = withAuth(async (req: NextRequest, ctx) => {const dmId = ctx.params?.id@@ -48,7 +46,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {{ hasMoreOlder: around.hasMoreOlder, hasMoreNewer: around.hasMoreNewer },)- const { messages, latestSeq } = await enrichAndFinalize(db, ctx.userId, dmId, items)+ const { messages, latestSeq } = await enrichMessages(db, ctx.userId, { dmConversationId: dmId }, items)return writeJSON({ messages, hasMoreOlder, hasMoreNewer, olderCursor, newerCursor, latestSeq })}@@ -59,7 +57,7 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {limit: pageSize,})const { items, hasMoreNewer, newerCursor } = buildSinceResponse(rows, pageSize)- const { messages, latestSeq } = await enrichAndFinalize(db, ctx.userId, dmId, items)+ const { messages, latestSeq } = await enrichMessages(db, ctx.userId, { dmConversationId: dmId }, items)return writeJSON({ messages, hasMoreNewer, newerCursor, latestSeq })}@@ -70,45 +68,10 @@ export const GET = withAuth(async (req: NextRequest, ctx) => {})const { items, hasMore, cursor: nextCursor } = buildPaginatedResponse(rows, pageSize)- const { messages, latestSeq } = await enrichAndFinalize(db, ctx.userId, dmId, items.slice().reverse())+ const { messages, latestSeq } = await enrichMessages(db, ctx.userId, { dmConversationId: dmId }, items.slice().reverse())return writeJSON({ messages, hasMore, cursor: nextCursor, latestSeq })})-// DM sibling of the channel route's helper — no thread-indicator enrichment-// (DMs can't parent threads), everything else is symmetric.-async function enrichAndFinalize(- db: ReturnType<typeof getDb>,- userId: string,- dmId: string,- items: Array<{ id: string; replyToId: string | null } & Record<string, unknown>>,-): Promise<{ messages: unknown[]; latestSeq: number }> {- const messageIds = items.map((m) => m.id)- const replyToIds = items.map((r) => r.replyToId).filter(Boolean) as string[]-- const [allAttachments, allReactions, replyMessages, latestSeq] = await Promise.all([- messageIds.length > 0- ? queries.communityAttachment.listByMessageIds(db, messageIds)- : Promise.resolve([]),- messageIds.length > 0- ? queries.communityReaction.listReactionsByMessageIds(db, messageIds, userId)- : Promise.resolve([]),- replyToIds.length > 0- ? queries.communityMessage.getMessagesByIdsInScope(db, replyToIds, { dmConversationId: dmId })- : Promise.resolve([]),- queries.communityMessage.getLatestMessageSeq(db, { dmConversationId: dmId }),- ])-- const attachmentsByMessage = groupAttachments(allAttachments)- const reactionsByMessage = groupReactions(allReactions, userId)-- const replyMap = new Map(replyMessages.map((m) => [m.id, m]))-- const messages = items.map((r) =>- mapMessageForApi(r as never, { replyMap, attachmentsByMessage, reactionsByMessage }),- )- return { messages, latestSeq }-}-export const POST = withAuth(async (req: NextRequest, ctx) => {const dmId = ctx.params?.idif (!dmId) return writeError("missing dm id", 400)diff --git a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsxindex 5b8fdb4e6..22851d229 100644--- a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx+++ b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx@@ -1,6 +1,6 @@"use client"-import { useCallback, useEffect, useMemo, useState } from "react"+import { useCallback, useEffect, useMemo, useRef, useState } from "react"import { useParams, useRouter, useSearchParams } from "next/navigation"import { toast } from "sonner"import { apiFetch, toastApiError } from "@/lib/api/client"@@ -35,6 +35,7 @@ import { useChannelMembers, useAddableMembers, useAddChannelMember, useRemoveChaimport { useThreadParticipants, useAddThreadParticipant, useRemoveThreadParticipant } from "@/hooks/community/use-thread-participants"import { useMessages } from "@/hooks/community/use-messages"import { useChannelReadStateSnapshot } from "@/hooks/community/use-channel-read-state"+import { useChannelBootstrap } from "@/hooks/community/use-channel-bootstrap"import { useChannelWatermark } from "@/hooks/community/use-channel-watermark"import { useEagerChannelRead } from "@/hooks/community/use-eager-channel-read"import {@@ -289,22 +290,33 @@ function ChannelView() {serverName: currentServer?.name ?? "",}))}, [currentServer, serverId])+ // A jump-open (?msg=) must anchor on the jump target, not the read pointer,+ // so it keeps the legacy read-state → ?anchor=jump path. Otherwise use the+ // combined bootstrap: ONE request resolves the read pointer AND seeds the+ // initial message window, collapsing the old serial read-state → messages+ // chain (see plans/community-switch-perf-optimization.md WS2).+ const useBootstrap = !jumpTargetId+ const bootstrap = useChannelBootstrap(channelId, { enabled: useBootstrap })+ const legacySnapshot = useChannelReadStateSnapshot(useBootstrap ? null : channelId)+// Frozen-once snapshot of the viewer's read pointer for this channel — the// anchor for the "New" divider AND the mount-time initial scroll target.// The value NEVER changes during the mount even as the watermark advances.- const { snapshot: readSnapshot, isFetching: readSnapshotFetching } =- useChannelReadStateSnapshot(channelId)+ const readSnapshot = useBootstrap ? bootstrap.readState : legacySnapshot.snapshot+ const readSnapshotFetching = useBootstrap ? bootstrap.isFetching : legacySnapshot.isFetching// Anchor the initial page on the read pointer so an unread-heavy channel// opens with a centered window instead of the newest 50. Pass `undefined`- // while the snapshot is still resolving — the hook stays disabled until+ // while the pointer is still resolving — the hook stays disabled until// the value settles (a bare `null` would fall back to newest-mode too- // early).+ // early). On the bootstrap path the initial page is pre-seeded, so trust it+ // and don't refetch page 0 on mount.const messagesQuery = useMessages(channelId, {lastReadMessageId: readSnapshotFetching? undefined: (readSnapshot?.lastReadMessageId ?? null),anchorMessageId: jumpTargetId,+ trustSeededInitialPage: useBootstrap && bootstrap.isReady,})const {messages,@@ -562,16 +574,18 @@ function ChannelView() {const togglePanel = (k: Exclude<RightPanel, null>) =>setRightPanel((p) => (p === k ? null : k))- const enterThread = (id: string) => {+ const enterThread = useCallback((id: string) => {// No eager read PUT here — the thread page's `useEagerChannelRead` fires it// on mount AFTER its read-state snapshot latches, so the "New" divider// still anchors to the pre-open pointer. A PUT here would race the snapshot.router.push(`/c/channels/${params.serverId}/${id}`)- }+ }, [router, params.serverId])- const openProfile: OpenProfile = (name, e, discriminator, userId) => {- uiHandlers.openProfile?.(name, e, discriminator, userId)- }+ // Stable so it doesn't bust the memoized message rows; reads uiHandlers+ // lazily through the actions ref (assigned just below).+ const openProfile = useCallback<OpenProfile>((name, e, discriminator, userId) => {+ actionsCtxRef.current.uiHandlers.openProfile?.(name, e, discriminator, userId)+ }, [])// ── Message actions ─────────────────────────────────────────────────────//@@ -604,17 +618,34 @@ function ChannelView() {[sendMessageMut, channelId, currentUser.id, currentUser.name, currentUser.avatar],)- const messageActions = {+ // Latest-ref for the values the message actions read at call time. Keeping+ // these off the callback deps lets `messageActions` stay reference-STABLE+ // across renders (a new `messages` array on every WS tick would otherwise+ // rebuild every handler and defeat the memoized message rows). The handlers+ // only ever read these lazily on click, so a ref is exactly right.+ const actionsCtxRef = useRef<{+ messages: Msg[]+ pinnedIds: Set<string>+ channelName: string+ uiHandlers: typeof uiHandlers+ }>({ messages, pinnedIds, channelName, uiHandlers })+ // Latest-ref write during render is intentional here: the ref only feeds+ // click-time reads inside the stable `messageActions` callbacks, never+ // render output, so it can't cause a missed update.+ /* eslint-disable-next-line react-hooks/immutability -- latest-ref for lazy click reads */+ actionsCtxRef.current = { messages, pinnedIds, channelName, uiHandlers }++ const messageActions = useMemo(() => ({onToggleReaction: (id: string, emoji: string) =>toggleReactionApi({ channelId, messageId: id, emoji, userId: currentUser.id }),onReact: (id: string, emoji: string) =>toggleReactionApi({ channelId, messageId: id, emoji, userId: currentUser.id }),onReply: (id: string) => {- const m = messages.find((x) => x.id === id)+ const m = actionsCtxRef.current.messages.find((x) => x.id === id)if (m) setReplyTo({ id: m.id, authorName: m.authorName ?? "", text: m.content ?? "" })},onPin: (id: string) => {- const isPinned = pinnedIds.has(id)+ const isPinned = actionsCtxRef.current.pinnedIds.has(id)if (isPinned) {unpinMessageMut.mutate({ channelId, messageId: id }, {onSuccess: () => toast("Message unpinned"),@@ -629,8 +660,8 @@ function ChannelView() {}},onCreateThread: async (id: string) => {- const m = messages.find((x) => x.id === id)- const name = deriveThreadName(m?.content, channelName)+ const m = actionsCtxRef.current.messages.find((x) => x.id === id)+ const name = deriveThreadName(m?.content, actionsCtxRef.current.channelName)try {const data = await createThreadMut.mutateAsync({ channelId, messageId: id, name })router.push(`/c/channels/${params.serverId}/${data.id}`)@@ -639,15 +670,15 @@ function ChannelView() {}},onCopy: (id: string) => {- const m = messages.find((x) => x.id === id)+ const m = actionsCtxRef.current.messages.find((x) => x.id === id)if (m?.content) { navigator.clipboard?.writeText(m.content); toast("Copied to clipboard") }},onRetry: (id: string) => {- const m = messages.find((x) => x.id === id)+ const m = actionsCtxRef.current.messages.find((x) => x.id === id)if (m?.content) void doSend(m.content)},onPreviewImage: (url: string) => {- uiHandlers.previewImage?.(url)+ actionsCtxRef.current.uiHandlers.previewImage?.(url)},onDownloadFile: (url: string) => {const a = document.createElement("a")@@ -655,10 +686,24 @@ function ChannelView() {a.download = url.split("/").pop() ?? "file"a.click()},- }+ // Deps are all reference-stable: channelId, the mutation objects (TanStack+ // returns stable refs), doSend (useCallback), router/params. Volatile reads+ // go through actionsCtxRef.+ }), [channelId, currentUser.id, toggleReactionApi, unpinMessageMut, pinMessageMut, createThreadMut, doSend, router, params.serverId])- const threadActions = { ...messageActions, onCreateThread: undefined }+ const threadActions = useMemo(+ () => ({ ...messageActions, onCreateThread: undefined }),+ [messageActions],+ )+ // Reference-stable across renders (members churns on every presence/roster+ // tick). A new identity here would bust every memoized message row on a+ // switch — the exact re-render storm we're killing. Read `members` lazily+ // through a ref and rebuild the resolver per call; the resolver is cheap.+ // Memoized on `members`: identity changes only when the roster changes (not+ // on every render), so it doesn't needlessly bust the memoized message rows,+ // while still refreshing names when membership genuinely updates. Called+ // during render (typing names), so a ref-during-render approach is out.const resolveUserName = useMemo(() => makeUserNameResolver(members), [members])// ── Send messages ───────────────────────────────────────────────────────diff --git a/src/web/src/components/community/message-body.tsx b/src/web/src/components/community/message-body.tsxindex 42c80e2e7..1c72b3511 100644--- a/src/web/src/components/community/message-body.tsx+++ b/src/web/src/components/community/message-body.tsx@@ -1,4 +1,4 @@-import { useMemo } from "react"+import { memo, useMemo } from "react"import { Streamdown } from "streamdown"import rehypeSanitize, { defaultSchema, type Options as SanitizeSchema } from "rehype-sanitize"import { harden } from "rehype-harden"@@ -83,7 +83,7 @@ const REHYPE_PLUGINS: PluggableList = [// URL stays as a plain auto-linked <a> in the message body, and a rich join// card renders BELOW it. Both surfaces coexist so users can still copy/share// the raw link even when the card is present.-export function MessageBody({ text, onOpenProfile }: { text: string; onOpenProfile?: OpenProfile }) {+function MessageBodyImpl({ text, onOpenProfile }: { text: string; onOpenProfile?: OpenProfile }) {const inviteTokens = useMemo(() => extractInviteTokens(text), [text])const components = useMemo(() => buildMdComponents(onOpenProfile), [onOpenProfile])return (@@ -125,3 +125,10 @@ export function MessageBody({ text, onOpenProfile }: { text: string; onOpenProfi</div>)}++// Memoized: the message body is pure in (text, onOpenProfile). Once the row's+// `onOpenProfile` is reference-stable (see message-list callback stabilization),+// re-rendering the parent Message no longer re-runs Streamdown's markdown parse+// + its per-Block subtree — the largest single cost in the switch re-render+// storm (Streamdown/Block were top react-scan offenders).+export const MessageBody = memo(MessageBodyImpl)diff --git a/src/web/src/components/community/message-list.tsx b/src/web/src/components/community/message-list.tsxindex 7594d578a..5b78a9035 100644--- a/src/web/src/components/community/message-list.tsx+++ b/src/web/src/components/community/message-list.tsx@@ -4,7 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"import { ArrowDown } from "lucide-react"import { tid } from "@/lib/community/testids"import { DateDivider, NewDivider } from "./dividers"-import { Message } from "./message"+import { MessageRow } from "./message-row"import { TypingIndicator } from "./typing-indicator"import { ChannelIcon } from "./channel-icon"import { Skeleton } from "@/components/ui/skeleton"@@ -369,22 +369,22 @@ export function MessageList({// only ever observes rows that exist in the DOM,// which virtualization doesn't change).<div data-msg-id={item.m.id} data-testid={tid.message(item.m.id)}>- <Message+ <MessageRowm={item.m}pinned={pinnedIds?.has(item.m.id)}+ highlighted={jumped === item.m.id}onOpenThread={onOpenThread}onOpenProfile={onOpenProfile}- onJumpReply={() => item.m.replyTo && jumpTo(item.m.replyTo.id)}- onToggleReaction={onToggleReaction ? (emoji) => onToggleReaction(item.m.id, emoji) : undefined}- onReact={onReact ? (emoji) => onReact(item.m.id, emoji) : undefined}- onReply={onReply ? () => onReply(item.m.id) : undefined}- onPin={onPin ? () => onPin(item.m.id) : undefined}- onCreateThread={onCreateThread ? () => onCreateThread(item.m.id) : undefined}- onCopy={onCopy ? () => onCopy(item.m.id) : undefined}- onRetry={onRetry ? () => onRetry(item.m.id) : undefined}+ onToggleReactionId={onToggleReaction}+ onReactId={onReact}+ onReplyId={onReply}+ onPinId={onPin}+ onCreateThreadId={onCreateThread}+ onCopyId={onCopy}+ onRetryId={onRetry}+ onJumpToId={jumpTo}onPreviewImage={onPreviewImage}onDownloadFile={onDownloadFile}- highlighted={jumped === item.m.id}resolveUserName={resolveUserName}onImageLoad={onImageLoad}/>diff --git a/src/web/src/components/community/message-row.tsx b/src/web/src/components/community/message-row.tsxnew file mode 100644index 000000000..bc46a2da6--- /dev/null+++ b/src/web/src/components/community/message-row.tsx@@ -0,0 +1,91 @@+"use client"++import { memo, useCallback } from "react"+import { Message } from "./message"+import type { RenderMsg, OpenProfile } from "./_types"++// A thin, memoized per-row wrapper between the virtualized list and `Message`.+//+// Why it exists: the list's `.map()` used to create a fresh inline arrow for+// every callback of every row on every render (`onReply={() => onReply(m.id)}`+// etc.), which gave `Message` new prop identities each render and defeated its+// memo. This wrapper takes the ID-BASED callbacks straight from the parent+// (which are reference-stable — see MessageList's useCallback bundle) plus the+// message, and binds the per-row (no-arg / emoji-only) handlers ONCE via+// `useCallback` keyed on the id. So `Message` receives stable callbacks and its+// custom-comparator memo can actually bail out. See+// plans/community-switch-perf-optimization.md (WS3).+export interface MessageRowProps {+ m: RenderMsg+ pinned?: boolean+ highlighted?: boolean+ onOpenThread: (id: string) => void+ onOpenProfile?: OpenProfile+ onToggleReactionId?: (id: string, emoji: string) => void+ onReactId?: (id: string, emoji: string) => void+ onReplyId?: (id: string) => void+ onPinId?: (id: string) => void+ onCreateThreadId?: (id: string) => void+ onCopyId?: (id: string) => void+ onRetryId?: (id: string) => void+ onJumpToId?: (id: string) => void+ onPreviewImage?: (name: string) => void+ onDownloadFile?: (name: string) => void+ resolveUserName?: (userId: string) => string+ onImageLoad?: () => void+}++function MessageRowImpl(props: MessageRowProps) {+ const {+ m, pinned, highlighted, onOpenThread, onOpenProfile,+ onToggleReactionId, onReactId, onReplyId, onPinId, onCreateThreadId,+ onCopyId, onRetryId, onJumpToId, onPreviewImage, onDownloadFile,+ resolveUserName, onImageLoad,+ } = props+ const id = m.id+ const replyToId = m.replyTo?.id++ // Each bound callback is stable across renders as long as the id-based+ // handler and the id are stable — so `Message`'s memo bails out. Each+ // useCallback takes an inline function (lint requires it) and internally+ // no-ops / short-circuits when its id-based source is absent; we then map an+ // absent source to `undefined` at the prop site so `Message` sees the same+ // "feature off" signal it did before.+ const onToggleReaction = useCallback((emoji: string) => onToggleReactionId?.(id, emoji), [onToggleReactionId, id])+ const onReact = useCallback((emoji: string) => onReactId?.(id, emoji), [onReactId, id])+ const onReply = useCallback(() => onReplyId?.(id), [onReplyId, id])+ const onPin = useCallback(() => onPinId?.(id), [onPinId, id])+ const onCreateThread = useCallback(() => onCreateThreadId?.(id), [onCreateThreadId, id])+ const onCopy = useCallback(() => onCopyId?.(id), [onCopyId, id])+ const onRetry = useCallback(() => onRetryId?.(id), [onRetryId, id])+ const onJumpReply = useCallback(() => { if (replyToId) onJumpToId?.(replyToId) }, [onJumpToId, replyToId])++ // Map an absent id-based source to `undefined` so `Message` sees the same+ // "feature off" signal it used to (its interactive/menu logic keys off which+ // handlers are undefined). The bound callbacks above stay reference-stable,+ // and these ternaries are stable too (they only flip when the source appears+ // /disappears, which is rare), so the memo still bails on normal re-renders.+ return (+ <Message+ m={m}+ pinned={pinned}+ highlighted={highlighted}+ onOpenThread={onOpenThread}+ onOpenProfile={onOpenProfile}+ onJumpReply={onJumpToId && replyToId ? onJumpReply : undefined}+ onToggleReaction={onToggleReactionId ? onToggleReaction : undefined}+ onReact={onReactId ? onReact : undefined}+ onReply={onReplyId ? onReply : undefined}+ onPin={onPinId ? onPin : undefined}+ onCreateThread={onCreateThreadId ? onCreateThread : undefined}+ onCopy={onCopyId ? onCopy : undefined}+ onRetry={onRetryId ? onRetry : undefined}+ onPreviewImage={onPreviewImage}+ onDownloadFile={onDownloadFile}+ resolveUserName={resolveUserName}+ onImageLoad={onImageLoad}+ />+ )+}++export const MessageRow = memo(MessageRowImpl)diff --git a/src/web/src/components/community/message.render.test.ts b/src/web/src/components/community/message.render.test.tsnew file mode 100644index 000000000..894f5c525--- /dev/null+++ b/src/web/src/components/community/message.render.test.ts@@ -0,0 +1,138 @@+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"+import React from "react"+import TestRenderer, { act } from "react-test-renderer"+import { Message } from "./message"+import type { RenderMsg } from "./_types"++// WS3 render-behavior tests (see plans/community-switch-perf-optimization.md):+// - the custom memo comparator bails out despite the per-render `m` clone,+// - but does NOT drop legit content/reaction/thread updates,+// - and overlay roots are lazily mounted (bare row until activated).+//+// Uses react-test-renderer under the repo's node env (no jsdom / @testing-+// library), matching message-list.mount-identity.test.ts.++function baseMsg(over: Partial<RenderMsg> = {}): RenderMsg {+ return {+ id: "m1",+ type: "chat",+ authorId: "u1",+ authorName: "Alice",+ content: "hello",+ createdAt: new Date(0).toISOString(),+ grouped: false,+ ...over,+ }+}++const genericMock = {+ willUpdate: () => {}, didUpdate: () => {},+ addEventListener: () => {}, removeEventListener: () => {},+ getBoundingClientRect: () => ({ top: 0, left: 0, right: 0, bottom: 0, width: 0, height: 0 }),+}++let renderCount = 0+// A probe that counts how many times the body content actually renders by+// wrapping the memoized Message; we detect bail-out by rendering Message with a+// spy callback that increments on each real render via a child sentinel.+function makeTree(props: Parameters<typeof Message>[0]) {+ return React.createElement(Message, props)+}++beforeEach(() => {+ renderCount = 0+ const g = globalThis as unknown as { ResizeObserver: unknown; IntersectionObserver: unknown }+ g.ResizeObserver = class { observe() {} disconnect() {} unobserve() {} }+ g.IntersectionObserver = class { observe() {} disconnect() {} unobserve() {} }+})+afterEach(() => {+ vi.restoreAllMocks()+})++describe("Message memo comparator", () => {+ it("bails out when compared fields are unchanged despite a fresh `m` clone", () => {+ const onOpenThread = vi.fn()+ const stableProps = { onOpenThread }+ // Spy on the resolver: it's called during render, so call count tracks renders.+ const resolveUserName = vi.fn((id: string) => id)++ let renderer: TestRenderer.ReactTestRenderer+ const m1 = baseMsg({ reactions: [{ emoji: "👍", count: 1, me: false, userIds: ["u2"] }] })+ act(() => {+ renderer = TestRenderer.create(+ makeTree({ m: m1, resolveUserName, ...stableProps }),+ { createNodeMock: () => genericMock },+ )+ })+ const callsAfterFirst = resolveUserName.mock.calls.length++ // Re-render with a NEW clone that is field-equal (the message-list-items+ // clone pattern: { ...m }). Comparator must bail → resolver not called again.+ act(() => {+ renderer!.update(makeTree({ m: { ...m1 }, resolveUserName, ...stableProps }))+ })+ expect(resolveUserName.mock.calls.length).toBe(callsAfterFirst)+ })++ it("re-renders when content changes (edit)", () => {+ const onOpenThread = vi.fn()+ const resolveUserName = vi.fn((id: string) => id)+ let renderer: TestRenderer.ReactTestRenderer+ const m1 = baseMsg({ reactions: [{ emoji: "👍", count: 1, me: false, userIds: ["u2"] }] })+ act(() => {+ renderer = TestRenderer.create(+ makeTree({ m: m1, resolveUserName, onOpenThread }),+ { createNodeMock: () => genericMock },+ )+ })+ const before = resolveUserName.mock.calls.length+ act(() => {+ renderer!.update(makeTree({ m: { ...m1, content: "edited" }, resolveUserName, onOpenThread }))+ })+ expect(resolveUserName.mock.calls.length).toBeGreaterThan(before)+ })++ it("re-renders when reactions change", () => {+ const onOpenThread = vi.fn()+ const resolveUserName = vi.fn((id: string) => id)+ let renderer: TestRenderer.ReactTestRenderer+ const m1 = baseMsg({ reactions: [{ emoji: "👍", count: 1, me: false, userIds: ["u2"] }] })+ act(() => {+ renderer = TestRenderer.create(+ makeTree({ m: m1, resolveUserName, onOpenThread }),+ { createNodeMock: () => genericMock },+ )+ })+ const before = resolveUserName.mock.calls.length+ act(() => {+ renderer!.update(makeTree({+ m: { ...m1, reactions: [{ emoji: "👍", count: 2, me: true, userIds: ["u2", "u3"] }] },+ resolveUserName, onOpenThread,+ }))+ })+ expect(resolveUserName.mock.calls.length).toBeGreaterThan(before)+ })+})++describe("Message lazy overlays", () => {+ it("does not mount the ContextMenu root until the row is activated", () => {+ const onOpenThread = vi.fn()+ let renderer: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(+ // interactive requires a menu handler present + not compact+ makeTree({ m: baseMsg(), onOpenThread, onReply: () => {}, onReact: () => {} }),+ { createNodeMock: () => genericMock },+ )+ })+ // Before activation: the row renders but the ContextMenu content+ // (MessageContextItems) is not in the tree. We assert no element carries the+ // context-menu content marker by checking the rendered JSON has no+ // "ContextMenu"-typed node. A cheap structural proxy: the "Add reaction"+ // toolbar (only mounted when activated) is absent.+ const json = renderer!.toJSON()+ const tree = JSON.stringify(json)+ // The reaction-add testid only renders inside the activated toolbar.+ expect(tree).not.toContain("reaction-add")+ })+})diff --git a/src/web/src/components/community/message.tsx b/src/web/src/components/community/message.tsxindex 1a68fb2d9..d42b73d63 100644--- a/src/web/src/components/community/message.tsx+++ b/src/web/src/components/community/message.tsx@@ -1,6 +1,6 @@"use client"-import { useState } from "react"+import { memo, useState } from "react"import type React from "react"import {MessagesSquare, UserPlus, SmilePlus, Reply,@@ -31,7 +31,7 @@ export function attachmentAspectRatio(width: number | undefined, height: numberreturn width && height ? `${width}/${height}` : ATTACHMENT_FALLBACK_ASPECT_RATIO}-export function Message({+function MessageImpl({m, compact, pinned, onOpenThread, onOpenProfile, onJumpReply,onToggleReaction, onReact, onReply, onPin, onCreateThread, onCopy, onRetry,onPreviewImage, onDownloadFile, highlighted, resolveUserName, onImageLoad,@@ -61,6 +61,13 @@ export function Message({}) {// keep the hover toolbar pinned open while its ⋯ dropdown is openconst [toolbarOpen, setToolbarOpen] = useState(false)+ // Lazy-mount the row's Base UI overlay roots (ContextMenu / DropdownMenu /+ // EmojiPicker Popover / reaction Tooltips). Eagerly mounting them per visible+ // row was the bulk of the switch re-render storm (FloatingTree/MenuRoot ×1000s+ // — see plans/community-switch-perf-optimization.md). Activate on the first+ // hover OR focus OR keydown/contextmenu — focus/keydown are required for a11y+ // (keyboard context menu / Tab-to-row have no pointerenter).+ const [activated, setActivated] = useState(false)if (m.type === "system") {const Icon = m.systemKind === "thread" ? MessagesSquare : UserPlus@@ -81,6 +88,7 @@ export function Message({}const showMenu = hasMessageMenu(menuHandlers)const interactive = !compact && showMenu+ const activate = interactive && !activated ? () => setActivated(true) : undefinedconst row = (<divclassName={[@@ -88,9 +96,12 @@ export function Message({m.grouped ? "py-0" : "mt-3 pt-1.5 pb-0",highlighted ? "bg-primary/10" : "hover:bg-accent/40",].join(" ")}+ onPointerEnter={activate}+ onFocusCapture={activate}+ onKeyDownCapture={activate}><div className="min-w-0 flex-1">- {interactive && (+ {interactive && activated && (<div className={`absolute right-2 z-20 flex items-center gap-1 rounded-lg border border-border/60 bg-card px-2 py-1 shadow-(--e1) transition-opacity duration-150 ${m.grouped ? "-top-2" : "-top-3"} ${toolbarOpen ? "opacity-100" : "pointer-events-none opacity-0 group-hover:pointer-events-auto group-hover:opacity-100"}`}>{onReact && (<EmojiPickerPopover side="bottom" align="end" onPick={(e) => onReact(e)} onOpenChange={setToolbarOpen}>@@ -270,7 +281,10 @@ export function Message({<NumberTicker value={r.count} className="text-xs text-muted-foreground" /></button>)- if (!names) return <div key={i}>{chip}</div>+ // Until the row is activated, render the bare chip (still fully+ // clickable) without its Base UI Tooltip root — the name tooltip+ // only matters on hover, and hover activates the row.+ if (!names || !activated) return <div key={i}>{chip}</div>return (<Tooltip key={i}><TooltipTrigger render={chip} />@@ -278,14 +292,20 @@ export function Message({</Tooltip>)})}- <Tooltip>- <EmojiPickerPopover side="top" align="start" onPick={(e) => onReact?.(e)}>- <TooltipTrigger render={<button className="grid h-6 w-7 place-items-center rounded-md bg-secondary text-muted-foreground hover:text-foreground" aria-label="Add reaction" />}>- <SmilePlus className="size-4" />- </TooltipTrigger>- </EmojiPickerPopover>- <TooltipContent>Add reaction</TooltipContent>- </Tooltip>+ {activated ? (+ <Tooltip>+ <EmojiPickerPopover side="top" align="start" onPick={(e) => onReact?.(e)}>+ <TooltipTrigger render={<button className="grid h-6 w-7 place-items-center rounded-md bg-secondary text-muted-foreground hover:text-foreground" aria-label="Add reaction" />}>+ <SmilePlus className="size-4" />+ </TooltipTrigger>+ </EmojiPickerPopover>+ <TooltipContent>Add reaction</TooltipContent>+ </Tooltip>+ ) : (+ <button className="grid h-6 w-7 place-items-center rounded-md bg-secondary text-muted-foreground hover:text-foreground" aria-label="Add reaction">+ <SmilePlus className="size-4" />+ </button>+ )}</div>)}@@ -319,7 +339,12 @@ export function Message({</div>)- if (!interactive) return row+ // Not interactive, or not yet activated → render the bare row (which carries+ // the pointerenter/focus/keydown activation handlers). The row's Base UI+ // ContextMenu root is only mounted once hover/focus has activated it — and a+ // right-click is always preceded by a pointerenter (mouse arriving on the+ // row), and Shift+F10 by focus, so the menu is mounted before it's invoked.+ if (!interactive || !activated) return rowreturn (<ContextMenu><ContextMenuTrigger className="select-text" render={row} />@@ -329,3 +354,59 @@ export function Message({</ContextMenu>)}++type MessageProps = Parameters<typeof MessageImpl>[0]++// Custom comparator — REQUIRED, not optional. `flattenMessageItems`+// (message-list-items.ts) spreads a fresh `{ ...m, grouped }` object for every+// message on every render, so a default shallow memo would compare `m` by+// reference, always see "new", and never bail out (a no-op). We instead compare+// the fields that legitimately change and REQUIRE the callbacks + resolveUserName+// to be reference-stable (see message-list callback stabilization). An id-only+// comparator would silently drop edits / reaction / thread-count updates — so+// every user-visible field is enumerated here.+function messagePropsEqual(prev: MessageProps, next: MessageProps): boolean {+ if (prev.m !== next.m) {+ const a = prev.m+ const b = next.m+ if (+ a.id !== b.id ||+ a.type !== b.type ||+ a.content !== b.content ||+ a.grouped !== b.grouped ||+ a.failed !== b.failed ||+ a.authorName !== b.authorName ||+ a.authorAvatar !== b.authorAvatar ||+ a.color !== b.color ||+ a.createdAt !== b.createdAt ||+ a.reactions !== b.reactions ||+ a.attachments !== b.attachments ||+ a.embeds !== b.embeds ||+ a.replyTo !== b.replyTo ||+ a.thread !== b.thread+ ) {+ return false+ }+ }+ return (+ prev.compact === next.compact &&+ prev.pinned === next.pinned &&+ prev.highlighted === next.highlighted &&+ prev.onOpenThread === next.onOpenThread &&+ prev.onOpenProfile === next.onOpenProfile &&+ prev.onJumpReply === next.onJumpReply &&+ prev.onToggleReaction === next.onToggleReaction &&+ prev.onReact === next.onReact &&+ prev.onReply === next.onReply &&+ prev.onPin === next.onPin &&+ prev.onCreateThread === next.onCreateThread &&+ prev.onCopy === next.onCopy &&+ prev.onRetry === next.onRetry &&+ prev.onPreviewImage === next.onPreviewImage &&+ prev.onDownloadFile === next.onDownloadFile &&+ prev.resolveUserName === next.resolveUserName &&+ prev.onImageLoad === next.onImageLoad+ )+}++export const Message = memo(MessageImpl, messagePropsEqual)diff --git a/src/web/src/hooks/community/use-channel-bootstrap.test.ts b/src/web/src/hooks/community/use-channel-bootstrap.test.tsnew file mode 100644index 000000000..fbf06c386--- /dev/null+++ b/src/web/src/hooks/community/use-channel-bootstrap.test.ts@@ -0,0 +1,52 @@+import { describe, it, expect } from "vitest"+import { buildMessagesSeed } from "./use-channel-bootstrap"++// The seed shape is load-bearing: useMessages' getNext/PreviousPageParam and+// anchor-revalidation read `pageParams`, and WS inserts patch `pages[0]` using+// the anchor-mode envelope. A wrong shape silently breaks pagination / live+// updates. See plans/community-switch-perf-optimization.md WS2.++function resp(over: Record<string, unknown> = {}) {+ return {+ readState: { lastReadMessageId: "m_10", lastReadAt: "t", lastReadSeq: 10 },+ anchorMode: "anchor" as const,+ anchorMessageId: "m_10",+ messages: [{ id: "m_10", type: "chat" as const }],+ latestSeq: 20,+ hasMoreOlder: true,+ hasMoreNewer: true,+ olderCursor: "oc",+ newerCursor: "nc",+ ...over,+ } as Parameters<typeof buildMessagesSeed>[0]+}++describe("buildMessagesSeed", () => {+ it("seeds a single page with the mandatory anchor pageParam", () => {+ const seed = buildMessagesSeed(resp())+ expect(seed.pages).toHaveLength(1)+ expect(seed.pageParams).toEqual([{ mode: "anchor", anchor: "m_10" }])+ })++ it("carries the anchor-mode envelope (hasMoreOlder/Newer + cursors) for WS-patch compat", () => {+ const seed = buildMessagesSeed(resp())+ const page = seed.pages[0]+ expect(page.hasMoreOlder).toBe(true)+ expect(page.hasMoreNewer).toBe(true)+ expect(page.olderCursor).toBe("oc")+ expect(page.newerCursor).toBe("nc")+ expect(page.latestSeq).toBe(20)+ // Never the legacy `hasMore` field — that would misroute getNextPageParam.+ expect(page.hasMore).toBeUndefined()+ })++ it("uses a newest pageParam when the server fell back (deleted/absent anchor)", () => {+ const seed = buildMessagesSeed(resp({ anchorMode: "newest", anchorMessageId: null }))+ expect(seed.pageParams).toEqual([{ mode: "newest" }])+ })++ it("uses newest when anchorMode is anchor but the id is missing (defensive)", () => {+ const seed = buildMessagesSeed(resp({ anchorMode: "anchor", anchorMessageId: null }))+ expect(seed.pageParams).toEqual([{ mode: "newest" }])+ })+})diff --git a/src/web/src/hooks/community/use-channel-bootstrap.ts b/src/web/src/hooks/community/use-channel-bootstrap.tsnew file mode 100644index 000000000..c6f83f9e9--- /dev/null+++ b/src/web/src/hooks/community/use-channel-bootstrap.ts@@ -0,0 +1,122 @@+"use client"++import { useEffect, useRef, useState } from "react"+import { useQuery, useQueryClient, type InfiniteData } from "@tanstack/react-query"+import { apiFetch } from "@/lib/api/client"+import { communityKeys } from "@/lib/query-keys"+import type { ChannelReadStateSnapshot } from "./use-channel-read-state"+import type { MessagesPage, MessagesPageParam } from "./use-messages"++// Response of GET /api/community/channels/:id/bootstrap — the read pointer plus+// the initial (anchor-centered or newest) message window, in one round-trip.+// See plans/community-switch-perf-optimization.md (WS2).+type ChannelBootstrapResponse = {+ readState: ChannelReadStateSnapshot+ anchorMode: "anchor" | "newest"+ anchorMessageId: string | null+} & MessagesPage++/**+ * Build the `InfiniteData` seed for `channelMessages(id)` from a bootstrap+ * response. Pure + exported so the seed shape (mandatory `pageParams`, anchor+ * vs newest mode, anchor-mode envelope) is unit-tested without a render loop.+ */+export function buildMessagesSeed(+ data: ChannelBootstrapResponse,+): InfiniteData<MessagesPage, MessagesPageParam> {+ const page: MessagesPage = {+ messages: data.messages as MessagesPage["messages"],+ latestSeq: data.latestSeq,+ hasMoreOlder: data.hasMoreOlder,+ hasMoreNewer: data.hasMoreNewer,+ olderCursor: data.olderCursor,+ newerCursor: data.newerCursor,+ }+ const pageParam: MessagesPageParam =+ data.anchorMode === "anchor" && data.anchorMessageId+ ? { mode: "anchor", anchor: data.anchorMessageId }+ : { mode: "newest" }+ return { pages: [page], pageParams: [pageParam] }+}++/**+ * De-serialized channel open. Replaces the read-state → gated messages serial+ * chain on the INITIAL window: one request seeds both the read-state snapshot+ * cache and the `channelMessages` infinite-query cache, so `useMessages` can+ * paginate + WS-patch from the seed without a second round-trip.+ *+ * Skipped when `jumpTargetId` is set — a jump-open must anchor on the jump+ * target, not the read pointer, and the seed-then-trust mechanism would+ * otherwise override it (the page keeps the legacy read-state + ?anchor=jump+ * path in that case).+ *+ * Freeze-once: the returned `readState` latches the first resolved value for+ * the mount (like `useChannelReadStateSnapshot`'s `snapshotRef`), so a refetch+ * returning an advanced pointer never walks the "New" divider down the list.+ */+export function useChannelBootstrap(+ channelId: string | null | undefined,+ opts?: { enabled?: boolean },+): {+ readState: ChannelReadStateSnapshot | null+ isFetching: boolean+ isReady: boolean+} {+ const queryClient = useQueryClient()+ const enabled = !!channelId && (opts?.enabled ?? true)++ const query = useQuery<ChannelBootstrapResponse>({+ queryKey: channelId+ ? communityKeys.channelBootstrap(channelId)+ : ["community", "channel", "__none__", "bootstrap"],+ queryFn: async () => {+ const data = await apiFetch<ChannelBootstrapResponse>(+ `/api/community/channels/${channelId}/bootstrap`,+ )+ // Seed the message infinite-query cache so `useMessages` mounts on a+ // trusted first window instead of refetching it. The pageParams entry is+ // mandatory: getNextPageParam/getPreviousPageParam + anchor-revalidation+ // read it. Newest fallback seeds a `{ mode: "newest" }` param.+ queryClient.setQueryData(communityKeys.channelMessages(channelId!), buildMessagesSeed(data))+ // Seed the read-state snapshot cache too, so any consumer of that key+ // reads the same pointer without its own network fetch.+ queryClient.setQueryData(+ communityKeys.channelReadStateSnapshot(channelId!),+ data.readState,+ )+ return data+ },+ enabled,+ staleTime: Infinity,+ gcTime: 0,+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,+ retry: 1,+ })++ // Freeze the first resolved read pointer for the mount (see hook doc).+ const readRef = useRef<ChannelReadStateSnapshot | null>(null)+ const lastChannelIdRef = useRef<string | null | undefined>(channelId)+ /* eslint-disable react-hooks/refs -- sync channel-switch reset, mirrors use-channel-read-state */+ if (lastChannelIdRef.current !== channelId) {+ readRef.current = null+ lastChannelIdRef.current = channelId+ }+ /* eslint-enable react-hooks/refs */+ const [, force] = useState(0)+ useEffect(() => {+ if (readRef.current !== null) return+ if (query.data?.readState) {+ readRef.current = query.data.readState+ force((n) => n + 1)+ }+ }, [query.data])++ /* eslint-disable react-hooks/refs -- latched read pointer */+ return {+ readState: readRef.current ?? query.data?.readState ?? null,+ isFetching: query.isFetching,+ isReady: query.isSuccess,+ }+ /* eslint-enable react-hooks/refs */+}diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.tsindex 9a86ec0f2..396d17225 100644--- a/src/web/src/hooks/community/use-messages.ts+++ b/src/web/src/hooks/community/use-messages.ts@@ -170,6 +170,14 @@ type MessagesOpts = {* read snapshot resolves must NOT leave the query disabled.*/anchorMessageId?: string | null+ /**+ * When true, the initial page is trusted from a pre-seeded cache (the channel+ * bootstrap wrote `channelMessages(id)` before this hook mounted), so the+ * hook must NOT refetch page 0 on mount — otherwise the de-serialization win+ * is lost (bootstrap + a redundant messages fetch). Pagination (older/newer)+ * still refetches normally. Only affects the initial window.+ */+ trustSeededInitialPage?: boolean}// Shared pagination + reducer used by both channel and DM hooks. Kept inline@@ -237,6 +245,15 @@ function useMessagesInner(return { mode: "newer", cursor }},enabled,+ // Trust a bootstrap-seeded initial window: treat it as fresh so the hook+ // doesn't refetch page 0 on mount (otherwise the de-serialization win is+ // lost — bootstrap + a redundant messages fetch). Pagination still fetches+ // older/newer via getNext/PreviousPageParam. Without a seed these fall to+ // the library defaults (staleTime 0, refetchOnMount true), so the+ // non-bootstrap paths (DM, jump, forum) are unchanged.+ ...(opts?.trustSeededInitialPage+ ? { staleTime: Infinity, refetchOnMount: false as const }+ : {}),})// Flush any pending mark-read on scope switch / unmount so the 500msdiff --git a/src/web/src/lib/community/enrich-messages.ts b/src/web/src/lib/community/enrich-messages.tsnew file mode 100644index 000000000..9c529b9f2--- /dev/null+++ b/src/web/src/lib/community/enrich-messages.ts@@ -0,0 +1,64 @@+import { queries } from "@alook/shared"+import type { getDb } from "@/lib/db"+import { groupAttachments, groupReactions } from "@/lib/community/messages"+import { mapMessageForApi } from "@/lib/community/message-payload"++// Message enrichment shared by the channel messages route, the channel+// bootstrap route, and the DM messages route (previously three near-identical+// copies — see plans/community-switch-perf-optimization.md WS2). Attaches+// attachments, reactions, reply-target previews, `latestSeq`, and — for channel+// scope only — child-channel thread indicators.+//+// `items` is expected in chronological ASC (the wire order). Scope is a channel+// XOR a DM conversation; child-channel threads only exist under channels.++type Db = ReturnType<typeof getDb>++export type MessageScope = { channelId: string } | { dmConversationId: string }++function scopeSeqTarget(scope: MessageScope): { channelId: string } | { dmConversationId: string } {+ return scope+}++export async function enrichMessages(+ db: Db,+ userId: string,+ scope: MessageScope,+ items: Array<{ id: string; replyToId: string | null } & Record<string, unknown>>,+): Promise<{ messages: unknown[]; latestSeq: number }> {+ const isChannel = "channelId" in scope+ const messageIds = items.map((m) => m.id)+ const replyToIds = items.map((r) => r.replyToId).filter(Boolean) as string[]++ const [allAttachments, allReactions, replyMessages, childChannels, latestSeq] = await Promise.all([+ messageIds.length > 0+ ? queries.communityAttachment.listByMessageIds(db, messageIds)+ : Promise.resolve([]),+ messageIds.length > 0+ ? queries.communityReaction.listReactionsByMessageIds(db, messageIds, userId)+ : Promise.resolve([]),+ replyToIds.length > 0+ ? queries.communityMessage.getMessagesByIdsInScope(db, replyToIds, scope)+ : Promise.resolve([]),+ // Thread indicators only exist for channel-scoped messages.+ isChannel+ ? queries.communityChannel.listChildChannels(db, scope.channelId)+ : Promise.resolve([]),+ queries.communityMessage.getLatestMessageSeq(db, scopeSeqTarget(scope)),+ ])++ const attachmentsByMessage = groupAttachments(allAttachments)+ const reactionsByMessage = groupReactions(allReactions, userId)+ const replyMap = new Map(replyMessages.map((m) => [m.id, m]))++ const threadByMessageId = new Map(+ childChannels+ .filter((c) => c.parentMessageId)+ .map((c) => [c.parentMessageId!, { id: c.id, name: c.name, messageCount: c.messageCount ?? 0 }] as const),+ )++ const messages = items.map((r) =>+ mapMessageForApi(r as never, { replyMap, attachmentsByMessage, reactionsByMessage, threadByMessageId }),+ )+ return { messages, latestSeq }+}diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.tsindex e7599e2eb..d96cb6900 100644--- a/src/web/src/lib/query-keys.ts+++ b/src/web/src/lib/query-keys.ts@@ -74,6 +74,12 @@ export const communityKeys = {// anchored while the watermark advances.channelReadStateSnapshot: (channelId: string) =>[...communityKeys.all, "channel", channelId, "read-state-snapshot"] as const,+ // Channel-open bootstrap (read pointer + initial message window in one+ // request). Frozen per mount like the snapshot; gcTime:0 so a fresh mount+ // re-fetches. Distinct key so it doesn't collide with the seeded+ // channelMessages / read-state-snapshot caches it writes.+ channelBootstrap: (channelId: string) =>+ [...communityKeys.all, "channel", channelId, "bootstrap"] as const,// DM sibling of `channelReadStateSnapshot`. Same freeze semantics — the// hook latches the first non-null response so the "New" divider anchor// stays put while the progressive watermark advances.