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
feat(web): persist canonical structural navigation hints (#743)
Gener8071e3792d54
diff --git a/src/web/src/app/c/QueryProvider.dom.test.ts b/src/web/src/app/c/QueryProvider.dom.test.tsindex b457e0d23..206c01bf2 100644--- a/src/web/src/app/c/QueryProvider.dom.test.ts+++ b/src/web/src/app/c/QueryProvider.dom.test.ts@@ -7,6 +7,12 @@ import { communityKeys } from "@/lib/query-keys"const queryClient = vi.hoisted(() => ({id: "query-client",invalidateQueries: vi.fn(() => Promise.resolve()),+ getQueryData: vi.fn(() => undefined),+ removeQueries: vi.fn(),+ getQueryCache: vi.fn(() => ({+ subscribe: vi.fn(() => () => {}),+ getAll: vi.fn(() => []),+ })),}))const createQueryClient = vi.hoisted(() => vi.fn(() => queryClient))const seedPersistedMessageProfiles = vi.hoisted(() => vi.fn())diff --git a/src/web/src/app/c/QueryProvider.tsx b/src/web/src/app/c/QueryProvider.tsxindex 6c0ebd783..1154c014c 100644--- a/src/web/src/app/c/QueryProvider.tsx+++ b/src/web/src/app/c/QueryProvider.tsx@@ -19,6 +19,7 @@ import {getAccountUnreadProjection,} from "@/hooks/community/account-unread-projection"import { communityKeys } from "@/lib/query-keys"+import { installStructuralSnapshotProjection } from "@/hooks/community/use-structural-snapshot"/*** Owns the TanStack QueryClient for the community subtree.@@ -95,6 +96,11 @@ export function QueryProvider({}}, [queryClient])+ useEffect(+ () => installStructuralSnapshotProjection(queryClient, userId),+ [queryClient, userId],+ )+return (<PersistQueryClientProviderclient={queryClient}diff --git a/src/web/src/app/c/channels/layout.route-memory.dom.test.ts b/src/web/src/app/c/channels/layout.route-memory.dom.test.tsindex 46165a2e3..1c91e56b7 100644--- a/src/web/src/app/c/channels/layout.route-memory.dom.test.ts+++ b/src/web/src/app/c/channels/layout.route-memory.dom.test.ts@@ -6,6 +6,9 @@ const mocks = vi.hoisted(() => ({replace: vi.fn(),cancelPendingNavigation: vi.fn(),runEject: vi.fn(),+ serverListSuccess: { current: true },+ serverListFetching: { current: false },+ serverAccessRevoked: { current: false },}))vi.mock("next/navigation", () => ({@@ -60,7 +63,15 @@ vi.mock("@/contexts/community/current-user", () => ({}))vi.mock("@/hooks/community/use-servers", () => ({useServer: () => ({ server: undefined }),- useServers: () => ({ servers: [], isSuccess: true, isFetching: false }),+ useServers: () => ({+ servers: [],+ isSuccess: mocks.serverListSuccess.current,+ isFetching: mocks.serverListFetching.current,+ }),+}))+vi.mock("@/hooks/community/use-structural-snapshot", () => ({+ useStructuralSnapshot: () => null,+ structuralHintServer: () => null,}))vi.mock("@/hooks/community/use-server-members", () => ({useServerMembers: () => ({@@ -79,8 +90,15 @@ vi.mock("@/hooks/community/use-forum-sidebar-threads", () => ({useForumSidebarThreads: () => ({ threads: [], parentUnread: {} }),}))vi.mock("@/stores/community/ws", () => ({- useCommunityWsStore: (selector: (state: { profilesByUserId: Map<string, unknown> }) => unknown) =>- selector({ profilesByUserId: new Map() }),+ useCommunityWsStore: (selector: (state: {+ profilesByUserId: Map<string, unknown>+ revokedServerIds: Set<string>+ }) => unknown) => selector({+ profilesByUserId: new Map(),+ revokedServerIds: mocks.serverAccessRevoked.current+ ? new Set(["missing-server"])+ : new Set(),+ }),}))vi.mock("@/hooks/community/use-notification-settings", () => ({resolveServerNotificationDisplayLevel: () => "default",@@ -115,6 +133,9 @@ describe("ServerLayout cold-entry ejection context", () => {mocks.replace.mockClear()mocks.cancelPendingNavigation.mockClear()mocks.runEject.mockReset()+ mocks.serverListSuccess.current = true+ mocks.serverListFetching.current = false+ mocks.serverAccessRevoked.current = falsemocks.runEject.mockImplementation((args: { replace: (destination: string) => void }) => {args.replace("/c/me/machines")return true@@ -132,4 +153,18 @@ describe("ServerLayout cold-entry ejection context", () => {expect(mocks.cancelPendingNavigation).toHaveBeenCalledTimes(1)expect(mocks.replace).toHaveBeenCalledWith("/c/me/machines")})++ it("treats a target-specific access revoke as definitive while the list read is retired", () => {+ mocks.serverListSuccess.current = false+ mocks.serverListFetching.current = true+ mocks.serverAccessRevoked.current = true++ render(createElement(ServerLayout, null, createElement("div")))++ expect(mocks.runEject).toHaveBeenCalledWith(expect.objectContaining({+ serverId: "missing-server",+ isSuccess: true,+ isFetching: false,+ }))+ })})diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsxindex bd3cb1606..f0ff44c69 100644--- a/src/web/src/app/c/channels/layout.tsx+++ b/src/web/src/app/c/channels/layout.tsx@@ -64,6 +64,10 @@ import {useKickMember,useRevokeInvite,} from "@/hooks/community/mutations"+import {+ structuralHintServer,+ useStructuralSnapshot,+} from "@/hooks/community/use-structural-snapshot"export default function ServerLayout({ children }: { children: ReactNode }) {const params = useParams<{ serverId: string; channelId?: string }>()@@ -79,8 +83,21 @@ export default function ServerLayout({ children }: { children: ReactNode }) {useCommunityStore.getState().uiHandlers.cancelPendingNavigation?.()}, [])const currentUser = useCurrentUser()+ const serverAccessRevoked = useCommunityWsStore(+ (state) => state.revokedServerIds.has(serverId),+ )+ const structuralSnapshot = useStructuralSnapshot(currentUser.id)+ const structuralServer = useMemo(+ () => structuralHintServer(structuralSnapshot, serverId),+ [serverId, structuralSnapshot],+ )const { server: currentServer } = useServer(serverId)- const membersHook = useServerMembers(serverId)+ const sidebarCategories = useMemo(+ () => currentServer?.categories ?? structuralServer?.categoriesView ?? [],+ [currentServer, structuralServer],+ )+ const sidebarHintOnly = !currentServer && !!structuralServer+ const membersHook = useServerMembers(currentServer ? serverId : null)const profilesByUserId = useCommunityWsStore((s) => s.profilesByUserId)const enrichedMembers = useMemo(() =>@@ -103,7 +120,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {// stable across presence ticks.const myMember = membersHook.members.find((m) => m.userId === currentUser.id)const isAdmin = canManageServer(myMember?.role)- usePresence(serverId)+ usePresence(currentServer ? serverId : null)const notifs = useNotificationSettings()const notifLevel = resolveServerNotificationDisplayLevel(notifs.server[serverId])const channelNotif = notifs.channel@@ -111,14 +128,15 @@ export default function ServerLayout({ children }: { children: ReactNode }) {const currentChannelMeta = useCurrentChannelMeta()const activeForumThreadId = useMemo(() => {if (!currentChannelId || !currentChannelMeta?.parentChannelId) return null- const parent = currentServer?.categories+ const parent = sidebarCategories.flatMap((category) => category.channels).find((channel) => channel.id === currentChannelMeta.parentChannelId)return isForum(parent?.type) ? currentChannelId : null- }, [currentChannelId, currentChannelMeta?.parentChannelId, currentServer])+ }, [currentChannelId, currentChannelMeta?.parentChannelId, sidebarCategories])const sidebarRouteCandidate = useMemo(() => {- const topLevelChannels = currentServer?.categories- ?.flatMap((category) => category.channels) ?? null+ const topLevelChannels = sidebarCategories.length > 0+ ? sidebarCategories.flatMap((category) => category.channels)+ : nullconst parent = currentChannelId === routeChannelId && currentChannelMeta?.parentChannelId? topLevelChannels?.find((channel) => channel.id === currentChannelMeta.parentChannelId): null@@ -127,7 +145,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {topLevelChannels?.map((channel) => channel.id) ?? null,isForum(parent?.type),)- }, [currentChannelId, currentChannelMeta?.parentChannelId, currentServer, routeChannelId])+ }, [currentChannelId, currentChannelMeta?.parentChannelId, routeChannelId, sidebarCategories])const forumSidebar = useForumSidebarThreads(serverId,sidebarRouteCandidate,@@ -186,8 +204,10 @@ export default function ServerLayout({ children }: { children: ReactNode }) {ejectedRef.current = runAuthoritativeServerEject({serverId,servers: serversList.servers,- isSuccess: serversList.isSuccess,- isFetching: serversList.isFetching,+ // A target-specific 403/404 is already definitive even if revoking the+ // target advanced the access epoch and retired an in-flight list read.+ isSuccess: serverAccessRevoked || serversList.isSuccess,+ isFetching: serverAccessRevoked ? false : serversList.isFetching,consumeVoluntaryLeave,clearLastChannel,toast,@@ -198,7 +218,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {router.replace(destination)},})- }, [cancelPendingNavigation, currentUser.id, pathname, serverId, serversList.isSuccess, serversList.isFetching, serversList.servers, router, searchParams])+ }, [cancelPendingNavigation, currentUser.id, pathname, serverAccessRevoked, serverId, serversList.isSuccess, serversList.isFetching, serversList.servers, router, searchParams])// Reset the guard when the URL changes to a NEW server id — otherwise// navigating server → dangling-server → server would leave the ref// latched and skip the eject.@@ -264,14 +284,14 @@ export default function ServerLayout({ children }: { children: ReactNode }) {currentServer,])- const categories = useMemo(() => (currentServer?.categories ?? []).map((category) => ({+ const categories = useMemo(() => sidebarCategories.map((category) => ({...category,channels: category.channels.map((channel) =>forumSidebar.parentUnread[channel.id] === undefined? channel: { ...channel, unread: forumSidebar.parentUnread[channel.id] },),- })), [currentServer?.categories, forumSidebar.parentUnread])+ })), [forumSidebar.parentUnread, sidebarCategories])const channelTree = useChannelTree(categories)const setActiveChannel = useCallback((id: string) => {@@ -368,35 +388,36 @@ export default function ServerLayout({ children }: { children: ReactNode }) {const channelProps = useMemo(() => ({tree: channelTree,- serverName: currentServer?.name ?? "",- serverIcon: currentServer?.icon ?? null,+ serverName: currentServer?.name ?? structuralServer?.name ?? "",+ serverIcon: currentServer?.icon ?? structuralServer?.icon ?? null,activeChannel: currentChannelMeta?.parentChannelId ?? currentChannelId ?? "",isAdmin,currentUserId: currentUser.id,- loading: !currentServer || forumSidebar.isLoading,+ loading: (!currentServer && !structuralServer)+ || (!sidebarHintOnly && forumSidebar.isLoading),setActiveChannel,prefetchChannel,forumThreadsByParent,activeThreadId: activeForumThreadId,onSelectForumThread: setActiveForumThread,- onOpenSettings: isAdmin ? onSidebarOpenSettings : undefined,+ onOpenSettings: !sidebarHintOnly && isAdmin ? onSidebarOpenSettings : undefined,onBlockedCreate,mutedChannels,- onCreateChannel: onCreateChannelInSidebar,- onCreateCategory: onCreateCategoryInSidebar,- onRenameChannel,- onDeleteChannel: onDeleteChannelInSidebar,- onDeleteCategory: onDeleteCategoryInSidebar,- onUpdateCategory: onUpdateCategoryInSidebar,- onReorderCategories: onReorderCategoriesInSidebar,- onReorderChannels: onReorderChannelsInSidebar,- onMoveChannel: onMoveChannelInSidebar,+ onCreateChannel: sidebarHintOnly ? undefined : onCreateChannelInSidebar,+ onCreateCategory: sidebarHintOnly ? undefined : onCreateCategoryInSidebar,+ onRenameChannel: sidebarHintOnly ? undefined : onRenameChannel,+ onDeleteChannel: sidebarHintOnly ? undefined : onDeleteChannelInSidebar,+ onDeleteCategory: sidebarHintOnly ? undefined : onDeleteCategoryInSidebar,+ onUpdateCategory: sidebarHintOnly ? undefined : onUpdateCategoryInSidebar,+ onReorderCategories: sidebarHintOnly ? undefined : onReorderCategoriesInSidebar,+ onReorderChannels: sidebarHintOnly ? undefined : onReorderChannelsInSidebar,+ onMoveChannel: sidebarHintOnly ? undefined : onMoveChannelInSidebar,onBlockedMove,serverId,invitePopoverOpen,- onInvitePopoverOpenChange: setInvitePopoverOpen,+ onInvitePopoverOpenChange: sidebarHintOnly ? undefined : setInvitePopoverOpen,}), [- channelTree, currentServer, currentChannelMeta?.parentChannelId,+ channelTree, currentServer, structuralServer, sidebarHintOnly, currentChannelMeta?.parentChannelId,currentChannelId, isAdmin, currentUser.id, setActiveChannel, prefetchChannel,forumThreadsByParent, forumSidebar.isLoading, activeForumThreadId, setActiveForumThread,onSidebarOpenSettings, onBlockedCreate, mutedChannels,@@ -419,7 +440,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {), [channelProps])const serverSettingsDialog = (- <Dialog open={serverSettingsOpen} onOpenChange={(o) => { if (!o) closeSettings() }}>+ <Dialog open={serverSettingsOpen && !!currentServer && isAdmin} onOpenChange={(o) => { if (!o) closeSettings() }}><DialogContent className="flex h-dvh max-h-dvh w-screen max-w-none flex-col gap-0 overflow-hidden rounded-none p-0 sm:h-[calc(100vh-4rem)] sm:max-h-180 sm:w-[calc(100vw-4rem)] sm:max-w-4xl sm:rounded-xl" showCloseButton={false}><ServerSettingssection={settingsSection}diff --git a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.tsindex a3c116c95..974165adc 100644--- a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts+++ b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts@@ -20,6 +20,7 @@ const {mockSplitMode,mockSplitParentSurface,mockCommitLastCommunityRoute,+ mockSetLastChannel,mockNavigationGate,mockCurrentChannelId,mockCanManageServer,@@ -34,6 +35,7 @@ const {mockSplitMode: { value: "full" as "split" | "full" },mockSplitParentSurface: vi.fn(() => null),mockCommitLastCommunityRoute: vi.fn(),+ mockSetLastChannel: vi.fn(),mockNavigationGate: { allowed: true },mockCurrentChannelId: { value: "channel_1" as string | null },mockCanManageServer: vi.fn((role?: string | null) => role === "owner" || role === "admin"),@@ -62,6 +64,7 @@ const {retryMetadata: vi.fn(),routeHydrated: true,routeLifecycle: "ready" as "pending" | "ready" | "terminal-error",+ skeletonSubtype: "unknown" as "unknown" | "text" | "forum" | "thread",},mockMemberViewModel: {composerMembers: [],@@ -104,14 +107,20 @@ vi.mock("@/components/community/channels/channel-header", () => ({mockHeaderParentNavigate.current = kind === "thread" ? mobileBack : undefinedreturn React.createElement(React.Fragment, null, endActions)},- ChannelHeaderSkeleton: () => null,+ ChannelHeaderSkeleton: ({ kind = "text" }: { kind?: string }) =>+ React.createElement("div", { "data-testid": "channel-header-skeleton", "data-kind": kind }),}))vi.mock("@/components/community/messages/message-list", () => ({ MessageList: vi.fn(() => null) }))+vi.mock("@/components/community/channels/conversation-message-skeleton", () => ({+ ConversationMessageSkeleton: () => React.createElement("div", { "data-message-list-skeleton": true }),+}))vi.mock("@/components/community/messages/composer", () => ({Composer: () => null,ComposerSkeleton: () => null,}))-vi.mock("@/components/community/channels/forum-view", () => ({ ForumViewSkeleton: () => null }))+vi.mock("@/components/community/channels/forum-view", () => ({+ ForumViewSkeleton: () => React.createElement("div", { "data-testid": "forum-view-skeleton" }),+}))vi.mock("@/components/community/channels/forum-channel-surface", () => ({ForumChannelSurface: vi.fn(() => null),}))@@ -133,7 +142,9 @@ vi.mock("@alook/shared", () => ({deriveThreadName: () => "thread",USE_SERVER_DEFAULT: "default",}))-vi.mock("@/lib/community/last-channel", () => ({ setLastChannel: vi.fn() }))+vi.mock("@/lib/community/last-channel", () => ({+ setLastChannel: (...args: unknown[]) => mockSetLastChannel(...args),+}))vi.mock("@/lib/community/last-community-route", () => ({commitLastCommunityRoute: (...args: unknown[]) => mockCommitLastCommunityRoute(...args),}))@@ -173,17 +184,20 @@ vi.mock("@/components/community/channels/thread-split-view", () => ({split,parent,thread,+ conversationSubtype,}: {containerRef: React.Ref<HTMLElement>split: booleanparent: React.ReactNodethread: React.ReactNode+ conversationSubtype?: string}) => React.createElement("main",{ref: containerRef,"data-testid": "community-thread-split","data-layout": split ? "split" : "full",+ "data-community-conversation-subtype": conversationSubtype,},split && React.createElement("section",@@ -322,6 +336,7 @@ describe("ChannelRoute message surface ownership", () => {mockHeaderServerNavigate.current = undefinedmockHeaderParentNavigate.current = undefinedmockCommitLastCommunityRoute.mockClear()+ mockSetLastChannel.mockClear()mockNavigationGate.allowed = truemockCurrentChannelId.value = "channel_1"mockMemberViewModel.myRole = "member"@@ -343,6 +358,7 @@ describe("ChannelRoute message surface ownership", () => {retryingMetadata: false,routeHydrated: true,routeLifecycle: "ready",+ skeletonSubtype: "unknown",})})@@ -394,6 +410,68 @@ describe("ChannelRoute message surface ownership", () => {expect(mockedMessageList).not.toHaveBeenCalled()})+ it("uses a structural forum hint for skeleton shape without mounting or remembering content", () => {+ Object.assign(mockRouteModel, {+ server: null,+ channel: null,+ parent: null,+ currentChannelMeta: null,+ isForum: false,+ isChild: false,+ isForumPostChild: false,+ routeHydrated: false,+ routeLifecycle: "pending",+ skeletonSubtype: "forum",+ })+ mockNavigationGate.allowed = false+ mockCurrentChannelId.value = null++ render(React.createElement(ChannelRoute, {+ serverParam: "server_1",+ channelId: "channel_1",+ }))++ expect(screen.getByTestId("channel-header-skeleton").getAttribute("data-kind")).toBe("forum")+ expect(screen.getByTestId("forum-view-skeleton")).not.toBeNull()+ expect(screen.getByTestId("forum-view-skeleton").closest(+ '[data-community-conversation-subtype="forum"]',+ )).not.toBeNull()+ expect(mockedForumChannelSurface).not.toHaveBeenCalled()+ expect(mockedMessageList).not.toHaveBeenCalled()+ expect(mockSetLastChannel).not.toHaveBeenCalled()+ expect(mockCommitLastCommunityRoute).not.toHaveBeenCalled()+ })++ it("uses a structural text hint without mounting the live MessageList", () => {+ Object.assign(mockRouteModel, {+ server: null,+ channel: null,+ parent: null,+ currentChannelMeta: null,+ isForum: false,+ isChild: false,+ isForumPostChild: false,+ routeHydrated: false,+ routeLifecycle: "pending",+ skeletonSubtype: "text",+ })+ mockNavigationGate.allowed = false+ mockCurrentChannelId.value = null++ const renderer = render(React.createElement(ChannelRoute, {+ serverParam: "server_1",+ channelId: "channel_1",+ }))++ expect(renderer.container.querySelector("[data-message-list-skeleton]")).not.toBeNull()+ expect(renderer.container.querySelector(+ '[data-community-conversation-subtype="text"]',+ )).not.toBeNull()+ expect(mockedMessageList).not.toHaveBeenCalled()+ expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()+ expect(mockCommitLastCommunityRoute).not.toHaveBeenCalled()+ })+it("renders the terminal metadata error without opening a feed and forwards Retry", async () => {Object.assign(mockRouteModel, {isChild: true, routeLifecycle: "terminal-error", routeHydrated: false,diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsxindex f884d0782..46e316188 100644--- a/src/web/src/components/community/channels/channel-route.tsx+++ b/src/web/src/components/community/channels/channel-route.tsx@@ -4,7 +4,7 @@ import { useCallback, useEffect, useMemo, useState } from "react"import { useRouter, useSearchParams } from "next/navigation"import { toastApiError } from "@/lib/api/client"import { ChannelHeaderSkeleton, type ChannelNotifLevel } from "@/components/community/channels/channel-header"-import { MessageList } from "@/components/community/messages/message-list"+import { ConversationMessageSkeleton } from "@/components/community/channels/conversation-message-skeleton"import { ComposerSkeleton } from "@/components/community/messages/composer"import { ForumViewSkeleton } from "@/components/community/channels/forum-view"import { TextChannelSurface } from "@/components/community/channels/text-channel-surface"@@ -59,12 +59,6 @@ export function ChannelRoute({ serverParam, channelId }: {const searchParams = useSearchParams()const serverId = decodeURIComponent(serverParam)const currentUser = useCurrentUser()- // Remember this as the server's last-opened channel (per-browser navigation- // memory) so re-entering the server restores here instead of the default.- // Pure localStorage write; failures are swallowed in the helper.- useEffect(() => {- setLastChannel(serverId, channelId)- }, [serverId, channelId])// Cross-channel "jump to message" target, captured ONCE at mount from `?msg=`.// `ChannelView` is keyed by `serverId/channelId`, so a fresh jump remounts and// re-reads this. The param is stripped from the URL right after (below) so a@@ -92,14 +86,10 @@ export function ChannelRoute({ serverParam, channelId }: {isForumPostChild,isNotifyUnit,} = routeModel- useEffect(() => {- if (routeModel.routeLifecycle !== "ready") return- commitLastCommunityRoute(currentUser.id, channelHref(serverId, channelId))- }, [channelId, currentUser.id, routeModel.routeLifecycle, serverId])const forumPostOpener = useForumOpenerHint(serverId,currentChannelMeta?.parentMessageId,- isForumPostChild && routeModel.routeHydrated,+ isForumPostChild && routeModel.routeHydrated && navigationGate.allowed,)const threadOpenerHandoff = useThreadOpenerRouteGate({serverId,@@ -126,6 +116,7 @@ export function ChannelRoute({ serverParam, channelId }: {isChildChannel,isNotifyUnit,currentUser,+ accessAllowed: routeModel.routeLifecycle === "ready" && navigationGate.allowed,})const {composerMembers,@@ -197,23 +188,34 @@ export function ChannelRoute({ serverParam, channelId }: {}, [uiHandlers])const channelHydrated =+ routeModel.routeLifecycle === "ready" &¤tChannelId === channelId &&routeModel.routeHydrated &&(!isForumPostChild || !forumPostOpener.isLoading) &&navigationGate.allowed+ // Route memory is an access-bearing navigation decision. Structural hints+ // can choose the skeleton, but only live data plus the current access gate+ // may commit the destination for a later cold entry.+ useEffect(() => {+ if (!channelHydrated) return+ setLastChannel(serverId, channelId)+ commitLastCommunityRoute(currentUser.id, channelHref(serverId, channelId))+ }, [channelHydrated, channelId, currentUser.id, serverId])const subtype = resolveConversationSubtype({routeLifecycle: routeModel.routeLifecycle,accessAllowed: navigationGate.allowed,isChild: isChildChannel,isForum,+ structuralHint: routeModel.skeletonSubtype,})+ if (routeModel.metadataError) {+ return <ConversationResolutionErrorFrame+ retrying={routeModel.retryingMetadata}+ onRetry={() => { void routeModel.retryMetadata() }}+ />+ }if (subtype === "unknown") {- return routeModel.metadataError- ? <ConversationResolutionErrorFrame- retrying={routeModel.retryingMetadata}- onRetry={() => { void routeModel.retryMetadata() }}- />- : <ConversationResolutionPendingFrame />+ return <ConversationResolutionPendingFrame />}if (!channelHydrated) {if (subtype === "thread") {@@ -222,13 +224,14 @@ export function ChannelRoute({ serverParam, channelId }: {<ThreadSplitViewcontainerRef={threadSplit.containerRef}split={split}+ conversationSubtype="thread"parent={split ? (<><ChannelHeaderSkeleton kind={isForumPostChild ? "forum" : "text"} /><main className="flex min-h-0 min-w-0 flex-1 flex-col">{isForumPostChild? <ForumViewSkeleton />- : <MessageList channel="" messages={[]} loading onOpenThread={() => {}} />}+ : <ConversationMessageSkeleton />}</main></>) : null}@@ -236,7 +239,7 @@ export function ChannelRoute({ serverParam, channelId }: {<><ChannelHeaderSkeleton kind="thread" compactActions={split} /><div className="flex min-h-0 min-w-0 flex-1 flex-col">- <MessageList key={channelId} channel="" messages={[]} loading onOpenThread={() => {}} />+ <ConversationMessageSkeleton /><ComposerSkeleton /></div></>@@ -248,7 +251,10 @@ export function ChannelRoute({ serverParam, channelId }: {return (<><ChannelHeaderSkeleton kind="forum" />- <main className="flex min-h-0 min-w-0 flex-1 flex-col">+ <main+ data-community-conversation-subtype="forum"+ className="flex min-h-0 min-w-0 flex-1 flex-col"+ ><ForumViewSkeleton /></main></>@@ -257,20 +263,11 @@ export function ChannelRoute({ serverParam, channelId }: {return (<><ChannelHeaderSkeleton />- <main className="flex min-h-0 min-w-0 flex-1 flex-col">- {/*- `key={channelId}` MUST match the hydrated branches' key below —- verified empirically that a mismatched key- (this branch had none before) is what causes React to treat this- and the hydrated-branch `<MessageList>` as different component- identities, forcing a full unmount/remount instead of a props- update on one instance when `channelHydrated` flips true. With- matching keys, this works correctly even though this early- `return` and the hydrated branches' `return` produce- structurally different JSX trees — React's reconciliation only- needs the position + type + key to line up.- */}- <MessageList key={channelId} channel="" messages={[]} loading={true} onOpenThread={() => { }} />+ <main+ data-community-conversation-subtype="text"+ className="flex min-h-0 min-w-0 flex-1 flex-col"+ >+ <ConversationMessageSkeleton /><ComposerSkeleton /></main></>diff --git a/src/web/src/components/community/channels/channel-sidebar.crumb.test.ts b/src/web/src/components/community/channels/channel-sidebar.crumb.test.tsindex 7f1ba820e..6810146e4 100644--- a/src/web/src/components/community/channels/channel-sidebar.crumb.test.ts+++ b/src/web/src/components/community/channels/channel-sidebar.crumb.test.ts@@ -102,6 +102,26 @@ const renderForum = (muted = false, activeThreadId = "post_2") => renderToStatic}),)+const privateHintTree = {+ ...emptyTree,+ catOrder: ["cat_private"],+ order: { cat_private: [] },+ catNames: { cat_private: "Private" },+ catPrivate: { cat_private: true },+ catPending: { cat_private: false },+} as unknown as ChannelTree++const renderPrivateHint = (onCreateChannel?: () => void) => renderToStaticMarkup(+ createElement(ChannelSidebar, {+ tree: privateHintTree,+ serverName: "Alpha",+ activeChannel: "",+ isAdmin: false,+ setActiveChannel: vi.fn(),+ onCreateChannel,+ }),+)+describe("ChannelSidebar header", () => {it("keeps the channel list scrollable without reserving scrollbar width", () => {const html = render()@@ -156,4 +176,9 @@ describe("ChannelSidebar header", () => {expect(html).toContain('aria-current="page"')expect(html).not.toContain("bg-primary")})++ it("keeps hint-only private categories inert until live actions are installed", () => {+ expect(renderPrivateHint()).not.toContain('aria-label="Create channel in Private"')+ expect(renderPrivateHint(vi.fn())).toContain('aria-label="Create channel in Private"')+ })})diff --git a/src/web/src/components/community/channels/channel-sidebar.tsx b/src/web/src/components/community/channels/channel-sidebar.tsxindex f490e6b21..ba2283c50 100644--- a/src/web/src/components/community/channels/channel-sidebar.tsx+++ b/src/web/src/components/community/channels/channel-sidebar.tsx@@ -235,7 +235,7 @@ export const ChannelSidebar = memo(function ChannelSidebar({// - uncategorized (empty categoryId) / public category → admins only// - private category → any member (they own the channel + its roster)const canCreateInCategory = (categoryId: string) =>- catPrivate[categoryId] ? true : isAdmin+ Boolean(onCreateChannel) && (catPrivate[categoryId] ? true : isAdmin)const requestCreateChannel = (categoryId: string) => {if (!canCreateInCategory(categoryId)) { onBlockedCreate?.(); return }setDialog({ kind: "create-channel", categoryId })diff --git a/src/web/src/components/community/channels/conversation-message-skeleton.tsx b/src/web/src/components/community/channels/conversation-message-skeleton.tsxnew file mode 100644index 000000000..76a94e9bf--- /dev/null+++ b/src/web/src/components/community/channels/conversation-message-skeleton.tsx@@ -0,0 +1,5 @@+import { MessageListSkeleton } from "../messages/message-list-view"++export function ConversationMessageSkeleton() {+ return <MessageListSkeleton />+}diff --git a/src/web/src/components/community/channels/thread-split-view.tsx b/src/web/src/components/community/channels/thread-split-view.tsxindex 91d10ebbe..eda16ac2b 100644--- a/src/web/src/components/community/channels/thread-split-view.tsx+++ b/src/web/src/components/community/channels/thread-split-view.tsx@@ -27,11 +27,13 @@ export function ThreadSplitView({split,parent,thread,+ conversationSubtype,}: {containerRef: RefCallback<HTMLElement>split: booleanparent: ReactNodethread: ReactNode+ conversationSubtype?: "thread"}) {const { defaultLayout, onLayoutChanged } = useDefaultLayout({id: "community-thread-split-layout",@@ -44,6 +46,7 @@ export function ThreadSplitView({ref={containerRef}data-testid={tid.threadSplit}data-layout={split ? "split" : "full"}+ data-community-conversation-subtype={conversationSubtype}className="flex min-h-0 min-w-0 flex-1">{split ? (diff --git a/src/web/src/components/community/members/channel-member-view-model.dom.test.ts b/src/web/src/components/community/members/channel-member-view-model.dom.test.tsindex 6f3bd881a..037811927 100644--- a/src/web/src/components/community/members/channel-member-view-model.dom.test.ts+++ b/src/web/src/components/community/members/channel-member-view-model.dom.test.ts@@ -7,6 +7,7 @@ import { useAddableMembers, useChannelMembers } from "@/hooks/community/use-chanconst mocks = vi.hoisted(() => ({serverMembers: [] as Array<Record<string, unknown>>,+ serverMemberArgs: [] as Array<string | null>,channelMembers: new Map<string, Array<Record<string, unknown>>>(),channelQueryState: new Map<string, {resolved?: boolean@@ -39,14 +40,17 @@ const mocks = vi.hoisted(() => ({vi.mock("sonner", () => ({ toast: vi.fn() }))vi.mock("@/lib/api/client", () => ({ toastApiError: vi.fn() }))vi.mock("@/hooks/community/use-server-members", () => ({- useServerMembers: () => ({- members: mocks.serverMembers,- loading: false,- loadingMore: false,- hasMore: true,- loadMore: mocks.loadMore,- searchMembers: mocks.serverSearch,- }),+ useServerMembers: (serverId: string | null) => {+ mocks.serverMemberArgs.push(serverId)+ return {+ members: mocks.serverMembers,+ loading: false,+ loadingMore: false,+ hasMore: true,+ loadMore: mocks.loadMore,+ searchMembers: mocks.serverSearch,+ }+ },}))vi.mock("@/hooks/community/use-channel-members", () => ({useChannelMembers: vi.fn((channelId: string, enabled = true) => {@@ -188,6 +192,7 @@ describe("useChannelMemberViewModel", () => {member("viewer_1", "Viewer", { role: "admin" }),member("alice_1", "Alice"),]+ mocks.serverMemberArgs = []mocks.channelMembers = new Map()mocks.channelQueryState = new Map()mocks.channelRefetches = new Map()@@ -238,6 +243,21 @@ describe("useChannelMemberViewModel", () => {expect(mocks.removeThreadHookArgs.at(-1)).toEqual(["thread_1", "server_1", "viewer_1", true])})+ it("does not activate member queries before current live access is proved", () => {+ act(() => {+ rtlRender(renderHarness(props({ accessAllowed: false })))+ })++ expect(mocks.serverMemberArgs.at(-1)).toBeNull()+ expect(mockedUseChannelMembers).toHaveBeenNthCalledWith(1, "channel_1", false)+ expect(mockedUseChannelMembers).toHaveBeenNthCalledWith(2, "", false)+ expect(mockedUseAddableMembers).toHaveBeenCalledWith(+ "server_1",+ "channel_1",+ false,+ )+ })+afterEach(() => {vi.clearAllMocks()})diff --git a/src/web/src/components/community/members/channel-member-view-model.tsx b/src/web/src/components/community/members/channel-member-view-model.tsxindex 31a0a6f15..b33f21864 100644--- a/src/web/src/components/community/members/channel-member-view-model.tsx+++ b/src/web/src/components/community/members/channel-member-view-model.tsx@@ -70,6 +70,7 @@ export function useChannelMemberViewModel({isChildChannel,isNotifyUnit,currentUser,+ accessAllowed = true,}: {serverId: stringchannelId: string@@ -80,6 +81,7 @@ export function useChannelMemberViewModel({isChildChannel: booleanisNotifyUnit: booleancurrentUser: { id: string }+ accessAllowed?: boolean}): {composerMembers: Member[]composerMentionCandidates?: MentionCandidateSource@@ -88,7 +90,7 @@ export function useChannelMemberViewModel({resolveUserName: (userId: string) => stringmyRole: Role | undefined} {- const membersHook = useServerMembers(serverId)+ const membersHook = useServerMembers(accessAllowed && currentServer ? serverId : null)const profilesByUserId = useCommunityWsStore((state) => state.profilesByUserId)const [memberUi, setMemberUi] = useState({ channelId, query: "", dialogOpen: false })const memberQuery = memberUi.channelId === channelId ? memberUi.query : ""@@ -134,10 +136,13 @@ export function useChannelMemberViewModel({const channelMembersHook = useChannelMembers(channelId,- isNotifyUnit || (currentChannelPrivate && !isNotifyUnit),+ accessAllowed && (isNotifyUnit || (currentChannelPrivate && !isNotifyUnit)),)const parentChannelId = isNotifyUnit ? currentChannelMeta?.parentChannelId ?? null : null- const parentChannelMembersHook = useChannelMembers(parentChannelId ?? "", !!parentChannelId)+ const parentChannelMembersHook = useChannelMembers(+ parentChannelId ?? "",+ accessAllowed && !!parentChannelId,+ )const participantMembersData = channelMembersHook.dataconst parentMembersData = parentChannelMembersHook.dataconst refetchParticipantMembers = channelMembersHook.refetch@@ -168,7 +173,7 @@ export function useChannelMemberViewModel({const addableChannelMembers = useAddableMembers(serverId,channelId,- manageMembersOpen && currentChannelPrivate && !isNotifyUnit,+ accessAllowed && manageMembersOpen && currentChannelPrivate && !isNotifyUnit,)const {data: addableMembersData,diff --git a/src/web/src/components/community/messages/message-list-facade.contract.test.ts b/src/web/src/components/community/messages/message-list-facade.contract.test.tsindex a198ccc24..9fac2f531 100644--- a/src/web/src/components/community/messages/message-list-facade.contract.test.ts+++ b/src/web/src/components/community/messages/message-list-facade.contract.test.ts@@ -80,7 +80,6 @@ describe("MessageList facade contract", () => {const importers = ["src/app/c/me/[dmId]/page.tsx","src/components/community/channels/thread-channel-surface.tsx",- "src/components/community/channels/channel-route.tsx","src/components/community/channels/text-channel-surface.tsx",]for (const path of importers) {diff --git a/src/web/src/components/community/messages/message-list-view.tsx b/src/web/src/components/community/messages/message-list-view.tsxindex 7e44f8ab3..5e8d90c57 100644--- a/src/web/src/components/community/messages/message-list-view.tsx+++ b/src/web/src/components/community/messages/message-list-view.tsx@@ -89,6 +89,30 @@ export function renderMessageListView()}+export function MessageListSkeleton({ variant = "channel" }: { variant?: "channel" | "dm" }) {+ return (+ <div+ aria-busy="true"+ data-message-list-skeleton+ className="relative flex min-h-0 flex-1 flex-col"+ >+ <div data-message-scroller-boundary className="relative min-h-0 flex-1">+ <div+ data-testid={tid.messageScroller}+ className="h-full overflow-x-clip overflow-y-auto thin-scrollbar"+ >+ <div+ data-message-list-content+ className="flex min-h-full flex-col justify-end px-4 pb-14 pt-8 sm:pb-18"+ >+ <MessageListSkeletonContent variant={variant} />+ </div>+ </div>+ </div>+ </div>+ )+}+function MessageListSkeletonContent({ variant }: { variant: "channel" | "dm" }) {const clusters: number[][] = [[220, 140],diff --git a/src/web/src/components/community/shell/shell-frame.dom.test.ts b/src/web/src/components/community/shell/shell-frame.dom.test.tsindex 87649fb55..81920b8cd 100644--- a/src/web/src/components/community/shell/shell-frame.dom.test.ts+++ b/src/web/src/components/community/shell/shell-frame.dom.test.ts@@ -16,6 +16,7 @@ const mocks = vi.hoisted(() => {pendingHref: { current: null as string | null },navigationPending: { current: false },serverCache: new Set<string>(),+ structuralSnapshot: { current: null as null | Record<string, unknown> },breakpoint: { current: "desktop" },onboardingState: { current: null as Record<string, unknown> | null },replace: vi.fn(),@@ -73,6 +74,9 @@ vi.mock("@/stores/community/ws", () => ({vi.mock("@/contexts/community/current-user", () => ({useCurrentUser: () => ({ id: "viewer" }),}))+vi.mock("@/hooks/community/use-structural-snapshot", () => ({+ useStructuralSnapshot: () => mocks.structuralSnapshot.current,+}))vi.mock("./use-shell-rail-controller", () => ({useShellRailController: (options: unknown) => {mocks.railOptions(options)@@ -112,6 +116,7 @@ describe("ShellFrame orchestration", () => {mocks.pendingHref.current = nullmocks.navigationPending.current = falsemocks.serverCache.clear()+ mocks.structuralSnapshot.current = nullmocks.breakpoint.current = "desktop"mocks.onboardingState.current = nullmocks.registerUiHandlers.mockClear()@@ -195,6 +200,50 @@ describe("ShellFrame orchestration", () => {}))})+ it("does not promote a rail-only structural identity to a warm server target", () => {+ mocks.currentHref.current = "/c/channels/s1/c1"+ mocks.pendingHref.current = "/c/channels/s2"+ mocks.navigationPending.current = true+ mocks.structuralSnapshot.current = {+ serverOrder: ["s2"],+ servers: [{ id: "s2", categories: [], channels: [] }],+ }++ render(createElement(ShellFrame, {+ ...baseProps,+ frameHref: "/c/channels/s1/c1",+ }))++ expect(checkpoint()).toMatchObject({+ mode: "cold-scope",+ sidebar: { kind: "server-skeleton", serverId: "s2" },+ })+ })++ it("uses a captured structural tree as a warm server target", () => {+ mocks.currentHref.current = "/c/channels/s1/c1"+ mocks.pendingHref.current = "/c/channels/s2"+ mocks.navigationPending.current = true+ mocks.structuralSnapshot.current = {+ serverOrder: ["s2"],+ servers: [{+ id: "s2",+ categories: [],+ channels: [{ id: "c2", name: "cached", type: "text", categoryId: null }],+ }],+ }++ render(createElement(ShellFrame, {+ ...baseProps,+ frameHref: "/c/channels/s1/c1",+ }))++ expect(checkpoint()).toMatchObject({+ mode: "warm-scope",+ main: { kind: "keep" },+ })+ })+it("lets an exact warm target skip both forced checkpoints without relabeling A", () => {mocks.currentHref.current = "/c/channels/s1/c1"mocks.pendingHref.current = "/c/channels/s2"diff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsxindex d6fe2e51b..8f3fcbd6a 100644--- a/src/web/src/components/community/shell/shell-frame.tsx+++ b/src/web/src/components/community/shell/shell-frame.tsx@@ -21,6 +21,7 @@ import { useShellProfileController } from "./use-shell-profile-controller"import { useShellInboxController } from "./use-shell-inbox-controller"import { useCommunityNavigationController } from "./use-community-navigation-controller"import type { ShellFrameProps } from "./shell-frame-types"+import { useStructuralSnapshot } from "@/hooks/community/use-structural-snapshot"/** Shared community shell orchestration for the server and DM layouts. */export function ShellFrame(props: ShellFrameProps) {@@ -36,6 +37,7 @@ export function ShellFrame(props: ShellFrameProps) {} = propsconst queryClient = useQueryClient()const currentUser = useCurrentUser()+ const structuralSnapshot = useStructuralSnapshot(currentUser.id, queryClient)const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)const breakpoint = useBreakpoint()const onboardingState = useCommunityOnboarding()@@ -59,8 +61,17 @@ export function ShellFrame(props: ShellFrameProps) {const target = navigation.pendingHref? normalizeCommunityHref(navigation.pendingHref): null- const targetReady = target?.scope.kind === "server"- ? queryClient.getQueryData(communityKeys.server(target.scope.serverId)) !== undefined+ const targetServerId = target?.scope.kind === "server" ? target.scope.serverId : null+ const structuralTarget = targetServerId+ ? structuralSnapshot?.servers.find((server) => server.id === targetServerId)+ : null+ const targetReady = targetServerId+ ? queryClient.getQueryData(communityKeys.server(targetServerId)) !== undefined+ // `replaceServers` can seed a rail-only identity with an empty tree.+ // Only a snapshot containing actual tree structure can replace the+ // target-scoped cold checkpoint.+ || Boolean(structuralTarget+ && (structuralTarget.categories.length > 0 || structuralTarget.channels.length > 0)): target?.scope.kind === "me"? queryClient.getQueryData(communityKeys.dms()) !== undefined: false@@ -87,6 +98,7 @@ export function ShellFrame(props: ShellFrameProps) {projectedActiveServerId,onOpenActiveServerSettings,onOpenActiveServerInvite,+ accountId: currentUser.id,})const profile = useShellProfileController({router: navigation,diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts b/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.tsindex 0e6e4a7ce..eebb3fd59 100644--- a/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts+++ b/src/web/src/components/community/shell/use-shell-profile-controller.dom.test.ts@@ -449,12 +449,14 @@ describe("useShellProfileController", () => {mocks.signOut.mockImplementation(async () => { order.push("signOut") })hook.router.push = (href: string) => { order.push(`push:${href}`) }await act(async () => hook.current.userSettingsProps.onLogout())- expect(order).toEqual(["cancel", "community", "ws", "stream", "reconcile", "query", "cache", "signOut", "push:/sign-in"])+ expect(order).toEqual(["cancel", "community", "ws", "stream", "reconcile", "query", "signOut", "cache", "push:/sign-in"])order.length = 0+ mocks.clearCache.mockClear()mocks.clearCache.mockResolvedValue(undefined)mocks.signOut.mockRejectedValue(new Error("auth"))await expect(act(async () => hook.current.userSettingsProps.onLogout())).rejects.toThrow("auth")+ expect(mocks.clearCache).not.toHaveBeenCalled()expect(order.some((entry) => entry.startsWith("push:"))).toBe(false)})diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.ts b/src/web/src/components/community/shell/use-shell-profile-controller.tsindex aeb1f1779..4876aa1a7 100644--- a/src/web/src/components/community/shell/use-shell-profile-controller.ts+++ b/src/web/src/components/community/shell/use-shell-profile-controller.ts@@ -278,7 +278,7 @@ export function useShellProfileController({}}- const clearLocalAccountState = async () => {+ const clearVolatileAccountState = () => {cancelPendingNavigation()useCommunityStore.getState().reset()useCommunityWsStore.getState().reset()@@ -286,17 +286,22 @@ export function useShellProfileController({disposeReadCoordinator(queryClient)disposeAccountReadStateReconciliation(queryClient)queryClient.clear()- await clearPersistedCache(currentUser.id).catch(() => {})}const onLogout = async () => {- await clearLocalAccountState()+ clearVolatileAccountState()await signOut()+ // Better Auth can synchronously remount the authenticated tree while its+ // sign-out state settles. Clear last so any transitional QueryProvider+ // has already captured the retired generation and cannot recreate this+ // account's persisted blob after logout.+ await clearPersistedCache(currentUser.id).catch(() => {})router.push("/sign-in")}const onAccountDeleted = async () => {- await clearLocalAccountState()+ clearVolatileAccountState()+ await clearPersistedCache(currentUser.id).catch(() => {})setEditingProfile(false)globalThis.location.replace(ACCOUNT_DELETED_SIGN_IN_PATH)}diff --git a/src/web/src/components/community/shell/use-shell-rail-controller.dom.test.ts b/src/web/src/components/community/shell/use-shell-rail-controller.dom.test.tsindex 3317c3d26..67a5a5049 100644--- a/src/web/src/components/community/shell/use-shell-rail-controller.dom.test.ts+++ b/src/web/src/components/community/shell/use-shell-rail-controller.dom.test.ts@@ -14,6 +14,7 @@ const mocks = vi.hoisted(() => ({toast: vi.fn(),toastApiError: vi.fn(),lastMeLeaf: { current: null as string | null },+ structuralSnapshot: null as null | Record<string, unknown>,}))vi.mock("sonner", () => ({ toast: mocks.toast }))@@ -31,6 +32,9 @@ vi.mock("@/hooks/community/use-servers", () => ({serverProjectedQueryFn: (_queryClient: unknown, id: string) => () => Promise.resolve({ id }),}))vi.mock("@/hooks/community/use-folders", () => ({ useFolders: () => ({ folders: mocks.folders }) }))+vi.mock("@/hooks/community/use-structural-snapshot", () => ({+ useStructuralSnapshot: () => mocks.structuralSnapshot,+}))vi.mock("@/hooks/community/mutations", () => ({useCreateServer: () => ({ mutateAsync: mocks.createServer }),useLeaveServer: () => ({ mutate: mocks.leaveServer }),@@ -129,6 +133,7 @@ describe("useShellRailController", () => {}mocks.folders.length = 0mocks.lastMeLeaf.current = null+ mocks.structuralSnapshot = null})it("commits cold server navigation synchronously without waiting for detail", async () => {@@ -145,6 +150,35 @@ describe("useShellRailController", () => {})+ it("renders a structural rail hint while keeping privileged actions disabled", async () => {+ mocks.structuralSnapshot = {+ schemaVersion: 1,+ accountId: "viewer-1",+ capturedAt: Date.now(),+ serverOrder: ["s3"],+ folders: [{ id: "f1", name: "Saved", serverIds: ["s3"] }],+ servers: [{+ id: "s3",+ name: "Hint",+ discriminator: "0003",+ icon: null,+ categories: [],+ channels: [{ id: "c3", name: "cached", type: "text", categoryId: null }],+ childRouteHints: [],+ }],+ }+ const hook = await renderController({ accountId: "viewer-1" })++ expect(hook.current.railProps.servers.map((server) => server.id)).toEqual(["s3"])+ expect(hook.current.railProps.folders.map((folder) => folder.id)).toEqual(["f1"])+ expect(hook.current.railProps.onLeaveServer).toBeUndefined()+ expect(hook.current.railProps.onOpenSettings).toBeUndefined()+ expect(hook.current.railProps.onOpenInvitePopover).toBeUndefined()++ await act(async () => hook.current.navigate("s3"))+ expect(hook.pushed).toEqual(["/c/channels/s3/c3"])+ })+it("projects the pending target for every rail entry without changing committed actions", async () => {const openSettings = vi.fn()const hook = await renderController({diff --git a/src/web/src/components/community/shell/use-shell-rail-controller.ts b/src/web/src/components/community/shell/use-shell-rail-controller.tsindex 44382f917..121eb5441 100644--- a/src/web/src/components/community/shell/use-shell-rail-controller.ts+++ b/src/web/src/components/community/shell/use-shell-rail-controller.ts@@ -22,6 +22,11 @@ import type { ShellFrameProps } from "./shell-frame-types"import type { View } from "./shell-types"import type { CommunityNavigationController } from "./use-community-navigation-controller"import type { QueryClient } from "@tanstack/react-query"+import { useStructuralSnapshot } from "@/hooks/community/use-structural-snapshot"+import {+ structuralSnapshotFolders,+ structuralSnapshotServers,+} from "@/lib/community/structural-snapshot"type Options = Pick<ShellFrameProps,@@ -35,6 +40,7 @@ type Options = Pick<breakpoint: BreakpointprojectedView?: ViewprojectedActiveServerId: string | undefined+ accountId?: string}export function useShellRailController({@@ -47,10 +53,19 @@ export function useShellRailController({projectedActiveServerId,onOpenActiveServerSettings,onOpenActiveServerInvite,+ accountId,}: Options) {+ const structuralSnapshot = useStructuralSnapshot(accountId ?? null, queryClient)const serversQuery = useServers()- const { servers } = serversQuery- const { folders } = useFolders()+ const foldersQuery = useFolders()+ const hasLiveServers = serversQuery.data !== undefined || !accountId+ const servers = hasLiveServers+ ? serversQuery.servers+ : structuralSnapshotServers(structuralSnapshot)+ const folders = foldersQuery.data?.folders+ ?? (accountId+ ? structuralSnapshotFolders(structuralSnapshot)+ : foldersQuery.folders)const currentServerId = useCommunityStore((state) => state.currentServerId)const { mutateAsync: createServerAsync } = useCreateServer()const { mutate: leaveServerMutate } = useLeaveServer()@@ -63,11 +78,15 @@ export function useShellRailController({const serverDestination = useCallback((id: string) => {const detail = queryClient.getQueryData<ServerDetail>(communityKeys.server(id))- const channelIds = detail?.categories.flatMap((category) =>+ const liveChannelIds = detail?.categories.flatMap((category) =>category.channels.filter((channel) => !channel.pending).map((channel) => channel.id)- ) ?? []+ )+ const channelIds = liveChannelIds+ ?? structuralSnapshot?.servers.find((server) => server.id === id)+ ?.channels.map((channel) => channel.id)+ ?? []return pickServerLandingHref(id, channelIds, getLastChannel(id))- }, [queryClient])+ }, [queryClient, structuralSnapshot])const resolveServerDestination = useCallback(async (id: string) => {const root = `/c/channels/${id}`const immediate = serverDestination(id)@@ -171,16 +190,16 @@ export function useShellRailController({servers: railServers,folders,activeServerId: projectedActiveServerId,- serversLoading: serversQuery.isPending,+ serversLoading: serversQuery.isPending && !structuralSnapshot,view: projectedView,onHome,onHomePrefetch,onServerNavigate,onServerPrefetch,onCreateServer,- onLeaveServer,- onOpenSettings,- onOpenInvitePopover,+ onLeaveServer: hasLiveServers ? onLeaveServer : undefined,+ onOpenSettings: hasLiveServers ? onOpenSettings : undefined,+ onOpenInvitePopover: hasLiveServers ? onOpenInvitePopover : undefined,},navigate,}diff --git a/src/web/src/hooks/community/community-ws/channel-scope-projection.ts b/src/web/src/hooks/community/community-ws/channel-scope-projection.tsindex 1a6956c9d..e79b95be8 100644--- a/src/web/src/hooks/community/community-ws/channel-scope-projection.ts+++ b/src/web/src/hooks/community/community-ws/channel-scope-projection.ts@@ -1,8 +1,7 @@-import type { QueryClient, Query } from "@tanstack/react-query"+import type { QueryClient } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"import type { ServerDetail } from "@/hooks/community/use-servers"import { useCommunityWsStore } from "@/stores/community/ws"-import { clearTypingIndicator } from "./typing"import { useCommunityStore } from "@/stores/community"import { useMessageStreamStore } from "@/stores/community/message-stream"import { clearLastChannel } from "@/lib/community/last-channel"@@ -10,7 +9,6 @@ import { channelHref } from "@/lib/community/community-route"import type { PageCache } from "./cache"import { removeThreadFromCache } from "./cache"import type { ForumFeedPage } from "@/hooks/community/use-forum-feed"-import type { ThreadsResponse } from "@/hooks/community/use-channel-panels"import { removeForumPostFromFeed } from "@/hooks/community/forum-feed-tag-transition"import type { InfiniteData } from "@tanstack/react-query"import {@@ -21,6 +19,8 @@ import {} from "@/hooks/community/use-forum-sidebar-threads"import type { CommunityWsProjectionTransaction } from "./projection-transaction"import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"+import { updateStructuralSnapshot } from "@/lib/community/structural-snapshot"+import { collectChannelScopeIds, evictScopeContent } from "./scope-eviction"export function projectChannelScopeEviction(projection: CommunityWsProjectionTransaction,@@ -38,90 +38,14 @@ export function projectChannelScopeEviction(evictChannelScopeQueryCaches(queryClient, serverId, id)evictScopeContent(queryClient, serverId, id)}+ updateStructuralSnapshot(queryClient, {+ type: "removeChannel",+ serverId,+ channelId,+ })})}-function collectChannelScopeIds(queryClient: QueryClient, serverId: string, channelId?: string) {- const ids = new Set<string>(channelId ? [channelId] : [])- const store = useCommunityStore.getState()- const current = store.currentChannelMeta- if (store.currentServerId === serverId && store.currentChannelId- && (!channelId || current?.parentChannelId === channelId)) ids.add(store.currentChannelId)- for (const [id, scope] of useCommunityWsStore.getState().channelAccessScopes) {- if (scope.serverId === serverId && (!channelId || scope.parentChannelId === channelId)) ids.add(id)- }- for (const [, meta] of queryClient.getQueriesData<{ id: string; parentChannelId?: string }>(- { queryKey: communityKeys.channelMetaRoot(serverId) },- )) {- if (meta && (!channelId || meta.parentChannelId === channelId)) ids.add(meta.id)- }- for (const { scope } of useMessageStreamStore.getState().entries.values()) {- if (!channelId && scope.kind === "channel" && scope.serverId === serverId) ids.add(scope.id)- }- const visit = (value: unknown) => {- if (Array.isArray(value)) { value.forEach(visit); return }- if (!value || typeof value !== "object") return- const row = value as Record<string, unknown>- if (!channelId || row.parentChannelId === channelId) {- if (typeof row.childChannelId === "string") ids.add(row.childChannelId)- if (typeof row.id === "string" && (row.type === "thread" || row.type === "text" || row.type === "forum")) ids.add(row.id)- }- for (const child of Object.values(row)) if (child && typeof child === "object") visit(child)- }- for (const [, data] of queryClient.getQueriesData({ queryKey: communityKeys.server(serverId) })) visit(data)- for (const [key, data] of queryClient.getQueriesData<ThreadsResponse | InfiniteData<ForumFeedPage>>({- queryKey: ["community", "channel"],- predicate: (query) => query.queryKey[3] === "threads" && (!channelId || query.queryKey[2] === channelId),- })) {- if (!data) continue- const pages = "pages" in data ? data.pages : [data]- for (const page of pages) {- if (page.serverId !== serverId) continue- ids.add(key[2] as string)- for (const thread of page.threads) ids.add(thread.id)- }- }- return ids-}--function scopeQuery(query: Query, serverId: string, channelId: string) {- const key = query.queryKey- if (key[0] !== "community") return false- if (key[1] === "channel" && key[2] === channelId) return true- if (key[1] === "message-context" && key[2] === "channel" && key[3] === channelId) return true- if (key[1] === "servers" && key[2] === serverId- && (key[3] === "channel-meta" || key[3] === "forum-sidebar-retained") && key[4] === channelId) return true- if (key[1] !== "message" && key[1] !== "reaction-details") return false- const data = query.state.data as { channelId?: string; scope?: { channelId?: string } } | undefined- const ownerChannelId = data?.channelId ?? data?.scope?.channelId- return !ownerChannelId || ownerChannelId === channelId-}--function evictScopeContent(queryClient: QueryClient, serverId: string, channelId: string) {- const predicate = (query: Query) => scopeQuery(query, serverId, channelId)- void queryClient.cancelQueries({ predicate })- queryClient.removeQueries({ predicate })- useMessageStreamStore.getState().removeScope({ kind: "channel", id: channelId, serverId })- const store = useCommunityStore.getState()- for (const userId of store.typingByScope.get(`ch:${channelId}`)?.keys() ?? []) clearTypingIndicator(`ch:${channelId}`, userId)- if (store.currentChannelId === channelId) {- store.setCurrentChannelMeta(null)- store.setCurrentChannelId(null)- }- if (store.subscription.channelId === channelId || store.subscription.secondaryChannelId === channelId) {- const subscription = { ...store.subscription }- if (subscription.channelId === channelId) delete subscription.channelId- if (subscription.secondaryChannelId === channelId) delete subscription.secondaryChannelId- useCommunityStore.setState({ subscription, ...(store.subscription.secondaryChannelId === channelId ? { secondaryChannelOwner: null } : {}) })- }-}--export function evictServerChannelScopes(queryClient: QueryClient, serverId: string) {- useCommunityWsStore.getState().revokeServerAccess(serverId)- for (const id of collectChannelScopeIds(queryClient, serverId)) evictScopeContent(queryClient, serverId, id)- void queryClient.cancelQueries({ queryKey: communityKeys.server(serverId) })-}-function evictChannelScopeQueryCaches(queryClient: QueryClient,serverId: string,@@ -234,6 +158,11 @@ export function applyForumPostUnitClientEffects(type: "messageRemoved",messageId: unit.openerMessageId,})+ updateStructuralSnapshot(queryClient, {+ type: "removeChildHint",+ serverId: unit.serverId,+ channelId: unit.childChannelId,+ })const store = useCommunityStore.getState()if (wasCurrent) {store.setCurrentChannelMeta(null)diff --git a/src/web/src/hooks/community/community-ws/membership-events.test.ts b/src/web/src/hooks/community/community-ws/membership-events.test.tsindex d87067a03..c21c827a2 100644--- a/src/web/src/hooks/community/community-ws/membership-events.test.ts+++ b/src/web/src/hooks/community/community-ws/membership-events.test.ts@@ -487,6 +487,22 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",id: "srv_1",categories: [{ id: "cat_1", channels: [{ id: "ch_1", type: "text" }] }],})+ capturedQueryClient.setQueryData(communityKeys.structuralSnapshot(), {+ schemaVersion: 1,+ accountId: "u_me",+ capturedAt: Date.now(),+ serverOrder: ["srv_1"],+ folders: [],+ servers: [{+ id: "srv_1",+ name: "Server",+ discriminator: "0001",+ icon: null,+ categories: [{ id: "cat_1", name: "Private" }],+ channels: [{ id: "ch_1", name: "secret", type: "text", categoryId: "cat_1" }],+ childRouteHints: [],+ }],+ })capturedOnMessage!({type: "community:channel.member_remove",@@ -498,6 +514,9 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",expect(capturedQueryClient.getQueryData<{categories: { channels: { id: string }[] }[]}>(serverKey)?.categories[0].channels).toEqual([])+ expect(capturedQueryClient.getQueryData<{+ servers: Array<{ channels: Array<{ id: string }> }>+ }>(communityKeys.structuralSnapshot())?.servers[0]?.channels).toEqual([])})it("adds/removes the viewer's participating child in the forum sidebar", async () => {diff --git a/src/web/src/hooks/community/community-ws/membership-events.ts b/src/web/src/hooks/community/community-ws/membership-events.tsindex 14185c83d..c1888388a 100644--- a/src/web/src/hooks/community/community-ws/membership-events.ts+++ b/src/web/src/hooks/community/community-ws/membership-events.ts@@ -25,7 +25,8 @@ import { useCommunityWsStore } from "@/stores/community/ws"import { fetchChannelMetadata, captureChannelMetadataToken, isChannelMetadataTokenCurrent } from "@/hooks/community/channel-metadata"import { runCommunityWsProjectionTransaction } from "./projection-transaction"import type { MembershipEventContext } from "@/hooks/community/community-ws/handler-context"-import { projectChannelScopeEviction, evictServerChannelScopes } from "./channel-scope-projection"+import { projectChannelScopeEviction } from "./channel-scope-projection"+import { evictServerChannelScopes } from "./scope-eviction"import { avatarInitial } from "@/lib/community/avatar"import {invalidateChannelRefDirectory,diff --git a/src/web/src/hooks/community/community-ws/reconnect.test.ts b/src/web/src/hooks/community/community-ws/reconnect.test.tsindex 8c779621a..e74d4b70d 100644--- a/src/web/src/hooks/community/community-ws/reconnect.test.ts+++ b/src/web/src/hooks/community/community-ws/reconnect.test.ts@@ -312,6 +312,14 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {const { useCommunityStore } = await import("@/stores/community")useCommunityStore.getState().setCurrentServerId("srv_open")capturedQueryClient.setQueryData(communityKeys.server("srv_open"), { id: "srv_open" })+ capturedQueryClient.setQueryData(communityKeys.structuralSnapshot(), {+ schemaVersion: 1,+ accountId: "viewer",+ capturedAt: Date.now(),+ serverOrder: ["srv_open"],+ folders: [],+ servers: [],+ })const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")// handleReconnect reads currentServerId via getState() at call time.@@ -342,6 +350,11 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {(k) => JSON.stringify(k) === JSON.stringify(communityKeys.members("srv_open")),),).toBe(true)+ expect(+ invalidatedKeys.some(+ (k) => JSON.stringify(k) === JSON.stringify(communityKeys.structuralSnapshot()),+ ),+ ).toBe(false)})it("keeps inactive retained/meta/hint data painted while marking it stale", async () => {diff --git a/src/web/src/hooks/community/community-ws/scope-eviction.ts b/src/web/src/hooks/community/community-ws/scope-eviction.tsnew file mode 100644index 000000000..26914f28d--- /dev/null+++ b/src/web/src/hooks/community/community-ws/scope-eviction.ts@@ -0,0 +1,125 @@+import type { Query, QueryClient } from "@tanstack/react-query"+import { communityKeys } from "@/lib/query-keys"+import { useCommunityWsStore } from "@/stores/community/ws"+import { useCommunityStore } from "@/stores/community"+import { useMessageStreamStore } from "@/stores/community/message-stream"+import { clearTypingIndicator } from "./typing"+import { updateStructuralSnapshot } from "@/lib/community/structural-snapshot"++type ThreadPageLike = {+ serverId?: string+ threads?: Array<{ id?: string }>+}++export function collectChannelScopeIds(+ queryClient: QueryClient,+ serverId: string,+ channelId?: string,+) {+ const ids = new Set<string>(channelId ? [channelId] : [])+ const store = useCommunityStore.getState()+ const current = store.currentChannelMeta+ if (store.currentServerId === serverId && store.currentChannelId+ && (!channelId || current?.parentChannelId === channelId)) ids.add(store.currentChannelId)+ for (const [id, scope] of useCommunityWsStore.getState().channelAccessScopes) {+ if (scope.serverId === serverId && (!channelId || scope.parentChannelId === channelId)) ids.add(id)+ }+ for (const [, meta] of queryClient.getQueriesData<{ id: string; parentChannelId?: string }>(+ { queryKey: communityKeys.channelMetaRoot(serverId) },+ )) {+ if (meta && (!channelId || meta.parentChannelId === channelId)) ids.add(meta.id)+ }+ for (const { scope } of useMessageStreamStore.getState().entries.values()) {+ if (!channelId && scope.kind === "channel" && scope.serverId === serverId) ids.add(scope.id)+ }+ const visit = (value: unknown) => {+ if (Array.isArray(value)) { value.forEach(visit); return }+ if (!value || typeof value !== "object") return+ const row = value as Record<string, unknown>+ if (!channelId || row.parentChannelId === channelId) {+ if (typeof row.childChannelId === "string") ids.add(row.childChannelId)+ if (typeof row.id === "string" && (row.type === "thread" || row.type === "text" || row.type === "forum")) ids.add(row.id)+ }+ for (const child of Object.values(row)) if (child && typeof child === "object") visit(child)+ }+ for (const [, data] of queryClient.getQueriesData({ queryKey: communityKeys.server(serverId) })) visit(data)+ for (const [key, data] of queryClient.getQueriesData<+ ThreadPageLike | { pages: ThreadPageLike[] }+ >({+ queryKey: ["community", "channel"],+ predicate: (query) => query.queryKey[3] === "threads" && (!channelId || query.queryKey[2] === channelId),+ })) {+ if (!data) continue+ const pages = "pages" in data ? data.pages : [data]+ for (const page of pages) {+ if (page.serverId !== serverId) continue+ ids.add(key[2] as string)+ for (const thread of page.threads ?? []) if (thread.id) ids.add(thread.id)+ }+ }+ return ids+}++function scopeQuery(query: Query, serverId: string, channelId: string) {+ const key = query.queryKey+ if (key[0] !== "community") return false+ if (key[1] === "channel" && key[2] === channelId) return true+ if (key[1] === "message-context" && key[2] === "channel" && key[3] === channelId) return true+ if (key[1] === "servers" && key[2] === serverId+ && (key[3] === "channel-meta" || key[3] === "forum-sidebar-retained") && key[4] === channelId) return true+ if (key[1] !== "message" && key[1] !== "reaction-details") return false+ const data = query.state.data as { channelId?: string; scope?: { channelId?: string } } | undefined+ const ownerChannelId = data?.channelId ?? data?.scope?.channelId+ return !ownerChannelId || ownerChannelId === channelId+}++export function evictScopeContent(+ queryClient: QueryClient,+ serverId: string,+ channelId: string,+) {+ const predicate = (query: Query) => scopeQuery(query, serverId, channelId)+ void queryClient.cancelQueries({ predicate })+ queryClient.removeQueries({ predicate })+ useMessageStreamStore.getState().removeScope({ kind: "channel", id: channelId, serverId })+ const store = useCommunityStore.getState()+ for (const userId of store.typingByScope.get(`ch:${channelId}`)?.keys() ?? []) {+ clearTypingIndicator(`ch:${channelId}`, userId)+ }+ if (store.currentChannelId === channelId) {+ store.setCurrentChannelMeta(null)+ store.setCurrentChannelId(null)+ }+ if (store.subscription.channelId === channelId || store.subscription.secondaryChannelId === channelId) {+ const subscription = { ...store.subscription }+ if (subscription.channelId === channelId) delete subscription.channelId+ if (subscription.secondaryChannelId === channelId) delete subscription.secondaryChannelId+ useCommunityStore.setState({+ subscription,+ ...(store.subscription.secondaryChannelId === channelId ? { secondaryChannelOwner: null } : {}),+ })+ }+}++export function evictServerChannelScopes(queryClient: QueryClient, serverId: string) {+ useCommunityWsStore.getState().revokeServerAccess(serverId)+ for (const id of collectChannelScopeIds(queryClient, serverId)) {+ evictScopeContent(queryClient, serverId, id)+ }+ void queryClient.cancelQueries({ queryKey: communityKeys.server(serverId) })+ queryClient.removeQueries({ queryKey: communityKeys.server(serverId) })+ queryClient.setQueryData<{ servers: Array<{ id: string }> } | undefined>(+ communityKeys.servers(),+ (current) => current+ ? { ...current, servers: current.servers.filter((server) => server.id !== serverId) }+ : current,+ )+ useMessageStreamStore.getState().removeServer(serverId)+ const community = useCommunityStore.getState()+ if (community.currentServerId === serverId) {+ community.setCurrentChannelMeta(null)+ community.setCurrentChannelId(null)+ community.setCurrentServerId(null)+ }+ updateStructuralSnapshot(queryClient, { type: "removeServer", serverId })+}diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.test.tsindex bf22a22c5..d88eccc92 100644--- a/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.test.ts@@ -2,8 +2,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { QueryObserver } from "@tanstack/react-query"import type {CommunityCategoryCreate,+ CommunityCategoryDelete,+ CommunityCategoryReorder,+ CommunityCategoryUpdate,CommunityChannelCreate,CommunityChannelDelete,+ CommunityChannelReorder,+ CommunityChannelUpdate,CommunityChildChannelCreate,CommunityChildChannelUpdate,CommunityServerDelete,@@ -77,12 +82,32 @@ function forumFeedIds(filter: string | null) {)?.pages.flatMap((page) => page.threads.map((thread) => thread.id)) ?? []}+function seedStructuralSnapshot(serverId = "srv_1") {+ capturedQueryClient.setQueryData(communityKeys.structuralSnapshot(), {+ schemaVersion: 1,+ accountId: "u_me",+ capturedAt: Date.now(),+ serverOrder: [serverId],+ folders: [],+ servers: [{+ id: serverId,+ name: "old",+ discriminator: "0001",+ icon: null,+ categories: [],+ channels: [{ id: "ch_old", name: "old", type: "text", categoryId: null }],+ childRouteHints: [],+ }],+ })+}+beforeEach(resetCommunityWsHarness)afterEach(cleanupCommunityWsHarness)describe("useCommunityWs — server.update patches server + list caches", () => {it("applies name and description changes to server(id) and servers()", async () => {await mountHook()+ seedStructuralSnapshot()capturedQueryClient.setQueryData(communityKeys.server("srv_1"), {id: "srv_1",name: "old",@@ -123,6 +148,11 @@ describe("useCommunityWs — server.update patches server + list caches", () =>communityKeys.servers(),)?.servers[0],).toMatchObject({ name: "new", description: "new description", initial: "N" })+ const structural = capturedQueryClient.getQueryData<{+ servers: Array<Record<string, unknown>>+ }>(communityKeys.structuralSnapshot())+ expect(structural?.servers[0]).toMatchObject({ name: "new" })+ expect(structural?.servers[0]).not.toHaveProperty("description")})})describe("useCommunityWs — child channel events", () => {@@ -145,11 +175,79 @@ describe("useCommunityWs — child channel events", () => {expect(keys.some((k) => k?.includes("forum-threads"))).toBe(false)expect(keys).not.toContainEqual(communityKeys.channelMessages("ch_1"))})++ it("projects a background child hint into the server that owns its parent", async () => {+ await mountHook()+ seedStructuralSnapshot("srv_background")+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().setCurrentServerId("srv_foreground")++ capturedOnMessage!({+ type: "community:channel.child_create",+ parentChannelId: "ch_old",+ parentMessageId: "opener_1",+ channel: {+ id: "child_1",+ name: "Thread",+ type: "thread",+ createdAt: "2026-09-08T00:00:00.000Z",+ },+ } satisfies CommunityChildChannelCreate)++ expect(capturedQueryClient.getQueryData<{+ servers: Array<{ id: string; childRouteHints: Array<{ id: string }> }>+ }>(communityKeys.structuralSnapshot())?.servers[0]).toMatchObject({+ id: "srv_background",+ childRouteHints: [{ id: "child_1" }],+ })+ })++ it("renames and archives a persisted child hint from structural events", async () => {+ await mountHook()+ seedStructuralSnapshot()+ capturedQueryClient.setQueryData<any>(+ communityKeys.structuralSnapshot(),+ (current: any) => ({+ ...current,+ servers: current.servers.map((server: any) => ({+ ...server,+ childRouteHints: [{+ id: "child_1",+ name: "Old",+ type: "thread",+ parentChannelId: "ch_old",+ parentMessageId: "opener_1",+ }],+ })),+ }),+ )++ capturedOnMessage!({+ type: "community:channel.child_update",+ parentChannelId: "ch_old",+ channelId: "child_1",+ changes: { name: "Renamed" },+ } satisfies CommunityChildChannelUpdate)+ expect(capturedQueryClient.getQueryData<any>(+ communityKeys.structuralSnapshot(),+ ).servers[0].childRouteHints[0].name).toBe("Renamed")++ capturedOnMessage!({+ type: "community:channel.child_update",+ parentChannelId: "ch_old",+ channelId: "child_1",+ changes: { archived: true },+ } satisfies CommunityChildChannelUpdate)+ expect(capturedQueryClient.getQueryData<any>(+ communityKeys.structuralSnapshot(),+ ).servers[0].childRouteHints).toEqual([])+ })})describe("useCommunityWs — channel.* invalidates server(id)", () => {it("channel.create invalidates server(serverId)", async () => {await mountHook()+ seedStructuralSnapshot()const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")const event: CommunityChannelCreate = {type: "community:channel.create",@@ -169,6 +267,59 @@ describe("useCommunityWs — channel.* invalidates server(id)", () => {return Array.isArray(key) && key.includes("srv_1")}),).toBe(true)+ expect(capturedQueryClient.getQueryData<{+ servers: Array<{ channels: Array<{ id: string }> }>+ }>(communityKeys.structuralSnapshot())?.servers[0]?.channels.map((channel) => channel.id))+ .toEqual(["ch_new", "ch_old"])+ })++ it("projects channel update and canonical reorder fields", async () => {+ await mountHook()+ seedStructuralSnapshot()++ capturedOnMessage!({+ type: "community:channel.create",+ serverId: "srv_1",+ channel: {+ id: "ch_second",+ name: "second",+ type: "text",+ categoryId: null,+ position: 1,+ createdAt: "2026-09-08T00:00:00.000Z",+ },+ } satisfies CommunityChannelCreate)+ capturedOnMessage!({+ type: "community:channel.update",+ serverId: "srv_1",+ channelId: "ch_second",+ changes: { name: "updated", type: "forum", categoryId: null },+ } satisfies CommunityChannelUpdate)+ capturedOnMessage!({+ type: "community:channel.update",+ serverId: "srv_1",+ channelId: "ch_second",+ changes: { name: "name-only" },+ } satisfies CommunityChannelUpdate)+ capturedOnMessage!({+ type: "community:channel.reorder",+ serverId: "srv_1",+ channels: [+ { id: "ch_old", position: 2 },+ { id: "ch_second", position: 1 },+ ],+ } satisfies CommunityChannelReorder)++ const channels = capturedQueryClient.getQueryData<any>(+ communityKeys.structuralSnapshot(),+ ).servers[0].channels+ expect(channels.map((channel: { id: string }) => channel.id))+ .toEqual(["ch_second", "ch_old"])+ expect(channels[0]).toMatchObject({+ name: "name-only",+ type: "forum",+ categoryId: null,+ })})})@@ -197,6 +348,44 @@ describe("useCommunityWs — category.* invalidates tree projections", () => {exact: true,})})++ it("projects category update, reorder, and delete into the structural tree", async () => {+ await mountHook()+ seedStructuralSnapshot()++ for (const [id, position] of [["cat_a", 0], ["cat_b", 1]] as const) {+ capturedOnMessage!({+ type: "community:category.create",+ serverId: "srv_1",+ category: { id, name: id, position, private: false },+ } satisfies CommunityCategoryCreate)+ }+ capturedOnMessage!({+ type: "community:category.update",+ serverId: "srv_1",+ categoryId: "cat_a",+ changes: { name: "Renamed", private: true, position: 1 },+ } satisfies CommunityCategoryUpdate)+ capturedOnMessage!({+ type: "community:category.reorder",+ serverId: "srv_1",+ categories: [+ { id: "cat_a", position: 2 },+ { id: "cat_b", position: 1 },+ ],+ } satisfies CommunityCategoryReorder)+ capturedOnMessage!({+ type: "community:category.delete",+ serverId: "srv_1",+ categoryId: "cat_b",+ } satisfies CommunityCategoryDelete)++ expect(capturedQueryClient.getQueryData<any>(+ communityKeys.structuralSnapshot(),+ ).servers[0].categories).toEqual([+ { id: "cat_a", name: "Renamed", private: true },+ ])+ })})describe("useCommunityWs — invite.create", () => {@@ -223,6 +412,43 @@ describe("useCommunityWs — invite.create", () => {})describe("useCommunityWs — channel.delete evicts channel-scoped caches", () => {+ it("prunes the structural channel and its child hints after scope eviction", async () => {+ await mountHook()+ seedStructuralSnapshot()+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.setState({+ typingByScope: new Map([["ch:ch_old", new Map([["u_typing", "Typer"]])]]),+ })+ capturedQueryClient.setQueryData<{ servers: Array<{+ childRouteHints: Array<Record<string, unknown>>+ }> }>(communityKeys.structuralSnapshot(), (current) => current && ({+ ...current,+ servers: current.servers.map((server) => ({+ ...server,+ childRouteHints: [{+ id: "child_1",+ name: "private title",+ type: "thread",+ parentChannelId: "ch_old",+ parentMessageId: "message_1",+ }],+ })),+ }))++ capturedOnMessage!({+ type: "community:channel.delete",+ serverId: "srv_1",+ channelId: "ch_old",+ } satisfies CommunityChannelDelete)++ const snapshot = capturedQueryClient.getQueryData<{+ servers: Array<{ channels: unknown[]; childRouteHints: unknown[] }>+ }>(communityKeys.structuralSnapshot())+ expect(snapshot?.servers[0]?.channels).toEqual([])+ expect(snapshot?.servers[0]?.childRouteHints).toEqual([])+ expect(useCommunityStore.getState().typingByScope.has("ch:ch_old")).toBe(false)+ })+it("fences a deleted channel's cached raw Inbox row", async () => {await mountHook({ viewerUserId: "u_me" })const unreadProjection = getAccountUnreadProjection(capturedQueryClient, "u_me")@@ -1004,6 +1230,7 @@ describe("useCommunityWs — server.update icon removal", () => {describe("useCommunityWs — server.delete resets store when focused server dies", () => {it("fences cached raw Inbox rows from the deleted server", async () => {await mountHook({ viewerUserId: "u_me" })+ seedStructuralSnapshot("srv_doomed")const unreadProjection = getAccountUnreadProjection(capturedQueryClient, "u_me")unreadProjection.recordArrival({ channelId: "ch_dead", serverId: "srv_doomed", seq: 1 })@@ -1013,6 +1240,9 @@ describe("useCommunityWs — server.delete resets store when focused server dies} satisfies CommunityServerDelete)expect(unreadProjection.projectUnread("inbox-unreads", "ch_dead", true, 1)).toBe(false)+ expect(capturedQueryClient.getQueryData<{+ serverOrder: string[]+ }>(communityKeys.structuralSnapshot())?.serverOrder).toEqual([])})it("clears currentServerId + currentChannelId if the deleted server is currently focused", async () => {diff --git a/src/web/src/hooks/community/community-ws/structure-tree-events.ts b/src/web/src/hooks/community/community-ws/structure-tree-events.tsindex 41340112e..23ecf90e2 100644--- a/src/web/src/hooks/community/community-ws/structure-tree-events.ts+++ b/src/web/src/hooks/community/community-ws/structure-tree-events.ts@@ -36,9 +36,9 @@ import {import type { StructureTreeEventContext } from "@/hooks/community/community-ws/handler-context"import {projectChannelScopeEviction,- evictServerChannelScopes,projectForumPostUnitEviction,} from "./channel-scope-projection"+import { evictServerChannelScopes } from "./scope-eviction"import {invalidateChannelMessages,invalidateChannelRefDirectory,@@ -49,6 +49,22 @@ import {} from "./invalidation-projections"import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"import { projectForumFeedWsTags } from "@/hooks/community/forum-feed-tag-transition"+import {+ updateStructuralSnapshot,+ type StructuralSnapshotV1,+} from "@/lib/community/structural-snapshot"++function structuralServerIdForParent(+ queryClient: StructureTreeEventContext["queryClient"],+ parentChannelId: string,+): string | null {+ const snapshot = queryClient.getQueryData<StructuralSnapshotV1>(+ communityKeys.structuralSnapshot(),+ )+ return snapshot?.servers.find((server) =>+ server.channels.some((channel) => channel.id === parentChannelId),+ )?.id ?? null+}export function handleChildChannelCreate(event: CommunityChildChannelCreate,@@ -121,6 +137,20 @@ export function handleChildChannelCreate(if (event.parentMessageId && !openerCached) {invalidateChannelMessages(projection, event.parentChannelId)}+ const structuralServerId = structuralServerIdForParent(queryClient, event.parentChannelId)+ if (structuralServerId && event.parentMessageId) {+ updateStructuralSnapshot(queryClient, {+ type: "upsertChildHint",+ serverId: structuralServerId,+ child: {+ id: event.channel.id,+ name: event.channel.name,+ type: "thread",+ parentChannelId: event.parentChannelId,+ parentMessageId: event.parentMessageId,+ },+ })+ }}export function handleChildChannelUpdate(@@ -150,6 +180,7 @@ export function handleChildChannelUpdate(})}const sidebarServerId = useCommunityStore.getState().currentServerId+ const structuralServerId = structuralServerIdForParent(queryClient, event.parentChannelId)if (changes.name !== undefined && sidebarServerId) {queryClient.setQueryData<Record<string, unknown> | undefined>(communityKeys.channelMeta(sidebarServerId, event.channelId),@@ -259,6 +290,20 @@ export function handleChildChannelUpdate(}}}+ if (structuralServerId) {+ updateStructuralSnapshot(queryClient, changes.archived === true+ ? {+ type: "removeChildHint",+ serverId: structuralServerId,+ channelId: event.channelId,+ }+ : {+ type: "patchChildHint",+ serverId: structuralServerId,+ channelId: event.channelId,+ ...(changes.name !== undefined ? { name: changes.name } : {}),+ })+ }}export function handleServerUpdate(@@ -303,6 +348,14 @@ export function handleServerUpdate(}: prev,)+ updateStructuralSnapshot(queryClient, {+ type: "patchServer",+ serverId: event.serverId,+ changes: {+ ...(event.changes.name !== undefined ? { name: event.changes.name } : {}),+ ...(event.changes.icon !== undefined ? { icon: event.changes.icon } : {}),+ },+ })}export function handleServerDelete(@@ -320,17 +373,6 @@ export function handleServerDelete(// detail subtree; the deleted server's own subtree is cleared by// the removeQueries below.invalidateServersList(projection)- queryClient.removeQueries({ queryKey: communityKeys.server(event.serverId) })- // #10: if the deleted server is the one the viewer is looking at,- // the store pointers now dangle — reset them so the UI drops back- // to a safe default instead of rendering a ghost server/channel.- const store = useCommunityStore.getState()- useMessageStreamStore.getState().removeServer(event.serverId)- if (store.currentServerId === event.serverId) {- store.setCurrentChannelMeta(null)- store.setCurrentChannelId(null)- store.setCurrentServerId(null)- }}type ChannelEvent =@@ -386,6 +428,43 @@ export function handleChannelEvent(invalidateChannelMessages(projection, event.parentChannelId)invalidateThreads(projection, event.parentChannelId)}+ } else if (event.type === "community:channel.create") {+ if (event.channel.type === "text" || event.channel.type === "forum") {+ updateStructuralSnapshot(queryClient, {+ type: "upsertChannel",+ serverId: event.serverId,+ channel: {+ id: event.channel.id,+ name: event.channel.name,+ type: event.channel.type,+ categoryId: event.channel.categoryId ?? null,+ },+ position: event.channel.position,+ })+ }+ } else if (event.type === "community:channel.update") {+ updateStructuralSnapshot(queryClient, {+ type: "patchChannel",+ serverId: event.serverId,+ channelId: event.channelId,+ changes: {+ ...(event.changes.name !== undefined ? { name: event.changes.name } : {}),+ ...(event.changes.type === "text" || event.changes.type === "forum"+ ? { type: event.changes.type }+ : {}),+ ...(event.changes.categoryId !== undefined+ ? { categoryId: event.changes.categoryId }+ : {}),+ },+ })+ } else {+ updateStructuralSnapshot(queryClient, {+ type: "reorderChannels",+ serverId: event.serverId,+ channelIds: [...event.channels]+ .sort((left, right) => left.position - right.position)+ .map((channel) => channel.id),+ })}invalidateServerDetail(projection, event.serverId)}@@ -398,8 +477,45 @@ type CategoryEvent =export function handleCategoryEvent(event: CategoryEvent,- { projection }: StructureTreeEventContext,+ { queryClient, projection }: StructureTreeEventContext,) {+ if (event.type === "community:category.create") {+ updateStructuralSnapshot(queryClient, {+ type: "upsertCategory",+ serverId: event.serverId,+ category: {+ id: event.category.id,+ name: event.category.name,+ private: event.category.private,+ },+ position: event.category.position,+ })+ } else if (event.type === "community:category.update") {+ updateStructuralSnapshot(queryClient, {+ type: "patchCategory",+ serverId: event.serverId,+ categoryId: event.categoryId,+ changes: {+ ...(event.changes.name !== undefined ? { name: event.changes.name } : {}),+ ...(event.changes.private !== undefined ? { private: event.changes.private } : {}),+ },+ position: event.changes.position,+ })+ } else if (event.type === "community:category.delete") {+ updateStructuralSnapshot(queryClient, {+ type: "removeCategory",+ serverId: event.serverId,+ categoryId: event.categoryId,+ })+ } else {+ updateStructuralSnapshot(queryClient, {+ type: "reorderCategories",+ serverId: event.serverId,+ categoryIds: [...event.categories]+ .sort((left, right) => left.position - right.position)+ .map((category) => category.id),+ })+ }invalidateChannelRefDirectory(projection)invalidateServerDetail(projection, event.serverId)}diff --git a/src/web/src/hooks/community/mutations/channels.test.ts b/src/web/src/hooks/community/mutations/channels.test.tsindex a589cb892..503d9d5a2 100644--- a/src/web/src/hooks/community/mutations/channels.test.ts+++ b/src/web/src/hooks/community/mutations/channels.test.ts@@ -67,6 +67,25 @@ beforeEach(() => {capturedQc = new QueryClient()})+function seedStructuralSnapshot() {+ capturedQc.setQueryData(communityKeys.structuralSnapshot(), {+ schemaVersion: 1,+ accountId: "u1",+ capturedAt: Date.now(),+ serverOrder: ["s1"],+ folders: [],+ servers: [{+ id: "s1",+ name: "Studio",+ discriminator: "0042",+ icon: null,+ categories: [{ id: "cat_1", name: "Channels" }],+ channels: [{ id: "c1", name: "general", type: "text", categoryId: "cat_1" }],+ childRouteHints: [],+ }],+ })+}+describe("useRenameChannel", () => {type CachedChannel = { id: string; name: string; active: boolean; unread: boolean }type CachedCategory = { id: string; name: string; channels: CachedChannel[] }@@ -134,6 +153,7 @@ describe("useRenameChannel", () => {it("reconciles both caches to the PATCH response's normalized name", async () => {seed()+ seedStructuralSnapshot()apiFetchMock.mockResolvedValueOnce({ id: "c1", name: "General-Chat" })const mod = await load()mod.useRenameChannel()@@ -146,6 +166,12 @@ describe("useRenameChannel", () => {)expect(serverChannels().find((channel) => channel.id === "c1")?.name).toBe("General-Chat")expect(directory()[0].channels.find((channel) => channel.id === "c1")?.name).toBe("General-Chat")+ expect(capturedQc.getQueryData<{+ servers: Array<{ channels: Array<{ id: string; name: string }> }>+ }>(communityKeys.structuralSnapshot())?.servers[0]?.channels[0]).toMatchObject({+ id: "c1",+ name: "General-Chat",+ })})it("restores both snapshots on failure without optimistic residue", async () => {@@ -510,4 +536,77 @@ describe("useDeleteCategory — optimistic removal with rollback", () => {await runMutation({ serverId: "s1", categoryId: "cat_2" }).catch(() => {})expect(cats().map((c) => c.id)).toEqual(["cat_1", "cat_2"])})++ it("prunes the persisted category after a committed delete", async () => {+ seed([{ id: "cat_1", name: "General", channels: [] }])+ seedStructuralSnapshot()+ apiFetchMock.mockResolvedValueOnce(undefined)+ const mod = await load()+ mod.useDeleteCategory()++ await runMutation({ serverId: "s1", categoryId: "cat_1" })++ const structural = capturedQc.getQueryData<{+ servers: Array<{ categories: Array<{ id: string }> }>+ }>(communityKeys.structuralSnapshot())+ expect(structural?.servers[0]?.categories).toEqual([])+ })+})++describe("committed category and order projections", () => {+ it("patches the persisted category name after update", async () => {+ seedStructuralSnapshot()+ apiFetchMock.mockResolvedValueOnce(undefined)+ const mod = await load()+ mod.useUpdateCategory()++ await runMutation({ serverId: "s1", categoryId: "cat_1", name: "Renamed" })++ expect(apiFetchMock).toHaveBeenCalledWith(+ "/api/community/servers/s1/categories/cat_1",+ { method: "PATCH", body: JSON.stringify({ name: "Renamed" }) },+ )+ const structural = capturedQc.getQueryData<{+ servers: Array<{ categories: Array<{ name: string }> }>+ }>(communityKeys.structuralSnapshot())+ expect(structural?.servers[0]?.categories[0]?.name).toBe("Renamed")+ })++ it("projects committed category and channel order", async () => {+ seedStructuralSnapshot()+ capturedQc.setQueryData<any>(communityKeys.structuralSnapshot(), (current: any) => ({+ ...current,+ servers: current.servers.map((server: any) => ({+ ...server,+ categories: [+ ...server.categories,+ { id: "cat_2", name: "Later", private: false },+ ],+ channels: [+ ...server.channels,+ { id: "c2", name: "later", type: "forum", categoryId: "cat_2" },+ ],+ })),+ }))+ const mod = await load()++ apiFetchMock.mockResolvedValueOnce(undefined)+ mod.useReorderCategories()+ await runMutation({ serverId: "s1", categoryIds: ["cat_2", "cat_1"] })++ apiFetchMock.mockResolvedValueOnce(undefined)+ mod.useReorderChannels()+ await runMutation({ serverId: "s1", channelIds: ["c2", "c1"] })++ const structural = capturedQc.getQueryData<{+ servers: Array<{+ categories: Array<{ id: string }>+ channels: Array<{ id: string }>+ }>+ }>(communityKeys.structuralSnapshot())+ expect(structural?.servers[0]?.categories.map((category) => category.id))+ .toEqual(["cat_2", "cat_1"])+ expect(structural?.servers[0]?.channels.map((channel) => channel.id))+ .toEqual(["c2", "c1"])+ })})diff --git a/src/web/src/hooks/community/mutations/channels.ts b/src/web/src/hooks/community/mutations/channels.tsindex 2844a0c21..26583a17e 100644--- a/src/web/src/hooks/community/mutations/channels.ts+++ b/src/web/src/hooks/community/mutations/channels.ts@@ -8,6 +8,9 @@ import type { ChannelRefDirectory } from "@/lib/community/channel-ref"import type { ServerDetail } from "@/hooks/community/use-servers"import { UNCATEGORIZED_CATEGORY_ID, type ChannelType } from "@alook/shared"import { getActiveAccountUnreadProjection } from "@/hooks/community/account-unread-projection"+import { updateStructuralSnapshot } from "@/lib/community/structural-snapshot"+import { runCommunityWsProjectionTransaction } from "@/hooks/community/community-ws/projection-transaction"+import { projectChannelScopeEviction } from "@/hooks/community/community-ws/channel-scope-projection"// Prefix marks an optimistic row so every consumer can tell it from a real// `ch_…` id without a separate flag, and guarantees it never collides with one.@@ -132,6 +135,16 @@ export function useCreateChannel() {})),}})+ updateStructuralSnapshot(queryClient, {+ type: "upsertChannel",+ serverId: args.serverId,+ channel: {+ id: data.channel.id,+ name: args.name.trim(),+ type: args.type,+ categoryId: isUncategorizedTarget(args.categoryId) ? null : args.categoryId,+ },+ })},onError: (_err, args, ctx) => {if (ctx?.snapshot) queryClient.setQueryData(communityKeys.server(args.serverId), ctx.snapshot)@@ -237,6 +250,12 @@ export function useRenameChannel() {queryClient.setQueryData<ChannelRefDirectory>(communityKeys.channelRefDirectory(), (prev) =>renameDirectoryChannel(prev, args.serverId, args.channelId, data.name),)+ updateStructuralSnapshot(queryClient, {+ type: "patchChannel",+ serverId: args.serverId,+ channelId: args.channelId,+ changes: { name: data.name },+ })},onError: (_err, args, ctx) => {if (ctx?.serverSnapshot) {@@ -273,6 +292,12 @@ export function useMoveChannel() {})},onSuccess: (_data, args) => {+ updateStructuralSnapshot(queryClient, {+ type: "patchChannel",+ serverId: args.serverId,+ channelId: args.channelId,+ changes: { categoryId: args.categoryId },+ })void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })invalidateChannelRefDirectory(queryClient)},@@ -293,6 +318,14 @@ export function useDeleteChannel() {channelId: args.channelId,})if (args.serverId) {+ runCommunityWsProjectionTransaction(queryClient, (projection) => {+ projectChannelScopeEviction(+ projection,+ queryClient,+ args.serverId,+ args.channelId,+ )+ })void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })}invalidateChannelRefDirectory(queryClient)@@ -361,6 +394,15 @@ export function useCreateCategory() {),}})+ updateStructuralSnapshot(queryClient, {+ type: "upsertCategory",+ serverId: args.serverId,+ category: {+ id: data.category.id,+ name: args.name.trim(),+ private: args.private === true,+ },+ })},onError: (_err, args, ctx) => {if (ctx?.snapshot) queryClient.setQueryData(communityKeys.server(args.serverId), ctx.snapshot)@@ -389,6 +431,14 @@ export function useUpdateCategory() {})},onSuccess: (_data, args) => {+ if (args.name !== undefined) {+ updateStructuralSnapshot(queryClient, {+ type: "patchCategory",+ serverId: args.serverId,+ categoryId: args.categoryId,+ changes: { name: args.name },+ })+ }void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })invalidateChannelRefDirectory(queryClient)},@@ -426,6 +476,13 @@ export function useDeleteCategory() {onError: (_err, args, ctx) => {if (ctx?.snapshot) queryClient.setQueryData(communityKeys.server(args.serverId), ctx.snapshot)},+ onSuccess: (_data, args) => {+ updateStructuralSnapshot(queryClient, {+ type: "removeCategory",+ serverId: args.serverId,+ categoryId: args.categoryId,+ })+ },onSettled: (_data, _err, args) => {void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })invalidateChannelRefDirectory(queryClient)@@ -445,6 +502,11 @@ export function useReorderCategories() {})},onSuccess: (_data, args) => {+ updateStructuralSnapshot(queryClient, {+ type: "reorderCategories",+ serverId: args.serverId,+ categoryIds: args.categoryIds,+ })void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })invalidateChannelRefDirectory(queryClient)},@@ -463,6 +525,11 @@ export function useReorderChannels() {})},onSuccess: (_data, args) => {+ updateStructuralSnapshot(queryClient, {+ type: "reorderChannels",+ serverId: args.serverId,+ channelIds: args.channelIds,+ })void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })invalidateChannelRefDirectory(queryClient)},diff --git a/src/web/src/hooks/community/mutations/server-rail.test.ts b/src/web/src/hooks/community/mutations/server-rail.test.tsindex baad7b5c5..d6f060374 100644--- a/src/web/src/hooks/community/mutations/server-rail.test.ts+++ b/src/web/src/hooks/community/mutations/server-rail.test.ts@@ -97,10 +97,33 @@ describe("useServerRailCommit", () => {it("reconciles temporary ids and invalidates both caches on settle", async () => {const options = useServerRailCommit() as anyawait options.onMutate(args)- options.onSuccess({ createdFolderIds: { temp_1: "folder_real" } })+ options.onSuccess({ createdFolderIds: { temp_1: "folder_real" } }, args)expect(queryClient.getQueryData<any>(communityKeys.folders()).folders[1].id).toBe("folder_real")const invalidate = vi.spyOn(queryClient, "invalidateQueries").mockResolvedValue(undefined as never)await options.onSettled()expect(invalidate).toHaveBeenCalledTimes(2)})++ it("drops empty folders from the persisted rail projection", () => {+ queryClient.setQueryData(communityKeys.structuralSnapshot(), {+ schemaVersion: 1,+ accountId: "u1",+ capturedAt: Date.now(),+ serverOrder: ["a", "b", "c"],+ folders: [{ id: "one", name: "One", serverIds: ["c"] }],+ servers: [],+ })+ const options = useServerRailCommit() as any+ const emptyAfter = {+ ...after,+ folderOrder: ["one", "empty"],+ folders: { one: ["c"], empty: [] },+ }+ options.onSuccess({ createdFolderIds: {} }, { ...args, after: emptyAfter })++ expect(queryClient.getQueryData<any>(communityKeys.structuralSnapshot())).toMatchObject({+ serverOrder: ["b", "a", "c"],+ folders: [{ id: "one", name: "One", serverIds: ["c"] }],+ })+ })})diff --git a/src/web/src/hooks/community/mutations/server-rail.ts b/src/web/src/hooks/community/mutations/server-rail.tsindex 0ea8575b2..ae9f27930 100644--- a/src/web/src/hooks/community/mutations/server-rail.ts+++ b/src/web/src/hooks/community/mutations/server-rail.ts@@ -8,6 +8,7 @@ import type { FoldersResponse } from "@/hooks/community/use-folders"import type { ServersResponse } from "@/hooks/community/use-servers"import type { FolderServer } from "@/lib/community/models/navigation"import type { RailState } from "@/lib/community/server-rail-model"+import { updateStructuralSnapshot } from "@/lib/community/structural-snapshot"export type ServerRailCommitArgs = {before: RailState@@ -107,10 +108,25 @@ export function useServerRailCommit() {queryClient.setQueryData(serversKey, context.servers)queryClient.setQueryData(foldersKey, context.folders)},- onSuccess: (response) => {+ onSuccess: (response, args) => {queryClient.setQueryData<FoldersResponse | undefined>(foldersKey, (folders) =>reconcileCreatedFolderIds(folders, response.createdFolderIds),)+ const folderNameById = new Map(+ (queryClient.getQueryData<FoldersResponse>(foldersKey)?.folders ?? [])+ .map((folder) => [folder.id, folder.name]),+ )+ updateStructuralSnapshot(queryClient, {+ type: "replaceRail",+ serverOrder: args.after.serverOrder,+ folders: args.after.folderOrder.flatMap((clientId) => {+ const id = response.createdFolderIds[clientId] ?? clientId+ const serverIds = args.after.folders[clientId] ?? []+ return serverIds.length > 0+ ? [{ id, name: folderNameById.get(id) ?? "Group", serverIds }]+ : []+ }),+ })},onSettled: async () => {await Promise.all([diff --git a/src/web/src/hooks/community/mutations/servers.test.ts b/src/web/src/hooks/community/mutations/servers.test.tsindex dc0491ddc..c1d3b7b9f 100644--- a/src/web/src/hooks/community/mutations/servers.test.ts+++ b/src/web/src/hooks/community/mutations/servers.test.ts@@ -64,6 +64,25 @@ beforeEach(() => {capturedQc = new QueryClient()})+function seedStructuralSnapshot(serverId = "srv_1") {+ capturedQc.setQueryData(communityKeys.structuralSnapshot(), {+ schemaVersion: 1,+ accountId: "u1",+ capturedAt: Date.now(),+ serverOrder: [serverId],+ folders: [],+ servers: [{+ id: serverId,+ name: "Server",+ discriminator: "0001",+ icon: null,+ categories: [],+ channels: [],+ childRouteHints: [],+ }],+ })+}+describe("useLeaveServer — optimistic + rollback", () => {it("fences every unread source in the departing scope and rolls back atomically", async () => {const mod = await load()@@ -104,6 +123,7 @@ describe("useLeaveServer — optimistic + rollback", () => {"%s success clears the server subtree, stream, and current private route",async (operation) => {apiFetchMock.mockResolvedValueOnce(undefined)+ seedStructuralSnapshot()const mod = await load()const { useCommunityStore } = await import("@/stores/community")const { useMessageStreamStore } = await import("@/stores/community/message-stream")@@ -144,12 +164,17 @@ describe("useLeaveServer — optimistic + rollback", () => {expect(capturedQc.getQueryState(communityKeys.server("srv_1"))).toBeUndefined()expect([...useMessageStreamStore.getState().entries.values()].some((entry) => entry.scope.serverId === "srv_1")).toBe(false)+ expect(capturedQc.getQueryData<{+ serverOrder: string[]+ }>(communityKeys.structuralSnapshot())?.serverOrder).toEqual([])},)})describe("useUpdateServer — rollback on both caches", () => {it("restores server-detail + servers-list on failure", async () => {+ seedStructuralSnapshot()+ const structuralBefore = capturedQc.getQueryData(communityKeys.structuralSnapshot())capturedQc.setQueryData(communityKeys.server("srv_1"), {id: "srv_1",name: "old",@@ -181,6 +206,7 @@ describe("useUpdateServer — rollback on both caches", () => {communityKeys.servers(),)expect(list?.servers[0]).toMatchObject({ name: "old", description: "d" })+ expect(capturedQc.getQueryData(communityKeys.structuralSnapshot())).toBe(structuralBefore)})it("keeps the canonical list metadata aligned with an optimistic detail update", async () => {diff --git a/src/web/src/hooks/community/mutations/servers.ts b/src/web/src/hooks/community/mutations/servers.tsindex 423211801..a9e9d18e7 100644--- a/src/web/src/hooks/community/mutations/servers.ts+++ b/src/web/src/hooks/community/mutations/servers.ts@@ -5,12 +5,12 @@ import { apiFetch, readUploadError } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import { avatarInitial } from "@/lib/community/avatar"import type { ServersResponse, ServerDetail } from "@/hooks/community/use-servers"-import { useCommunityStore } from "@/stores/community"-import { useMessageStreamStore } from "@/stores/community/message-stream"import {getActiveAccountUnreadProjection,type AccountUnreadScopeToken,} from "@/hooks/community/account-unread-projection"+import { updateStructuralSnapshot } from "@/lib/community/structural-snapshot"+import { evictServerChannelScopes } from "@/hooks/community/community-ws/scope-eviction"/*** Server-scoped mutations. `create`/`join` invalidate the rail; `leave`/`delete`@@ -75,15 +75,6 @@ export function useJoinServer() {export type LeaveServerArgs = { serverId: string }-function clearDepartedServer(serverId: string) {- useMessageStreamStore.getState().removeServer(serverId)- const store = useCommunityStore.getState()- if (store.currentServerId !== serverId) return- store.setCurrentChannelMeta(null)- store.setCurrentChannelId(null)- store.setCurrentServerId(null)-}-export function useLeaveServer() {const queryClient = useQueryClient()const unreadProjection = getActiveAccountUnreadProjection(queryClient)@@ -112,12 +103,11 @@ export function useLeaveServer() {},onSuccess: (_data, args, context) => {unreadProjection.commitScopeRetirement(context.token)- queryClient.removeQueries({ queryKey: communityKeys.server(args.serverId) })+ evictServerChannelScopes(queryClient, args.serverId)void queryClient.invalidateQueries({queryKey: communityKeys.channelRefDirectory(),exact: true,})- clearDepartedServer(args.serverId)},})}@@ -150,12 +140,11 @@ export function useDeleteServer() {},onSuccess: (_data, args, context) => {unreadProjection.commitScopeRetirement(context.token)- queryClient.removeQueries({ queryKey: communityKeys.server(args.serverId) })+ evictServerChannelScopes(queryClient, args.serverId)void queryClient.invalidateQueries({queryKey: communityKeys.channelRefDirectory(),exact: true,})- clearDepartedServer(args.serverId)},})}@@ -217,6 +206,13 @@ export function useUpdateServer() {if (ctx?.serverSnap) queryClient.setQueryData(communityKeys.server(args.serverId), ctx.serverSnap)if (ctx?.listSnap) queryClient.setQueryData(communityKeys.servers(), ctx.listSnap)},+ onSuccess: (_data, args) => {+ updateStructuralSnapshot(queryClient, {+ type: "patchServer",+ serverId: args.serverId,+ changes: { name: args.name },+ })+ },onSettled: () => {void queryClient.invalidateQueries({queryKey: communityKeys.channelRefDirectory(),@@ -263,6 +259,11 @@ export function useUploadServerIcon() {}: prev,)+ updateStructuralSnapshot(queryClient, {+ type: "patchServer",+ serverId: args.serverId,+ changes: { icon: bustUrl },+ })},})}diff --git a/src/web/src/hooks/community/use-channel-ref-directory.dom.test.ts b/src/web/src/hooks/community/use-channel-ref-directory.dom.test.tsindex f7da4d232..be2a8c4b2 100644--- a/src/web/src/hooks/community/use-channel-ref-directory.dom.test.ts+++ b/src/web/src/hooks/community/use-channel-ref-directory.dom.test.ts@@ -1,6 +1,6 @@import { createElement, type PropsWithChildren } from "react"import { QueryClientProvider } from "@tanstack/react-query"-import { beforeEach, describe, expect, it, vi } from "vitest"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { act, renderHook, waitFor } from "@/test/react-dom-harness"const apiFetch = vi.fn()@@ -11,6 +11,7 @@ vi.mock("@/lib/api/client", () => ({import { createQueryClient } from "@/lib/query-client"import { communityKeys } from "@/lib/query-keys"+import { useCommunityWsStore } from "@/stores/community/ws"import {channelRefDirectoryQueryFn,useChannelRefDirectory,@@ -60,7 +61,81 @@ describe("channelRefDirectoryQueryFn", () => {})describe("useChannelRefDirectory", () => {- beforeEach(() => vi.clearAllMocks())+ beforeEach(() => {+ vi.clearAllMocks()+ useCommunityWsStore.getState().reset()+ })++ afterEach(() => {+ act(() => useCommunityWsStore.getState().reset())+ })++ it("keeps a rail-only structural snapshot pending until the live directory resolves", () => {+ useCommunityWsStore.getState().activateProfileAccount("viewer_1")+ apiFetch.mockReturnValue(new Promise(() => {}))+ const client = createQueryClient()+ client.setQueryData(communityKeys.structuralSnapshot(), {+ schemaVersion: 1,+ accountId: "viewer_1",+ capturedAt: Date.now(),+ serverOrder: ["server_1"],+ folders: [],+ servers: [{+ id: "server_1",+ name: "Studio",+ discriminator: "0042",+ icon: null,+ categories: [],+ channels: [],+ childRouteHints: [],+ }],+ })++ const rendered = renderDirectory(client, true)++ expect(rendered.result.current).toMatchObject({+ directory: [],+ isResolved: false,+ isLoading: true,+ isError: false,+ })+ })++ it("uses a captured structural channel directory while the live query is disabled", () => {+ useCommunityWsStore.getState().activateProfileAccount("viewer_1")+ const client = createQueryClient()+ client.setQueryData(communityKeys.structuralSnapshot(), {+ schemaVersion: 1,+ accountId: "viewer_1",+ capturedAt: Date.now(),+ serverOrder: ["server_1"],+ folders: [],+ servers: [{+ id: "server_1",+ name: "Studio",+ discriminator: "0042",+ icon: null,+ categories: [],+ channels: [{ id: "channel_1", name: "general", type: "text", categoryId: null }],+ childRouteHints: [],+ }],+ })++ const rendered = renderDirectory(client, false)++ expect(apiFetch).not.toHaveBeenCalled()+ expect(rendered.result.current).toMatchObject({+ directory: [{+ id: "server_1",+ name: "Studio",+ discriminator: "0042",+ channels: [{ id: "channel_1", name: "general" }],+ }],+ isResolved: true,+ isLoading: false,+ isError: false,+ })+ })it("stays dormant until enabled, then owns pending and resolved items", async () => {const request = deferred<{ directory: Array<{diff --git a/src/web/src/hooks/community/use-channel-ref-directory.ts b/src/web/src/hooks/community/use-channel-ref-directory.tsindex 8f6b589e1..025301021 100644--- a/src/web/src/hooks/community/use-channel-ref-directory.ts+++ b/src/web/src/hooks/community/use-channel-ref-directory.ts@@ -4,6 +4,9 @@ import { useQuery } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import type { ChannelRefDirectory } from "@/lib/community/channel-ref"+import { structuralSnapshotDirectory } from "@/lib/community/structural-snapshot"+import { useStructuralSnapshot } from "./use-structural-snapshot"+import { useCommunityWsStore } from "@/stores/community/ws"const EMPTY_DIRECTORY = Object.freeze([]) as unknown as ChannelRefDirectory@@ -21,6 +24,8 @@ export function useChannelRefDirectory(enabled = true): {isError: booleanrefetch: ReturnType<typeof useQuery<ChannelRefDirectory>>["refetch"]} {+ const accountId = useCommunityWsStore((state) => state.profileViewerId)+ const structuralSnapshot = useStructuralSnapshot(accountId)const query = useQuery<ChannelRefDirectory>({queryKey: communityKeys.channelRefDirectory(),queryFn: channelRefDirectoryQueryFn,@@ -29,9 +34,16 @@ export function useChannelRefDirectory(enabled = true): {refetchOnReconnect: true,retry: false,})- const isResolved = query.data !== undefined+ const structuralDirectory = structuralSnapshotDirectory(structuralSnapshot)+ const directory = query.data ?? structuralDirectory+ // A server-list receipt creates rail identities before any server detail+ // tree has been loaded. An empty directory from that partial hint is not an+ // authoritative "no channels" result and must not suppress the live+ // directory's pending/error state.+ const hasStructuralChannels = structuralDirectory.some((server) => server.channels.length > 0)+ const isResolved = query.data !== undefined || hasStructuralChannelsreturn {- directory: query.data ?? EMPTY_DIRECTORY,+ directory: isResolved ? directory : EMPTY_DIRECTORY,isResolved,isLoading: enabled && !isResolved && query.isFetching,isError: enabled && !isResolved && query.isError,diff --git a/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts b/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.tsindex 23a1a8c6b..f6b3f1508 100644--- a/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts+++ b/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts@@ -3,6 +3,7 @@ import { QueryClient } from "@tanstack/react-query"import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { act, render } from "@/test/react-dom-harness"import { useCommunityStore } from "@/stores/community"+import { communityKeys } from "@/lib/query-keys"const mocks = vi.hoisted(() => ({subscribe: vi.fn(),@@ -53,7 +54,10 @@ import { buildChannelRouteModel, useChannelRouteModel } from "./use-channel-routfunction Harness({ channelId = "post-1" }: { channelId?: string }) {const result = useChannelRouteModel("server-1", "server-1", channelId, "viewer-1")- return React.createElement("span", { "data-lifecycle": result.routeLifecycle })+ return React.createElement("span", {+ "data-lifecycle": result.routeLifecycle,+ "data-skeleton-subtype": result.skeletonSubtype,+ })}function lifecycle(renderer: ReturnType<typeof render>) {@@ -108,6 +112,54 @@ describe("useChannelRouteModel subscription ownership", () => {act(() => renderer!.unmount())})+ it("uses persisted structure only to choose the pending skeleton subtype", () => {+ mocks.server = undefined+ queryClient.setQueryData(communityKeys.structuralSnapshot(), {+ schemaVersion: 1,+ accountId: "viewer-1",+ capturedAt: Date.now(),+ serverOrder: ["server-1"],+ folders: [],+ servers: [{+ id: "server-1",+ name: "Server",+ discriminator: "0001",+ icon: null,+ categories: [],+ channels: [{ id: "forum-1", name: "Forum", type: "forum", categoryId: null }],+ childRouteHints: [],+ }],+ })++ let renderer!: ReturnType<typeof render>+ act(() => {+ renderer = render(React.createElement(Harness, { channelId: "forum-1" }))+ })++ const node = renderer.container.querySelector("span")+ expect(node?.getAttribute("data-lifecycle")).toBe("pending")+ expect(node?.getAttribute("data-skeleton-subtype")).toBe("forum")+ expect(useCommunityStore.getState().currentChannelMeta).toBeNull()+ act(() => renderer.unmount())+ })++ it("reports the live top-level text subtype after access is ready", () => {+ mocks.server = {+ id: "server-1",+ categories: [{+ id: "cat-1",+ channels: [{ id: "text-1", name: "Chat", type: "text" }],+ }],+ }++ const renderer = render(React.createElement(Harness, { channelId: "text-1" }))++ const node = renderer.container.querySelector("span")+ expect(node?.getAttribute("data-lifecycle")).toBe("ready")+ expect(node?.getAttribute("data-skeleton-subtype")).toBe("text")+ act(() => renderer.unmount())+ })+it("does not hydrate a verified child with the previous child's store metadata", () => {const model = buildChannelRouteModel({diff --git a/src/web/src/hooks/community/use-channel-route-model.ts b/src/web/src/hooks/community/use-channel-route-model.tsindex 911ea1642..fe47c6089 100644--- a/src/web/src/hooks/community/use-channel-route-model.ts+++ b/src/web/src/hooks/community/use-channel-route-model.ts@@ -21,6 +21,8 @@ import {removeForumSidebarThreadExact,removeForumSidebarUnreadChild,} from "./use-forum-sidebar-threads"+import { useStructuralSnapshot } from "./use-structural-snapshot"+import { updateStructuralSnapshot } from "@/lib/community/structural-snapshot"type Server = ReturnType<typeof useServer>["server"]type ChannelMeta = ReturnType<typeof useCurrentChannelMeta>@@ -67,6 +69,10 @@ export function useChannelRouteModel(const router = useRouter()const queryClient = useQueryClient()const { server } = useServer(serverId)+ const structuralSnapshot = useStructuralSnapshot(accountId, queryClient)+ const structuralServer = structuralSnapshot?.servers.find((candidate) => candidate.id === serverId)+ const structuralTopLevel = structuralServer?.channels.find((candidate) => candidate.id === channelId)+ const structuralChild = structuralServer?.childRouteHints.find((candidate) => candidate.id === channelId)const currentChannelMeta = useCurrentChannelMeta()const topLevelChannel = server?.categories?.flatMap((category) => category.channels)@@ -115,6 +121,14 @@ export function useChannelRouteModel(: model.routeHydrated? "ready" as const: "pending" as const+ const skeletonSubtype = routeLifecycle === "ready"+ ? model.isChild+ ? "thread" as const+ : model.isForum+ ? "forum" as const+ : "text" as const+ : structuralTopLevel?.type+ ?? (structuralChild ? "thread" as const : "unknown" as const)useEffect(() => {useCommunityStore.getState().setCurrentChannelId(channelId)return () => { useCommunityStore.getState().setCurrentChannelId(null) }@@ -133,6 +147,11 @@ export function useChannelRouteModel(useCommunityStore.getState().setCurrentChannelMeta(null)removeForumSidebarUnreadChild(queryClient, serverId, channelId)removeForumSidebarThreadExact(queryClient, serverId, channelId)+ updateStructuralSnapshot(queryClient, {+ type: "removeChildHint",+ serverId,+ channelId,+ })const lastChannel = getLastChannel(serverId)if (lastChannel === channelId) {clearLastChannel(serverId)@@ -151,5 +170,12 @@ export function useChannelRouteModel(toastApiError(metaQuery.error, "Failed to load thread")}}, [accountId, channelId, isChild, metaQuery.data, metaQuery.error, metaQuery.isVerified, queryClient, router, serverId, serverParam])- return { ...model, routeLifecycle, metadataError, retryingMetadata, retryMetadata }+ return {+ ...model,+ routeLifecycle,+ skeletonSubtype,+ metadataError,+ retryingMetadata,+ retryMetadata,+ }}diff --git a/src/web/src/hooks/community/use-folders.test.ts b/src/web/src/hooks/community/use-folders.test.tsindex 72c57cf2d..2674dac2c 100644--- a/src/web/src/hooks/community/use-folders.test.ts+++ b/src/web/src/hooks/community/use-folders.test.ts@@ -1,6 +1,7 @@import { describe, it, expect, vi, beforeEach } from "vitest"import { QueryClient } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"+import { useCommunityWsStore } from "@/stores/community/ws"const apiFetchMock = vi.fn()vi.mock("@/lib/api/client", () => ({@@ -9,6 +10,7 @@ vi.mock("@/lib/api/client", () => ({beforeEach(() => {apiFetchMock.mockReset()+ useCommunityWsStore.getState().reset()})describe("useFolders / foldersQueryFn", () => {@@ -38,4 +40,17 @@ describe("useFolders / foldersQueryFn", () => {await qc.fetchQuery({ queryKey: key, queryFn: foldersQueryFn })expect(qc.getQueryData(key)).toEqual({ folders: [] })})++ it("rejects a folder response captured before the access epoch changes", async () => {+ useCommunityWsStore.getState().activateProfileAccount("viewer_1")+ let release!: (value: { folders: [] }) => void+ apiFetchMock.mockReturnValueOnce(new Promise((resolve) => { release = resolve }))+ const { foldersQueryFn } = await import("./use-folders")++ const pending = foldersQueryFn()+ useCommunityWsStore.getState().revokeServerAccess("server_1")+ release({ folders: [] })++ await expect(pending).rejects.toMatchObject({ name: "AbortError" })+ })})diff --git a/src/web/src/hooks/community/use-folders.ts b/src/web/src/hooks/community/use-folders.tsindex a1719237f..0e3f73569 100644--- a/src/web/src/hooks/community/use-folders.ts+++ b/src/web/src/hooks/community/use-folders.ts@@ -5,6 +5,7 @@ import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import { avatarInitial } from "@/lib/community/avatar"import type { CommunityFolder } from "@/lib/community/models/navigation"+import { useCommunityWsStore } from "@/stores/community/ws"/*** Fetches the user's server-folder groupings for the rail.@@ -26,7 +27,19 @@ export type FoldersResponse = { folders: CommunityFolder[] }const EMPTY_FOLDERS: readonly CommunityFolder[] = Object.freeze([])export const foldersQueryFn = async (): Promise<FoldersResponse> => {+ const before = useCommunityWsStore.getState()+ const token = {+ viewerId: before.profileViewerId,+ accountEpoch: before.profileAccountEpoch,+ accessEpoch: before.accessEpoch,+ }const data = await apiFetch<{ folders: RawFolder[] }>("/api/community/users/me/server-folders")+ const after = useCommunityWsStore.getState()+ if (+ after.profileViewerId !== token.viewerId+ || after.profileAccountEpoch !== token.accountEpoch+ || after.accessEpoch !== token.accessEpoch+ ) throw new DOMException("Stale structural query", "AbortError")const folders: CommunityFolder[] = data.folders.map((f) => ({id: f.id,name: f.name,diff --git a/src/web/src/hooks/community/use-servers.test.ts b/src/web/src/hooks/community/use-servers.test.tsindex 369a2e8ae..9684a94f3 100644--- a/src/web/src/hooks/community/use-servers.test.ts+++ b/src/web/src/hooks/community/use-servers.test.ts@@ -1,6 +1,8 @@import { describe, it, expect, vi, beforeEach } from "vitest"import { QueryClient } from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"+import { ApiError } from "@/lib/errors"+import { useCommunityWsStore } from "@/stores/community/ws"vi.mock("react", async (importOriginal) => {const actual = await importOriginal<typeof import("react")>()@@ -24,6 +26,7 @@ type CapturedQueryConfig = {let capturedQueryConfig: CapturedQueryConfig | null = nulllet capturedHookQueryClient: QueryClientlet capturedHookQueryData: unknown+let capturedHookQueryError: unknownvi.mock("@tanstack/react-query", async () => {const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query")return {@@ -31,7 +34,7 @@ vi.mock("@tanstack/react-query", async () => {useQueryClient: () => capturedHookQueryClient,useQuery: (config: CapturedQueryConfig) => {capturedQueryConfig = config- return { data: capturedHookQueryData }+ return { data: capturedHookQueryData, error: capturedHookQueryError }},}})@@ -41,6 +44,8 @@ beforeEach(() => {capturedQueryConfig = nullcapturedHookQueryClient = new QueryClient()capturedHookQueryData = undefined+ capturedHookQueryError = null+ useCommunityWsStore.getState().reset()})describe("useServers / serversQueryFn", () => {@@ -135,6 +140,22 @@ describe("useServers / serversQueryFn", () => {expect(projection.inspectForTests().pendingSnapshots).toBe(0)})+ it("rejects a server-list response captured for an earlier account epoch", async () => {+ useCommunityWsStore.getState().activateProfileAccount("u1")+ let release!: (value: { servers: [] }) => void+ apiFetchMock.mockReturnValueOnce(new Promise((resolve) => { release = resolve }))+ const { serversProjectedQueryFn } = await import("./use-servers")+ const { AccountUnreadProjection } = await import("./account-unread-projection")+ const projection = new AccountUnreadProjection("u1")++ const pending = serversProjectedQueryFn(projection)()+ useCommunityWsStore.getState().activateProfileAccount("u2")+ release({ servers: [] })++ await expect(pending).rejects.toMatchObject({ name: "AbortError" })+ expect(projection.inspectForTests().pendingSnapshots).toBe(0)+ })+it("correlates cold rail unread sources with their attention facets", async () => {apiFetchMock.mockResolvedValueOnce({ servers: [{id: "s1",@@ -248,6 +269,14 @@ describe("useServers / serversQueryFn", () => {})describe("useServer / serverQueryFn", () => {+ it.each([403, 404])("hides retained server detail after a definitive %s", async (status) => {+ capturedHookQueryData = { id: "srv_1", categories: [] }+ capturedHookQueryError = new ApiError("denied", status)+ const { useServer } = await import("./use-servers")++ expect(useServer("srv_1").server).toBeNull()+ })+it("keeps the null-server query disabled without issuing API requests", async () => {const { useServer } = await import("./use-servers")@@ -340,6 +369,85 @@ describe("useServer / serverQueryFn", () => {expect(projection.inspectForTests().pendingSnapshots).toBe(0)})+ it.each([+ ["offline", new Error("offline")],+ ["5xx", new ApiError("unavailable", 503)],+ ])("keeps the structural hint on a transient %s failure", async (_label, error) => {+ apiFetchMock.mockRejectedValue(error)+ const qc = new QueryClient()+ qc.setQueryData(communityKeys.servers(), { servers: [{+ id: "srv_1",+ name: "Alook",+ discriminator: "0001",+ description: "",+ icon: null,+ ownerId: "u_1",+ }] })+ const hint = {+ schemaVersion: 1 as const,+ accountId: "u_1",+ capturedAt: Date.now(),+ serverOrder: ["srv_1"],+ folders: [],+ servers: [{+ id: "srv_1",+ name: "Alook",+ discriminator: "0001",+ icon: null,+ categories: [],+ channels: [],+ childRouteHints: [],+ }],+ }+ qc.setQueryData(communityKeys.structuralSnapshot(), hint)+ const { serverProjectedQueryFn } = await import("./use-servers")++ await expect(serverProjectedQueryFn(qc, "srv_1")()).rejects.toBe(error)++ expect(qc.getQueryData(communityKeys.structuralSnapshot())).toEqual(hint)+ })++ it.each([403, 404])("evicts live and persisted server state on definitive %s", async (status) => {+ apiFetchMock.mockRejectedValue(new ApiError("denied", status))+ const qc = new QueryClient()+ qc.setQueryData(communityKeys.servers(), { servers: [{+ id: "srv_1",+ name: "Alook",+ discriminator: "0001",+ description: "",+ icon: null,+ ownerId: "u_1",+ }] })+ qc.setQueryData(communityKeys.server("srv_1"), {+ id: "srv_1",+ name: "Alook",+ categories: [],+ })+ qc.setQueryData(communityKeys.structuralSnapshot(), {+ schemaVersion: 1,+ accountId: "u_1",+ capturedAt: Date.now(),+ serverOrder: ["srv_1"],+ folders: [],+ servers: [{+ id: "srv_1",+ name: "Alook",+ discriminator: "0001",+ icon: null,+ categories: [],+ channels: [],+ childRouteHints: [],+ }],+ })+ const { serverProjectedQueryFn } = await import("./use-servers")++ await expect(serverProjectedQueryFn(qc, "srv_1")()).rejects.toMatchObject({ status })++ expect(qc.getQueryState(communityKeys.server("srv_1"))).toBeUndefined()+ expect(qc.getQueryData<{ servers: unknown[] }>(communityKeys.servers())?.servers).toEqual([])+ expect(qc.getQueryData<{ servers: unknown[] }>(communityKeys.structuralSnapshot())?.servers).toEqual([])+ })+it("merges stale server-detail positives before rejecting the cache write", async () => {apiFetchMock.mockImplementation(async (url: string) => {if (url.endsWith("/categories")) return { categories: [] }diff --git a/src/web/src/hooks/community/use-servers.ts b/src/web/src/hooks/community/use-servers.tsindex f7988f334..8d128909f 100644--- a/src/web/src/hooks/community/use-servers.ts+++ b/src/web/src/hooks/community/use-servers.ts@@ -21,6 +21,29 @@ import {} from "./account-unread-projection"import { useInboxProjectionTarget } from "./use-inbox-auto-collapse"import { reservedUnreadExclusion } from "./unread-presentation"+import { useCommunityWsStore } from "@/stores/community/ws"+import { ApiError } from "@/lib/errors"+import { evictServerChannelScopes } from "./community-ws/scope-eviction"++function captureStructuralQueryToken() {+ const state = useCommunityWsStore.getState()+ return {+ viewerId: state.profileViewerId,+ accountEpoch: state.profileAccountEpoch,+ accessEpoch: state.accessEpoch,+ }+}++function assertStructuralQueryTokenCurrent(+ token: ReturnType<typeof captureStructuralQueryToken>,+) {+ const state = useCommunityWsStore.getState()+ if (+ state.profileViewerId !== token.viewerId+ || state.profileAccountEpoch !== token.accountEpoch+ || state.accessEpoch !== token.accessEpoch+ ) throw new DOMException("Stale structural query", "AbortError")+}/*** Fetches the sidebar list of servers the current user is in.@@ -100,9 +123,11 @@ function serverListUnreadSources(data: ServersResponse): AccountUnreadSource[] {export const serversProjectedQueryFn = (projection: AccountUnreadProjection,) => async (context?: QueryFunctionContext) => {+ const structuralToken = captureStructuralQueryToken()const token = projection.beginSnapshot("servers", "channels")try {const data = await serversQueryFn(context)+ assertStructuralQueryTokenCurrent(structuralToken)projection.absorbSnapshot(token, serverListUnreadSources(data), {confirmedAccessScopes: data.servers.map((server) => ({kind: "server" as const,@@ -371,6 +396,7 @@ export const serverProjectedQueryFn = (serverId: string,signal?: AbortSignal,) => async () => {+ const structuralToken = captureStructuralQueryToken()const projection = getActiveAccountUnreadProjection(queryClient)const family = `server-detail:${serverId}` as constconst token = projection.beginSnapshot(family, "channels")@@ -381,6 +407,7 @@ export const serverProjectedQueryFn = (unreadData = response},})()+ assertStructuralQueryTokenCurrent(structuralToken)if (!unreadData) throw new Error("server unread response missing")const confirmedAccessScopes: AccountUnreadScope[] = [{ kind: "server", serverId },@@ -405,6 +432,9 @@ export const serverProjectedQueryFn = (} else {projection.cancelSnapshot(token)}+ if (error instanceof ApiError && (error.status === 403 || error.status === 404)) {+ evictServerChannelScopes(queryClient, serverId)+ }throw error}}@@ -522,6 +552,9 @@ export function useServer(}, [query.data, unreadExclusion, serverId, unreadProjection, unreadVersion])return {...query,- server: projectedServer,+ server: query.error instanceof ApiError+ && (query.error.status === 403 || query.error.status === 404)+ ? null+ : projectedServer,}}diff --git a/src/web/src/hooks/community/use-structural-snapshot.test.ts b/src/web/src/hooks/community/use-structural-snapshot.test.tsnew file mode 100644index 000000000..b05ad2067--- /dev/null+++ b/src/web/src/hooks/community/use-structural-snapshot.test.ts@@ -0,0 +1,344 @@+import { afterEach, beforeEach, describe, expect, it } from "vitest"+import { QueryClient } from "@tanstack/react-query"+import { communityKeys } from "@/lib/query-keys"+import type { ServerDetail, ServersResponse } from "./use-servers"+import type { FoldersResponse } from "./use-folders"+import { useCommunityWsStore } from "@/stores/community/ws"+import {+ installStructuralSnapshotProjection,+ structuralHintServer,+} from "./use-structural-snapshot"++function servers(name = "Alpha"): ServersResponse {+ return {+ servers: [{+ id: "server-1",+ name,+ discriminator: "0001",+ icon: null,+ initial: "A",+ active: false,+ unread: true,+ mentions: 4,+ ownerId: "owner-1",+ isOwner: true,+ }],+ }+}++describe("installStructuralSnapshotProjection", () => {+ let queryClient: QueryClient+ let dispose: () => void++ beforeEach(() => {+ useCommunityWsStore.getState().reset()+ useCommunityWsStore.getState().activateProfileAccount("account-a")+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ dispose = installStructuralSnapshotProjection(queryClient, "account-a")+ })++ afterEach(() => {+ dispose()+ queryClient.clear()+ useCommunityWsStore.getState().reset()+ })++ it("projects authoritative server, folder, tree, and child query success", async () => {+ await queryClient.fetchQuery({+ queryKey: communityKeys.servers(),+ queryFn: () => Promise.resolve(servers()),+ })+ const folders: FoldersResponse = {+ folders: [{+ id: "folder-1",+ name: "Work",+ position: 0,+ servers: [{ id: "server-1", name: "Alpha", initial: "A", icon: null }],+ }],+ }+ await queryClient.fetchQuery({+ queryKey: communityKeys.folders(),+ queryFn: () => Promise.resolve(folders),+ })+ const detail = {+ id: "server-1",+ name: "Alpha",+ discriminator: "0001",+ description: "not persisted",+ icon: null,+ ownerId: "owner-1",+ categories: [{+ id: "category-1",+ name: "General",+ private: 1,+ creatorId: "creator-1",+ channels: [{+ id: "channel-1",+ name: "chat",+ type: "text",+ active: false,+ unread: true,+ creatorId: "creator-1",+ }],+ }],+ } satisfies ServerDetail+ await queryClient.fetchQuery({+ queryKey: communityKeys.server("server-1"),+ queryFn: () => Promise.resolve(detail),+ })+ await queryClient.fetchQuery({+ queryKey: communityKeys.channelMeta("server-1", "child-1"),+ queryFn: () => Promise.resolve({+ id: "child-1",+ serverId: "server-1",+ name: "Thread",+ type: "thread",+ parentChannelId: "channel-1",+ parentMessageId: "message-1",+ creatorId: "creator-1",+ archived: false,+ lastMessageAt: null,+ createdAt: "2026-09-08T00:00:00.000Z",+ verifiedEpoch: 0,+ }),+ })++ expect(queryClient.getQueryData(communityKeys.structuralSnapshot())).toMatchObject({+ accountId: "account-a",+ serverOrder: ["server-1"],+ folders: [{ id: "folder-1", name: "Work", serverIds: ["server-1"] }],+ servers: [{+ id: "server-1",+ categories: [{ id: "category-1", name: "General", private: true }],+ channels: [{ id: "channel-1", name: "chat", type: "text", categoryId: "category-1" }],+ childRouteHints: [{+ id: "child-1",+ name: "Thread",+ type: "thread",+ parentChannelId: "channel-1",+ parentMessageId: "message-1",+ }],+ }],+ })+ })++ it("replays cached folder, tree, and child successes when the server list arrives last", async () => {+ await queryClient.fetchQuery({+ queryKey: communityKeys.folders(),+ queryFn: () => Promise.resolve({+ folders: [{+ id: "folder-1",+ name: "Work",+ position: 0,+ servers: [{ id: "server-1", name: "Alpha", initial: "A", icon: null }],+ }],+ } satisfies FoldersResponse),+ })+ await queryClient.fetchQuery({+ queryKey: communityKeys.server("server-1"),+ queryFn: () => Promise.resolve({+ id: "server-1",+ name: "Alpha",+ discriminator: "0001",+ description: "private live description",+ icon: null,+ ownerId: "owner-1",+ categories: [{+ id: "category-1",+ name: "General",+ private: 0,+ channels: [{+ id: "channel-1",+ name: "chat",+ type: "text",+ active: false,+ unread: false,+ }],+ }],+ } satisfies ServerDetail),+ })+ await queryClient.fetchQuery({+ queryKey: communityKeys.channelMeta("server-1", "child-1"),+ queryFn: () => Promise.resolve({+ id: "child-1",+ serverId: "server-1",+ name: "Thread",+ type: "thread",+ parentChannelId: "channel-1",+ parentMessageId: "message-1",+ creatorId: "creator-1",+ archived: false,+ lastMessageAt: null,+ createdAt: "2026-09-08T00:00:00.000Z",+ verifiedEpoch: 0,+ }),+ })+ expect(queryClient.getQueryData(communityKeys.structuralSnapshot())).toBeUndefined()++ await queryClient.fetchQuery({+ queryKey: communityKeys.servers(),+ queryFn: () => Promise.resolve(servers()),+ })++ expect(queryClient.getQueryData(communityKeys.structuralSnapshot())).toMatchObject({+ folders: [{ id: "folder-1", serverIds: ["server-1"] }],+ servers: [{+ id: "server-1",+ categories: [{ id: "category-1" }],+ channels: [{ id: "channel-1" }],+ childRouteHints: [{ id: "child-1" }],+ }],+ })+ })++ it("ignores manual optimistic cache writes", async () => {+ await queryClient.fetchQuery({+ queryKey: communityKeys.servers(),+ queryFn: () => Promise.resolve(servers()),+ })+ queryClient.setQueryData(communityKeys.servers(), servers("Optimistic"))+ expect(queryClient.getQueryData<{ servers: Array<{ name: string }> }>(+ communityKeys.structuralSnapshot(),+ )?.servers[0]?.name).toBe("Alpha")+ })++ it("rejects projection after the active account changes", async () => {+ useCommunityWsStore.getState().activateProfileAccount("account-b")+ await queryClient.fetchQuery({+ queryKey: communityKeys.servers(),+ queryFn: () => Promise.resolve(servers()),+ })+ expect(queryClient.getQueryData(communityKeys.structuralSnapshot())).toBeUndefined()+ })++ it("removes a malformed restored snapshot", () => {+ dispose()+ queryClient.setQueryData(communityKeys.structuralSnapshot(), {+ schemaVersion: 1,+ accountId: "account-a",+ capturedAt: Date.now(),+ serverOrder: [],+ folders: [],+ servers: [],+ role: "owner",+ })+ dispose = installStructuralSnapshotProjection(queryClient, "account-a")+ expect(queryClient.getQueryData(communityKeys.structuralSnapshot())).toBeUndefined()+ })++ it("removes structural state for an anonymous account", () => {+ queryClient.setQueryData(communityKeys.structuralSnapshot(), { unsafe: true })+ dispose()+ dispose = installStructuralSnapshotProjection(queryClient, null)++ expect(queryClient.getQueryData(communityKeys.structuralSnapshot())).toBeUndefined()+ })++ it("rejects malformed data that is already present when a query is added", () => {+ queryClient.getQueryCache().build(+ queryClient,+ { queryKey: communityKeys.structuralSnapshot() },+ { data: { unsafe: true } } as never,+ )++ expect(queryClient.getQueryData(communityKeys.structuralSnapshot())).toBeUndefined()+ })++ it("projects successful cache entries that predate projection installation", () => {+ dispose()+ queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ queryClient.setQueryData(communityKeys.servers(), servers("Cached"))++ dispose = installStructuralSnapshotProjection(queryClient, "account-a")++ expect(queryClient.getQueryData(communityKeys.structuralSnapshot())).toMatchObject({+ accountId: "account-a",+ servers: [{ id: "server-1", name: "Cached" }],+ })+ })++ it("removes an archived child receipt from the structural snapshot", async () => {+ await queryClient.fetchQuery({+ queryKey: communityKeys.servers(),+ queryFn: () => Promise.resolve(servers()),+ })+ await queryClient.fetchQuery({+ queryKey: communityKeys.server("server-1"),+ queryFn: () => Promise.resolve({+ id: "server-1",+ name: "Alpha",+ discriminator: "0001",+ description: "",+ icon: null,+ ownerId: "owner-1",+ categories: [{+ id: "category-1",+ name: "General",+ private: 0,+ channels: [{+ id: "channel-1",+ name: "chat",+ type: "text",+ active: false,+ unread: false,+ }],+ }],+ } satisfies ServerDetail),+ })+ queryClient.setQueryData(communityKeys.structuralSnapshot(), (current: any) => ({+ ...current,+ servers: current.servers.map((server: any) => ({+ ...server,+ childRouteHints: [{+ id: "child-1",+ name: "Thread",+ type: "thread",+ parentChannelId: "channel-1",+ parentMessageId: "message-1",+ }],+ })),+ }))+ await queryClient.fetchQuery({+ queryKey: communityKeys.channelMeta("server-1", "child-1"),+ queryFn: () => Promise.resolve({+ id: "child-1",+ serverId: "server-1",+ name: "Thread",+ type: "thread",+ parentChannelId: "channel-1",+ parentMessageId: "message-1",+ archived: true,+ }),+ })++ expect(queryClient.getQueryData<any>(+ communityKeys.structuralSnapshot(),+ ).servers[0].childRouteHints).toEqual([])+ })++ it("projects and misses structural server hints explicitly", () => {+ const snapshot = {+ schemaVersion: 1 as const,+ accountId: "account-a",+ capturedAt: Date.now(),+ serverOrder: ["server-1"],+ folders: [],+ servers: [{+ id: "server-1",+ name: "Alpha",+ discriminator: "0001",+ icon: null,+ categories: [],+ channels: [],+ childRouteHints: [],+ }],+ }++ expect(structuralHintServer(snapshot, "server-1")).toMatchObject({+ id: "server-1",+ categoriesView: [],+ })+ expect(structuralHintServer(snapshot, "missing")).toBeNull()+ expect(structuralHintServer(null, "server-1")).toBeNull()+ })+})diff --git a/src/web/src/hooks/community/use-structural-snapshot.ts b/src/web/src/hooks/community/use-structural-snapshot.tsnew file mode 100644index 000000000..0ef684259--- /dev/null+++ b/src/web/src/hooks/community/use-structural-snapshot.ts@@ -0,0 +1,191 @@+"use client"++import { useCallback, useMemo, useSyncExternalStore } from "react"+import { useQueryClient, type QueryClient, type QueryKey } from "@tanstack/react-query"+import { communityKeys } from "@/lib/query-keys"+import {+ parseStructuralSnapshot,+ projectServerDetailTree,+ structuralServerToCategories,+ type StructuralSnapshotV1,+ type StructuralServerV1,+ updateStructuralSnapshot,+} from "@/lib/community/structural-snapshot"+import { useCommunityWsStore } from "@/stores/community/ws"+import type { ServersResponse, ServerDetail } from "./use-servers"+import type { FoldersResponse } from "./use-folders"+import type { ChannelMetadata } from "./channel-metadata"++function sameKey(left: QueryKey, right: QueryKey): boolean {+ return left.length === right.length+ && left.every((value, index) => value === right[index])+}++function projectLiveStructuralQuery(+ queryClient: QueryClient,+ accountId: string,+ key: QueryKey,+ data: unknown,+): void {+ if (useCommunityWsStore.getState().profileViewerId !== accountId) return+ if (sameKey(key, communityKeys.servers())) {+ const response = data as ServersResponse+ updateStructuralSnapshot(queryClient, {+ type: "replaceServers",+ accountId,+ servers: response.servers.map((server) => ({+ id: server.id,+ name: server.name,+ discriminator: server.discriminator ?? "",+ icon: server.icon ?? null,+ })),+ })+ const folders = queryClient.getQueryData<FoldersResponse>(communityKeys.folders())+ if (folders) {+ projectLiveStructuralQuery(+ queryClient,+ accountId,+ communityKeys.folders(),+ folders,+ )+ }+ for (const server of response.servers) {+ const detail = queryClient.getQueryData<ServerDetail>(communityKeys.server(server.id))+ if (detail) {+ projectLiveStructuralQuery(+ queryClient,+ accountId,+ communityKeys.server(server.id),+ detail,+ )+ }+ }+ return+ }+ if (sameKey(key, communityKeys.folders())) {+ const response = data as FoldersResponse+ updateStructuralSnapshot(queryClient, {+ type: "replaceFolders",+ folders: response.folders.map((folder) => ({+ id: folder.id,+ name: folder.name,+ serverIds: folder.servers.map((server) => server.id),+ })),+ })+ return+ }+ if (key.length === 3 && key[0] === "community" && key[1] === "servers") {+ const serverId = String(key[2])+ if (serverId === "__none__" || serverId === "channel-ref-directory") return+ const tree = projectServerDetailTree(data as ServerDetail)+ updateStructuralSnapshot(queryClient, {+ type: "replaceServerTree",+ serverId,+ ...tree,+ })+ for (const [metaKey, meta] of queryClient.getQueriesData<ChannelMetadata & { archived: boolean }>({+ queryKey: communityKeys.channelMetaRoot(serverId),+ })) {+ if (meta) projectLiveStructuralQuery(queryClient, accountId, metaKey, meta)+ }+ return+ }+ if (+ key.length === 5+ && key[0] === "community"+ && key[1] === "servers"+ && key[3] === "channel-meta"+ ) {+ const meta = data as ChannelMetadata & { archived: boolean }+ if (meta.type !== "thread" || !meta.parentChannelId || !meta.parentMessageId) return+ if (meta.archived) {+ updateStructuralSnapshot(queryClient, {+ type: "removeChildHint",+ serverId: meta.serverId,+ channelId: meta.id,+ })+ return+ }+ updateStructuralSnapshot(queryClient, {+ type: "upsertChildHint",+ serverId: meta.serverId,+ child: {+ id: meta.id,+ name: meta.name,+ type: "thread",+ parentChannelId: meta.parentChannelId,+ parentMessageId: meta.parentMessageId,+ },+ })+ }+}++export function installStructuralSnapshotProjection(+ queryClient: QueryClient,+ accountId: string | null,+): () => void {+ if (!accountId) {+ queryClient.removeQueries({ queryKey: communityKeys.structuralSnapshot(), exact: true })+ return () => {}+ }+ const existing = queryClient.getQueryData(communityKeys.structuralSnapshot())+ if (existing !== undefined && !parseStructuralSnapshot(existing, accountId)) {+ queryClient.removeQueries({ queryKey: communityKeys.structuralSnapshot(), exact: true })+ }+ const unsubscribe = queryClient.getQueryCache().subscribe((event) => {+ if (event.type === "added" && sameKey(event.query.queryKey, communityKeys.structuralSnapshot())) {+ if (+ event.query.state.data !== undefined+ && !parseStructuralSnapshot(event.query.state.data, accountId)+ ) {+ queryClient.removeQueries({ queryKey: communityKeys.structuralSnapshot(), exact: true })+ }+ return+ }+ if (event.type !== "updated") return+ if (event.action.type !== "success" || event.action.manual) return+ projectLiveStructuralQuery(+ queryClient,+ accountId,+ event.query.queryKey,+ event.query.state.data,+ )+ })+ for (const query of queryClient.getQueryCache().getAll()) {+ if (query.state.status === "success") {+ projectLiveStructuralQuery(queryClient, accountId, query.queryKey, query.state.data)+ }+ }+ return unsubscribe+}++export function useStructuralSnapshot(+ accountId: string | null,+ providedQueryClient?: QueryClient,+): StructuralSnapshotV1 | null {+ const queryClient = useQueryClient(providedQueryClient)+ const getSnapshot = useCallback(+ () => queryClient.getQueryData<unknown>(communityKeys.structuralSnapshot()),+ [queryClient],+ )+ const subscribe = useCallback((notify: () => void) => {+ const cache = queryClient.getQueryCache?.()+ if (!cache) return () => {}+ return cache.subscribe((event) => {+ if (sameKey(event.query.queryKey, communityKeys.structuralSnapshot())) notify()+ })+ }, [queryClient])+ const data = useSyncExternalStore(subscribe, getSnapshot, getSnapshot)+ return useMemo(+ () => accountId ? parseStructuralSnapshot(data, accountId) : null,+ [accountId, data],+ )+}++export function structuralHintServer(+ snapshot: StructuralSnapshotV1 | null,+ serverId: string,+): (StructuralServerV1 & { categoriesView: ReturnType<typeof structuralServerToCategories> }) | null {+ const server = snapshot?.servers.find((candidate) => candidate.id === serverId)+ return server ? { ...server, categoriesView: structuralServerToCategories(server) } : null+}diff --git a/src/web/src/lib/community/conversation-subtype.test.ts b/src/web/src/lib/community/conversation-subtype.test.tsindex d628c662c..0a44c8da2 100644--- a/src/web/src/lib/community/conversation-subtype.test.ts+++ b/src/web/src/lib/community/conversation-subtype.test.ts@@ -27,4 +27,25 @@ describe("resolveConversationSubtype", () => {...metadata,})).toBe(expected)})++ it.each(["text", "forum", "thread"] as const)(+ "uses the persisted %s subtype only for a pending skeleton",+ (structuralHint) => {+ expect(resolveConversationSubtype({+ routeLifecycle: "pending",+ accessAllowed: false,+ isChild: false,+ isForum: false,+ structuralHint,+ })).toBe(structuralHint)++ expect(resolveConversationSubtype({+ routeLifecycle: "terminal-error",+ accessAllowed: true,+ isChild: false,+ isForum: false,+ structuralHint,+ })).toBe("unknown")+ },+ )})diff --git a/src/web/src/lib/community/conversation-subtype.ts b/src/web/src/lib/community/conversation-subtype.tsindex 667eb5582..23224e094 100644--- a/src/web/src/lib/community/conversation-subtype.ts+++ b/src/web/src/lib/community/conversation-subtype.ts@@ -1,21 +1,23 @@export type ConversationSubtype = "unknown" | "text" | "forum" | "thread"/**- * Persisted route data may describe a subtype, but it cannot authorize showing- * that subtype. Canonical metadata and the current navigation access proof must- * both be ready first.+ * Persisted route data may describe a skeleton subtype, but it cannot authorize+ * mounting the conversation content surface.*/export function resolveConversationSubtype({routeLifecycle,accessAllowed,isChild,isForum,+ structuralHint = "unknown",}: {routeLifecycle: "pending" | "ready" | "terminal-error"accessAllowed: booleanisChild: booleanisForum: boolean+ structuralHint?: ConversationSubtype}): ConversationSubtype {+ if (routeLifecycle === "pending") return structuralHintif (routeLifecycle !== "ready" || !accessAllowed) return "unknown"if (isChild) return "thread"return isForum ? "forum" : "text"diff --git a/src/web/src/lib/community/structural-snapshot.test.ts b/src/web/src/lib/community/structural-snapshot.test.tsnew file mode 100644index 000000000..d210e2071--- /dev/null+++ b/src/web/src/lib/community/structural-snapshot.test.ts@@ -0,0 +1,406 @@+import { describe, expect, it } from "vitest"+import { QueryClient } from "@tanstack/react-query"+import { communityKeys } from "@/lib/query-keys"+import {+ parseStructuralSnapshot,+ projectServerDetailTree,+ reduceStructuralSnapshot,+ STRUCTURAL_SNAPSHOT_CHILD_LIMIT,+ STRUCTURAL_SNAPSHOT_TTL_MS,+ structuralServerToCategories,+ structuralSnapshotDirectory,+ structuralSnapshotFolders,+ structuralSnapshotServers,+ type StructuralSnapshotV1,+ updateStructuralSnapshot,+} from "./structural-snapshot"++const NOW = 2_000_000_000_000++function snapshot(): StructuralSnapshotV1 {+ return {+ schemaVersion: 1,+ accountId: "account-a",+ capturedAt: NOW,+ serverOrder: ["server-b", "server-a"],+ folders: [{ id: "folder-1", name: "Work", serverIds: ["server-a"] }],+ servers: [+ {+ id: "server-a",+ name: "Alpha",+ discriminator: "0001",+ icon: null,+ categories: [{ id: "category-1", name: "General", private: false }],+ channels: [+ { id: "channel-a", name: "chat", type: "text", categoryId: "category-1" },+ { id: "channel-b", name: "ideas", type: "forum", categoryId: null },+ ],+ childRouteHints: [{+ id: "child-1",+ name: "thread",+ type: "thread",+ parentChannelId: "channel-a",+ parentMessageId: "message-1",+ }],+ },+ {+ id: "server-b",+ name: "Beta",+ discriminator: "0002",+ icon: "https://example.com/icon.png",+ categories: [],+ channels: [],+ childRouteHints: [],+ },+ ],+ }+}++describe("parseStructuralSnapshot", () => {+ it("round-trips the exact v1 allowlist", () => {+ expect(parseStructuralSnapshot(snapshot(), "account-a", NOW)).toEqual(snapshot())+ })++ it.each([+ ["wrong account", { ...snapshot(), accountId: "account-b" }],+ ["wrong version", { ...snapshot(), schemaVersion: 2 }],+ ["expired", { ...snapshot(), capturedAt: NOW - STRUCTURAL_SNAPSHOT_TTL_MS - 1 }],+ ["future", { ...snapshot(), capturedAt: NOW + 1 }],+ ["unknown top-level field", { ...snapshot(), role: "owner" }],+ ])("rejects %s", (_label, value) => {+ expect(parseStructuralSnapshot(value, "account-a", NOW)).toBeNull()+ })++ it("rejects unknown nested authorization and runtime fields", () => {+ const value = snapshot() as StructuralSnapshotV1 & {+ servers: Array<StructuralSnapshotV1["servers"][number] & { ownerId?: string }>+ }+ value.servers[0] = { ...value.servers[0]!, ownerId: "owner-1" }+ expect(parseStructuralSnapshot(value, "account-a", NOW)).toBeNull()++ })++ it("rejects duplicate, dangling, temporary, and over-limit references", () => {+ const duplicate = snapshot()+ duplicate.serverOrder = ["server-a", "server-a"]+ expect(parseStructuralSnapshot(duplicate, "account-a", NOW)).toBeNull()++ const dangling = snapshot()+ dangling.servers[0]!.channels[0]!.categoryId = "missing"+ expect(parseStructuralSnapshot(dangling, "account-a", NOW)).toBeNull()++ const temporary = snapshot()+ temporary.servers[0]!.channels[0]!.id = "tmp_ch_1"+ expect(parseStructuralSnapshot(temporary, "account-a", NOW)).toBeNull()++ const oversized = snapshot()+ oversized.servers[0]!.childRouteHints = Array.from(+ { length: STRUCTURAL_SNAPSHOT_CHILD_LIMIT + 1 },+ (_, index) => ({+ id: `child-${index}`,+ name: `Thread ${index}`,+ type: "thread" as const,+ parentChannelId: "channel-a",+ parentMessageId: `message-${index}`,+ }),+ )+ expect(parseStructuralSnapshot(oversized, "account-a", NOW)).toBeNull()+ })++ it("rejects malformed and unsafe child-route hints", () => {+ const unknownField = snapshot() as unknown as {+ servers: Array<{ childRouteHints: Array<Record<string, unknown>> }>+ }+ unknownField.servers[0]!.childRouteHints[0]!.permission = "read"+ expect(parseStructuralSnapshot(unknownField, "account-a", NOW)).toBeNull()++ const unsafeParentMessage = snapshot()+ unsafeParentMessage.servers[0]!.childRouteHints[0]!.parentMessageId = ""+ expect(parseStructuralSnapshot(unsafeParentMessage, "account-a", NOW)).toBeNull()+ })++ it("preserves an empty folder as structural rail state", () => {+ const value = snapshot()+ value.folders = [{ id: "folder-empty", name: "Later", serverIds: [] }]+ expect(parseStructuralSnapshot(value, "account-a", NOW)?.folders).toEqual(value.folders)++ const next = reduceStructuralSnapshot(value, {+ type: "replaceFolders",+ folders: value.folders,+ }, NOW)!+ expect(next.folders).toEqual(value.folders)+ })++ it("accepts a bounded 100-server structural fixture without runtime data", () => {+ const servers = Array.from({ length: 100 }, (_, serverIndex) => {+ const channels = Array.from({ length: 10 }, (_, channelIndex) => ({+ id: `server-${serverIndex}-channel-${channelIndex}`,+ name: `Channel ${channelIndex}`,+ type: channelIndex % 2 === 0 ? "text" as const : "forum" as const,+ categoryId: `server-${serverIndex}-category`,+ }))+ return {+ id: `server-${serverIndex}`,+ name: `Server ${serverIndex}`,+ discriminator: String(serverIndex).padStart(4, "0"),+ icon: null,+ categories: [{+ id: `server-${serverIndex}-category`,+ name: "General",+ private: false,+ }],+ channels,+ childRouteHints: Array.from({ length: STRUCTURAL_SNAPSHOT_CHILD_LIMIT }, (_, childIndex) => ({+ id: `server-${serverIndex}-child-${childIndex}`,+ name: `Thread ${childIndex}`,+ type: "thread" as const,+ parentChannelId: channels[0]!.id,+ parentMessageId: `server-${serverIndex}-message-${childIndex}`,+ })),+ }+ })+ const value: StructuralSnapshotV1 = {+ schemaVersion: 1,+ accountId: "account-a",+ capturedAt: NOW,+ serverOrder: servers.map((server) => server.id),+ folders: [],+ servers,+ }++ const parsed = parseStructuralSnapshot(value, "account-a", NOW)++ expect(parsed?.servers).toHaveLength(100)+ expect(parsed?.servers.flatMap((server) => server.channels)).toHaveLength(1_000)+ expect(parsed?.servers.flatMap((server) => server.childRouteHints)).toHaveLength(3_200)+ expect(JSON.stringify(parsed).length).toBeLessThan(1_000_000)+ })+})++describe("reduceStructuralSnapshot", () => {+ it("authoritatively replaces server membership while preserving known trees", () => {+ const next = reduceStructuralSnapshot(snapshot(), {+ type: "replaceServers",+ accountId: "account-a",+ servers: [{ id: "server-a", name: "Renamed", discriminator: "0001", icon: null }],+ }, NOW + 1)!+ expect(next.serverOrder).toEqual(["server-a"])+ expect(next.servers[0]?.name).toBe("Renamed")+ expect(next.servers[0]?.channels.map((channel) => channel.id)).toEqual(["channel-a", "channel-b"])+ expect(next.folders).toEqual([{ id: "folder-1", name: "Work", serverIds: ["server-a"] }])+ })++ it("retains only child hints whose parent remains in a replaced server tree", () => {+ const next = reduceStructuralSnapshot(snapshot(), {+ type: "replaceServerTree",+ serverId: "server-a",+ categories: [{ id: "category-1", name: "General", private: false }],+ channels: [{ id: "channel-a", name: "chat", type: "text", categoryId: "category-1" }],+ }, NOW + 1)!++ expect(next.servers[0]?.childRouteHints.map((child) => child.id)).toEqual(["child-1"])+ })++ it("prunes a parent channel and every related child hint atomically", () => {+ const next = reduceStructuralSnapshot(snapshot(), {+ type: "removeChannel",+ serverId: "server-a",+ channelId: "channel-a",+ }, NOW + 1)!+ expect(next.servers[0]?.channels.map((channel) => channel.id)).toEqual(["channel-b"])+ expect(next.servers[0]?.childRouteHints).toEqual([])+ })++ it("bounds child hints by most-recent insertion", () => {+ let current = snapshot()+ current.servers[0]!.childRouteHints = []+ for (let index = 0; index < STRUCTURAL_SNAPSHOT_CHILD_LIMIT + 5; index += 1) {+ current = reduceStructuralSnapshot(current, {+ type: "upsertChildHint",+ serverId: "server-a",+ child: {+ id: `child-${index}`,+ name: `Thread ${index}`,+ type: "thread",+ parentChannelId: "channel-a",+ parentMessageId: `message-${index}`,+ },+ }, NOW + index)!+ }+ expect(current.servers[0]?.childRouteHints).toHaveLength(STRUCTURAL_SNAPSHOT_CHILD_LIMIT)+ expect(current.servers[0]?.childRouteHints[0]?.id).toBe(`child-${STRUCTURAL_SNAPSHOT_CHILD_LIMIT + 4}`)+ })++ it("reconciles every ordered tree and rail mutation through one reducer", () => {+ let current = snapshot()+ current = reduceStructuralSnapshot(current, {+ type: "replaceRail",+ serverOrder: ["server-a", "unknown", "server-a"],+ folders: [+ { id: "folder-a", name: "A", serverIds: ["server-a"] },+ { id: "folder-b", name: "B", serverIds: ["server-b"] },+ ],+ }, NOW + 1)!+ expect(current.serverOrder).toEqual(["server-a", "server-b"])++ current = reduceStructuralSnapshot(current, {+ type: "upsertCategory",+ serverId: "server-a",+ category: { id: "category-2", name: "Later", private: true },+ }, NOW + 2)!+ current = reduceStructuralSnapshot(current, {+ type: "patchCategory",+ serverId: "server-a",+ categoryId: "category-2",+ changes: { name: "First" },+ position: -5,+ }, NOW + 3)!+ current = reduceStructuralSnapshot(current, {+ type: "reorderCategories",+ serverId: "server-a",+ categoryIds: ["category-1", "missing"],+ }, NOW + 4)!+ expect(current.servers[0]?.categories.map((category) => category.id))+ .toEqual(["category-1", "category-2"])++ current = reduceStructuralSnapshot(current, {+ type: "upsertChannel",+ serverId: "server-a",+ channel: { id: "channel-c", name: "later", type: "text", categoryId: "category-2" },+ }, NOW + 5)!+ current = reduceStructuralSnapshot(current, {+ type: "patchChannel",+ serverId: "server-a",+ channelId: "channel-c",+ changes: { name: "renamed", type: "forum" },+ }, NOW + 6)!+ current = reduceStructuralSnapshot(current, {+ type: "reorderChannels",+ serverId: "server-a",+ channelIds: ["channel-c", "missing", "channel-a"],+ }, NOW + 7)!+ expect(current.servers[0]?.channels.map((channel) => channel.id))+ .toEqual(["channel-c", "channel-a", "channel-b"])++ current = reduceStructuralSnapshot(current, {+ type: "patchChildHint",+ serverId: "server-a",+ channelId: "child-1",+ name: "renamed child",+ }, NOW + 8)!+ expect(current.servers[0]?.childRouteHints[0]?.name).toBe("renamed child")+ current = reduceStructuralSnapshot(current, {+ type: "patchChildHint",+ serverId: "server-a",+ channelId: "child-1",+ }, NOW + 9)!+ expect(current.servers[0]?.childRouteHints[0]?.name).toBe("renamed child")+ current = reduceStructuralSnapshot(current, {+ type: "removeChildHint",+ serverId: "server-a",+ channelId: "child-1",+ }, NOW + 10)!+ expect(current.servers[0]?.childRouteHints).toEqual([])++ current = reduceStructuralSnapshot(current, {+ type: "removeCategory",+ serverId: "server-a",+ categoryId: "category-2",+ }, NOW + 11)!+ expect(current.servers[0]?.channels.find((channel) => channel.id === "channel-c")?.categoryId)+ .toBeNull()++ current = reduceStructuralSnapshot(current, {+ type: "removeServer",+ serverId: "server-a",+ }, NOW + 12)!+ expect(current.folders).toEqual([{ id: "folder-b", name: "B", serverIds: ["server-b"] }])+ expect(current.servers.map((server) => server.id)).toEqual(["server-b"])++ const defaultTimestamp = reduceStructuralSnapshot(current, {+ type: "replaceFolders",+ folders: [],+ })!+ expect(defaultTimestamp.capturedAt).toBeGreaterThanOrEqual(Date.now() - 1_000)+ })++ it("updates exactly one QueryClient owner", () => {+ const queryClient = new QueryClient()+ updateStructuralSnapshot(queryClient, {+ type: "replaceServers",+ accountId: "account-a",+ servers: [{ id: "server-a", name: "Alpha", discriminator: "0001", icon: null }],+ }, NOW)+ expect(queryClient.getQueryData(communityKeys.structuralSnapshot())).toEqual({+ schemaVersion: 1,+ accountId: "account-a",+ capturedAt: NOW,+ serverOrder: ["server-a"],+ folders: [],+ servers: [{+ id: "server-a",+ name: "Alpha",+ discriminator: "0001",+ icon: null,+ categories: [],+ channels: [],+ childRouteHints: [],+ }],+ })+ })+})++describe("structural projections", () => {+ it("drops runtime fields and derives uncategorized channels", () => {+ const tree = projectServerDetailTree({+ categories: [+ {+ id: "category-1",+ name: "General",+ private: 1,+ creatorId: "creator-1",+ channels: [{+ id: "channel-a",+ name: "chat",+ type: "text",+ topic: "secret",+ unread: true,+ }],+ },+ {+ id: "__uncategorized__",+ name: "",+ channels: [{ id: "channel-b", name: "ideas", type: "forum" }],+ },+ {+ id: "tmp_cat_1",+ name: "Pending",+ pending: true,+ channels: [{ id: "tmp_ch_1", name: "Pending", type: "text", pending: true }],+ },+ ],+ })+ expect(tree).toEqual({+ categories: [{ id: "category-1", name: "General", private: true }],+ channels: [+ { id: "channel-a", name: "chat", type: "text", categoryId: "category-1" },+ { id: "channel-b", name: "ideas", type: "forum", categoryId: null },+ ],+ })+ const projected = structuralServerToCategories({+ ...snapshot().servers[0]!,+ ...tree,+ })+ expect(projected.map((category) => category.id)).toEqual(["category-1", "__uncategorized__"])+ })++ it("projects ordered rail, folder references, and top-level directory", () => {+ const value = snapshot()+ expect(structuralSnapshotServers(value).map((server) => server.id)).toEqual(["server-b", "server-a"])+ expect(structuralSnapshotFolders(value)[0]?.servers.map((server) => server.id)).toEqual(["server-a"])+ expect(structuralSnapshotDirectory(value)[0]?.channels.map((channel) => channel.id)).toEqual([+ "channel-a",+ "channel-b",+ ])+ })+})diff --git a/src/web/src/lib/community/structural-snapshot.ts b/src/web/src/lib/community/structural-snapshot.tsnew file mode 100644index 000000000..d409f82b0--- /dev/null+++ b/src/web/src/lib/community/structural-snapshot.ts@@ -0,0 +1,642 @@+import type { QueryClient } from "@tanstack/react-query"+import { UNCATEGORIZED_CATEGORY_ID } from "@alook/shared"+import { avatarInitial } from "@/lib/community/avatar"+import type { ChannelRefDirectory } from "@/lib/community/channel-ref"+import type {+ Category,+ CommunityFolder,+ Server,+} from "@/lib/community/models/navigation"+import { communityKeys } from "@/lib/query-keys"++const STRUCTURAL_SNAPSHOT_VERSION = 1 as const+export const STRUCTURAL_SNAPSHOT_TTL_MS = 24 * 60 * 60 * 1000+export const STRUCTURAL_SNAPSHOT_CHILD_LIMIT = 32++export type StructuralCategoryV1 = {+ id: string+ name: string+ private: boolean+}++export type StructuralChannelV1 = {+ id: string+ name: string+ type: "text" | "forum"+ categoryId: string | null+}++type StructuralChildRouteHintV1 = {+ id: string+ name: string+ type: "thread"+ parentChannelId: string+ parentMessageId: string+}++export type StructuralServerV1 = {+ id: string+ name: string+ discriminator: string+ icon: string | null+ categories: StructuralCategoryV1[]+ channels: StructuralChannelV1[]+ childRouteHints: StructuralChildRouteHintV1[]+}++export type StructuralSnapshotV1 = {+ schemaVersion: 1+ accountId: string+ capturedAt: number+ serverOrder: string[]+ folders: Array<{+ id: string+ name: string+ serverIds: string[]+ }>+ servers: StructuralServerV1[]+}++export type StructuralSnapshotEvent =+ | {+ type: "replaceServers"+ accountId: string+ servers: Array<Pick<StructuralServerV1, "id" | "name" | "discriminator" | "icon">>+ }+ | {+ type: "replaceFolders"+ folders: Array<{ id: string; name: string; serverIds: string[] }>+ }+ | {+ type: "replaceServerTree"+ serverId: string+ categories: StructuralCategoryV1[]+ channels: StructuralChannelV1[]+ }+ | {+ type: "replaceRail"+ serverOrder: string[]+ folders: Array<{ id: string; name: string; serverIds: string[] }>+ }+ | {+ type: "patchServer"+ serverId: string+ changes: Partial<Pick<StructuralServerV1, "name" | "icon">>+ }+ | { type: "removeServer"; serverId: string }+ | {+ type: "upsertCategory"+ serverId: string+ category: StructuralCategoryV1+ position?: number+ }+ | {+ type: "patchCategory"+ serverId: string+ categoryId: string+ changes: Partial<Pick<StructuralCategoryV1, "name" | "private">>+ position?: number+ }+ | { type: "removeCategory"; serverId: string; categoryId: string }+ | {+ type: "reorderCategories"+ serverId: string+ categoryIds: string[]+ }+ | {+ type: "upsertChannel"+ serverId: string+ channel: StructuralChannelV1+ position?: number+ }+ | {+ type: "patchChannel"+ serverId: string+ channelId: string+ changes: Partial<Pick<StructuralChannelV1, "name" | "type" | "categoryId">>+ }+ | { type: "removeChannel"; serverId: string; channelId: string }+ | {+ type: "reorderChannels"+ serverId: string+ channelIds: string[]+ }+ | {+ type: "upsertChildHint"+ serverId: string+ child: StructuralChildRouteHintV1+ }+ | {+ type: "patchChildHint"+ serverId: string+ channelId: string+ name?: string+ }+ | { type: "removeChildHint"; serverId: string; channelId: string }++type ServerDetailSource = {+ categories: Array<{+ id: string+ name: string+ private?: boolean | number+ pending?: boolean+ channels: Array<{+ id: string+ name: string+ type?: string+ pending?: boolean+ }>+ }>+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value)+}++function hasExactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {+ const actual = Object.keys(value).sort()+ const expected = [...keys].sort()+ return actual.length === expected.length+ && actual.every((key, index) => key === expected[index])+}++function isSafeId(value: unknown): value is string {+ return typeof value === "string"+ && value.length > 0+ && !value.startsWith("tmp_")+ && !value.startsWith("temp_")+}++function isString(value: unknown): value is string {+ return typeof value === "string"+}++function unique(values: readonly string[]): boolean {+ return new Set(values).size === values.length+}++function parseCategory(value: unknown): StructuralCategoryV1 | null {+ if (!isRecord(value) || !hasExactKeys(value, ["id", "name", "private"])) return null+ if (!isSafeId(value.id) || !isString(value.name) || typeof value.private !== "boolean") return null+ return { id: value.id, name: value.name, private: value.private }+}++function parseChannel(value: unknown): StructuralChannelV1 | null {+ if (!isRecord(value) || !hasExactKeys(value, ["id", "name", "type", "categoryId"])) return null+ if (!isSafeId(value.id) || !isString(value.name)) return null+ if (value.type !== "text" && value.type !== "forum") return null+ if (value.categoryId !== null && !isSafeId(value.categoryId)) return null+ return {+ id: value.id,+ name: value.name,+ type: value.type,+ categoryId: value.categoryId,+ }+}++function parseChild(value: unknown): StructuralChildRouteHintV1 | null {+ if (!isRecord(value) || !hasExactKeys(value, [+ "id",+ "name",+ "type",+ "parentChannelId",+ "parentMessageId",+ ])) return null+ if (+ !isSafeId(value.id)+ || !isString(value.name)+ || value.type !== "thread"+ || !isSafeId(value.parentChannelId)+ || !isSafeId(value.parentMessageId)+ ) return null+ return {+ id: value.id,+ name: value.name,+ type: "thread",+ parentChannelId: value.parentChannelId,+ parentMessageId: value.parentMessageId,+ }+}++function parseServer(value: unknown): StructuralServerV1 | null {+ if (!isRecord(value) || !hasExactKeys(value, [+ "id",+ "name",+ "discriminator",+ "icon",+ "categories",+ "channels",+ "childRouteHints",+ ])) return null+ if (+ !isSafeId(value.id)+ || !isString(value.name)+ || !isString(value.discriminator)+ || (value.icon !== null && !isString(value.icon))+ || !Array.isArray(value.categories)+ || !Array.isArray(value.channels)+ || !Array.isArray(value.childRouteHints)+ || value.childRouteHints.length > STRUCTURAL_SNAPSHOT_CHILD_LIMIT+ ) return null+ const categories = value.categories.map(parseCategory)+ const channels = value.channels.map(parseChannel)+ const children = value.childRouteHints.map(parseChild)+ if (categories.some((row) => row === null)+ || channels.some((row) => row === null)+ || children.some((row) => row === null)) return null+ const parsedCategories = categories as StructuralCategoryV1[]+ const parsedChannels = channels as StructuralChannelV1[]+ const parsedChildren = children as StructuralChildRouteHintV1[]+ const categoryIds = parsedCategories.map((row) => row.id)+ const channelIds = parsedChannels.map((row) => row.id)+ const childIds = parsedChildren.map((row) => row.id)+ if (!unique(categoryIds) || !unique(channelIds) || !unique(childIds)) return null+ const categorySet = new Set(categoryIds)+ const channelSet = new Set(channelIds)+ if (parsedChannels.some((row) => row.categoryId !== null && !categorySet.has(row.categoryId))) return null+ if (parsedChildren.some((row) => !channelSet.has(row.parentChannelId))) return null+ if ([...channelIds, ...childIds].some((id, index, all) => all.indexOf(id) !== index)) return null+ return {+ id: value.id,+ name: value.name,+ discriminator: value.discriminator,+ icon: value.icon,+ categories: parsedCategories,+ channels: parsedChannels,+ childRouteHints: parsedChildren,+ }+}++export function parseStructuralSnapshot(+ value: unknown,+ accountId: string,+ now = Date.now(),+): StructuralSnapshotV1 | null {+ if (!accountId || !isRecord(value) || !hasExactKeys(value, [+ "schemaVersion",+ "accountId",+ "capturedAt",+ "serverOrder",+ "folders",+ "servers",+ ])) return null+ if (+ value.schemaVersion !== STRUCTURAL_SNAPSHOT_VERSION+ || value.accountId !== accountId+ || typeof value.capturedAt !== "number"+ || !Number.isFinite(value.capturedAt)+ || value.capturedAt < 0+ || value.capturedAt > now+ || now - value.capturedAt > STRUCTURAL_SNAPSHOT_TTL_MS+ || !Array.isArray(value.serverOrder)+ || !Array.isArray(value.folders)+ || !Array.isArray(value.servers)+ ) return null+ if (!value.serverOrder.every(isSafeId) || !unique(value.serverOrder)) return null+ const serverOrder = value.serverOrder as string[]+ const servers = value.servers.map(parseServer)+ if (servers.some((server) => server === null)) return null+ const parsedServers = servers as StructuralServerV1[]+ const serverIds = parsedServers.map((server) => server.id)+ if (!unique(serverIds)+ || serverIds.length !== serverOrder.length+ || serverIds.some((id) => !serverOrder.includes(id))) return null+ const serverSet = new Set(serverIds)+ const claimed = new Set<string>()+ const folders: StructuralSnapshotV1["folders"] = []+ for (const valueFolder of value.folders) {+ if (!isRecord(valueFolder) || !hasExactKeys(valueFolder, ["id", "name", "serverIds"])) return null+ if (!isSafeId(valueFolder.id) || !isString(valueFolder.name) || !Array.isArray(valueFolder.serverIds)) return null+ if (!valueFolder.serverIds.every(isSafeId)+ || !unique(valueFolder.serverIds)+ || valueFolder.serverIds.some((id) => !serverSet.has(id) || claimed.has(id))) return null+ for (const id of valueFolder.serverIds) claimed.add(id)+ folders.push({ id: valueFolder.id, name: valueFolder.name, serverIds: [...valueFolder.serverIds] })+ }+ if (!unique(folders.map((folder) => folder.id))) return null+ return {+ schemaVersion: STRUCTURAL_SNAPSHOT_VERSION,+ accountId,+ capturedAt: value.capturedAt,+ serverOrder: [...serverOrder],+ folders,+ servers: parsedServers,+ }+}++function moveToPosition<T>(values: readonly T[], value: T, position?: number): T[] {+ const next = [...values]+ const index = position === undefined+ ? next.length+ : Math.max(0, Math.min(Math.trunc(position), next.length))+ next.splice(index, 0, value)+ return next+}++function orderByIds<T extends { id: string }>(values: readonly T[], ids: readonly string[]): T[] {+ const byId = new Map(values.map((value) => [value.id, value]))+ const ordered = ids.flatMap((id) => {+ const value = byId.get(id)+ if (!value) return []+ byId.delete(id)+ return [value]+ })+ return [...ordered, ...byId.values()]+}++function withServer(+ snapshot: StructuralSnapshotV1,+ serverId: string,+ update: (server: StructuralServerV1) => StructuralServerV1,+ now: number,+): StructuralSnapshotV1 {+ let changed = false+ const servers = snapshot.servers.map((server) => {+ if (server.id !== serverId) return server+ const next = update(server)+ changed = changed || next !== server+ return next+ })+ return changed ? { ...snapshot, capturedAt: now, servers } : snapshot+}++function normalizedFolders(+ snapshot: StructuralSnapshotV1,+ folders: StructuralSnapshotV1["folders"],+): StructuralSnapshotV1["folders"] {+ const serverIds = new Set(snapshot.serverOrder)+ const claimed = new Set<string>()+ const folderIds = new Set<string>()+ return folders.flatMap((folder) => {+ if (!isSafeId(folder.id) || !isString(folder.name) || folderIds.has(folder.id)) return []+ folderIds.add(folder.id)+ const ids = folder.serverIds.filter((id) => {+ if (!serverIds.has(id) || claimed.has(id)) return false+ claimed.add(id)+ return true+ })+ return [{ id: folder.id, name: folder.name, serverIds: ids }]+ })+}++export function reduceStructuralSnapshot(+ current: StructuralSnapshotV1 | undefined,+ event: StructuralSnapshotEvent,+ now = Date.now(),+): StructuralSnapshotV1 | undefined {+ if (event.type === "replaceServers") {+ const previous = current?.accountId === event.accountId ? current : undefined+ const previousById = new Map(previous?.servers.map((server) => [server.id, server]) ?? [])+ const servers = event.servers+ .filter((server) => isSafeId(server.id))+ .filter((server, index, all) => all.findIndex((candidate) => candidate.id === server.id) === index)+ .map((server) => ({+ id: server.id,+ name: server.name,+ discriminator: server.discriminator,+ icon: server.icon,+ categories: previousById.get(server.id)?.categories ?? [],+ channels: previousById.get(server.id)?.channels ?? [],+ childRouteHints: previousById.get(server.id)?.childRouteHints ?? [],+ }))+ const snapshot: StructuralSnapshotV1 = {+ schemaVersion: STRUCTURAL_SNAPSHOT_VERSION,+ accountId: event.accountId,+ capturedAt: now,+ serverOrder: servers.map((server) => server.id),+ folders: [],+ servers,+ }+ snapshot.folders = normalizedFolders(snapshot, previous?.folders ?? [])+ return snapshot+ }+ if (!current) return current+ if (event.type === "replaceFolders") {+ return { ...current, capturedAt: now, folders: normalizedFolders(current, event.folders) }+ }+ if (event.type === "replaceRail") {+ const known = new Set(current.serverOrder)+ const serverOrder = event.serverOrder.filter(+ (id, index, values) => known.has(id) && values.indexOf(id) === index,+ )+ for (const id of current.serverOrder) if (!serverOrder.includes(id)) serverOrder.push(id)+ const next = { ...current, capturedAt: now, serverOrder }+ return { ...next, folders: normalizedFolders(next, event.folders) }+ }+ if (event.type === "removeServer") {+ if (!current.serverOrder.includes(event.serverId)) return current+ return {+ ...current,+ capturedAt: now,+ serverOrder: current.serverOrder.filter((id) => id !== event.serverId),+ folders: current.folders.flatMap((folder) => {+ const serverIds = folder.serverIds.filter((id) => id !== event.serverId)+ return serverIds.length > 0 ? [{ ...folder, serverIds }] : []+ }),+ servers: current.servers.filter((server) => server.id !== event.serverId),+ }+ }+ if (event.type === "patchServer") {+ return withServer(current, event.serverId, (server) => ({ ...server, ...event.changes }), now)+ }+ if (event.type === "replaceServerTree") {+ return withServer(current, event.serverId, (server) => ({+ ...server,+ categories: event.categories,+ channels: event.channels,+ childRouteHints: server.childRouteHints.filter((child) =>+ event.channels.some((channel) => channel.id === child.parentChannelId)),+ }), now)+ }+ if (event.type === "upsertCategory") {+ return withServer(current, event.serverId, (server) => {+ const without = server.categories.filter((category) => category.id !== event.category.id)+ return { ...server, categories: moveToPosition(without, event.category, event.position) }+ }, now)+ }+ if (event.type === "patchCategory") {+ return withServer(current, event.serverId, (server) => {+ const existing = server.categories.find((category) => category.id === event.categoryId)+ if (!existing) return server+ const category = { ...existing, ...event.changes }+ const categories = server.categories.filter((row) => row.id !== event.categoryId)+ return {+ ...server,+ categories: event.position === undefined+ ? server.categories.map((row) => row.id === event.categoryId ? category : row)+ : moveToPosition(categories, category, event.position),+ }+ }, now)+ }+ if (event.type === "removeCategory") {+ return withServer(current, event.serverId, (server) => ({+ ...server,+ categories: server.categories.filter((category) => category.id !== event.categoryId),+ channels: server.channels.map((channel) =>+ channel.categoryId === event.categoryId ? { ...channel, categoryId: null } : channel),+ }), now)+ }+ if (event.type === "reorderCategories") {+ return withServer(current, event.serverId, (server) => ({+ ...server,+ categories: orderByIds(server.categories, event.categoryIds),+ }), now)+ }+ if (event.type === "upsertChannel") {+ return withServer(current, event.serverId, (server) => {+ const without = server.channels.filter((channel) => channel.id !== event.channel.id)+ return { ...server, channels: moveToPosition(without, event.channel, event.position) }+ }, now)+ }+ if (event.type === "patchChannel") {+ return withServer(current, event.serverId, (server) => ({+ ...server,+ channels: server.channels.map((channel) =>+ channel.id === event.channelId ? { ...channel, ...event.changes } : channel),+ }), now)+ }+ if (event.type === "reorderChannels") {+ return withServer(current, event.serverId, (server) => ({+ ...server,+ channels: orderByIds(server.channels, event.channelIds),+ }), now)+ }+ if (event.type === "removeChannel") {+ return withServer(current, event.serverId, (server) => ({+ ...server,+ channels: server.channels.filter((channel) => channel.id !== event.channelId),+ childRouteHints: server.childRouteHints.filter((child) =>+ child.id !== event.channelId && child.parentChannelId !== event.channelId),+ }), now)+ }+ if (event.type === "upsertChildHint") {+ return withServer(current, event.serverId, (server) => {+ if (!server.channels.some((channel) => channel.id === event.child.parentChannelId)) return server+ const childRouteHints = [+ event.child,+ ...server.childRouteHints.filter((child) => child.id !== event.child.id),+ ].slice(0, STRUCTURAL_SNAPSHOT_CHILD_LIMIT)+ return { ...server, childRouteHints }+ }, now)+ }+ if (event.type === "patchChildHint") {+ return withServer(current, event.serverId, (server) => ({+ ...server,+ childRouteHints: server.childRouteHints.map((child) =>+ child.id === event.channelId && event.name !== undefined+ ? { ...child, name: event.name }+ : child),+ }), now)+ }+ return withServer(current, event.serverId, (server) => ({+ ...server,+ childRouteHints: server.childRouteHints.filter((child) => child.id !== event.channelId),+ }), now)+}++export function updateStructuralSnapshot(+ queryClient: QueryClient,+ event: StructuralSnapshotEvent,+ now = Date.now(),+): void {+ queryClient.setQueryData<StructuralSnapshotV1 | undefined>(+ communityKeys.structuralSnapshot(),+ (current) => reduceStructuralSnapshot(current, event, now),+ )+}++export function projectServerDetailTree(detail: ServerDetailSource): {+ categories: StructuralCategoryV1[]+ channels: StructuralChannelV1[]+} {+ const categories: StructuralCategoryV1[] = []+ const channels: StructuralChannelV1[] = []+ for (const category of detail.categories) {+ if (category.pending || !isSafeId(category.id)) continue+ const uncategorized = category.id === UNCATEGORIZED_CATEGORY_ID || category.name === ""+ if (!uncategorized) {+ categories.push({+ id: category.id,+ name: category.name,+ private: category.private === true || category.private === 1,+ })+ }+ for (const channel of category.channels) {+ if (channel.pending || !isSafeId(channel.id)) continue+ if (channel.type !== "text" && channel.type !== "forum") continue+ channels.push({+ id: channel.id,+ name: channel.name,+ type: channel.type,+ categoryId: uncategorized ? null : category.id,+ })+ }+ }+ return { categories, channels }+}++export function structuralServerToCategories(server: StructuralServerV1): Category[] {+ const categories: Category[] = server.categories.map((category) => ({+ id: category.id,+ name: category.name,+ private: category.private,+ channels: server.channels+ .filter((channel) => channel.categoryId === category.id)+ .map((channel) => ({ ...channel, active: false, unread: false })),+ }))+ const uncategorized = server.channels+ .filter((channel) => channel.categoryId === null)+ .map((channel) => ({ ...channel, active: false, unread: false }))+ if (uncategorized.length > 0) {+ categories.push({+ id: UNCATEGORIZED_CATEGORY_ID,+ name: "",+ private: false,+ channels: uncategorized,+ })+ }+ return categories+}++export function structuralSnapshotServers(snapshot: StructuralSnapshotV1 | null): Server[] {+ if (!snapshot) return []+ const byId = new Map(snapshot.servers.map((server) => [server.id, server]))+ return snapshot.serverOrder.flatMap((id) => {+ const server = byId.get(id)+ if (!server) return []+ return [{+ id: server.id,+ name: server.name,+ discriminator: server.discriminator,+ icon: server.icon,+ initial: avatarInitial(server.name),+ active: false,+ unread: false,+ mentions: 0,+ }]+ })+}++export function structuralSnapshotFolders(snapshot: StructuralSnapshotV1 | null): CommunityFolder[] {+ if (!snapshot) return []+ const byId = new Map(structuralSnapshotServers(snapshot).map((server) => [server.id, server]))+ return snapshot.folders.map((folder, position) => ({+ id: folder.id,+ name: folder.name,+ position,+ servers: folder.serverIds.flatMap((id) => {+ const server = byId.get(id)+ return server ? [{ id, name: server.name, initial: server.initial, icon: server.icon }] : []+ }),+ }))+}++export function structuralSnapshotDirectory(snapshot: StructuralSnapshotV1 | null): ChannelRefDirectory {+ if (!snapshot) return []+ return snapshot.servers.map((server) => ({+ id: server.id,+ name: server.name,+ discriminator: server.discriminator,+ channels: server.channels.map((channel) => ({ id: channel.id, name: channel.name })),+ }))+}diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.tsindex c602b2b5e..c39529175 100644--- a/src/web/src/lib/query-keys.ts+++ b/src/web/src/lib/query-keys.ts@@ -18,6 +18,8 @@ export const communityKeys = {// ── Servers ──────────────────────────────────────────────────────────────servers: () => [...communityKeys.all, "servers"] as const,+ structuralSnapshot: () =>+ [...communityKeys.all, "structural-snapshot"] as const,channelRefDirectory: () =>[...communityKeys.servers(), "channel-ref-directory"] as const,server: (serverId: string) =>diff --git a/src/web/src/lib/query-persister.race.test.ts b/src/web/src/lib/query-persister.race.test.tsnew file mode 100644index 000000000..657225288--- /dev/null+++ b/src/web/src/lib/query-persister.race.test.ts@@ -0,0 +1,59 @@+import "fake-indexeddb/auto"+import { describe, expect, it, vi } from "vitest"+import type { PersistedClient } from "@tanstack/react-query-persist-client"++const controls = vi.hoisted(() => ({+ blockNextSet: false,+ releaseSet: null as (() => void) | null,+ setStarted: null as (() => void) | null,+}))++vi.mock("idb-keyval", async (importOriginal) => {+ const actual = await importOriginal<typeof import("idb-keyval")>()+ return {+ ...actual,+ set: vi.fn(async (...args: Parameters<typeof actual.set>) => {+ if (controls.blockNextSet) {+ controls.blockNextSet = false+ controls.setStarted?.()+ await new Promise<void>((resolve) => {+ controls.releaseSet = resolve+ })+ }+ return actual.set(...args)+ }),+ }+})++import { get } from "idb-keyval"+import { clearPersistedCache, createIdbPersister } from "./query-persister"++describe("createIdbPersister — logout race", () => {+ it("makes clear the final operation after an already-started write", async () => {+ const userId = "u_inflight_logout"+ await clearPersistedCache(userId)+ const stale = createIdbPersister(userId)+ const writeStarted = new Promise<void>((resolve) => {+ controls.setStarted = resolve+ })+ controls.blockNextSet = true++ const client: PersistedClient = {+ timestamp: 1,+ buster: "v1",+ clientState: { mutations: [], queries: [] },+ }+ const pendingWrite = stale.persistClient(client)+ await writeStarted++ // Model QueryProvider retaining a persister from an older client chunk+ // while logout imports a freshly evaluated copy of this module.+ vi.resetModules()+ const { clearPersistedCache: clearFromReloadedModule } = await import("./query-persister")+ const pendingClear = clearFromReloadedModule(userId)+ controls.releaseSet?.()+ await Promise.all([pendingWrite, pendingClear])++ expect(await get(`alook:qc:v1:${userId}:client`)).toBeUndefined()+ })+})diff --git a/src/web/src/lib/query-persister.test.ts b/src/web/src/lib/query-persister.test.tsindex 06d2129f4..b82e7b728 100644--- a/src/web/src/lib/query-persister.test.ts+++ b/src/web/src/lib/query-persister.test.ts@@ -1,6 +1,6 @@import "fake-indexeddb/auto"import { describe, expect, it, beforeEach } from "vitest"-import { get } from "idb-keyval"+import { get, set } from "idb-keyval"import { QueryClient } from "@tanstack/react-query"import type { PersistedClient } from "@tanstack/react-query-persist-client"import { communityKeys } from "@/lib/query-keys"@@ -24,6 +24,10 @@ describe("shouldPersistQueryKey", () => {expect(shouldPersistQueryKey(communityKeys.dmMessages("dm_1"))).toBe(true)})+ it("persists the single structural snapshot query", () => {+ expect(shouldPersistQueryKey(communityKeys.structuralSnapshot())).toBe(true)+ })+it("does NOT persist channel read-state snapshot (refetched on every mount)", () => {expect(shouldPersistQueryKey(communityKeys.channelReadStateSnapshot("ch_1")),@@ -437,4 +441,110 @@ describe("createIdbPersister — user scoping", () => {const bobBlob = await readPersistedBlob("u_bob")expect(bobBlob.timestamp).toBe(2)})++ it("removes the current generation through the persister adapter", async () => {+ const persister = createIdbPersister("u_remove")+ await persister.persistClient({+ timestamp: 4,+ buster: "v1",+ clientState: { mutations: [], queries: [] },+ })++ await persister.removeClient()++ expect(await get("alook:qc:v1:u_remove:client")).toBeUndefined()+ })++ it("blocks a delayed writer created before clear", async () => {+ const stale = createIdbPersister("u_alice")+ await clearPersistedCache("u_alice")+ await stale.persistClient({+ timestamp: 3,+ buster: "v1",+ clientState: { mutations: [], queries: [] },+ })+ expect(await get(`alook:qc:v1:u_alice:client`)).toBeUndefined()+ })+})++describe("createIdbPersister — structural snapshot boundary", () => {+ beforeEach(async () => {+ await clearPersistedCache("u_structural")+ await clearPersistedCache(null)+ })++ function structuralData(accountId: string) {+ return {+ schemaVersion: 1 as const,+ accountId,+ capturedAt: Date.now(),+ serverOrder: ["server-1"],+ folders: [],+ servers: [{+ id: "server-1",+ name: "Server",+ discriminator: "0001",+ icon: null,+ categories: [],+ channels: [{ id: "channel-1", name: "chat", type: "text" as const, categoryId: null }],+ childRouteHints: [],+ }],+ }+ }++ function clientWithStructuralData(data: unknown): PersistedClient {+ const qc = new QueryClient()+ qc.setQueryData(communityKeys.structuralSnapshot(), data)+ return {+ timestamp: Date.now(),+ buster: "v1",+ clientState: {+ mutations: [],+ queries: [{+ queryKey: communityKeys.structuralSnapshot(),+ queryHash: JSON.stringify(communityKeys.structuralSnapshot()),+ state: qc.getQueryState(communityKeys.structuralSnapshot())!,+ }],+ },+ }+ }++ it("keeps a strict same-account snapshot", async () => {+ const persister = createIdbPersister("u_structural")+ const data = structuralData("u_structural")+ await persister.persistClient(clientWithStructuralData(data))+ const blob = await readPersistedBlob("u_structural")+ expect(blob.clientState.queries).toHaveLength(1)+ expect(blob.clientState.queries[0]?.state.data).toEqual(data)+ })++ it("drops wrong-account, anonymous, and unknown-field snapshots", async () => {+ const wrongAccount = createIdbPersister("u_structural")+ await wrongAccount.persistClient(clientWithStructuralData(structuralData("someone-else")))+ expect((await readPersistedBlob("u_structural")).clientState.queries).toHaveLength(0)++ const unknownField = structuralData("u_structural") as ReturnType<typeof structuralData> & { role?: string }+ unknownField.role = "owner"+ await wrongAccount.persistClient(clientWithStructuralData(unknownField))+ expect((await readPersistedBlob("u_structural")).clientState.queries).toHaveLength(0)++ const anonymous = createIdbPersister(null)+ await anonymous.persistClient(clientWithStructuralData(structuralData("u_structural")))+ expect((await readPersistedBlob(null)).clientState.queries).toHaveLength(0)+ })++ it("reapplies the allowlist and account schema to a directly restored blob", async () => {+ const injected = clientWithStructuralData(structuralData("someone-else"))+ const unrelated = new QueryClient()+ unrelated.setQueryData(communityKeys.servers(), { servers: [] })+ injected.clientState.queries.push({+ queryKey: communityKeys.servers(),+ queryHash: JSON.stringify(communityKeys.servers()),+ state: unrelated.getQueryState(communityKeys.servers())!,+ })+ await set("alook:qc:v1:u_structural:client", JSON.stringify(injected))++ const restored = await createIdbPersister("u_structural").restoreClient()+ expect(restored?.clientState.queries).toEqual([])+ })})diff --git a/src/web/src/lib/query-persister.ts b/src/web/src/lib/query-persister.tsindex 3c8c8a0a8..1db020c94 100644--- a/src/web/src/lib/query-persister.ts+++ b/src/web/src/lib/query-persister.ts@@ -5,6 +5,9 @@ import type {} from "@tanstack/react-query-persist-client"import { del, get, set } from "idb-keyval"import type { MessagesPage, Msg } from "@/lib/community/models/message"+import {+ parseStructuralSnapshot,+} from "@/lib/community/structural-snapshot"/*** IDB namespace root. Bumping the tail segment (`v1` → `v2`) invalidates every@@ -38,6 +41,7 @@ export const PERSIST_MAX_AGE_MS = 24 * 60 * 60 * 1000const PERSISTED_KINDS = new Set<string>(["channelMessages","dmMessages",+ "structuralSnapshot",])// Query keys start with `["community", <kind>, ...]` — the first segment is@@ -49,6 +53,9 @@ function keyKindFor(queryKey: readonly unknown[]): string | null {if (!Array.isArray(queryKey) || queryKey.length < 2) return nullif (queryKey[0] !== "community") return nullconst second = queryKey[1]+ if (second === "structural-snapshot" && queryKey.length === 2) {+ return "structuralSnapshot"+ }// Message queries: ["community", "channel", <id>, "messages"] or// ["community", "dm", <id>, "messages"].if (second === "channel" || second === "dm") {@@ -163,14 +170,22 @@ function scrubPage(page: MessagesPage): MessagesPage {* from the persister's `serialize` hook, so the filter is applied every time* TanStack throttles a save.*/-function scrubDehydratedClient(client: PersistedClient): PersistedClient {+function scrubDehydratedClient(+ client: PersistedClient,+ userId: string | null,+ now = Date.now(),+): PersistedClient {const queries: typeof client.clientState.queries = []for (const q of client.clientState.queries) {const kind = keyKindFor(q.queryKey)- if (kind !== "channelMessages" && kind !== "dmMessages") {- queries.push(q)+ if (kind === "structuralSnapshot") {+ if (!userId) continue+ const snapshot = parseStructuralSnapshot(q.state.data, userId, now)+ if (!snapshot) continue+ queries.push({ ...q, state: { ...q.state, data: snapshot } })continue}+ if (kind !== "channelMessages" && kind !== "dmMessages") continueconst data = q.state.data as| { pages: MessagesPage[]; pageParams: unknown[] }| undefined@@ -196,6 +211,45 @@ function blobKeyFor(userId: string | null): string {return `${namespaceFor(userId)}:client`}+type PersistCoordination = {+ generations: Map<string, number>+ operations: Map<string, Promise<void>>+}++// Keep the fence shared across client chunks and dev hot-reloads. QueryProvider+// can retain a persister created by an older module instance while the logout+// surface imports a freshly evaluated one; module-local maps would let those+// two instances race even though they operate on the same IndexedDB key.+const persistGlobal = globalThis as typeof globalThis & {+ __alookQueryPersistCoordinationV1?: PersistCoordination+}+const persistCoordination = persistGlobal.__alookQueryPersistCoordinationV1 ?? {+ generations: new Map<string, number>(),+ operations: new Map<string, Promise<void>>(),+}+persistGlobal.__alookQueryPersistCoordinationV1 = persistCoordination+const persistGenerations = persistCoordination.generations+const persistOperations = persistCoordination.operations++/**+ * Serialize reads, writes, and clears for one account namespace.+ *+ * The generation check rejects work that starts after a logout, but it cannot+ * cancel an IndexedDB write that already passed the check. Keeping the clear+ * behind that in-flight write makes the delete the final operation from the+ * retired generation, while a newly authenticated persister queues after it.+ */+function runPersistOperation<T>(key: string, operation: () => Promise<T>): Promise<T> {+ const previous = persistOperations.get(key) ?? Promise.resolve()+ const result = previous.then(operation, operation)+ const tail = result.then(() => undefined, () => undefined)+ persistOperations.set(key, tail)+ void tail.then(() => {+ if (persistOperations.get(key) === tail) persistOperations.delete(key)+ })+ return result+}+/*** Create an async-storage persister scoped to a specific user id.*@@ -205,25 +259,37 @@ function blobKeyFor(userId: string | null): string {*/export function createIdbPersister(userId: string | null): Persister {const key = blobKeyFor(userId)+ const generation = persistGenerations.get(key) ?? 0return createAsyncStoragePersister({storage: {getItem: async (_k: string) => {- const value = await get<string>(key)- return value ?? null+ return runPersistOperation(key, async () => {+ const value = await get<string>(key)+ return value ?? null+ })},setItem: async (_k: string, value: string) => {- await set(key, value)+ await runPersistOperation(key, async () => {+ if ((persistGenerations.get(key) ?? 0) !== generation) return+ await set(key, value)+ })},removeItem: async (_k: string) => {- await del(key)+ await runPersistOperation(key, async () => {+ if ((persistGenerations.get(key) ?? 0) !== generation) return+ await del(key)+ })},},// Passed to storage under the covers, but our storage adapter ignores the// key argument (we own the namespace). Leaving a stable literal keeps the// persister's internal throttle bookkeeping predictable.key: "alook-query-cache",- serialize: (client) => JSON.stringify(scrubDehydratedClient(client)),- deserialize: (raw) => JSON.parse(raw) as PersistedClient,+ serialize: (client) => JSON.stringify(scrubDehydratedClient(client, userId)),+ deserialize: (raw) => scrubDehydratedClient(+ JSON.parse(raw) as PersistedClient,+ userId,+ ),})}@@ -233,5 +299,7 @@ export function createIdbPersister(userId: string | null): Persister {* history to the next tab.*/export async function clearPersistedCache(userId: string | null): Promise<void> {- await del(blobKeyFor(userId))+ const key = blobKeyFor(userId)+ persistGenerations.set(key, (persistGenerations.get(key) ?? 0) + 1)+ await runPersistOperation(key, async () => del(key))}