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(community): kill the channel-switch re-render storm
Generf11a34834f6b
diff --git a/src/web/scripts/perf-report.test.ts b/src/web/scripts/perf-report.test.tsindex 23909c548..d19555d41 100644--- a/src/web/scripts/perf-report.test.ts+++ b/src/web/scripts/perf-report.test.ts@@ -87,8 +87,31 @@ describe("analyzeSwitch — non-network attribution", () => {})})-describe("analyzeSwitch — StrictMode adjustment", () => {- it("halves mount count for fibers that double-committed", () => {+describe("analyzeSwitch — mount de-echo (ring-buffer dedup)", () => {+ it("dedups mounts by fiberId regardless of how many commits re-report them", () => {+ // react-scan re-reports every still-mounted fiber on each later commit, so+ // the same first-mount fiber appears once per subsequent commit. The naive+ // total is inflated; deduping by fiberId recovers the true count. Here two+ // fibers are echoed across three commits (2 raw each → 6 raw), but only 2+ // components actually mounted.+ const echo = [+ { name: "ChannelView", fiberId: 7, actualDuration: 3 },+ { name: "MessageList", fiberId: 8, actualDuration: 2 },+ ]+ const a = analyzeSwitch(+ baseSwitch({+ commits: [+ { ts: 1050, kind: "commit", mounts: [...echo], rerenders: [] },+ { ts: 1080, kind: "commit", mounts: [...echo], rerenders: [] },+ { ts: 1120, kind: "commit", mounts: [...echo], rerenders: [] },+ ],+ }),+ )+ expect(a.mountCountRaw).toBe(6)+ expect(a.mountCountUnique).toBe(2)+ })++ it("counts id-less mounts individually (cannot dedup a missing id)", () => {const a = analyzeSwitch(baseSwitch({commits: [@@ -96,18 +119,34 @@ describe("analyzeSwitch — StrictMode adjustment", () => {ts: 1050,kind: "commit",mounts: [- { name: "ChannelView", fiberId: 7, actualDuration: 3 },- { name: "ChannelView", fiberId: 7, actualDuration: 3 },- { name: "MessageList", fiberId: 8, actualDuration: 2 },- { name: "MessageList", fiberId: 8, actualDuration: 2 },+ { name: "A", fiberId: 1, actualDuration: 1 },+ { name: "Anon", actualDuration: 1 },+ { name: "Anon", actualDuration: 1 },],rerenders: [],},],}),)- expect(a.mountCountRaw).toBe(4)- expect(a.mountCountAdjusted).toBe(2)+ expect(a.mountCountRaw).toBe(3)+ expect(a.mountCountUnique).toBe(3) // 1 unique id + 2 id-less+ })+})++describe("analyzeSwitch — re-renders are genuine (not deduped away)", () => {+ it("keeps every re-render in raw but counts distinct components in unique", () => {+ // Root re-renders across 3 commits — 3 genuine renders, 1 distinct component.+ const a = analyzeSwitch(+ baseSwitch({+ commits: [+ { ts: 1050, kind: "commit", mounts: [], rerenders: [{ name: "Root", fiberId: 3, actualDuration: 5 }] },+ { ts: 1080, kind: "commit", mounts: [], rerenders: [{ name: "Root", fiberId: 3, actualDuration: 4 }] },+ { ts: 1120, kind: "commit", mounts: [], rerenders: [{ name: "Root", fiberId: 3, actualDuration: 6 }] },+ ],+ }),+ )+ expect(a.rerenderCountRaw).toBe(3)+ expect(a.rerenderCountUnique).toBe(1)})})diff --git a/src/web/scripts/perf-report.ts b/src/web/scripts/perf-report.tsindex a79b68892..5adbcc007 100644--- a/src/web/scripts/perf-report.ts+++ b/src/web/scripts/perf-report.ts@@ -32,9 +32,19 @@ export interface SwitchAnalysis {networkSpanMs: number/** true if read-state's response-end precedes messages' request-start. */readStateBlocksMessages: boolean | null+ /** Total mount events reported by react-scan across all commits — INFLATED:+ * the ring buffer re-reports every still-mounted fiber on each subsequent+ * commit, so a single first-mount shows up once per later commit. */mountCountRaw: number- mountCountAdjusted: number+ /** Distinct fiber ids that mounted — the real "how many components first+ * mounted this switch". This is the trustworthy render-cost number. */+ mountCountUnique: number+ /** Total re-render events. Unlike mounts these are NOT inflated: each+ * (fiberId, commit, duration) triple is unique, so a fiber re-rendering N+ * times across N commits is N genuine renders. */rerenderCountRaw: number+ /** Distinct fiber ids that re-rendered at least once. */+ rerenderCountUnique: numberunmounts: string[]topRenders: Array<{ name: string; count: number; reason?: string }>/** attribution of the perceived total. */@@ -46,26 +56,27 @@ function findResource(resources: CapturedResource[], needle: string): CapturedRe}/**- * Detect StrictMode double-commit inflation: in dev, the same logical fiber- * (fiberId) mounts twice in immediate succession. We halve mount counts for- * fiberIds seen exactly twice back-to-back.+ * Count mount events two ways. react-scan's ring buffer re-reports every+ * still-mounted fiber on each subsequent commit, so `mountRaw` (the naive+ * total) is inflated 6-13× by that echo — an earlier heuristic tried to undo+ * it by "halving fibers seen an even number of times", but the real repeat+ * rate isn't 2× and that produced numbers ~3-4× too high. A first mount is+ * unique per fiber by definition, so deduping by fiberId is lossless and+ * yields the true count. Fibers without an id (rare) each count as their own+ * mount — they can't be deduped and dropping them would under-count.*/-function adjustForStrictMode(sw: CapturedSwitch): { mountRaw: number; mountAdjusted: number } {- const mountIds: number[] = []+function countMounts(sw: CapturedSwitch): { mountRaw: number; mountUnique: number } {let mountRaw = 0+ const ids = new Set<number>()+ let idless = 0for (const commit of sw.commits) {for (const m of commit.mounts) {mountRaw++- if (typeof m.fiberId === "number") mountIds.push(m.fiberId)+ if (typeof m.fiberId === "number") ids.add(m.fiberId)+ else idless++}}- // Count fiberIds appearing an even number of times as StrictMode doubles.- const seen = new Map<number, number>()- for (const id of mountIds) seen.set(id, (seen.get(id) ?? 0) + 1)- let doubled = 0- for (const [, n] of seen) if (n >= 2) doubled += Math.floor(n / 2)- const mountAdjusted = Math.max(mountRaw - doubled, 0)- return { mountRaw, mountAdjusted }+ return { mountRaw, mountUnique: ids.size + idless }}export function analyzeSwitch(sw: CapturedSwitch): SwitchAnalysis {@@ -101,18 +112,23 @@ export function analyzeSwitch(sw: CapturedSwitch): SwitchAnalysis {const readStateBlocksMessages =readState && messages ? readState.responseEnd <= messages.startTime + 1 : null- const { mountRaw, mountAdjusted } = adjustForStrictMode(sw)+ const { mountRaw, mountUnique } = countMounts(sw)let rerenderCountRaw = 0+ const rerenderIds = new Set<number>()+ let rerenderIdless = 0const renderTally = new Map<string, { count: number; reason?: string }>()for (const commit of sw.commits) {for (const r of commit.rerenders) {rerenderCountRaw+++ if (typeof r.fiberId === "number") rerenderIds.add(r.fiberId)+ else rerenderIdless++const cur = renderTally.get(r.name) ?? { count: 0, reason: r.reason }cur.count++if (!cur.reason && r.reason) cur.reason = r.reasonrenderTally.set(r.name, cur)}}+ const rerenderCountUnique = rerenderIds.size + rerenderIdlessconst topRenders = [...renderTally.entries()].map(([name, v]) => ({ name, count: v.count, reason: v.reason })).sort((a, b) => b.count - a.count)@@ -129,7 +145,7 @@ export function analyzeSwitch(sw: CapturedSwitch): SwitchAnalysis {: `network-bound (${networkMs.toFixed(0)}ms of ${perceivedMs.toFixed(0)}ms)`} else {const nonNetwork = perceivedMs - networkMs- verdict = `NOT network-bound — ${nonNetwork.toFixed(0)}ms of ${perceivedMs.toFixed(0)}ms is render/remount/reflow (network only ${networkMs.toFixed(0)}ms); remount=${mountAdjusted} fibers, unmounts=${sw.unmounts.length}`+ verdict = `NOT network-bound — ${nonNetwork.toFixed(0)}ms of ${perceivedMs.toFixed(0)}ms is render/remount/reflow (network only ${networkMs.toFixed(0)}ms); mounts=${mountUnique} fibers, unmounts=${sw.unmounts.length}`}return {@@ -144,8 +160,9 @@ export function analyzeSwitch(sw: CapturedSwitch): SwitchAnalysis {networkSpanMs,readStateBlocksMessages,mountCountRaw: mountRaw,- mountCountAdjusted: mountAdjusted,+ mountCountUnique: mountUnique,rerenderCountRaw,+ rerenderCountUnique,unmounts: sw.unmounts,topRenders,verdict,@@ -165,8 +182,11 @@ export function renderReport(file: CaptureFile): string {lines.push("")lines.push("> Baseline: on local, network is ~0, so a visible loading spell is itself the anomaly. " +- "The headline is perceived latency (click → content stable). Counts are dev-mode; " +- "StrictMode-adjusted values remove the double-invoke inflation.",+ "The headline is perceived latency (click → content stable). Counts are dev-mode. " ++ "Mounts are reported as `unique` (distinct fiber ids — the trustworthy number) and " ++ "`raw` (react-scan re-reports every still-mounted fiber on each later commit, inflating " ++ "the raw total 6-13×). Re-renders are NOT inflated (each is a genuine distinct render), " ++ "so `raw` is real; `unique` counts how many distinct components re-rendered.",)lines.push("")@@ -187,7 +207,9 @@ export function renderReport(file: CaptureFile): string {: " · read-state/messages overlap (parallel)"),)lines.push(- `- renders: mounts ${a.mountCountRaw} raw / ${a.mountCountAdjusted} StrictMode-adjusted · re-renders ${a.rerenderCountRaw} · unmounts ${a.unmounts.length}`,+ `- renders: mounts ${a.mountCountUnique} unique (${a.mountCountRaw} raw w/ ring-buffer echo) · ` ++ `re-renders ${a.rerenderCountRaw} (${a.rerenderCountUnique} distinct components) · ` ++ `unmounts ${a.unmounts.length}`,)if (a.topRenders.length) {lines.push("- top re-renders:")diff --git a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsxindex 690ae0fb6..f05eb102c 100644--- a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx+++ b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx@@ -432,11 +432,15 @@ function ChannelView() {const typingNames = useTypingNamesForScope(`ch:${channelId}`)// Mutations- const sendMessageMut = useSendMessage()+ // Destructure the reference-STABLE mutation methods (TanStack binds+ // `.mutate`/`.mutateAsync` in the observer, but returns a NEW wrapper object+ // every render — depending on the whole object would bust every downstream+ // useMemo/useCallback every render). See doSend / messageActions deps.+ const { mutateAsync: sendMessageAsync } = useSendMessage()const toggleReactionApi = useToggleReactionApi()- const pinMessageMut = usePinMessage()- const unpinMessageMut = useUnpinMessage()- const createThreadMut = useCreateThread()+ const { mutate: pinMessageMutate } = usePinMessage()+ const { mutate: unpinMessageMutate } = useUnpinMessage()+ const { mutateAsync: createThreadAsync } = useCreateThread()const createForumPostMut = useCreateForumPost()const updatePostTagsMut = useUpdatePostTags()const deleteForumPostMut = useDeleteForumPost()@@ -614,7 +618,7 @@ function ChannelView() {const doSend = useCallback(async (content: string, opts?: { replyToId?: string; mentionType?: MentionType; attachments?: UploadedAttachment[] }): Promise<SendMessageResult | null> => {try {- return await sendMessageMut.mutateAsync({+ return await sendMessageAsync({channelId,content,replyToId: opts?.replyToId,@@ -630,7 +634,7 @@ function ChannelView() {return null}},- [sendMessageMut, channelId, currentUser.id, currentUser.name, currentUser.avatar],+ [sendMessageAsync, channelId, currentUser.id, currentUser.name, currentUser.avatar],)// Latest-ref for the values the message actions read at call time. Keeping@@ -662,12 +666,12 @@ function ChannelView() {onPin: (id: string) => {const isPinned = actionsCtxRef.current.pinnedIds.has(id)if (isPinned) {- unpinMessageMut.mutate({ channelId, messageId: id }, {+ unpinMessageMutate({ channelId, messageId: id }, {onSuccess: () => toast("Message unpinned"),onError: (e) => toastApiError(e, "Failed to unpin message"),})} else {- pinMessageMut.mutate({ channelId, messageId: id }, {+ pinMessageMutate({ channelId, messageId: id }, {onSuccess: () => toast("Message pinned"),onError: (e) => toastApiError(e, "Failed to pin message"),})@@ -678,7 +682,7 @@ function ChannelView() {const m = actionsCtxRef.current.messages.find((x) => x.id === id)const name = deriveThreadName(m?.content, actionsCtxRef.current.channelName)try {- const data = await createThreadMut.mutateAsync({ channelId, messageId: id, name })+ const data = await createThreadAsync({ channelId, messageId: id, name })router.push(`/c/channels/${params.serverId}/${data.id}`)} catch (e) {toastApiError(e, "Failed to create thread")@@ -701,25 +705,32 @@ 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])+ // Deps are all reference-stable: channelId/currentUser.id (strings),+ // toggleReactionApi (useCallback), the mutation METHODS (TanStack binds+ // `.mutate`/`.mutateAsync` stably — NOT the whole mutation object, which is+ // a new wrapper every render), doSend (useCallback), router/params. Volatile+ // reads go through actionsCtxRef. This stability is load-bearing: an unstable+ // messageActions busts MessageRow/Message's memo and re-renders every visible+ // row on every commit (see message.tsx messagePropsEqual).+ }), [channelId, currentUser.id, toggleReactionApi, unpinMessageMutate, pinMessageMutate, createThreadAsync, doSend, router, params.serverId])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])+ // Reference-stable across renders. MUST depend on the RAW roster+ // (`membersHook.members`), NOT the presence-enriched `members` (line ~110):+ // `makeUserNameResolver` only reads id/name/email, never presence, yet the+ // enriched array gets a new identity on every presence/status tick. Keying+ // this resolver on it re-created it on every tick and busted every memoized+ // message row (react-scan measured MessageImpl re-rendering with+ // `props:[resolveUserName]` — ~1/3 of the switch re-render storm). The raw+ // roster's identity changes only when membership/names genuinely change.+ const resolveUserName = useMemo(+ () => makeUserNameResolver(membersHook.members),+ [membersHook.members],+ )// ── Send messages ───────────────────────────────────────────────────────const sendMessage = async (markdown: string, attachments?: SendAttachment[], mentionType?: MentionType) => {diff --git a/src/web/src/components/community/shell-frame.tsx b/src/web/src/components/community/shell-frame.tsxindex cde49f75f..6350e13b1 100644--- a/src/web/src/components/community/shell-frame.tsx+++ b/src/web/src/components/community/shell-frame.tsx@@ -119,15 +119,21 @@ export function ShellFrame({const watchInboxItem = inbox.watchItem// Mutations wired through the shell.- const createServer = useCreateServer()- const joinServer = useJoinServer()- const leaveServer = useLeaveServer()- const uploadServerIcon = useUploadServerIcon()- const deleteFolder = useDeleteServerFolder()- const reorderServers = useReorderServers()- const reorderFolders = useReorderFolders()- const updateFolderItems = useUpdateFolderItems()- const createFolderWith = useCreateServerFolderWith()+ // Destructure the STABLE mutation methods, not the whole mutation object.+ // TanStack's `useMutation` returns a fresh wrapper object every render but+ // binds `.mutate`/`.mutateAsync` stably; depending on the wrapper made every+ // rail callback below rebuild each render, busting ServerRail's memo and+ // re-rendering the whole shell (children included) on any shell re-render.+ // Mirrors the message-side fix (see page.tsx messageActions deps note).+ const { mutateAsync: createServerAsync } = useCreateServer()+ const { mutateAsync: joinServerAsync } = useJoinServer()+ const { mutate: leaveServerMutate } = useLeaveServer()+ const { mutate: uploadServerIconMutate } = useUploadServerIcon()+ const { mutate: deleteFolderMutate } = useDeleteServerFolder()+ const { mutate: reorderServersMutate } = useReorderServers()+ const { mutate: reorderFoldersMutate } = useReorderFolders()+ const { mutate: updateFolderItemsMutate } = useUpdateFolderItems()+ const { mutate: createFolderWithMutate } = useCreateServerFolderWith()const createOrGetDm = useCreateOrGetDm()const sendDmMessage = useSendDmMessage()const markAllInboxRead = useMarkAllInboxRead()@@ -171,11 +177,11 @@ export function ShellFrame({const onRailCreateServer = useCallback(async (name: string, icon?: File) => {try {- const data = await createServer.mutateAsync({ name })+ const data = await createServerAsync({ name })const newId = data.server.idtoast(`Server "${name}" created`)if (icon) {- uploadServerIcon.mutate(+ uploadServerIconMutate({ serverId: newId, file: icon },{ onError: (e) => toastApiError(e, "Server created, but the icon failed to upload") },)@@ -185,19 +191,19 @@ export function ShellFrame({toastApiError(e, "Failed to create server")}},- [createServer, uploadServerIcon, router],+ [createServerAsync, uploadServerIconMutate, router],)const onRailJoinServer = useCallback(async (invite: string) => {try {- const data = await joinServer.mutateAsync({ inviteCode: invite })+ const data = await joinServerAsync({ inviteCode: invite })toast("Joined server")router.push(`/c/channels/${data.serverId}`)} catch (e) {toastApiError(e, "Failed to join server")}},- [joinServer, router],+ [joinServerAsync, router],)const onRailLeaveServer = useCallback((id: string) => {@@ -206,7 +212,7 @@ export function ShellFrame({// eject effect first. Marker present → layout stays silent and// this button owns the "Left server" toast.markVoluntaryLeave(id)- leaveServer.mutate(+ leaveServerMutate({ serverId: id },{onSuccess: () => {@@ -219,7 +225,7 @@ export function ShellFrame({},)},- [leaveServer, currentServerId, router, servers],+ [leaveServerMutate, currentServerId, router, servers],)const onRailOpenSettings = useCallback((id?: string) => {@@ -235,7 +241,7 @@ export function ShellFrame({)const onRailUngroupFolder = useCallback((fId: string) => {- deleteFolder.mutate(+ deleteFolderMutate({ folderId: fId },{onSuccess: () => toast("Group removed"),@@ -243,43 +249,43 @@ export function ShellFrame({},)},- [deleteFolder],+ [deleteFolderMutate],)const onRailReorderRail = useCallback((ids: string[]) => {- reorderServers.mutate(+ reorderServersMutate({ serverIds: ids },{ onError: (e) => toastApiError(e, "Failed to save server order") },)},- [reorderServers],+ [reorderServersMutate],)const onRailReorderFolders = useCallback((ids: string[]) => {- reorderFolders.mutate(+ reorderFoldersMutate({ folderIds: ids },{ onError: (e) => toastApiError(e, "Failed to reorder groups") },)},- [reorderFolders],+ [reorderFoldersMutate],)const onRailFolderItemsChange = useCallback((fId: string, ids: string[]) => {- updateFolderItems.mutate(+ updateFolderItemsMutate({ folderId: fId, serverIds: ids },{ onError: (e) => toastApiError(e, "Failed to update group") },)},- [updateFolderItems],+ [updateFolderItemsMutate],)const onRailDragCreateFolder = useCallback((a: string, b: string) => {- createFolderWith.mutate(+ createFolderWithMutate({ serverIdA: a, serverIdB: b },{ onError: (e) => toastApiError(e, "Failed to create group") },)},- [createFolderWith],+ [createFolderWithMutate],)const railProps = {diff --git a/src/web/src/components/community/sortable-server.tsx b/src/web/src/components/community/sortable-server.tsxindex e3c743b8d..241665494 100644--- a/src/web/src/components/community/sortable-server.tsx+++ b/src/web/src/components/community/sortable-server.tsx@@ -1,6 +1,6 @@"use client";-import { useState } from "react";+import { memo, useState } from "react";import { useSortable } from "@dnd-kit/sortable";import { CSS } from "@dnd-kit/utilities";import {@@ -22,18 +22,7 @@ import { MarbleBackground } from "@/components/avatar";import { tid } from "@/lib/community/testids";import type { Server } from "./_types";-export function SortableServer({- server,- active,- onClick,- onLeave,- onOpenSettings,- onOpenInvitePopover,- onCreateFolder,- groupTarget,- inFolder,- dragging: isDragActive,-}: {+type SortableServerProps = {server: Server;active?: boolean;onClick: () => void;@@ -44,7 +33,20 @@ export function SortableServer({groupTarget?: boolean;inFolder?: boolean;dragging?: boolean;-}) {+};++function SortableServerImpl({+ server,+ active,+ onClick,+ onLeave,+ onOpenSettings,+ onOpenInvitePopover,+ onCreateFolder,+ groupTarget,+ inFolder,+ dragging: isDragActive,+}: SortableServerProps) {const {attributes,listeners,@@ -66,6 +68,123 @@ export function SortableServer({const lineSide: "top" | "bottom" =activeIndex !== -1 && activeIndex < index ? "bottom" : "top";const [confirmLeave, setConfirmLeave] = useState(false);+ // Lazy-mount the row's Base UI ContextMenu + ConfirmDialog. Eagerly mounting+ // them per rail icon (one Tooltip + ContextMenu + Dialog stack × N servers)+ // was the bulk of the switch re-render storm — the DialogPortal /+ // ContextMenuTrigger / FloatingTree ×1000s in perf:switch came from the rail,+ // not the message list (which already lazies its overlays; see message.tsx).+ // Activate on first hover OR focus OR keydown/contextmenu — focus/keydown are+ // required for a11y (keyboard context menu / Tab-to-icon have no pointerenter,+ // and a right-click is always preceded by a pointerenter so the menu is+ // mounted before it's invoked).+ const [activated, setActivated] = useState(false);+ const activate = activated ? undefined : () => setActivated(true);++ const icon = (+ <div+ ref={setNodeRef}+ style={style}+ className="group relative flex w-full justify-center"+ onPointerEnter={activate}+ onFocusCapture={activate}+ onKeyDownCapture={activate}+ >+ {showLine && (+ <div+ className={`pointer-events-none absolute inset-x-3 z-10 h-0.5 rounded-full bg-primary ${lineSide === "top" ? "-top-1" : "-bottom-1"}`}+ />+ )}+ <RailIndicator active={active} />+ <div+ className={[+ "relative size-10 transition-all duration-150",+ groupTarget ? "scale-110 rounded-xl ring-2 ring-primary" : "",+ isDragging+ ? "rounded-xl border-2 border-dashed border-muted-foreground/40"+ : "",+ ].join(" ")}+ >+ <button+ data-testid={tid.serverIcon(server.id)}+ onClick={active ? undefined : onClick}+ {...attributes}+ {...listeners}+ className={[+ "relative grid size-10 touch-none place-items-center overflow-hidden font-brand text-xl font-bold transition-all duration-150 active:cursor-grabbing",+ active+ ? "cursor-default rounded-xl"+ : "cursor-pointer rounded-[18px] hover:rounded-xl",+ server.icon+ ? active+ ? "bg-primary text-primary-foreground"+ : "bg-card hover:bg-primary hover:text-primary-foreground"+ : "text-white [text-shadow:0_1px_2px_rgb(0_0_0/0.35)] hover:brightness-110",+ ].join(" ")}+ >+ {server.icon ? (+ <img+ src={server.icon}+ alt={server.name}+ className="size-full object-cover"+ />+ ) : (+ <>+ <MarbleBackground seed={server.id} />+ <span className="relative -translate-x-[2px] [-webkit-text-stroke:0.5px_currentColor]">+ {server.initial}+ </span>+ </>+ )}+ </button>+ {server.mentions > 0 && (+ <span+ data-testid={tid.railUnreadBadge(server.id)}+ className="pointer-events-none absolute -bottom-1 -right-1 grid h-5 min-w-5 place-items-center rounded-full bg-primary px-1 text-[11px] font-bold text-primary-foreground ring-2 ring-(--d-rail)"+ >+ <NumberTicker value={server.mentions} />+ </span>+ )}+ </div>+ </div>+ );++ // Until activated, the icon carries no ContextMenu root — just the Tooltip.+ const withMenu = !activated ? (+ icon+ ) : (+ <ContextMenu>+ <ContextMenuTrigger render={icon} />+ <ContextMenuContent className="w-52">+ <div className="truncate px-2 py-1 text-xs font-semibold text-muted-foreground">+ {server.name}+ </div>+ {onOpenInvitePopover && (+ <ContextMenuItem onClick={onOpenInvitePopover}>+ Invite to Server+ </ContextMenuItem>+ )}+ {!inFolder && onCreateFolder && (+ <ContextMenuItem onClick={onCreateFolder}>+ Create group+ </ContextMenuItem>+ )}+ <ContextMenuItem onClick={onOpenSettings}>+ Server settings+ </ContextMenuItem>+ {!server.isOwner && !inFolder && (+ <>+ <ContextMenuSeparator />+ <ContextMenuItem+ onClick={() => setConfirmLeave(true)}+ className="text-destructive data-highlighted:bg-destructive/10 data-highlighted:text-destructive"+ >+ Leave server+ </ContextMenuItem>+ </>+ )}+ </ContextMenuContent>+ </ContextMenu>+ );return (<>@@ -73,120 +192,63 @@ export function SortableServer({<TooltipTriggerrender={<span className="flex w-full justify-center" />}>- <ContextMenu>- <ContextMenuTrigger- render={- <div- ref={setNodeRef}- style={style}- className="group relative flex w-full justify-center"- />- }- >- {showLine && (- <div- className={`pointer-events-none absolute inset-x-3 z-10 h-0.5 rounded-full bg-primary ${lineSide === "top" ? "-top-1" : "-bottom-1"}`}- />- )}- <RailIndicator active={active} />- <div- className={[- "relative size-10 transition-all duration-150",- groupTarget ? "scale-110 rounded-xl ring-2 ring-primary" : "",- isDragging- ? "rounded-xl border-2 border-dashed border-muted-foreground/40"- : "",- ].join(" ")}- >- <button- data-testid={tid.serverIcon(server.id)}- onClick={active ? undefined : onClick}- {...attributes}- {...listeners}- className={[- "relative grid size-10 touch-none place-items-center overflow-hidden font-brand text-xl font-bold transition-all duration-150 active:cursor-grabbing",- active- ? "cursor-default rounded-xl"- : "cursor-pointer rounded-[18px] hover:rounded-xl",- server.icon- ? active- ? "bg-primary text-primary-foreground"- : "bg-card hover:bg-primary hover:text-primary-foreground"- : "text-white [text-shadow:0_1px_2px_rgb(0_0_0/0.35)] hover:brightness-110",- ].join(" ")}- >- {server.icon ? (- <img- src={server.icon}- alt={server.name}- className="size-full object-cover"- />- ) : (- <>- <MarbleBackground seed={server.id} />- <span className="relative -translate-x-[2px] [-webkit-text-stroke:0.5px_currentColor]">- {server.initial}- </span>- </>- )}- </button>- {server.mentions > 0 && (- <span- data-testid={tid.railUnreadBadge(server.id)}- className="pointer-events-none absolute -bottom-1 -right-1 grid h-5 min-w-5 place-items-center rounded-full bg-primary px-1 text-[11px] font-bold text-primary-foreground ring-2 ring-(--d-rail)"- >- <NumberTicker value={server.mentions} />- </span>- )}- </div>- </ContextMenuTrigger>- <ContextMenuContent className="w-52">- <div className="truncate px-2 py-1 text-xs font-semibold text-muted-foreground">- {server.name}- </div>- {onOpenInvitePopover && (- <ContextMenuItem onClick={onOpenInvitePopover}>- Invite to Server- </ContextMenuItem>- )}- {!inFolder && onCreateFolder && (- <ContextMenuItem onClick={onCreateFolder}>- Create group- </ContextMenuItem>- )}- <ContextMenuItem onClick={onOpenSettings}>- Server settings- </ContextMenuItem>- {!server.isOwner && !inFolder && (- <>- <ContextMenuSeparator />- <ContextMenuItem- onClick={() => setConfirmLeave(true)}- className="text-destructive data-highlighted:bg-destructive/10 data-highlighted:text-destructive"- >- Leave server- </ContextMenuItem>- </>- )}- </ContextMenuContent>- </ContextMenu>+ {withMenu}</TooltipTrigger><TooltipContent side="right" sideOffset={8}>{server.name}</TooltipContent></Tooltip>- <ConfirmDialog- open={confirmLeave}- onOpenChange={setConfirmLeave}- title={`Leave ${server.name}?`}- description="You won't see this server's channels anymore, and you'll need a new invite to come back."- confirmLabel="Leave server"- confirmVariant="destructive"- onConfirm={() => {- setConfirmLeave(false);- onLeave?.();- }}- />+ {/* ConfirmDialog only mounts once the menu has been activated AND the+ user chose Leave — never eagerly per rail icon. */}+ {activated && (+ <ConfirmDialog+ open={confirmLeave}+ onOpenChange={setConfirmLeave}+ title={`Leave ${server.name}?`}+ description="You won't see this server's channels anymore, and you'll need a new invite to come back."+ confirmLabel="Leave server"+ confirmVariant="destructive"+ onConfirm={() => {+ setConfirmLeave(false);+ onLeave?.();+ }}+ />+ )}</>);}++// Custom comparator — REQUIRED. The rail rebuilds `railServers` (a fresh+// `{ ...s, active }` per server) on every presence/roster/mention tick, and+// each rail item passes fresh per-render arrow callbacks, so a default shallow+// memo would always see "new" and never bail out. We compare the `server`+// fields that actually change plus the derived layout props, and DELIBERATELY+// ignore the callbacks: every one closes over only a stable id + a+// shell-frame `useCallback`'d handler, so their identity churn carries no new+// behavior. Without this, the whole rail (N servers × their Tooltip/Avatar)+// re-renders on every tick — the SortableServer/TooltipTrigger ×N in+// perf:switch after the lazy-overlay pass.+function serverPropsEqual(prev: SortableServerProps, next: SortableServerProps): boolean {+ const a = prev.server;+ const b = next.server;+ return (+ a.id === b.id &&+ a.name === b.name &&+ a.initial === b.initial &&+ a.icon === b.icon &&+ a.mentions === b.mentions &&+ a.isOwner === b.isOwner &&+ prev.active === next.active &&+ prev.groupTarget === next.groupTarget &&+ prev.inFolder === next.inFolder &&+ prev.dragging === next.dragging &&+ // The presence of an optional handler flips menu items on/off, so compare+ // definedness (not identity) — a menu row appears/disappears with it.+ !!prev.onLeave === !!next.onLeave &&+ !!prev.onOpenSettings === !!next.onOpenSettings &&+ !!prev.onOpenInvitePopover === !!next.onOpenInvitePopover &&+ !!prev.onCreateFolder === !!next.onCreateFolder+ );+}++export const SortableServer = memo(SortableServerImpl, serverPropsEqual);diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.tsindex 391fa2cfa..e40a1bc94 100644--- a/src/web/src/hooks/community/mutations/messages.ts+++ b/src/web/src/hooks/community/mutations/messages.ts@@ -1,5 +1,6 @@"use client"+import { useCallback } from "react"import {useMutation,useQueryClient,@@ -488,7 +489,7 @@ export function _resetReactionTimers_forTesting() {*/export function useToggleReactionApi(): (args: ToggleReactionArgs) => void {const queryClient = useQueryClient()- return (args) => {+ return useCallback((args: ToggleReactionArgs) => {const key = args.channelId? communityKeys.channelMessages(args.channelId): args.dmId@@ -532,7 +533,7 @@ export function useToggleReactionApi(): (args: ToggleReactionArgs) => void {})}, REACTION_DEBOUNCE_MS)reactionTimers.set(timerKey, { timer, originalMe })- }+ }, [queryClient])}// ── Pin / unpin ────────────────────────────────────────────────────────────diff --git a/src/web/src/stores/community/index.ts b/src/web/src/stores/community/index.tsindex da10ad844..f7bab3062 100644--- a/src/web/src/stores/community/index.ts+++ b/src/web/src/stores/community/index.ts@@ -154,7 +154,10 @@ export const useCommunityStore = create<CommunityStoreState>((set, get) => ({setCurrentServerId: (id) => set({ currentServerId: id }),- setCurrentChannelId: (id) => set({ currentChannelId: id }),+ setCurrentChannelId: (id) => {+ if (get().currentChannelId === id) return // no-op on identical value+ set({ currentChannelId: id })+ },setCurrentChannelMeta: (meta) => set({ currentChannelMeta: meta }),diff --git a/src/web/src/test/e2e-ui/perf/perf-capture-types.ts b/src/web/src/test/e2e-ui/perf/perf-capture-types.tsindex 0acfd3b77..3edc98d63 100644--- a/src/web/src/test/e2e-ui/perf/perf-capture-types.ts+++ b/src/web/src/test/e2e-ui/perf/perf-capture-types.ts@@ -69,8 +69,8 @@ declare global {__PERF_RESOURCES__?: Array<{ name: string; startTime: number; responseEnd: number }>__PERF_SHIFTS__?: Array<{ ts: number; value: number; hadRecentInput: boolean }>__PERF_RESIZES__?: number[]- __PERF_RESIZE_ATTACHED__?: boolean- __PERF_ATTACH_RESIZE__?: () => void+ __PERF_RESIZE_OBSERVER__?: ResizeObserver+ __PERF_ATTACH_RESIZE__?: () => boolean__PERF_SKELETON_TS__?: number | null__PERF_PAINTED_TS__?: number | null}diff --git a/src/web/src/test/e2e-ui/perf/switch.perf.ts b/src/web/src/test/e2e-ui/perf/switch.perf.tsindex 21d75462b..23a1d48fb 100644--- a/src/web/src/test/e2e-ui/perf/switch.perf.ts+++ b/src/web/src/test/e2e-ui/perf/switch.perf.ts@@ -101,12 +101,19 @@ const INPAGE_SETUP = `}});try { lo.observe({ type: 'layout-shift', buffered: true }); } catch (_) {}+ // Attach a ResizeObserver to the message scroll container. The container is+ // persistent, but on a cold switch it may be re-created (React swaps the+ // subtree), so a once-only global guard would leave the observer watching a+ // detached node and never fire again — hence NO cross-switch guard here, and+ // we disconnect the prior observer before re-observing the current root.window.__PERF_ATTACH_RESIZE__ = () => {const root = document.querySelector('.thin-scrollbar');- if (!root || window.__PERF_RESIZE_ATTACHED__) return;- window.__PERF_RESIZE_ATTACHED__ = true;+ if (!root) return false;+ if (window.__PERF_RESIZE_OBSERVER__) window.__PERF_RESIZE_OBSERVER__.disconnect();const rz = new ResizeObserver(() => { window.__PERF_RESIZES__.push(performance.now()); });rz.observe(root);+ window.__PERF_RESIZE_OBSERVER__ = rz;+ return true;};})()`@@ -235,10 +242,26 @@ test("community switch perceived-latency capture", async ({ browser }) => {await navigate()- // Record skeleton + painted anchors as they appear.+ // Record skeleton + painted anchors as they appear. Both are captured in+ // ONE polling loop so whichever DOM state shows first stamps its own+ // timestamp: the message-list loading state renders `[data-slot=skeleton]`+ // in the scroll container, then swaps to `[data-msg-id]` rows once loaded.+ // A memory/disk-warm switch can paint rows with no skeleton frame at all,+ // so skeleton stays null there (correctly — there was no loading spell).await page.waitForFunction(() => {+ // Scope the skeleton probe to the message scroll container — a bare+ // `[data-slot=skeleton]` also matches sidebar/member-list skeletons+ // elsewhere on the page (and leftovers from the prior switch), which+ // stamped a bogus 16ms skeleton on memory-warm switches that have no+ // loading spell at all.+ if (+ window.__PERF_SKELETON_TS__ == null &&+ document.querySelector(".thin-scrollbar [data-slot='skeleton']")+ ) {+ window.__PERF_SKELETON_TS__ = performance.now()+ }const painted = document.querySelector("[data-msg-id]")if (painted && window.__PERF_PAINTED_TS__ == null) {window.__PERF_PAINTED_TS__ = performance.now()@@ -249,6 +272,12 @@ test("community switch perceived-latency capture", async ({ browser }) => {).catch(() => {})+ // Re-attach the ResizeObserver to the CURRENT scroll container. Attaching+ // once before navigate() misses cold switches where React re-creates the+ // container after the click, leaving the pre-switch observer on a detached+ // node — the bug that left contentStableTs perpetually null.+ await page.evaluate(() => window.__PERF_ATTACH_RESIZE__?.())+// Let reflow settle so the ResizeObserver captures content-stable.await page.waitForTimeout(600)