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
fix(web): improve community navigation and reconnect recovery (#476)
Genera56556a77a7c
diff --git a/src/web/src/app/c/channels/[serverId]/loading.tsx b/src/web/src/app/c/channels/[serverId]/loading.tsxnew file mode 100644index 000000000..ea87b3bf4--- /dev/null+++ b/src/web/src/app/c/channels/[serverId]/loading.tsx@@ -0,0 +1,5 @@+import { ChannelLoadingFrame } from "@/components/community/channels/channel-loading-frame"++export default function ServerRouteLoading() {+ return <ChannelLoadingFrame />+}diff --git a/src/web/src/app/c/community-shell.identity.test.ts b/src/web/src/app/c/community-shell.identity.test.tsnew file mode 100644index 000000000..8b6d9d8cf--- /dev/null+++ b/src/web/src/app/c/community-shell.identity.test.ts@@ -0,0 +1,64 @@+import { beforeEach, describe, expect, it, vi } from "vitest"+import React, { useState } from "react"+import TestRenderer, { act } from "react-test-renderer"++let activeUser = { id: "user-a", name: "A", email: "[email protected]", avatar: "A" }+let providerInstance = 0+const renderedProviders: Array<{ userId: string | null; instance: number }> = []++vi.mock("./QueryProvider", () => ({+ QueryProvider: ({ children, userId }: { children: React.ReactNode; userId: string | null }) => {+ const [instance] = useState(() => {+ providerInstance += 1+ return providerInstance+ })+ renderedProviders.push({ userId, instance })+ return children+ },+}))+vi.mock("@/contexts/community/current-user", () => ({+ CurrentUserProvider: ({ children }: { children: React.ReactNode }) => children,+ useCurrentUser: () => activeUser,+ useSetCurrentUser: () => vi.fn(),+}))+vi.mock("@/hooks/community/use-community-ws", () => ({ useCommunityWs: vi.fn() }))+vi.mock("@/lib/api/client", () => ({ apiFetch: vi.fn(() => new Promise(() => undefined)) }))+vi.mock("@/components/perf/perf-trace-bootstrap", () => ({ PerfTraceBootstrap: () => null }))+vi.mock("@/components/community/onboarding/community-onboarding-guide", () => ({+ CommunityOnboardingGuide: () => null,+}))++import { CommunityShell } from "./community-shell"++beforeEach(() => {+ activeUser = { id: "user-a", name: "A", email: "[email protected]", avatar: "A" }+ providerInstance = 0+ renderedProviders.length = 0+})++describe("CommunityShell identity boundary", () => {+ it("remounts the in-memory query client boundary when the signed-in user changes", () => {+ let renderer!: TestRenderer.ReactTestRenderer+ act(() => {+ renderer = TestRenderer.create(React.createElement(+ CommunityShell,+ { currentUser: activeUser },+ React.createElement("span", null, "content"),+ ))+ })+ const userAInstance = renderedProviders.at(-1)?.instance++ activeUser = { id: "user-b", name: "B", email: "[email protected]", avatar: "B" }+ act(() => {+ renderer.update(React.createElement(+ CommunityShell,+ { currentUser: activeUser },+ React.createElement("span", null, "content"),+ ))+ })++ expect(renderedProviders.at(-1)).toEqual({ userId: "user-b", instance: 2 })+ expect(userAInstance).toBe(1)+ renderer.unmount()+ })+})diff --git a/src/web/src/app/c/community-shell.tsx b/src/web/src/app/c/community-shell.tsxindex 96f3820e7..e5b271f77 100644--- a/src/web/src/app/c/community-shell.tsx+++ b/src/web/src/app/c/community-shell.tsx@@ -34,7 +34,7 @@ export function CommunityShell({children: ReactNode}) {return (- <QueryProvider userId={currentUser.id}>+ <QueryProvider key={currentUser.id} userId={currentUser.id}><CurrentUserProvider initialUser={currentUser}><CommunityBootstrap>{children}</CommunityBootstrap></CurrentUserProvider>diff --git a/src/web/src/app/c/me/loading.tsx b/src/web/src/app/c/me/loading.tsxnew file mode 100644index 000000000..6125f5c95--- /dev/null+++ b/src/web/src/app/c/me/loading.tsx@@ -0,0 +1,5 @@+import { ChannelLoadingFrame } from "@/components/community/channels/channel-loading-frame"++export default function MeRouteLoading() {+ return <ChannelLoadingFrame />+}diff --git a/src/web/src/components/community/channels/channel-loading-frame.tsx b/src/web/src/components/community/channels/channel-loading-frame.tsxnew file mode 100644index 000000000..4fe4303f2--- /dev/null+++ b/src/web/src/components/community/channels/channel-loading-frame.tsx@@ -0,0 +1,42 @@+import { Skeleton } from "@/components/ui/skeleton"++export function ChannelLoadingFrame() {+ return (+ <div+ aria-busy="true"+ aria-label="Loading conversation"+ className="flex min-h-0 min-w-0 flex-1 flex-col"+ >+ <header className="flex h-12 shrink-0 items-center gap-2 border-b border-border/40 px-3">+ <Skeleton className="size-4 rounded" />+ <Skeleton className="h-4 w-40 rounded" />+ <div className="ml-auto flex items-center gap-2">+ <Skeleton className="size-7 rounded-md" />+ <Skeleton className="size-7 rounded-md" />+ <Skeleton className="size-7 rounded-md" />+ </div>+ </header>+ <main className="flex min-h-0 min-w-0 flex-1 flex-col px-3 py-4">+ <div className="flex flex-1 flex-col justify-end gap-4">+ <MessageRowSkeleton width="w-2/3" />+ <MessageRowSkeleton width="w-4/5" />+ <MessageRowSkeleton width="w-1/2" />+ </div>+ <Skeleton className="mt-4 h-12 w-full shrink-0 rounded-xl" />+ </main>+ <span className="sr-only">Loading conversation</span>+ </div>+ )+}++function MessageRowSkeleton({ width }: { width: string }) {+ return (+ <div className="flex items-start gap-3">+ <Skeleton className="size-9 shrink-0 rounded-full" />+ <div className="flex min-w-0 flex-1 flex-col gap-2">+ <Skeleton className="h-3.5 w-28 rounded" />+ <Skeleton className={`h-3.5 rounded ${width}`} />+ </div>+ </div>+ )+}diff --git a/src/web/src/components/community/shell/shell-frame-view.test.ts b/src/web/src/components/community/shell/shell-frame-view.test.tsindex b5ee8dd7a..65c5ade00 100644--- a/src/web/src/components/community/shell/shell-frame-view.test.ts+++ b/src/web/src/components/community/shell/shell-frame-view.test.ts@@ -36,6 +36,9 @@ vi.mock("./community-inbox-popover", () => ({vi.mock("./shell-frame-overlays", () => ({ShellFrameOverlays: (props: Record<string, unknown>) => createElement("shell-overlays", props),}))+vi.mock("@/components/community/channels/channel-loading-frame", () => ({+ ChannelLoadingFrame: () => createElement("channel-loading-frame"),+}))const rail = { railProps: { activeServerId: "s1" } } as neverconst profile = {@@ -76,6 +79,7 @@ describe("ShellFrameView", () => {renderer = TestRenderer.create(createElement(ShellFrameView, {breakpoint: "desktop",mobileZone: "messages",+ navigationPending: false,sidebar,cancelPendingNavigation: vi.fn(),rail,@@ -124,6 +128,7 @@ describe("ShellFrameView", () => {renderer = TestRenderer.create(createElement(ShellFrameView, {breakpoint: "mobile",mobileZone: "nav",+ navigationPending: false,sidebar,cancelPendingNavigation: vi.fn(),rail,@@ -142,6 +147,7 @@ describe("ShellFrameView", () => {renderer.update(createElement(ShellFrameView, {breakpoint: "mobile",mobileZone: "messages",+ navigationPending: false,sidebar,cancelPendingNavigation: vi.fn(),rail,@@ -159,6 +165,7 @@ describe("ShellFrameView", () => {const sidebar = vi.fn(() => createElement("sidebar-content"))const common = {mobileZone: "nav" as const,+ navigationPending: false,sidebar,cancelPendingNavigation: vi.fn(),rail,@@ -196,4 +203,45 @@ describe("ShellFrameView", () => {await act(async () => renderer.unmount())expect(mocks.disconnect).toHaveBeenCalledTimes(2)})++ it("replaces committed content with immediate pending feedback in every shell zone", async () => {+ const sidebar = vi.fn(() => createElement("sidebar-content"))+ const common = {+ sidebar,+ cancelPendingNavigation: vi.fn(),+ navigationPending: true,+ rail,+ profile,+ inbox,+ }+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(createElement(+ ShellFrameView,+ { ...common, breakpoint: "desktop", mobileZone: "messages" },+ createElement("main-content"),+ ), { createNodeMock: () => ({ offsetWidth: 240 }) })+ })+ expect(renderer.root.findAllByType("channel-loading-frame")).toHaveLength(1)+ expect(renderer.root.findAllByType("main-content")).toHaveLength(0)++ await act(async () => {+ renderer.update(createElement(+ ShellFrameView,+ { ...common, breakpoint: "mobile", mobileZone: "nav" },+ createElement("main-content"),+ ))+ })+ expect(renderer.root.findAllByType("channel-loading-frame")).toHaveLength(1)++ await act(async () => {+ renderer.update(createElement(+ ShellFrameView,+ { ...common, breakpoint: "mobile", mobileZone: "messages" },+ createElement("main-content"),+ ))+ })+ expect(renderer.root.findAllByType("channel-loading-frame")).toHaveLength(1)+ expect(renderer.root.findAllByType("main-content")).toHaveLength(0)+ })})diff --git a/src/web/src/components/community/shell/shell-frame-view.tsx b/src/web/src/components/community/shell/shell-frame-view.tsxindex 9d5f5ec70..5f7f7718d 100644--- a/src/web/src/components/community/shell/shell-frame-view.tsx+++ b/src/web/src/components/community/shell/shell-frame-view.tsx@@ -4,6 +4,7 @@ import { useEffect, useRef, useState } from "react"import { useDefaultLayout } from "react-resizable-panels"import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from "@/components/ui/resizable"import { AppSurface } from "@/components/ui/app-surface"+import { ChannelLoadingFrame } from "@/components/community/channels/channel-loading-frame"import { Shell } from "./shell"import { ServerRail } from "./server-rail"import { UserBar } from "./user-bar"@@ -24,6 +25,7 @@ type Props = Pick<ShellFrameProps, "sidebar" | "children" | "extraDialogs"> & {breakpoint: BreakpointmobileZone: MobileZonecancelPendingNavigation: () => void+ navigationPending: booleanrail: ReturnType<typeof useShellRailController>profile: ReturnType<typeof useShellProfileController>inbox: ReturnType<typeof useShellInboxController>@@ -36,6 +38,7 @@ export function ShellFrameView({children,extraDialogs,cancelPendingNavigation,+ navigationPending,rail,profile,inbox,@@ -89,7 +92,7 @@ export function ShellFrameView({defaultSize="76%"className="flex min-w-0 flex-col bg-background">- {children}+ {navigationPending ? <ChannelLoadingFrame /> : children}</ResizablePanel></ResizablePanelGroup></AppSurface>@@ -147,7 +150,12 @@ export function ShellFrameView({)}{mobileZone === "messages" && (<div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background">- {children}+ {navigationPending ? <ChannelLoadingFrame /> : children}+ </div>+ )}+ {mobileZone === "nav" && navigationPending && (+ <div className="absolute inset-0 z-20 flex bg-background">+ <ChannelLoadingFrame /></div>)}<ShellFrameOverlaysdiff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsxindex 50f3c5a2f..97859a2f4 100644--- a/src/web/src/components/community/shell/shell-frame.tsx+++ b/src/web/src/components/community/shell/shell-frame.tsx@@ -97,6 +97,7 @@ export function ShellFrame(props: ShellFrameProps) {sidebar={sidebar}extraDialogs={extraDialogs}cancelPendingNavigation={rail.cancelPendingNavigation}+ navigationPending={rail.navigationPending}rail={rail}profile={profile}inbox={inbox}diff --git a/src/web/src/components/community/shell/use-shell-profile-controller.test.ts b/src/web/src/components/community/shell/use-shell-profile-controller.test.tsindex 4790cfc41..1584ab47b 100644--- a/src/web/src/components/community/shell/use-shell-profile-controller.test.ts+++ b/src/web/src/components/community/shell/use-shell-profile-controller.test.ts@@ -108,7 +108,7 @@ async function renderController() {prefetch: vi.fn(),}const cancelPendingNavigation = vi.fn()- const queryClient = { fetchQuery: mocks.fetchQuery }+ const queryClient = { fetchQuery: mocks.fetchQuery, clear: vi.fn() }let current!: Resultlet renderer!: TestRenderer.ReactTestRendererawait act(async () => {@@ -123,7 +123,7 @@ async function renderController() {onResult: (result) => { current = result },}))})- return { get current() { return current }, renderer, router, pushed, cancelPendingNavigation }+ return { get current() { return current }, renderer, router, pushed, cancelPendingNavigation, queryClient }}function deferred<T>() {@@ -280,11 +280,12 @@ describe("useShellProfileController", () => {mocks.communityReset.mockImplementation(() => { order.push("community") })mocks.wsReset.mockImplementation(() => { order.push("ws") })mocks.streamReset.mockImplementation(() => { order.push("stream") })+ hook.queryClient.clear.mockImplementation(() => { order.push("query") })mocks.clearCache.mockImplementation(async () => { order.push("cache"); throw new Error("cache") })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", "cache", "signOut", "push:/sign-in"])+ expect(order).toEqual(["cancel", "community", "ws", "stream", "query", "cache", "signOut", "push:/sign-in"])order.length = 0mocks.clearCache.mockResolvedValue(undefined)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 cd22c25a6..592d783cf 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@@ -250,6 +250,7 @@ export function useShellProfileController({useCommunityStore.getState().reset()useCommunityWsStore.getState().reset()useMessageStreamStore.getState().resetAll()+ queryClient.clear()await clearPersistedCache(currentUser.id).catch(() => {})await signOut()router.push("/sign-in")diff --git a/src/web/src/components/community/shell/use-shell-rail-controller.test.ts b/src/web/src/components/community/shell/use-shell-rail-controller.test.tsindex c7495a597..ed3e62ae5 100644--- a/src/web/src/components/community/shell/use-shell-rail-controller.test.ts+++ b/src/web/src/components/community/shell/use-shell-rail-controller.test.ts@@ -69,12 +69,6 @@ function Capture({ options, onResult }: {return null}-function deferred() {- let resolve!: () => void- const promise = new Promise<void>((done) => { resolve = done })- return { promise, resolve }-}-async function renderController(overrides: Record<string, unknown> = {}) {const pushed: string[] = []const replaced: string[] = []@@ -132,84 +126,53 @@ describe("useShellRailController", () => {}})- it("commits only the latest deferred server navigation", async () => {- const first = deferred()- const second = deferred()+ it("commits cold server navigation synchronously without waiting for detail", async () => {const hook = await renderController()- hook.queryClient.fetchQuery.mockImplementation(({ queryKey }: { queryKey: unknown[] }) => {- const id = String(queryKey.at(-1))- return id === "s1" ? first.promise : second.promise- })+ expect(hook.current.navigationPending).toBe(false)await act(async () => {hook.current.railProps.onServerNavigate("s1")hook.current.railProps.onServerNavigate("s2")})- hook.cache.set("s2", { categories: [{ channels: [{ id: "c2", pending: false }] }] })- await act(async () => second.resolve())- hook.cache.set("s1", { categories: [{ channels: [{ id: "c1", pending: false }] }] })- await act(async () => first.resolve())- expect(hook.pushed).toEqual(["/c/channels/s2/c2"])+ expect(hook.pushed).toEqual(["/c/channels/s2"])+ expect(hook.current.navigationPending).toBe(true)+ expect(hook.queryClient.fetchQuery).not.toHaveBeenCalled()expect(mocks.markSwitch).toHaveBeenNthCalledWith(1, "server", "s1")expect(mocks.markSwitch).toHaveBeenNthCalledWith(2, "server", "s2")- })-- it("supersedes pending navigation on URL changes and direct channel navigation", async () => {- const pathnamePending = deferred()- const channelPending = deferred()- const hook = await renderController()- hook.queryClient.fetchQuery.mockReturnValueOnce(pathnamePending.promise)- await act(async () => hook.current.railProps.onServerNavigate("s2"))- hook.options.currentHref = "/c/me"+ hook.options.currentHref = "/c/channels/s2"await hook.rerender()- hook.cache.set("s2", { categories: [{ channels: [{ id: "late", pending: false }] }] })- await act(async () => pathnamePending.resolve())- expect(hook.pushed).toEqual([])+ expect(hook.current.navigationPending).toBe(false)+ })- hook.cache.delete("s2")- hook.queryClient.fetchQuery.mockReturnValueOnce(channelPending.promise)+ it("does not leave deferred server work that can overwrite a direct channel navigation", async () => {+ const hook = await renderController()await act(async () => {hook.current.railProps.onServerNavigate("s2")hook.current.navigate("s1", "c1")})- hook.cache.set("s2", { categories: [{ channels: [{ id: "late-again", pending: false }] }] })- await act(async () => channelPending.resolve())- expect(hook.pushed).toEqual(["/c/channels/s1/c1"])+ expect(hook.pushed).toEqual(["/c/channels/s2", "/c/channels/s1/c1"])+ expect(hook.queryClient.fetchQuery).not.toHaveBeenCalled()expect(mocks.markSwitch).toHaveBeenLastCalledWith("channel", "c1")})- it("cancels pending navigation for settings and invite actions", async () => {- const pending = deferred()- const invitePending = deferred()+ it("keeps settings and invite actions synchronous and scoped to their target", async () => {const openSettings = vi.fn()const openInvite = vi.fn()const hook = await renderController({onOpenActiveServerSettings: openSettings,onOpenActiveServerInvite: openInvite,})- hook.queryClient.fetchQuery.mockReturnValue(pending.promise)-await act(async () => {- hook.current.railProps.onServerNavigate("s2")hook.current.railProps.onOpenSettings("s1")})expect(openSettings).toHaveBeenCalledTimes(1)expect(hook.pushed).toEqual([])- hook.cache.set("s2", { categories: [{ channels: [{ id: "late", pending: false }] }] })- await act(async () => pending.resolve())- expect(hook.pushed).toEqual([])-- hook.cache.delete("s2")- hook.queryClient.fetchQuery.mockReturnValueOnce(invitePending.promise)await act(async () => {- hook.current.railProps.onServerNavigate("s2")hook.current.railProps.onOpenInvitePopover("s1")})expect(openInvite).toHaveBeenCalledTimes(1)- hook.cache.set("s2", { categories: [{ channels: [{ id: "invite-late", pending: false }] }] })- await act(async () => invitePending.resolve())expect(hook.pushed).toEqual([])await act(async () => hook.current.railProps.onOpenSettings("s2"))await act(async () => hook.current.railProps.onOpenInvitePopover("s2"))@@ -226,19 +189,15 @@ describe("useShellRailController", () => {expect(hook.pushed).toEqual([])})- it("cancels pending navigation before committing Home", async () => {- const pending = deferred()+ it("commits Home immediately after a cold server intent", async () => {const hook = await renderController()- hook.queryClient.fetchQuery.mockReturnValue(pending.promise)await act(async () => {hook.current.railProps.onServerNavigate("s2")hook.current.railProps.onHome()})- expect(hook.pushed).toEqual(["/c/me"])- hook.cache.set("s2", { categories: [{ channels: [{ id: "late", pending: false }] }] })- await act(async () => pending.resolve())- expect(hook.pushed).toEqual(["/c/me"])+ expect(hook.pushed).toEqual(["/c/channels/s2", "/c/me"])+ expect(hook.queryClient.fetchQuery).not.toHaveBeenCalled()})it("adds the nav pane on mobile and skips an exact current rail target", async () => {@@ -277,7 +236,10 @@ describe("useShellRailController", () => {hook.cache.set(id, { categories: [{ channels: [{ id: "fetched", pending: false }] }] })})await act(async () => hook.current.railProps.onServerNavigate("s2"))- expect(hook.pushed).toContain("/c/channels/s2/fetched")+ expect(hook.pushed).toContain("/c/channels/s2")+ expect(hook.queryClient.fetchQuery).not.toHaveBeenCalled()+ await act(async () => hook.current.railProps.onServerPrefetch("s2"))+ expect(hook.prefetched).toContain("/c/channels/s2/fetched")expect(hook.queryClient.fetchQuery).toHaveBeenLastCalledWith(expect.objectContaining({queryKey: expect.any(Array),queryFn: expect.any(Function),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 1cd88e620..f29b324de 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@@ -1,6 +1,6 @@"use client"-import { useCallback, useEffect, useMemo, useRef } from "react"+import { useCallback, useEffect, useMemo, useRef, useState } from "react"import { toast } from "sonner"import { toastApiError } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"@@ -21,7 +21,6 @@ import {import { getLastChannel, pickServerLandingHref } from "@/lib/community/last-channel"import { getLastMeLeaf, pickMeLandingLocation } from "@/lib/community/last-me-location"import {- commitLatestNavigationIntent,createNavigationIntentGate,supersedeNavigationIntent,} from "@/lib/community/navigation-intent"@@ -81,11 +80,13 @@ export function useShellRailController({)const navigationGateRef = useRef(createNavigationIntentGate())+ const [navigationPending, setNavigationPending] = useState(false)const cancelPendingNavigation = useCallback(() => {supersedeNavigationIntent(navigationGateRef.current)}, [])useEffect(() => {cancelPendingNavigation()+ setNavigationPending(false)}, [cancelPendingNavigation, currentHref])const serverDestination = useCallback((id: string) => {@@ -115,17 +116,16 @@ export function useShellRailController({withMobileZone(destination, breakpoint === "mobile" ? mobileZone : "messages"),[breakpoint])const pushIfChanged = useCallback((destination: string) => {- if (destination !== currentHref) router.push(destination)+ if (destination === currentHref) return+ setNavigationPending(true)+ router.push(destination)}, [currentHref, router])const onServerNavigate = useCallback((id: string) => {markSwitch("server", id)- void commitLatestNavigationIntent(- navigationGateRef.current,- () => resolveServerDestination(id),- (destination) => pushIfChanged(paneHref(destination, "nav")),- )- }, [paneHref, pushIfChanged, resolveServerDestination])+ cancelPendingNavigation()+ pushIfChanged(paneHref(serverDestination(id), "nav"))+ }, [cancelPendingNavigation, paneHref, pushIfChanged, serverDestination])const onHome = useCallback(() => {cancelPendingNavigation()pushIfChanged(paneHref(pickMeLandingLocation(getLastMeLeaf()), "nav"))@@ -232,12 +232,9 @@ export function useShellRailController({pushIfChanged(paneHref(`/c/channels/${serverId}/${channelId}`, "messages"))return}- void commitLatestNavigationIntent(- navigationGateRef.current,- () => resolveServerDestination(serverId),- (destination) => pushIfChanged(paneHref(destination, "messages")),- )- }, [cancelPendingNavigation, paneHref, pushIfChanged, resolveServerDestination])+ cancelPendingNavigation()+ pushIfChanged(paneHref(serverDestination(serverId), "messages"))+ }, [cancelPendingNavigation, paneHref, pushIfChanged, serverDestination])return {railProps: {@@ -262,5 +259,6 @@ export function useShellRailController({},navigate,cancelPendingNavigation,+ navigationPending,}}diff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.test.tsindex 5a826e23f..49c3abe97 100644--- a/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts@@ -5,6 +5,7 @@ import {QueryObserver,} from "@tanstack/react-query"import { communityKeys } from "@/lib/query-keys"+import { ApiError } from "@/lib/errors"import { reconcileFocusedMessageQueries } from "./reconnect-messages"const apiFetchMock = vi.hoisted(() => vi.fn())@@ -81,6 +82,75 @@ beforeEach(() => {})describe("focused message reconnect catch-up", () => {+ it("keeps the painted message cache visible while reconnect reconciliation is in flight", async () => {+ const queryClient = new QueryClient()+ const queryKey = communityKeys.channelMessages("ch_visible")+ const { unsubscribe } = seedActiveQuery(queryClient, queryKey)+ let resolveRefresh!: (page: {+ messages: Array<Record<string, unknown>>+ hasMore: boolean+ cursor: string+ latestSeq: number+ }) => void+ apiFetchMock.mockReturnValueOnce(new Promise((resolve) => {+ resolveRefresh = resolve+ }))++ const reconciliation = reconcileFocusedMessageQueries(+ queryClient,+ "channel",+ "ch_visible",+ )+ await vi.waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())++ expect(queryClient.getQueryData<{+ pages: Array<{ messages: Array<{ id: string }> }>+ }>(queryKey)?.pages.flatMap((page) => page.messages.map((message) => message.id))).toEqual([+ "m_2",+ "m_1",+ ])++ resolveRefresh({+ messages: [{+ id: "m_2",+ type: "chat",+ seq: 2,+ createdAt: "2026-08-15T00:00:02.000Z",+ }],+ hasMore: true,+ cursor: "older-2",+ latestSeq: 2,+ })+ await reconciliation+ unsubscribe()+ })++ it("evicts a focused scope only after an authoritative access denial", async () => {+ const queryClient = new QueryClient()+ const queryKey = communityKeys.channelMessages("ch_denied")+ const { unsubscribe } = seedActiveQuery(queryClient, queryKey)+ apiFetchMock.mockRejectedValueOnce(new ApiError("forbidden", 403))++ await reconcileFocusedMessageQueries(queryClient, "channel", "ch_denied")++ expect(queryClient.getQueryData(queryKey)).toBeUndefined()+ unsubscribe()+ })++ it("retains the focused scope on transient reconnect failure", async () => {+ const queryClient = new QueryClient()+ const queryKey = communityKeys.channelMessages("ch_offline")+ const { unsubscribe } = seedActiveQuery(queryClient, queryKey)+ apiFetchMock.mockRejectedValueOnce(new ApiError("unavailable", 503))++ await expect(+ reconcileFocusedMessageQueries(queryClient, "channel", "ch_offline"),+ ).rejects.toThrow("focused messages failed")++ expect(queryClient.getQueryData(queryKey)).toBeDefined()+ unsubscribe()+ })+it("cancels and replays an in-flight older-page fetch so neither side overwrites the other", async () => {const queryClient = new QueryClient()const queryKey = communityKeys.channelMessages("ch_race")diff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.tsindex de904a003..0b168c437 100644--- a/src/web/src/hooks/community/community-ws/reconnect-messages.ts+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.ts@@ -1,6 +1,8 @@import type { InfiniteData, QueryClient, QueryKey } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"+import { ApiError } from "@/lib/errors"import { communityKeys } from "@/lib/query-keys"+import { useMessageStreamStore } from "@/stores/community/message-stream"import type {MessagesPage,MessagesPageParam,@@ -18,6 +20,27 @@ type WarmReconnectWindow = {const MAX_CATCH_UP_PAGES = 8+function isDefinitiveAccessDenial(error: unknown): boolean {+ return error instanceof ApiError && (error.status === 403 || error.status === 404)+}++function clearDeniedMessageScope(+ queryClient: QueryClient,+ kind: "channel" | "dm",+ scopeId: string,+) {+ useMessageStreamStore.getState().removeScope(+ kind === "channel"+ ? { kind, id: scopeId, serverId: "" }+ : { kind, id: scopeId },+ )+ queryClient.removeQueries({+ queryKey: kind === "channel"+ ? communityKeys.channelMessages(scopeId)+ : communityKeys.dmMessages(scopeId),+ })+}+function isMessageCache(value: unknown): value is MessageCache {if (!value || typeof value !== "object") return falseconst candidate = value as Partial<MessageCache>@@ -209,19 +232,16 @@ export async function reconcileFocusedMessageQueries({ revert: true, silent: true },)- const window = warmReconnectWindow(query.queryKey, query.state.data)- if (!window) {- // There is no painted history to protect. Delegate recovery to the- // query's canonical queryFn so cold/failed active screens do not remain- // stuck after `refetchOnReconnect` is intentionally disabled.- await queryClient.refetchQueries(- { queryKey: query.queryKey, exact: true, type: "active" },- { throwOnError: true },- )- return- }-+ let accessDenied = falsetry {+ const window = warmReconnectWindow(query.queryKey, query.state.data)+ if (!window) {+ await queryClient.refetchQueries(+ { queryKey: query.queryKey, exact: true, type: "active" },+ { throwOnError: true },+ )+ return+ }const refreshed = await fetchCurrentWindow(scopeId,window.pageParam,@@ -236,8 +256,12 @@ export async function reconcileFocusedMessageQueries(? mergeReconciledPages(current, refreshed, catchUp): current))+ } catch (error) {+ if (!isDefinitiveAccessDenial(error)) throw error+ accessDenied = true+ clearDeniedMessageScope(queryClient, kind, scopeId)} finally {- if (pendingDirection) {+ if (pendingDirection && !accessDenied) {await query.fetch(undefined, {meta: { fetchMore: { direction: pendingDirection } },})diff --git a/src/web/src/hooks/community/community-ws/reconnect.test.ts b/src/web/src/hooks/community/community-ws/reconnect.test.tsindex ddd383313..b4af15178 100644--- a/src/web/src/hooks/community/community-ws/reconnect.test.ts+++ b/src/web/src/hooks/community/community-ws/reconnect.test.ts@@ -26,6 +26,10 @@ vi.mock("@/lib/analytics", async () => {beforeEach(resetCommunityWsHarness)afterEach(cleanupCommunityWsHarness)+async function flushMicrotasks(iterations = 12) {+ for (let index = 0; index < iterations; index += 1) await Promise.resolve()+}+describe("useCommunityWs — resyncs machines on WS reconnect", () => {it("invalidates communityKeys.machines() when the captured onReconnect fires", async () => {await mountHook()@@ -167,7 +171,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {).toBe(true)})- it("drops every inactive retained/meta/hint access result before reconnect validation", async () => {+ it("keeps inactive retained/meta/hint data painted while marking it stale", async () => {await mountHook()const { useCommunityStore } = await import("@/stores/community")useCommunityStore.getState().setCurrentServerId("srv_open")@@ -190,15 +194,18 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {await capturedOnReconnect!({ reconnectDurationMs: 0 })- expect(capturedQueryClient.getQueriesData({- queryKey: communityKeys.forumSidebarRetainedRoot("srv_open"),- })).toEqual([])- expect(capturedQueryClient.getQueriesData({- queryKey: communityKeys.channelMetaRoot("srv_open"),- })).toEqual([])- expect(capturedQueryClient.getQueriesData({- queryKey: communityKeys.forumOpenerHintRoot("srv_open"),- })).toEqual([])+ expect(capturedQueryClient.getQueryData(+ communityKeys.forumSidebarRetained("srv_open", "post-a"),+ )).toEqual({ id: "post-a" })+ expect(capturedQueryClient.getQueryData(+ communityKeys.channelMeta("srv_open", "post-a"),+ )).toEqual({ id: "post-a", verifiedEpoch: 0 })+ expect(capturedQueryClient.getQueryData(+ communityKeys.forumOpenerHint("srv_open", "opener-a"),+ )).toEqual({ id: "opener-a", content: "private title" })+ expect(capturedQueryClient.getQueryState(+ communityKeys.channelMeta("srv_open", "post-a"),+ )?.isInvalidated).toBe(true)})it("reconciles the focused DM's messages on reconnect, but NOT its read-state snapshot", async () => {@@ -296,18 +303,15 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {]) {expect(calls).toContainEqual({ queryKey, exact: true, refetchType: "active" })}- expect(capturedQueryClient.getQueryState(+ for (const queryKey of [communityKeys.forumSidebarRetained(serverId, "child"),- )).toBeUndefined()- expect(capturedQueryClient.getQueryState(communityKeys.channelMeta(serverId, "child"),- )).toBeUndefined()- expect(capturedQueryClient.getQueryState(communityKeys.forumOpenerHint(serverId, "opener"),- )).toBeUndefined()- expect(capturedQueryClient.getQueryState(communityKeys.forumSidebarUnreadFallbacks(serverId),- )).toBeUndefined()+ ]) {+ expect(capturedQueryClient.getQueryData(queryKey)).toEqual({})+ expect(capturedQueryClient.getQueryState(queryKey)?.isInvalidated).toBe(true)+ }}expect(calls.some(({ queryKey }) => queryKey?.includes("__none__"))).toBe(false)expect(calls.some(({ queryKey }) => queryKey?.includes("srv_ghost"))).toBe(false)@@ -403,6 +407,72 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {expect(order.indexOf("authoritative-invalidate")).toBeGreaterThan(1)})+ it("waits for focused route reconciliation before starting background domains", async () => {+ const { reconcileCommunityWsReconnect } = await import("./reconnect")+ const { useCommunityStore } = await import("@/stores/community")+ useCommunityStore.getState().subscribe({ channelId: "ch_priority" })+ let releaseMembers!: () => void+ let releaseAddable!: () => void+ const members = new Promise<void>((resolve) => { releaseMembers = resolve })+ const addable = new Promise<void>((resolve) => { releaseAddable = resolve })+ const started: string[] = []+ const originalInvalidate = capturedQueryClient.invalidateQueries.bind(capturedQueryClient)+ vi.spyOn(capturedQueryClient, "invalidateQueries").mockImplementation((filters, options) => {+ const key = JSON.stringify(filters.queryKey)+ started.push(key)+ if (key === JSON.stringify(communityKeys.channelMembers("ch_priority"))) return members+ if (key === JSON.stringify(communityKeys.channelAddableMembers("ch_priority"))) return addable+ return originalInvalidate(filters, options)+ })++ const work = reconcileCommunityWsReconnect(capturedQueryClient)+ await flushMicrotasks()+ expect(started).toContain(JSON.stringify(communityKeys.channelMembers("ch_priority")))+ expect(started).not.toContain(JSON.stringify(communityKeys.inbox()))++ releaseMembers()+ releaseAddable()+ await work+ expect(started).toContain(JSON.stringify(communityKeys.inbox()))+ })++ it("limits background reconciliation to three policies at a time", async () => {+ const { reconcileCommunityWsReconnect } = await import("./reconnect")+ const gates = new Map<string, { promise: Promise<void>; resolve: () => void }>()+ const started: string[] = []+ vi.spyOn(capturedQueryClient, "invalidateQueries").mockImplementation((filters) => {+ const key = JSON.stringify(filters.queryKey)+ started.push(key)+ let resolve!: () => void+ const promise = new Promise<void>((done) => { resolve = done })+ gates.set(key, { promise, resolve })+ return promise+ })++ const work = reconcileCommunityWsReconnect(capturedQueryClient)+ await flushMicrotasks()+ expect(started).toEqual(expect.arrayContaining([+ JSON.stringify(communityKeys.inbox()),+ JSON.stringify(communityKeys.dms()),+ JSON.stringify(communityKeys.friends()),+ JSON.stringify(communityKeys.servers()),+ ]))+ expect(started).not.toContain(JSON.stringify(communityKeys.machines()))+ expect(started).not.toContain(JSON.stringify([...communityKeys.all, "bot"]))++ gates.get(JSON.stringify(communityKeys.friends()))!.resolve()+ await flushMicrotasks()+ expect(started).toContain(JSON.stringify(communityKeys.machines()))+ expect(started).not.toContain(JSON.stringify([...communityKeys.all, "bot"]))++ gates.get(JSON.stringify(communityKeys.machines()))!.resolve()+ await flushMicrotasks()+ expect(started).toContain(JSON.stringify([...communityKeys.all, "bot"]))++ for (const gate of gates.values()) gate.resolve()+ await work+ })+it("refetches an active focused addable-members picker after a socket gap", async () => {const { reconcileCommunityWsReconnect } = await import("./reconnect")const { useCommunityStore } = await import("@/stores/community")@@ -482,12 +552,14 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {expect(queryClient.getQueryData(queryKey)).toMatchObject({ version: 2 })expect(fetches.get(JSON.stringify(queryKey))).toBe(2)}- expect(queryClient.getQueriesData({- queryKey: communityKeys.forumSidebarRetainedRoot("srv_b"),- })).toEqual([])- expect(queryClient.getQueriesData({ queryKey: communityKeys.channelMetaRoot("srv_b") })).toEqual([])- expect(queryClient.getQueriesData({ queryKey: communityKeys.forumOpenerHintRoot("srv_b") })).toEqual([])- expect(queryClient.getQueryState(communityKeys.forumSidebarUnreadFallbacks("srv_b"))).toBeUndefined()+ for (const queryKey of [+ communityKeys.forumSidebarRetained("srv_b", "private-child"),+ communityKeys.channelMeta("srv_b", "private-child"),+ communityKeys.forumOpenerHint("srv_b", "private-opener"),+ communityKeys.forumSidebarUnreadFallbacks("srv_b"),+ ]) {+ expect(queryClient.getQueryState(queryKey)?.isInvalidated).toBe(true)+ }unsubscribes.forEach((unsubscribe) => unsubscribe())queryClient.clear()})diff --git a/src/web/src/hooks/community/community-ws/reconnect.ts b/src/web/src/hooks/community/community-ws/reconnect.tsindex 070cd8e0c..e70e3f447 100644--- a/src/web/src/hooks/community/community-ws/reconnect.ts+++ b/src/web/src/hooks/community/community-ws/reconnect.ts@@ -12,6 +12,22 @@ import {type CommunityWsReconcilePolicy,} from "@/lib/analytics"+const RESET_POLICIES = new Set<CommunityWsReconcilePolicy>([+ "presence-overlay",+ "status-overlay",+ "ephemeral-typing",+])++const FOCUSED_POLICIES = new Set<CommunityWsReconcilePolicy>([+ "focused-messages",+ "focused-opener",+ "focused-channel-roster",+ "focused-pins",+ "focused-threads",+])++const BACKGROUND_RECONCILE_CONCURRENCY = 3+const EXACT_SERVER_QUERY_FAMILIES = new Set(["forum-sidebar-base","forum-sidebar-unread-fallbacks",@@ -69,11 +85,13 @@ function cachedServerIds(queryKeys: readonly QueryKey[]) {}async function reconcileCachedServer(queryClient: QueryClient, serverId: string) {- queryClient.removeQueries({+ const derivedRevalidation = queryClient.invalidateQueries({predicate: (query) => isDerivedServerAccessQueryKey(query.queryKey, serverId),+ refetchType: "active",})const settled = await Promise.allSettled([+ derivedRevalidation,queryClient.invalidateQueries({queryKey: communityKeys.server(serverId),exact: true,@@ -218,6 +236,30 @@ async function executePolicy(}}+async function executePoliciesBounded(+ policies: readonly CommunityWsReconcilePolicy[],+ executors: Record<CommunityWsReconcilePolicy, () => void | Promise<void>>,+ concurrency: number,+): Promise<boolean[]> {+ const results = new Array<boolean>(policies.length)+ let nextIndex = 0+ const worker = async () => {+ while (nextIndex < policies.length) {+ const index = nextIndex+ nextIndex += 1+ const policy = policies[index]!+ results[index] = await executePolicy(policy, executors[policy])+ }+ }+ await Promise.all(+ Array.from(+ { length: Math.min(Math.max(1, concurrency), policies.length) },+ () => worker(),+ ),+ )+ return results+}+export type CommunityWsReconcileSummary = {policyCount: numbersuccessCount: number@@ -232,26 +274,40 @@ export async function reconcileCommunityWsReconnect(): Promise<CommunityWsReconcileSummary> {const startedAt = Date.now()const executors = policyExecutors(queryClient)- const resetPolicies = new Set<CommunityWsReconcilePolicy>([- "presence-overlay",- "status-overlay",- ])- const resetResults = communityWsReconnectPolicies- .filter((policy) => resetPolicies.has(policy))- .map((policy) => executePolicy(policy, executors[policy]))- const authoritativeResults = communityWsReconnectPolicies- .filter((policy) => !resetPolicies.has(policy))- .map((policy) => executePolicy(policy, executors[policy]))- const settled = await Promise.allSettled(- [...resetResults, ...authoritativeResults],+ const resetPolicies = communityWsReconnectPolicies.filter((policy) => RESET_POLICIES.has(policy))+ const focusedMessagePolicies = communityWsReconnectPolicies.filter((policy) => policy === "focused-messages")+ const focusedRoutePolicies = communityWsReconnectPolicies.filter(+ (policy) => FOCUSED_POLICIES.has(policy) && policy !== "focused-messages",+ )+ const backgroundPolicies = communityWsReconnectPolicies.filter(+ (policy) => !RESET_POLICIES.has(policy) && !FOCUSED_POLICIES.has(policy),+ )++ const resetResults = await Promise.all(+ resetPolicies.map((policy) => executePolicy(policy, executors[policy])),+ )+ const focusedMessageResults = await Promise.all(+ focusedMessagePolicies.map((policy) => executePolicy(policy, executors[policy])),+ )+ const focusedRouteResults = await Promise.all(+ focusedRoutePolicies.map((policy) => executePolicy(policy, executors[policy])),+ )+ const backgroundResults = await executePoliciesBounded(+ backgroundPolicies,+ executors,+ BACKGROUND_RECONCILE_CONCURRENCY,)- const successCount = settled.filter(- (result) => result.status === "fulfilled" && result.value,- ).length+ const results = [+ ...resetResults,+ ...focusedMessageResults,+ ...focusedRouteResults,+ ...backgroundResults,+ ]+ const successCount = results.filter(Boolean).lengthconst summary = {- policyCount: settled.length,+ policyCount: results.length,successCount,- failureCount: settled.length - successCount,+ failureCount: results.length - successCount,durationMs: Math.max(0, Date.now() - startedAt),reconnectDurationMs,}diff --git a/src/web/src/hooks/community/use-channel-message-feed.ts b/src/web/src/hooks/community/use-channel-message-feed.tsindex 233b25126..b99b0e329 100644--- a/src/web/src/hooks/community/use-channel-message-feed.ts+++ b/src/web/src/hooks/community/use-channel-message-feed.ts@@ -28,9 +28,13 @@ export function useChannelMessageFeed({? undefined: (readSnapshot?.lastReadMessageId ?? null),anchorMessageId,+ waitForAnchor: false,})const { newDividerBefore, anchorFound } = useMemo(() => {if (!readSnapshot) return { newDividerBefore: undefined, anchorFound: false }+ if (!messagesQuery.anchorReconciled) {+ return { newDividerBefore: undefined, anchorFound: false }+ }const lastId = readSnapshot.lastReadMessageIdif (!lastId) {for (const message of messagesQuery.messages) {@@ -48,7 +52,7 @@ export function useChannelMessageFeed({}}return { newDividerBefore: undefined, anchorFound: true }- }, [messagesQuery.messages, readSnapshot, viewerUserId])+ }, [messagesQuery.anchorReconciled, messagesQuery.messages, readSnapshot, viewerUserId])const [scrollRootEl, setScrollRootEl] = useState<HTMLDivElement | null>(null)useChannelWatermark({ channelId, messages: messagesQuery.messages, scrollRootEl })useEagerChannelRead({diff --git a/src/web/src/hooks/community/use-channel-read-state.test.ts b/src/web/src/hooks/community/use-channel-read-state.test.tsindex eed8362c2..8a5c39db8 100644--- a/src/web/src/hooks/community/use-channel-read-state.test.ts+++ b/src/web/src/hooks/community/use-channel-read-state.test.ts@@ -35,9 +35,14 @@ let queryReturn: { data: unknown; isFetching: boolean } = {data: undefined,isFetching: false,}-let lastUseQueryConfig: { retry?: number; staleTime?: number; gcTime?: number } = {}+let lastUseQueryConfig: {+ retry?: number+ staleTime?: number+ gcTime?: number+ queryFn?: (context: { signal: AbortSignal }) => Promise<unknown>+} = {}vi.mock("@tanstack/react-query", () => ({- useQuery: (config: { retry?: number; staleTime?: number; gcTime?: number }) => {+ useQuery: (config: typeof lastUseQueryConfig) => {lastUseQueryConfig = config ?? {}return queryReturn},@@ -45,9 +50,8 @@ vi.mock("@tanstack/react-query", () => ({// apiFetch is unused directly (the queryFn is stubbed by the useQuery mock)// but the module still imports it, so provide a stub.-vi.mock("@/lib/api/client", () => ({- apiFetch: vi.fn(),-}))+const apiFetchMock = vi.hoisted(() => vi.fn())+vi.mock("@/lib/api/client", () => ({ apiFetch: apiFetchMock }))function resetHarness() {refs = new Map()@@ -63,6 +67,7 @@ async function loadHook() {beforeEach(() => {resetHarness()+ apiFetchMock.mockReset()})describe("useChannelReadStateSnapshot — freeze invariant", () => {@@ -166,6 +171,20 @@ describe("useChannelReadStateSnapshot — freeze invariant", () => {expect(lastUseQueryConfig.retry).toBe(1)})+ it("forwards TanStack cancellation to the read-state request", async () => {+ const useHook = await loadHook()+ useHook("ch_abort")+ const controller = new AbortController()+ apiFetchMock.mockResolvedValue({ lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 })++ await lastUseQueryConfig.queryFn?.({ signal: controller.signal })++ expect(apiFetchMock).toHaveBeenCalledWith(+ "/api/community/channels/ch_abort/read-state",+ { signal: controller.signal },+ )+ })+it("returns null when the query errors — snapshotRef never latches a fabricated value", async () => {// Anti-latching invariant: on server D1 exhaustion, the handler throws,// the query rejects, `query.data` stays undefined, and the hookdiff --git a/src/web/src/hooks/community/use-channel-read-state.ts b/src/web/src/hooks/community/use-channel-read-state.tsindex 090ef02e2..6c6308912 100644--- a/src/web/src/hooks/community/use-channel-read-state.ts+++ b/src/web/src/hooks/community/use-channel-read-state.ts@@ -51,9 +51,10 @@ export function useChannelReadStateSnapshot(channelId: string | null | undefinedqueryKey: channelId? communityKeys.channelReadStateSnapshot(channelId): ["community", "channel", "__none__", "read-state-snapshot"],- queryFn: async () => {+ queryFn: async ({ signal }) => {return apiFetch<ChannelReadStateSnapshot>(`/api/community/channels/${channelId}/read-state`,+ { signal },)},enabled: !!channelId,diff --git a/src/web/src/hooks/community/use-channel-route-model.ts b/src/web/src/hooks/community/use-channel-route-model.tsindex c7c415573..ea55466ef 100644--- a/src/web/src/hooks/community/use-channel-route-model.ts+++ b/src/web/src/hooks/community/use-channel-route-model.ts@@ -81,18 +81,18 @@ export function useChannelRouteModel(serverId: string, serverParam: string, chanuseCommunityStore.getState().setCurrentChannelMeta(null)return}- if (metaQuery.data && metaQuery.isVerified) {+ const denied = isDefinitiveChildMetaFailure(metaQuery.error)+ if (denied || metaQuery.data?.archived) {+ useCommunityStore.getState().setCurrentChannelMeta(null)+ removeForumSidebarUnreadChild(queryClient, serverId, channelId)+ removeForumSidebarThreadExact(queryClient, serverId, channelId)+ if (getLastChannel(serverId) === channelId) clearLastChannel(serverId)+ router.replace(`/c/channels/${serverParam}`)+ } else if (metaQuery.data && metaQuery.isVerified) {useCommunityStore.getState().setCurrentChannelMeta(metaQuery.data)- } else if (metaQuery.error || metaQuery.data?.archived) {+ } else if (metaQuery.error) {useCommunityStore.getState().setCurrentChannelMeta(null)- if (metaQuery.data?.archived || isDefinitiveChildMetaFailure(metaQuery.error)) {- removeForumSidebarUnreadChild(queryClient, serverId, channelId)- removeForumSidebarThreadExact(queryClient, serverId, channelId)- if (getLastChannel(serverId) === channelId) clearLastChannel(serverId)- router.replace(`/c/channels/${serverParam}`)- } else {- toastApiError(metaQuery.error, "Failed to load thread")- }+ toastApiError(metaQuery.error, "Failed to load thread")}}, [channelId, isChild, metaQuery.data, metaQuery.error, metaQuery.isVerified, queryClient, router, serverId, serverParam])return modeldiff --git a/src/web/src/hooks/community/use-child-channel-meta.test.ts b/src/web/src/hooks/community/use-child-channel-meta.test.tsindex c82c57eca..05c0a47b6 100644--- a/src/web/src/hooks/community/use-child-channel-meta.test.ts+++ b/src/web/src/hooks/community/use-child-channel-meta.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest"import type { ChildChannelMeta } from "./use-forum-sidebar-threads"-import { isChildChannelMetaVerified } from "./use-child-channel-meta"+import { pickRenderableChildMeta } from "./use-child-channel-meta"const meta = (overrides: Partial<ChildChannelMeta> = {}): ChildChannelMeta => ({id: "post-1",@@ -16,15 +16,22 @@ const meta = (overrides: Partial<ChildChannelMeta> = {}): ChildChannelMeta => ({...overrides,})-describe("child channel metadata access epoch", () => {- it("fails closed while disconnected and until the current epoch validates", () => {- expect(isChildChannelMetaVerified(meta(), 2, true)).toBe(true)- expect(isChildChannelMetaVerified(meta(), 3, false)).toBe(false)- expect(isChildChannelMetaVerified(meta(), 3, true)).toBe(false)- expect(isChildChannelMetaVerified(meta({ verifiedEpoch: 3 }), 3, true)).toBe(true)+describe("child channel metadata stale rendering", () => {+ it("keeps a previously authorized snapshot renderable across a WS epoch", () => {+ const trusted = meta({ verifiedEpoch: 2 })+ expect(pickRenderableChildMeta(trusted, trusted, 3)).toBe(trusted)})- it("never verifies an archived child payload", () => {- expect(isChildChannelMetaVerified(meta({ archived: true }), 2, true)).toBe(false)+ it("does not render an old first response that was never trusted", () => {+ expect(pickRenderableChildMeta(meta({ verifiedEpoch: 2 }), undefined, 3)).toBeUndefined()+ })++ it("authoritative current-epoch archive removes a previously trusted snapshot", () => {+ const trusted = meta({ verifiedEpoch: 2 })+ expect(pickRenderableChildMeta(+ meta({ verifiedEpoch: 3, archived: true }),+ trusted,+ 3,+ )).toBeUndefined()})})diff --git a/src/web/src/hooks/community/use-child-channel-meta.ts b/src/web/src/hooks/community/use-child-channel-meta.tsindex a69db1136..406e0cf42 100644--- a/src/web/src/hooks/community/use-child-channel-meta.ts+++ b/src/web/src/hooks/community/use-child-channel-meta.ts@@ -1,6 +1,7 @@"use client"import { useQuery } from "@tanstack/react-query"+import { useEffect, useState } from "react"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import type {@@ -40,12 +41,14 @@ function projectChildMeta(payload: ChannelMetaPayload, verifiedEpoch: number): C}}-export function isChildChannelMetaVerified(+export function pickRenderableChildMeta(meta: ChildChannelMeta | undefined,+ trusted: ChildChannelMeta | undefined,accessEpoch: number,- accessConnected: boolean,-) {- return !!meta && accessConnected && meta.verifiedEpoch === accessEpoch && !meta.archived+): ChildChannelMeta | undefined {+ if (meta?.verifiedEpoch === accessEpoch) return meta.archived ? undefined : meta+ if (trusted?.id === meta?.id || !meta) return trusted?.archived ? undefined : trusted+ return undefined}export function useChildChannelMeta(@@ -54,7 +57,6 @@ export function useChildChannelMeta(enabled: boolean,) {const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)- const accessConnected = useCommunityWsStore((state) => state.accessConnected)const sidebar = useQuery<ForumSidebarQueryData>({queryKey: communityKeys.forumSidebarThreads(serverId),queryFn: () => Promise.reject(new Error("forum sidebar observer only")),@@ -75,8 +77,19 @@ export function useChildChannelMeta(staleTime: Infinity,gcTime: 5 * 60 * 1000,})+ const [trusted, setTrusted] = useState<{+ channelId: string+ meta: ChildChannelMeta+ } | null>(null)+ useEffect(() => {+ if (query.data?.verifiedEpoch !== accessEpoch) return+ setTrusted(query.data.archived ? null : { channelId, meta: query.data })+ }, [accessEpoch, channelId, query.data])+ const trustedMeta = trusted?.channelId === channelId ? trusted.meta : undefined+ const renderable = pickRenderableChildMeta(query.data, trustedMeta, accessEpoch)return {...query,- isVerified: isChildChannelMetaVerified(query.data, accessEpoch, accessConnected),+ data: renderable,+ isVerified: !!renderable,}}diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.test.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.test.tsindex fa8d4dcc2..6f53f4f5f 100644--- a/src/web/src/hooks/community/use-forum-sidebar-threads.test.ts+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.test.ts@@ -860,6 +860,33 @@ describe("forum sidebar Stage B resources", () => {renderer!.unmount()})+ it("keeps an already-rendered sidebar snapshot visible while WS is disconnected", async () => {+ apiFetchMock.mockResolvedValue(envelope(["base-1"]))+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ const renders: string[][] = []+ let renderer!: TestRenderer.ReactTestRenderer+ await act(async () => {+ renderer = TestRenderer.create(+ React.createElement(+ QueryClientProvider,+ { client: queryClient },+ React.createElement(Capture, {+ retainId: null,+ onRender: (ids) => renders.push(ids),+ }),+ ),+ )+ })+ await waitFor(() => renders.at(-1)?.includes("base-1") === true)++ await act(async () => {+ useCommunityWsStore.getState().markAccessDisconnected()+ })++ expect(renders.at(-1)).toEqual(["base-1"])+ renderer.unmount()+ })+it("replays a title patch that lands while the canonical request is in flight", async () => {let resolveRequest: ((value: SidebarThreadEnvelope) => void) | undefinedapiFetchMock.mockImplementation(() => new Promise((resolve) => { resolveRequest = resolve }))diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.tsindex e1308f64e..dae00b8c4 100644--- a/src/web/src/hooks/community/use-forum-sidebar-threads.ts+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.ts@@ -1,6 +1,6 @@"use client"-import { useEffect, useMemo, useRef } from "react"+import { useEffect, useMemo, useRef, useState } from "react"import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query"import { apiFetch } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"@@ -903,7 +903,6 @@ export function useForumSidebarThreads() {const queryClient = useQueryClient()const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)- const accessConnected = useCommunityWsStore((state) => state.accessConnected)const previousRetainId = useRef(retainId)// Observe (without fetching) the already-canonical ServerDetail cache so a// fresh `/unreads` result re-runs attribution even when the sidebar rows did@@ -971,12 +970,22 @@ export function useForumSidebarThreads(return normalized.retained},})- const baseIsVerified = accessConnected && query.data?.verifiedEpoch === accessEpoch+ const [trustedBase, setTrustedBase] = useState<{+ serverId: string+ data: ForumSidebarQueryData+ } | null>(null)+ useEffect(() => {+ if (query.data?.verifiedEpoch !== accessEpoch) return+ setTrustedBase({ serverId, data: query.data })+ }, [accessEpoch, query.data, serverId])+ const renderableBase = query.data?.verifiedEpoch === accessEpoch+ ? query.data+ : trustedBase?.serverId === serverId ? trustedBase.data : undefinedconst projection = useMemo(() => deriveForumSidebarProjection(- baseIsVerified ? query.data : undefined,- baseIsVerified ? retainedQuery.data : null,+ renderableBase,+ renderableBase ? retainedQuery.data : null,serverDetailQuery.data?.forumUnreadState,- ), [baseIsVerified, query.data, retainedQuery.data, serverDetailQuery.data?.forumUnreadState])+ ), [renderableBase, retainedQuery.data, serverDetailQuery.data?.forumUnreadState])useEffect(() => {if (!query.data) returndiff --git a/src/web/src/hooks/community/use-messages.activation-refetch.test.ts b/src/web/src/hooks/community/use-messages.activation-refetch.test.tsindex 5a5954999..2a496f9aa 100644--- a/src/web/src/hooks/community/use-messages.activation-refetch.test.ts+++ b/src/web/src/hooks/community/use-messages.activation-refetch.test.ts@@ -11,7 +11,12 @@ vi.mock("@/lib/api/client", () => ({apiFetch: (...args: unknown[]) => apiFetchMock(...args),}))-type Snapshot = { ids: string[]; isFetching: boolean }+type Snapshot = {+ anchorReconciled?: boolean+ hasMoreNewer?: boolean+ ids: string[]+ isFetching: boolean+}function deferred<T>() {let resolve!: (value: T) => void@@ -34,7 +39,12 @@ function DmCapture({ lastReadMessageId, onRender }: {onRender: (snapshot: Snapshot) => void}) {const result = useDmMessages("dm_activation", { lastReadMessageId })- onRender({ ids: result.messages.map((message) => message.id), isFetching: result.isFetching })+ onRender({+ anchorReconciled: result.anchorReconciled,+ hasMoreNewer: result.hasMoreNewer,+ ids: result.messages.map((message) => message.id),+ isFetching: result.isFetching,+ })return null}@@ -43,7 +53,30 @@ function ChannelCapture({ lastReadMessageId, onRender }: {onRender: (snapshot: Snapshot) => void}) {const result = useMessages("ch_activation", { serverId: "server_1", lastReadMessageId })- onRender({ ids: result.messages.map((message) => message.id), isFetching: result.isFetching })+ onRender({+ anchorReconciled: result.anchorReconciled,+ hasMoreNewer: result.hasMoreNewer,+ ids: result.messages.map((message) => message.id),+ isFetching: result.isFetching,+ })+ return null+}++function IndependentChannelCapture({ lastReadMessageId, onRender }: {+ lastReadMessageId: string | null | undefined+ onRender: (snapshot: Snapshot) => void+}) {+ const result = useMessages("ch_activation", {+ serverId: "server_1",+ lastReadMessageId,+ waitForAnchor: false,+ })+ onRender({+ anchorReconciled: result.anchorReconciled,+ hasMoreNewer: result.hasMoreNewer,+ ids: result.messages.map((message) => message.id),+ isFetching: result.isFetching,+ })return null}@@ -78,6 +111,114 @@ beforeEach(() => {})describe("useMessagesInner — disabled-to-enabled cache revalidation", () => {+ it("starts newest messages without waiting for read-state, then repairs a late anchor", async () => {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ const newest = deferred<MessagesPage>()+ apiFetchMock.mockImplementation((url: string) => {+ if (url.endsWith("?anchor=m_read")) {+ return Promise.resolve({+ messages: [{ id: "m_read", seq: 2, createdAt: "2026-08-09T00:00:02.000Z" }],+ hasMoreOlder: true,+ hasMoreNewer: true,+ latestSeq: 3,+ })+ }+ return newest.promise+ })+ const snapshots: Snapshot[] = []+ const onRender = (snapshot: Snapshot) => { snapshots.push(snapshot) }++ const renderer = renderCapture(+ queryClient,+ React.createElement(IndependentChannelCapture, {+ lastReadMessageId: undefined,+ onRender,+ }),+ )++ await waitFor(() => apiFetchMock.mock.calls.length === 1)+ expect(apiFetchMock).toHaveBeenCalledWith(+ "/api/community/channels/ch_activation/messages",+ { signal: expect.any(AbortSignal) },+ )++ newest.resolve({+ messages: [{ id: "m_new", seq: 3, createdAt: "2026-08-09T00:00:03.000Z" }],+ hasMore: true,+ cursor: "older",+ latestSeq: 3,+ })+ await waitFor(() => snapshots.at(-1)?.ids.includes("m_new") === true)++ updateCapture(+ renderer,+ queryClient,+ React.createElement(IndependentChannelCapture, {+ lastReadMessageId: "m_read",+ onRender,+ }),+ )+ await waitFor(() => apiFetchMock.mock.calls.some(+ ([url]) => url === "/api/community/channels/ch_activation/messages?anchor=m_read",+ ))+ await waitFor(() => snapshots.at(-1)?.ids.includes("m_read") === true)+ renderer.unmount()+ })++ it("reconciles a late anchor already present in the newest page without replacing painted rows", async () => {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ apiFetchMock.mockImplementation((url: string) => {+ if (url.endsWith("?anchor=m_read")) {+ return Promise.resolve({+ messages: [{ id: "m_read", seq: 1, createdAt: "2026-08-09T00:00:01.000Z" }],+ hasMoreOlder: false,+ hasMoreNewer: true,+ newerCursor: "m_read",+ latestSeq: 2,+ } satisfies MessagesPage)+ }+ return Promise.resolve({+ messages: [+ { id: "m_read", seq: 1, createdAt: "2026-08-09T00:00:01.000Z" },+ { id: "m_new", seq: 2, createdAt: "2026-08-09T00:00:02.000Z" },+ ],+ hasMore: false,+ latestSeq: 2,+ } satisfies MessagesPage)+ })+ const snapshots: Snapshot[] = []+ const onRender = (snapshot: Snapshot) => { snapshots.push(snapshot) }+ const renderer = renderCapture(+ queryClient,+ React.createElement(IndependentChannelCapture, {+ lastReadMessageId: undefined,+ onRender,+ }),+ )++ await waitFor(() => snapshots.at(-1)?.ids.includes("m_new") === true)+ expect(snapshots.at(-1)?.anchorReconciled).toBe(true)+ expect(snapshots.at(-1)?.hasMoreNewer).toBe(false)++ updateCapture(+ renderer,+ queryClient,+ React.createElement(IndependentChannelCapture, {+ lastReadMessageId: "m_read",+ onRender,+ }),+ )+ await waitFor(() => snapshots.at(-1)?.anchorReconciled === true)++ expect(apiFetchMock.mock.calls.map(([url]) => url)).toEqual([+ "/api/community/channels/ch_activation/messages",+ "/api/community/channels/ch_activation/messages?anchor=m_read",+ ])+ expect(snapshots.at(-1)?.ids).toEqual(["m_read", "m_new"])+ expect(snapshots.at(-1)?.hasMoreNewer).toBe(true)+ renderer.unmount()+ })+it("leaves browser network reconnect reconciliation to the bounded WS path", () => {const queryClient = new QueryClient()queryClient.setQueryData(communityKeys.dmMessages("dm_activation"), {diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.tsindex 61a298708..093095a40 100644--- a/src/web/src/hooks/community/use-messages.ts+++ b/src/web/src/hooks/community/use-messages.ts@@ -147,6 +147,16 @@ const ANCHOR_CACHE_FRESHNESS_MS = 30_000type PageCache = InfiniteData<MessagesPage, MessagesPageParam>+function cacheHasAnchorPage(+ cache: PageCache | undefined,+ anchorId: string | null,+): boolean {+ if (!anchorId || !cache) return false+ return cache.pageParams.some((pageParam) => (+ pageParam.mode === "anchor" && pageParam.anchor === anchorId+ ))+}+function cachedWindowNeedsAnchor(pages: MessagesPage[] | undefined,anchorId: string | null,@@ -162,6 +172,18 @@ function cachedWindowNeedsAnchor(return hasMessages}+function cachedWindowNeedsAnchorReconcile(+ cache: PageCache | undefined,+ anchorId: string | null,+ reconcileLateAnchor: boolean,+): boolean {+ if (!anchorId || !cache || cache.pages.length === 0) return false+ if (cachedWindowNeedsAnchor(cache.pages, anchorId)) return true+ if (!reconcileLateAnchor) return false+ const hasMessages = cache.pages.some((page) => page.messages.length > 0)+ return hasMessages && !cacheHasAnchorPage(cache, anchorId)+}+type MessagesReturn = Omit<UseInfiniteQueryResult<PageCache, Error>, "isLoading"> & {messages: Msg[]latestSeq: number@@ -173,6 +195,7 @@ type MessagesReturn = Omit<UseInfiniteQueryResult<PageCache, Error>, "isLoading"fetchNewer: () => voidjumpToPresent: () => voidpresentVersion: number+ anchorReconciled: boolean// Legacy alias — mirrors `hasMoreOlder`. Kept so consumers not yet migrated// off the older-only API still compile until every call site is updated.hasMore: boolean@@ -201,6 +224,12 @@ type MessagesOpts = {* read snapshot resolves must NOT leave the query disabled.*/anchorMessageId?: string | null+ /**+ * Default true preserves anchor-first consumers. Channel first paint sets+ * false so newest messages and read-state load independently; a late read+ * pointer is reconciled by the existing anchor-repair effect.+ */+ waitForAnchor?: boolean}type ChannelMessagesOpts = MessagesOpts & {@@ -232,8 +261,9 @@ function useMessagesInner(// (currently DM) pass `null` explicitly. An explicit `anchorMessageId`// (jump target) satisfies the gate on its own — a jump must not wait on the// read snapshot.- const anchorResolved =- opts?.anchorMessageId != null || opts?.lastReadMessageId !== undefined+ const anchorResolved = opts?.waitForAnchor === false+ || opts?.anchorMessageId != null+ || opts?.lastReadMessageId !== undefined// Jump target wins over the read pointer for the initial anchor window.const anchorId = opts?.anchorMessageId ?? opts?.lastReadMessageId ?? nullconst enabled = !!scopeId && anchorResolved@@ -297,9 +327,10 @@ function useMessagesInner(// A nonempty window missing the resolved anchor is the one exception: Fix// 3 below owns that repair and must fetch the NEW anchor page before any// persisted pageParam can replace or discard the existing history.- staleTime: (cachedQuery) => cachedWindowNeedsAnchor(- (cachedQuery.state.data as PageCache | undefined)?.pages,+ staleTime: (cachedQuery) => cachedWindowNeedsAnchorReconcile(+ cachedQuery.state.data as PageCache | undefined,forceNewest ? null : anchorId,+ opts?.waitForAnchor === false,) ? Infinity : 0,})@@ -387,7 +418,11 @@ function useMessagesInner(if (!anchorId) returnif (query.isFetching) returnif (query.isPending) return- if (!cachedWindowNeedsAnchor(query.data?.pages, anchorId)) return+ if (!cachedWindowNeedsAnchorReconcile(+ query.data,+ anchorId,+ opts?.waitForAnchor === false,+ )) returnconst resetKey = `${scopeId ?? ""}::${anchorId}`if (anchorResetKeyRef.current === resetKey) returnanchorResetKeyRef.current = resetKey@@ -438,7 +473,12 @@ function useMessagesInner(// into a single page — `hasMoreOlder`/`hasMoreNewer` come from the// new anchor page since it alone knows the true state of both// edges relative to the (possibly wider) merged window.- const merged = mergeMessagesPages([...current.pages, page])+ const currentMessages = mergeMessagesPages(current.pages)+ const anchorAlreadyPainted = opts?.waitForAnchor === false+ && currentMessages.some((message) => message.id === anchorId)+ const merged = anchorAlreadyPainted+ ? currentMessages+ : mergeMessagesPages([...current.pages, page])const mergedPage: MessagesPage = {...page,messages: merged,@@ -466,6 +506,7 @@ function useMessagesInner(queryClient,queryKey,queryFn,+ opts?.waitForAnchor,])const messages = useMemo<Msg[]>(() => {@@ -547,6 +588,7 @@ function useMessagesInner(presentVersion: forceNewest && presentOverride?.phase === "present"? presentOverride.attemptId: 0,+ anchorReconciled: !anchorId || cacheHasAnchorPage(query.data, anchorId),hasMore: hasMoreOlder,}}diff --git a/src/web/src/hooks/community/use-scroll-anchor.test.ts b/src/web/src/hooks/community/use-scroll-anchor.test.tsindex afe805cab..1e8676957 100644--- a/src/web/src/hooks/community/use-scroll-anchor.test.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.test.ts@@ -115,6 +115,31 @@ describe("decideScrollAction — mount (rewritten — neither case is free withexpect(phase2.nextState.didDividerConverge).toBe(true)})+ it("does not run a delayed phase-1 mount after an upward user intent", () => {+ const result = decideScrollAction(baseInput({+ initialScrollReady: true,+ newDividerBefore: "m2",+ isAtEnd: true,+ userScrolledAway: true,+ }))+ expect(result.action).toEqual({ type: "none" })+ expect(result.nextState.didInitialScroll).toBe(true)+ expect(result.nextState.didDividerConverge).toBe(true)+ })++ it("does not run phase-2 convergence from a stale at-end sample after an upward user intent", () => {+ const phase1 = decideScrollAction(baseInput({ initialScrollReady: false }))+ const phase2 = decideScrollAction(baseInput({+ state: phase1.nextState,+ initialScrollReady: true,+ newDividerBefore: "m2",+ isAtEnd: true,+ userScrolledAway: true,+ }))+ expect(phase2.action).toEqual({ type: "none" })+ expect(phase2.nextState.didDividerConverge).toBe(true)+ })+it("fires exactly once — a second commit with didInitialScroll already true does not re-mount-scroll", () => {const first = decideScrollAction(baseInput())expect(first.action.type).toBe("mount")@@ -184,6 +209,19 @@ describe("decideScrollAction — self-send / peer-follow (both hand-rolled — fexpect(action).toEqual({ type: "none" })})+ it("peer send does not follow a stale at-end sample after an upward user intent", () => {+ const state = mountedState()+ const messages = [{ id: "m1" }, { id: "m2" }, { id: "m3" }, { id: "m4", authorId: "peer" }]+ const { action } = decideScrollAction(baseInput({+ state,+ messages,+ viewerUserId: "viewer",+ isAtEnd: true,+ userScrolledAway: true,+ }))+ expect(action).toEqual({ type: "none" })+ })+it("peer send is ignored (no auto-follow) when hasMoreNewer is true — loaded window isn't tail-attached, even if isAtEnd is true", () => {const state = mountedState()const messages = [{ id: "m1" }, { id: "m2" }, { id: "m3" }, { id: "m4", authorId: "peer" }]diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.tsindex a3c8c5901..f1b8c8d91 100644--- a/src/web/src/hooks/community/use-scroll-anchor.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.ts@@ -124,6 +124,7 @@ export interface DecideScrollActionInput {// Whether the viewport was within NEAR_BOTTOM_PX of the end BEFORE this// commit's append — the caller reads this off `virtualizer.isAtEnd(NEAR_BOTTOM_PX)`.isAtEnd: boolean+ userScrolledAway?: boolean}type ScrollAction =@@ -151,7 +152,7 @@ export interface DecideScrollActionResult {* real virtualizer. Exported for unit testing without DOM/hooks.*/export function decideScrollAction(input: DecideScrollActionInput): DecideScrollActionResult {- const { state, messages, newDividerBefore, initialScrollReady, heroMeasured, hasMoreNewer, viewerUserId, isAtEnd } = input+ const { state, messages, newDividerBefore, initialScrollReady, heroMeasured, hasMoreNewer, viewerUserId, isAtEnd, userScrolledAway } = inputconst nextTail = messages[messages.length - 1]?.id ?? nullconst nextLen = messages.length@@ -206,6 +207,12 @@ export function decideScrollAction(input: DecideScrollActionInput): DecideScroll// Still bails until `heroMeasured` in both cases — firing on a default-0// scrollMargin mis-targets the scroll (see `heroMeasured`'s doc comment).if (!state.didInitialScroll) {+ if (heroMeasured && userScrolledAway) {+ return {+ action: { type: "none" },+ nextState: { ...baseNextState, didInitialScroll: true, didDividerConverge: true },+ }+ }if (heroMeasured && initialScrollReady) {return {action: { type: "mount", newDividerBefore },@@ -243,7 +250,7 @@ export function decideScrollAction(input: DecideScrollActionInput): DecideScrollif (!initialScrollReady || !heroMeasured) {return { action: { type: "none" }, nextState: baseNextState }}- if (newDividerBefore && isAtEnd) {+ if (newDividerBefore && isAtEnd && !userScrolledAway) {return {action: { type: "mount", newDividerBefore },nextState: { ...baseNextState, didDividerConverge: true },@@ -271,7 +278,7 @@ export function decideScrollAction(input: DecideScrollActionInput): DecideScroll// present (`hasMoreNewer` false) AND the viewer was already at/near the// bottom just BEFORE this append — otherwise leave the "↓ N" pill to// prompt them back down.- if (!hasMoreNewer && isAtEnd) {+ if (!hasMoreNewer && isAtEnd && !userScrolledAway) {return { action: { type: "scrollToEnd" }, nextState: liveState }}return { action: { type: "none" }, nextState: liveState }@@ -440,12 +447,35 @@ export function useScrollAnchor({// move `scrollTop`, so it fires no scroll event; this ref therefore still// holds the pre-append position when the layout effect below reads it.const wasAtEndRef = useRef(true)+ const userScrolledAwayRef = useRef(false)useLayoutEffect(() => {const el = scrollRef.currentif (!el) return- const onScroll = () => { wasAtEndRef.current = virtualizer.isAtEnd(NEAR_BOTTOM_PX) }+ let lastScrollTop = el.scrollTop+ const onScroll = () => {+ const nextScrollTop = el.scrollTop+ const isAtEnd = virtualizer.isAtEnd(NEAR_BOTTOM_PX)+ wasAtEndRef.current = isAtEnd+ if (isAtEnd) userScrolledAwayRef.current = false+ else if (nextScrollTop < lastScrollTop - 1) userScrolledAwayRef.current = true+ lastScrollTop = nextScrollTop+ }+ const onWheel = (event: WheelEvent) => {+ if (event.deltaY < 0) userScrolledAwayRef.current = true+ }+ const onKeyDown = (event: KeyboardEvent) => {+ if (["ArrowUp", "PageUp", "Home"].includes(event.key)) {+ userScrolledAwayRef.current = true+ }+ }el.addEventListener("scroll", onScroll, { passive: true })- return () => el.removeEventListener("scroll", onScroll)+ el.addEventListener("wheel", onWheel, { passive: true })+ el.addEventListener("keydown", onKeyDown)+ return () => {+ el.removeEventListener("scroll", onScroll)+ el.removeEventListener("wheel", onWheel)+ el.removeEventListener("keydown", onKeyDown)+ }}, [virtualizer])useLayoutEffect(() => {@@ -458,6 +488,7 @@ export function useScrollAnchor({hasMoreNewer,viewerUserId,isAtEnd: wasAtEndRef.current,+ userScrolledAway: userScrolledAwayRef.current,})stateRef.current = nextState@@ -494,6 +525,7 @@ export function useScrollAnchor({lastTailId: tailId,}wasAtEndRef.current = true+ userScrolledAwayRef.current = falsevirtualizer.scrollToEnd()}, [hasMoreNewer, presentVersion, tailId, virtualizer])@@ -565,6 +597,8 @@ export function useScrollAnchor({const belowCount = virtualizer.isAtEnd(NEAR_BOTTOM_PX) ? 0 : computeBelowCount(items, lastVisibleIndex)const scrollToBottom = useCallback(() => {+ userScrolledAwayRef.current = false+ wasAtEndRef.current = truevirtualizer.scrollToEnd({ behavior: "smooth" })}, [virtualizer])diff --git a/src/web/src/lib/use-user-ws.test.ts b/src/web/src/lib/use-user-ws.test.tsindex 904ca4c11..ef87a190f 100644--- a/src/web/src/lib/use-user-ws.test.ts+++ b/src/web/src/lib/use-user-ws.test.ts@@ -4,8 +4,13 @@ import type { UseUserWsOptions } from "./use-user-ws"// --- Mock WebSocket ---class MockWebSocket {+ static CONNECTING = 0+ static OPEN = 1+ static CLOSING = 2+ static CLOSED = 3static instances: MockWebSocket[] = []url: string+ readyState = MockWebSocket.CONNECTINGonopen: (() => void) | null = nullonmessage: ((e: { data: string }) => void) | null = nullonerror: (() => void) | null = null@@ -18,17 +23,40 @@ class MockWebSocket {MockWebSocket.instances.push(this)}send(data: string) { this.sent.push(data) }- close() { this.closed = true; this.onclose?.() }+ close() { this.closed = true; this.readyState = MockWebSocket.CLOSED; this.onclose?.() }// Helpers for tests- simulateOpen() { this.onopen?.() }+ simulateOpen() { this.readyState = MockWebSocket.OPEN; this.onopen?.() }simulateMessage(data: unknown) { this.onmessage?.({ data: JSON.stringify(data) }) }simulateRawMessage(data: string) { this.onmessage?.({ data }) }- simulateClose() { this.onclose?.() }+ simulateClose() { this.readyState = MockWebSocket.CLOSED; this.onclose?.() }}vi.stubGlobal("WebSocket", MockWebSocket)+class MockEventTarget {+ listeners = new Map<string, Set<() => void>>()+ addEventListener(type: string, listener: () => void) {+ const listeners = this.listeners.get(type) ?? new Set<() => void>()+ listeners.add(listener)+ this.listeners.set(type, listeners)+ }+ removeEventListener(type: string, listener: () => void) {+ this.listeners.get(type)?.delete(listener)+ }+ dispatch(type: string) {+ for (const listener of this.listeners.get(type) ?? []) listener()+ }+ reset() {+ this.listeners.clear()+ }+}++const mockDocument = Object.assign(new MockEventTarget(), { visibilityState: "visible" })+const mockWindow = Object.assign(new MockEventTarget(), { location: { origin: "http://localhost:3000" } })+vi.stubGlobal("document", mockDocument)+vi.stubGlobal("window", mockWindow)+// Mock fetch for /api/ws/tokenconst mockFetch = vi.fn()vi.stubGlobal("fetch", mockFetch)@@ -124,6 +152,9 @@ function resetMockState() {callbackCounter = 0effectMemo = new Map()effectCounter = 0+ mockDocument.visibilityState = "visible"+ mockDocument.reset()+ mockWindow.reset()}describe("useUserWs", () => {@@ -144,7 +175,7 @@ describe("useUserWs", () => {const mod = await import("./use-user-ws")mod.useUserWs(onMessage, options)// Wait for async connect to complete- await vi.runAllTimersAsync()+ await flushPromises()return mod}@@ -275,7 +306,7 @@ describe("useUserWs", () => {const onMsg = vi.fn()await mountHook(onMsg)- await vi.runAllTimersAsync()+ await flushPromises()const ws = MockWebSocket.instances[0]expect(ws).toBeDefined()@@ -299,7 +330,7 @@ describe("useUserWs", () => {const cb1 = vi.fn()await mountHook(cb1)- await vi.runAllTimersAsync()+ await flushPromises()const ws = MockWebSocket.instances[0]ws.simulateOpen()@@ -327,7 +358,7 @@ describe("useUserWs", () => {const onMsg = vi.fn()await mountHook(onMsg)- await vi.runAllTimersAsync()+ await flushPromises()const ws = MockWebSocket.instances[0]ws.simulateOpen()@@ -345,6 +376,111 @@ describe("useUserWs", () => {expect(MockWebSocket.instances.length).toBeGreaterThan(instancesBefore)})+ it("passes an AbortSignal to the token fetch and aborts it at the hard timeout", async () => {+ mockFetch.mockImplementation((_url: string, init?: RequestInit) => new Promise((_resolve, reject) => {+ init?.signal?.addEventListener("abort", () => {+ const error = new Error("aborted")+ error.name = "AbortError"+ reject(error)+ })+ }))++ const mod = await import("./use-user-ws")+ mod.useUserWs(vi.fn())+ const signal = (mockFetch.mock.calls[0]?.[1] as RequestInit | undefined)?.signal++ expect(signal).toBeInstanceOf(AbortSignal)+ expect(signal?.aborted).toBe(false)+ await vi.advanceTimersByTimeAsync(10_000)+ await flushPromises()+ expect(signal?.aborted).toBe(true)++ effectCleanup?.()+ })++ it("suppresses reconnect while hidden and reconnects immediately when visible", async () => {+ setupTokenFetch()+ await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })+ const first = MockWebSocket.instances[0]!+ first.simulateOpen()+ first.simulateMessage({ type: "auth.ok" })++ mockDocument.visibilityState = "hidden"+ mockDocument.dispatch("visibilitychange")+ first.simulateClose()+ const fetchesWhileHidden = mockFetch.mock.calls.length+ await vi.advanceTimersByTimeAsync(60_000)+ expect(mockFetch).toHaveBeenCalledTimes(fetchesWhileHidden)++ mockDocument.visibilityState = "visible"+ mockDocument.dispatch("visibilitychange")+ await flushPromises()++ expect(mockFetch.mock.calls.length).toBe(fetchesWhileHidden + 1)+ expect(MockWebSocket.instances).toHaveLength(2)+ })++ it("keeps a fresh authenticated socket across pageshow and online", async () => {+ setupTokenFetch()+ await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })+ const ws = MockWebSocket.instances[0]!+ ws.simulateOpen()+ ws.simulateMessage({ type: "auth.ok" })+ const fetchCount = mockFetch.mock.calls.length++ mockWindow.dispatch("pageshow")+ mockWindow.dispatch("online")+ await flushPromises()++ expect(mockFetch).toHaveBeenCalledTimes(fetchCount)+ expect(MockWebSocket.instances).toEqual([ws])+ expect(ws.closed).toBe(false)+ })++ it("keeps cached UI ownership but replaces a stale authenticated socket on foreground", async () => {+ setupTokenFetch()+ const onDisconnect = vi.fn()+ await mountHook(vi.fn(), { onDisconnect, requestDaemonStatusOnAuth: false })+ const first = MockWebSocket.instances[0]!+ first.simulateOpen()+ first.simulateMessage({ type: "auth.ok" })++ vi.setSystemTime(Date.now() + 31_000)+ mockWindow.dispatch("pageshow")+ await flushPromises()++ expect(onDisconnect).toHaveBeenCalledTimes(1)+ expect(first.closed).toBe(true)+ expect(MockWebSocket.instances).toHaveLength(2)+ })++ it("coalesces visible, pageshow, and online while one replacement token request is pending", async () => {+ setupTokenFetch()+ await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })+ const first = MockWebSocket.instances[0]!+ first.simulateOpen()+ first.simulateMessage({ type: "auth.ok" })++ mockDocument.visibilityState = "hidden"+ mockDocument.dispatch("visibilitychange")+ first.simulateClose()++ const replacement = deferred<Response>()+ mockFetch.mockReturnValueOnce(replacement.promise)+ mockDocument.visibilityState = "visible"+ mockDocument.dispatch("visibilitychange")+ mockWindow.dispatch("pageshow")+ mockWindow.dispatch("online")++ expect(mockFetch).toHaveBeenCalledTimes(2)+ replacement.resolve({+ ok: true,+ json: () => Promise.resolve({ userId: "user-1", token: "tok-456" }),+ } as Response)+ await flushPromises()+ expect(MockWebSocket.instances).toHaveLength(2)+ })+it("failed connect (fetch rejects) retries with backoff and cleanup prevents further reconnects", async () => {// All connects will failmockFetch.mockRejectedValue(new Error("network error"))@@ -376,7 +512,7 @@ describe("useUserWs", () => {const onMsg = vi.fn()const mod = await import("./use-user-ws")const { send } = mod.useUserWs(onMsg)- await vi.runAllTimersAsync()+ await flushPromises()const ws = MockWebSocket.instances[0]ws.simulateOpen()@@ -403,7 +539,7 @@ describe("useUserWs", () => {const onMsg = vi.fn()await mountHook(onMsg)- await vi.runAllTimersAsync()+ await flushPromises()const ws = MockWebSocket.instances[0]ws.simulateOpen()@@ -585,6 +721,7 @@ describe("useUserWs", () => {await mountHook(vi.fn(), { requestDaemonStatusOnAuth: false })const ws = MockWebSocket.instances[0]ws.simulateOpen()+ ws.simulateMessage({ type: "auth.ok" })warn.mockClear()await vi.advanceTimersByTimeAsync(29_000)diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.tsindex 77e780337..3e4278b42 100644--- a/src/web/src/lib/use-user-ws.ts+++ b/src/web/src/lib/use-user-ws.ts@@ -15,6 +15,13 @@ import { isLocalMode, WS_DO_PORT_DEFAULT } from "@/lib/utils"const isLocal = isLocalMode()const WS_RECONNECT_INIT = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_DELAY_MS) || 1000const WS_RECONNECT_MAX = Number(process.env.NEXT_PUBLIC_WS_RECONNECT_MAX_DELAY_MS) || 30_000+const WS_TOKEN_TIMEOUT_MS = Number(process.env.NEXT_PUBLIC_WS_TOKEN_TIMEOUT_MS) || 10_000+const WS_CONNECT_TIMEOUT_MS = Number(process.env.NEXT_PUBLIC_WS_CONNECT_TIMEOUT_MS) || 10_000+const WS_STALE_AFTER_MS = 30_000++function isPageHidden(): boolean {+ return typeof document !== "undefined" && document.visibilityState === "hidden"+}/*** Incoming WS message shape delivered to the `onMessage` handler.@@ -84,6 +91,10 @@ export function useUserWs(const onAuthenticatedRef = useRef(options?.onAuthenticated)const requestDaemonStatusOnAuthRef = useRef(options?.requestDaemonStatusOnAuth ?? true)const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)+ const tokenAbortRef = useRef<AbortController | null>(null)+ const tokenTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)+ const connectTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)+ const connectStartedAtRef = useRef(0)const hasAuthenticatedBeforeRef = useRef(false)const authenticatedGenerationRef = useRef<number | null>(null)const disconnectedAtRef = useRef<number | null>(null)@@ -111,8 +122,27 @@ export function useUserWs(const connectRef = useRef<(() => Promise<void>) | null>(null)+ const retireSocket = useCallback((reportDisconnect = true) => {+ const ws = wsRef.current+ wsRef.current = null+ if (reportDisconnect && authenticatedGenerationRef.current !== null) {+ authenticatedGenerationRef.current = null+ disconnectedAtRef.current ??= Date.now()+ runLifecycleCallback("disconnect", onDisconnectRef.current)+ }+ if (pingIntervalRef.current) { clearInterval(pingIntervalRef.current); pingIntervalRef.current = null }+ if (livenessIntervalRef.current) { clearInterval(livenessIntervalRef.current); livenessIntervalRef.current = null }+ if (connectTimeoutRef.current !== null) { clearTimeout(connectTimeoutRef.current); connectTimeoutRef.current = null }+ ws?.close()+ }, [])+const scheduleReconnect = useCallback((generation: number) => {if (generation !== connectionGenerationRef.current) return+ if (isPageHidden()) return+ if (reconnectTimerRef.current !== null) {+ clearTimeout(reconnectTimerRef.current)+ reconnectTimerRef.current = null+ }const delay = Math.min(reconnectDelay.current, WS_RECONNECT_MAX)reconnectDelay.current = Math.min(delay * 2, WS_RECONNECT_MAX)reconnectTimerRef.current = setTimeout(() => {@@ -122,13 +152,26 @@ export function useUserWs(}, [])const connect = useCallback(async () => {+ if (isPageHidden()) returnconst generation = connectionGenerationRef.current + 1connectionGenerationRef.current = generation+ if (reconnectTimerRef.current !== null) {+ clearTimeout(reconnectTimerRef.current)+ reconnectTimerRef.current = null+ }+ tokenAbortRef.current?.abort()+ const tokenController = new AbortController()+ tokenAbortRef.current = tokenController+ let tokenTimedOut = false+ tokenTimeoutRef.current = setTimeout(() => {+ tokenTimedOut = true+ tokenController.abort()+ }, WS_TOKEN_TIMEOUT_MS)let userId: stringlet authToken: stringlet wsPort: number = WS_DO_PORT_DEFAULTtry {- const res = await fetch("/api/ws/token")+ const res = await fetch("/api/ws/token", { signal: tokenController.signal })if (!res.ok) {if (generation !== connectionGenerationRef.current) returnconsole.warn("[ws] token fetch failed:", res.status)@@ -142,9 +185,18 @@ export function useUserWs(if (body.wsPort) wsPort = body.wsPort} catch (err) {if (generation !== connectionGenerationRef.current) return+ if (tokenController.signal.aborted && !tokenTimedOut) returnconsole.warn("[ws] token fetch error:", err)scheduleReconnect(generation)return+ } finally {+ if (tokenAbortRef.current === tokenController) {+ if (tokenTimeoutRef.current !== null) {+ clearTimeout(tokenTimeoutRef.current)+ tokenTimeoutRef.current = null+ }+ tokenAbortRef.current = null+ }}const url = isLocal@@ -154,6 +206,7 @@ export function useUserWs(let ws: WebSockettry {if (generation !== connectionGenerationRef.current) return+ retireSocket()ws = new WebSocket(url)} catch (err) {if (generation !== connectionGenerationRef.current) return@@ -162,6 +215,11 @@ export function useUserWs(return}wsRef.current = ws+ connectStartedAtRef.current = Date.now()+ connectTimeoutRef.current = setTimeout(() => {+ if (ws !== wsRef.current || generation !== connectionGenerationRef.current) return+ ws.close()+ }, WS_CONNECT_TIMEOUT_MS)ws.onopen = () => {if (ws !== wsRef.current || generation !== connectionGenerationRef.current) return@@ -211,6 +269,10 @@ export function useUserWs(return}authenticatedGenerationRef.current = generation+ if (connectTimeoutRef.current !== null) {+ clearTimeout(connectTimeoutRef.current)+ connectTimeoutRef.current = null+ }const isReconnect = hasAuthenticatedBeforeRef.currenthasAuthenticatedBeforeRef.current = trueconst reconnectDurationMs = disconnectedAtRef.current === null@@ -259,29 +321,88 @@ export function useUserWs(}if (pingIntervalRef.current) { clearInterval(pingIntervalRef.current); pingIntervalRef.current = null }if (livenessIntervalRef.current) { clearInterval(livenessIntervalRef.current); livenessIntervalRef.current = null }+ if (connectTimeoutRef.current !== null) { clearTimeout(connectTimeoutRef.current); connectTimeoutRef.current = null }scheduleReconnect(generation)}- }, [scheduleReconnect])+ }, [retireSocket, scheduleReconnect])useEffect(() => {connectRef.current = connect}, [connect])useEffect(() => {- connect()+ void connect()+ const resumeConnection = () => {+ if (isPageHidden()) {+ if (reconnectTimerRef.current !== null) {+ clearTimeout(reconnectTimerRef.current)+ reconnectTimerRef.current = null+ }+ if (tokenAbortRef.current) {+ connectionGenerationRef.current += 1+ tokenAbortRef.current.abort()+ tokenAbortRef.current = null+ if (tokenTimeoutRef.current !== null) {+ clearTimeout(tokenTimeoutRef.current)+ tokenTimeoutRef.current = null+ }+ }+ return+ }++ reconnectDelay.current = WS_RECONNECT_INIT+ if (tokenAbortRef.current) return++ const ws = wsRef.current+ const generation = connectionGenerationRef.current+ const authenticated = authenticatedGenerationRef.current === generation+ const fresh = authenticated+ && ws?.readyState === WebSocket.OPEN+ && Date.now() - lastMessageAtRef.current <= WS_STALE_AFTER_MS+ const connecting = ws?.readyState === WebSocket.CONNECTING+ && Date.now() - connectStartedAtRef.current <= WS_CONNECT_TIMEOUT_MS+ if (fresh || connecting) return++ connectionGenerationRef.current += 1+ if (reconnectTimerRef.current !== null) {+ clearTimeout(reconnectTimerRef.current)+ reconnectTimerRef.current = null+ }+ retireSocket()+ void connectRef.current?.()+ }+ const onVisibilityChange = () => resumeConnection()+ const onPageShow = () => resumeConnection()+ const onOnline = () => resumeConnection()+ if (typeof document !== "undefined") {+ document.addEventListener("visibilitychange", onVisibilityChange)+ }+ if (typeof window !== "undefined") {+ window.addEventListener("pageshow", onPageShow)+ window.addEventListener("online", onOnline)+ }return () => {+ if (typeof document !== "undefined") {+ document.removeEventListener("visibilitychange", onVisibilityChange)+ }+ if (typeof window !== "undefined") {+ window.removeEventListener("pageshow", onPageShow)+ window.removeEventListener("online", onOnline)+ }connectionGenerationRef.current += 1+ tokenAbortRef.current?.abort()+ tokenAbortRef.current = nullif (reconnectTimerRef.current !== null) {clearTimeout(reconnectTimerRef.current)reconnectTimerRef.current = null}+ if (tokenTimeoutRef.current !== null) { clearTimeout(tokenTimeoutRef.current); tokenTimeoutRef.current = null }+ if (connectTimeoutRef.current !== null) { clearTimeout(connectTimeoutRef.current); connectTimeoutRef.current = null }if (pingIntervalRef.current) { clearInterval(pingIntervalRef.current); pingIntervalRef.current = null }if (livenessIntervalRef.current) { clearInterval(livenessIntervalRef.current); livenessIntervalRef.current = null }- const ws = wsRef.current- wsRef.current = null- ws?.close()+ retireSocket(false)}- }, [connect])+ }, [connect, retireSocket])const send = useCallback((msg: object) => {const ws = wsRef.currentdiff --git a/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts b/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.tsindex 25dd5d9e9..295e4d398 100644--- a/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts+++ b/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts@@ -53,8 +53,16 @@ test.describe.serial("forum sidebar Stage B request shape", () => {const initialCombined = page.waitForResponse((response) =>response.ok() && isSidebarRequest(response.url(), serverId),)+ const initialNewest = page.waitForResponse((response) => {+ if (!response.ok() || !isChannelMessagesRequest(response.url(), threadId)) return false+ return !new URL(response.url()).searchParams.has("anchor")+ })+ const initialAnchored = page.waitForResponse((response) => {+ if (!response.ok() || !isChannelMessagesRequest(response.url(), threadId)) return false+ return new URL(response.url()).searchParams.has("anchor")+ })await page.goto(`/c/channels/${serverId}/${threadId}`)- await initialCombined+ await Promise.all([initialCombined, initialNewest, initialAnchored])await page.waitForURL(new RegExp(threadId), { timeout: 20_000, waitUntil: "commit" })await expect(page.getByRole("heading", { name: forumTitle })).toBeVisible({ timeout: 20_000 })await expect(page.getByText("post body", { exact: true })).toBeVisible({ timeout: 20_000 })@@ -69,10 +77,13 @@ test.describe.serial("forum sidebar Stage B request shape", () => {const coldSuccessfulMessageResponses = successfulResponses.filter((url) =>isChannelMessagesRequest(url, threadId),)- expect(coldSuccessfulMessageResponses.length).toBeGreaterThanOrEqual(1)- for (const url of coldMessageRequests) {- expect(new URL(url).searchParams.get("anchor")).toBeTruthy()- }+ expect(coldSuccessfulMessageResponses).toHaveLength(2)+ expect(coldSuccessfulMessageResponses.filter((url) => !new URL(url).searchParams.has("anchor")))+ .toHaveLength(1)+ expect(coldSuccessfulMessageResponses.filter((url) => new URL(url).searchParams.has("anchor")))+ .toHaveLength(1)+ expect(new Set(coldSuccessfulMessageResponses).size).toBe(coldSuccessfulMessageResponses.length)+ expect(coldMessageRequests.length).toBeGreaterThanOrEqual(coldSuccessfulMessageResponses.length)requests.length = 0successfulResponses.length = 0@@ -92,9 +103,20 @@ test.describe.serial("forum sidebar Stage B request shape", () => {expect(requests.filter((url) => isExactChannelRequest(url, threadId))).toHaveLength(0)expect(requests.filter(isExactMessageRequest)).toHaveLength(0)const refreshMessageRequests = requests.filter((url) => isChannelMessagesRequest(url, threadId))- for (const url of refreshMessageRequests) {- expect(new URL(url).searchParams.get("anchor")).toBeTruthy()- }+ expect(refreshMessageRequests.length).toBeGreaterThanOrEqual(1)+ const refreshSuccessfulMessageResponses = successfulResponses.filter((url) =>+ isChannelMessagesRequest(url, threadId),+ )+ const refreshNewestResponses = refreshSuccessfulMessageResponses.filter((url) =>+ !new URL(url).searchParams.has("anchor"),+ )+ const refreshAnchorResponses = refreshSuccessfulMessageResponses.filter((url) =>+ new URL(url).searchParams.has("anchor"),+ )+ expect(refreshNewestResponses.length).toBeLessThanOrEqual(1)+ expect(refreshAnchorResponses.length).toBeLessThanOrEqual(1)+ expect(new Set(refreshSuccessfulMessageResponses).size)+ .toBe(refreshSuccessfulMessageResponses.length)})test("switching between top-level channels reuses the warm canonical base", async ({ asUser }) => {