Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

refactor(community): canonicalize forum sidebar cache

Generdd69d4bd863d
diff --git a/src/shared/src/db/queries/community/thread.ts b/src/shared/src/db/queries/community/thread.ts
index 3602e19b7..3ab09999b 100644
--- a/src/shared/src/db/queries/community/thread.ts
+++ b/src/shared/src/db/queries/community/thread.ts
@@ -383,7 +383,9 @@ export async function listParticipatingForumThreads(
}
) {
const parentChannelIds = [...new Set(params.parentChannelIds)];
- if (parentChannelIds.length === 0 || params.limitPerParent < 1) return [];
+ if (parentChannelIds.length === 0 || params.limitPerParent < 1) {
+ return { canonical: [], retained: null };
+ }
const activityAt = sql<string>`coalesce(${communityChannel.lastMessageAt}, ${communityChannel.createdAt})`;
const select = {
@@ -452,13 +454,14 @@ export async function listParticipatingForumThreads(
.orderBy(asc(ranked.parentChannelId), desc(ranked.activityAt), desc(ranked.id));
}),
);
- let rows = batches.flat();
+ const rows = batches.flat();
+ let retained: (typeof rows)[number] | null = null;
if (params.retainId) {
// Scope the retained lookup inside the same caller-authorized parent set,
// rather than fetching an arbitrary id first and masking it in JS. Chunking
// preserves that structural scope without exceeding D1's bind ceiling.
- const retained = (await Promise.all(
+ retained = (await Promise.all(
chunk(parentChannelIds, D1_MAX_IN_PARAMS).map((parentIds) => db
.select(select)
.from(communityChannel)
@@ -478,24 +481,15 @@ export async function listParticipatingForumThreads(
isNotNull(communityChannel.parentMessageId),
))
.limit(1)),
- )).flat()[0];
-
- if (
- retained?.parentChannelId &&
- !rows.some((row) => row.id === retained.id)
- ) {
- const parentId = retained.parentChannelId;
- const otherParents = rows.filter((row) => row.parentChannelId !== parentId);
- const ordinary = rows
- .filter((row) => row.parentChannelId === parentId)
- .slice(0, params.limitPerParent - 1);
- rows = [...otherParents, ...ordinary, retained];
- }
+ )).flat()[0] ?? null;
}
- return rows.sort((a, b) =>
- compareSqliteBinary(a.parentChannelId ?? "", b.parentChannelId ?? "") ||
- compareSqliteBinary(b.activityAt, a.activityAt) ||
- compareSqliteBinary(b.id, a.id)
- );
+ return {
+ canonical: rows.sort((a, b) =>
+ compareSqliteBinary(a.parentChannelId ?? "", b.parentChannelId ?? "") ||
+ compareSqliteBinary(b.activityAt, a.activityAt) ||
+ compareSqliteBinary(b.id, a.id)
+ ),
+ retained,
+ };
}
diff --git a/src/shared/test/queries/community-thread.test.ts b/src/shared/test/queries/community-thread.test.ts
index 892797a5d..1197253e0 100644
--- a/src/shared/test/queries/community-thread.test.ts
+++ b/src/shared/test/queries/community-thread.test.ts
@@ -145,7 +145,8 @@ describe("listForumThreadsByActivity against real SQLite", () => {
activeAfter: "2026-08-08T03:00:00.000Z",
limitPerParent: 2,
});
- expect(recent.map((row) => row.id)).toEqual(["t_new", "t_tie_b", "foreign"]);
+ expect(recent.canonical.map((row) => row.id)).toEqual(["t_new", "t_tie_b", "foreign"]);
+ expect(recent.retained).toBeNull();
const retained = await threadQueries.listParticipatingForumThreads(db as never, {
parentChannelIds: ["forum_1", "forum_2"],
@@ -154,7 +155,8 @@ describe("listForumThreadsByActivity against real SQLite", () => {
limitPerParent: 2,
retainId: "t_created",
});
- expect(retained.map((row) => row.id)).toEqual(["t_new", "t_created", "foreign"]);
+ expect(retained.canonical.map((row) => row.id)).toEqual(["t_new", "t_tie_b", "foreign"]);
+ expect(retained.retained?.id).toBe("t_created");
const outOfScopeRetained = await threadQueries.listParticipatingForumThreads(db as never, {
parentChannelIds: ["forum_1"],
@@ -163,7 +165,8 @@ describe("listForumThreadsByActivity against real SQLite", () => {
limitPerParent: 2,
retainId: "foreign",
});
- expect(outOfScopeRetained.map((row) => row.id)).toEqual(["t_new", "t_tie_b"]);
+ expect(outOfScopeRetained.canonical.map((row) => row.id)).toEqual(["t_new", "t_tie_b"]);
+ expect(outOfScopeRetained.retained).toBeNull();
});
});
diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts b/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts
index 427489ae4..f5e137125 100644
--- a/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts
+++ b/src/web/src/app/api/community/servers/[id]/channels/route.human.test.ts
@@ -70,14 +70,15 @@ describe("GET /api/community/servers/[id]/channels — human resource", () => {
{ id: "forum_visible", serverId: "server_1", name: "Forum", type: "forum" },
{ id: "text_visible", serverId: "server_1", name: "General", type: "text" },
])
- mockListParticipatingForumThreads.mockResolvedValue([{
+ const thread = {
id: "thread_1",
serverId: "server_1",
parentChannelId: "forum_visible",
parentMessageId: "message_1",
type: "thread",
activityAt: "2026-08-08T11:00:00.000Z",
- }])
+ }
+ mockListParticipatingForumThreads.mockResolvedValue({ canonical: [thread], retained: thread })
mockGetMessagesByIds.mockResolvedValue([{ id: "message_1", content: "Current title" }])
mockListUnreadChannels.mockResolvedValue([{ channelId: "thread_1" }])
@@ -100,10 +101,62 @@ describe("GET /api/community/servers/[id]/channels — human resource", () => {
expiresAt: "2026-08-11T11:00:00.000Z",
unread: true,
})],
+ canonicalChannels: [expect.objectContaining({
+ id: "thread_1",
+ expiresAt: "2026-08-11T11:00:00.000Z",
+ unread: true,
+ })],
+ retainedChannel: expect.objectContaining({
+ id: "thread_1",
+ expiresAt: "2026-08-11T11:00:00.000Z",
+ unread: true,
+ }),
included: { parentMessages: [{ id: "message_1", content: "Current title" }] },
serverNow: "2026-08-08T12:00:00.000Z",
})
expect(mockListUnreadChannels).toHaveBeenCalledWith(expect.anything(), "user_1", ["thread_1"])
+ expect(mockGetMessagesByIds).toHaveBeenCalledWith(expect.anything(), ["message_1"])
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it("keeps canonical order intact and builds legacy retain order with binary comparison", async () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date("2026-08-08T12:00:00.000Z"))
+ mockGetMember.mockResolvedValue({ id: "member_1", role: "member" })
+ mockListServerChannelsForViewer.mockResolvedValue([
+ { id: "forum_visible", serverId: "server_1", name: "Forum", type: "forum" },
+ ])
+ const row = (id: string) => ({
+ id,
+ serverId: "server_1",
+ parentChannelId: "forum_visible",
+ parentMessageId: `message_${id}`,
+ type: "thread",
+ activityAt: "2026-08-08T11:00:00.000Z",
+ })
+ mockListParticipatingForumThreads.mockResolvedValue({
+ canonical: [row("z"), row("a")],
+ retained: row("ä"),
+ })
+ mockGetMessagesByIds.mockResolvedValue([
+ { id: "message_z", content: "Z" },
+ { id: "message_a", content: "A" },
+ { id: "message_ä", content: "Retained" },
+ ])
+
+ try {
+ const response = await GET(
+ new NextRequest("http://localhost/api/community/servers/server_1/channels?type=thread&parentType=forum&participating=true&activeWithin=72h&limitPerParent=2&retainId=ä&include=parentMessage"),
+ { params: { id: "server_1" } } as never,
+ )
+ const body = await response.json() as {
+ channels: Array<{ id: string }>
+ canonicalChannels: Array<{ id: string }>
+ }
+ expect(body.canonicalChannels.map((channel) => channel.id)).toEqual(["z", "a"])
+ expect(body.channels.map((channel) => channel.id)).toEqual(["ä", "z"])
} finally {
vi.useRealTimers()
}
diff --git a/src/web/src/app/api/community/servers/[id]/channels/route.ts b/src/web/src/app/api/community/servers/[id]/channels/route.ts
index 5a01c33a7..ad2e42383 100644
--- a/src/web/src/app/api/community/servers/[id]/channels/route.ts
+++ b/src/web/src/app/api/community/servers/[id]/channels/route.ts
@@ -5,6 +5,10 @@ import { withCommunityActor } from "@/lib/middleware/community-actor"
import { buildServerChannelGroups } from "@/lib/community/list-channels"
import { requireServerMember } from "@/lib/community/permissions"
+function compareBinary(left: string, right: string): number {
+ return left === right ? 0 : left < right ? -1 : 1
+}
+
/**
* GET /api/community/servers/[id]/channels — single-server channel list. Human
* callers receive the visible top-level tree, with one strict participating
@@ -57,13 +61,19 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
const serverNow = new Date().toISOString()
const windowMs = 72 * 60 * 60 * 1000
const activeAfter = new Date(Date.parse(serverNow) - windowMs).toISOString()
- const rows = await queries.communityThread.listParticipatingForumThreads(db, {
+ const projection = await queries.communityThread.listParticipatingForumThreads(db, {
parentChannelIds: forumIds,
userId: ctx.actor.userId,
activeAfter,
limitPerParent,
...(retainId ? { retainId } : {}),
})
+ const rows = [...new Map(
+ (projection.retained
+ ? [...projection.canonical, projection.retained]
+ : projection.canonical)
+ .map((channel) => [channel.id, channel] as const),
+ ).values()]
const parentMessageIds = rows
.map((channel) => channel.parentMessageId)
.filter((id): id is string => !!id)
@@ -72,12 +82,38 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
queries.communityInbox.listUnreadChannels(db, ctx.actor.userId, rows.map((channel) => channel.id)),
])
const unreadIds = new Set(unreadRows.map((row) => row.channelId))
- const channels = rows.map((channel) => ({
+ const projectChannel = (channel: (typeof rows)[number]) => ({
...channel,
expiresAt: new Date(Date.parse(channel.activityAt) + windowMs).toISOString(),
unread: unreadIds.has(channel.id),
- }))
- return NextResponse.json({ channels, included: { parentMessages }, serverNow })
+ })
+ const canonicalChannels = projection.canonical.map(projectChannel)
+ const retainedChannel = projection.retained ? projectChannel(projection.retained) : null
+ let channels = canonicalChannels
+ if (
+ retainedChannel?.parentChannelId &&
+ !canonicalChannels.some((channel) => channel.id === retainedChannel.id)
+ ) {
+ const parentId = retainedChannel.parentChannelId
+ channels = [
+ ...canonicalChannels.filter((channel) => channel.parentChannelId !== parentId),
+ ...canonicalChannels
+ .filter((channel) => channel.parentChannelId === parentId)
+ .slice(0, limitPerParent - 1),
+ retainedChannel,
+ ].sort((a, b) =>
+ compareBinary(a.parentChannelId ?? "", b.parentChannelId ?? "") ||
+ compareBinary(b.activityAt, a.activityAt) ||
+ compareBinary(b.id, a.id)
+ )
+ }
+ return NextResponse.json({
+ channels,
+ canonicalChannels,
+ retainedChannel,
+ included: { parentMessages },
+ serverNow,
+ })
}
const botUserId = ctx.actor.userId
diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsx
index 885948fe1..f85df5ebd 100644
--- a/src/web/src/app/c/channels/layout.tsx
+++ b/src/web/src/app/c/channels/layout.tsx
@@ -35,12 +35,12 @@ import {
import { clearLastChannel } from "@/lib/community/last-channel"
import { usePresence } from "@/hooks/community/use-server-panels"
import {
- patchForumSidebarUnread,
+ patchForumSidebarUnreadExact,
removeForumSidebarUnreadChild,
+ resolveForumSidebarRouteCandidate,
setForumSidebarParentUnreadBase,
useForumSidebarThreads,
type ForumSidebarThread,
- type ForumSidebarQueryData,
} from "@/hooks/community/use-forum-sidebar-threads"
import { useCommunityWsStore, useOnlineUserIds } from "@/stores/community/ws"
import { useNotificationSettings } from "@/hooks/community/use-notification-settings"
@@ -66,6 +66,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
const params = useParams<{ serverId: string; channelId?: string }>()
const searchParams = useSearchParams()
const serverId = decodeURIComponent(params.serverId)
+ const routeChannelId = params.channelId ? decodeURIComponent(params.channelId) : null
const hasChannel = !!params.channelId
const router = useRouter()
@@ -112,7 +113,16 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
.find((channel) => channel.id === currentChannelMeta.parentChannelId)
return isForum(parent?.type) ? currentChannelId : null
}, [currentChannelId, currentChannelMeta?.parentChannelId, currentServer])
- const forumSidebar = useForumSidebarThreads(serverId, activeForumThreadId)
+ const sidebarRouteCandidate = useMemo(() => {
+ const topLevelIds = currentServer?.categories
+ ?.flatMap((category) => category.channels.map((channel) => channel.id)) ?? null
+ return resolveForumSidebarRouteCandidate(routeChannelId, topLevelIds)
+ }, [routeChannelId, currentServer])
+ const forumSidebar = useForumSidebarThreads(
+ serverId,
+ sidebarRouteCandidate,
+ !!currentServer?.categories,
+ )
const forumThreadsByParent = useMemo(() => {
const grouped: Record<string, ForumSidebarThread[]> = {}
for (const thread of forumSidebar.threads) {
@@ -249,7 +259,14 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
)
}, [searchParams, serverId, router, hasChannel, currentServer, params.channelId])
- const categories = currentServer?.categories ?? []
+ const categories = useMemo(() => (currentServer?.categories ?? []).map((category) => ({
+ ...category,
+ channels: category.channels.map((channel) =>
+ forumSidebar.parentUnread[channel.id] === undefined
+ ? channel
+ : { ...channel, unread: forumSidebar.parentUnread[channel.id] },
+ ),
+ })), [currentServer?.categories, forumSidebar.parentUnread])
const channelTree = useChannelTree(categories)
const goHome = useCallback(() => {
@@ -309,10 +326,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
markSwitch("channel", id)
router.push(`/c/channels/${serverId}/${id}`)
removeForumSidebarUnreadChild(queryClient, serverId, id)
- queryClient.setQueriesData<ForumSidebarQueryData>(
- { queryKey: communityKeys.forumSidebarThreads(serverId) },
- (data) => patchForumSidebarUnread(data, id, false),
- )
+ patchForumSidebarUnreadExact(queryClient, serverId, id, false)
if (bp === "mobile") setMobileZone("messages")
}, [bp, queryClient, router, serverId])
diff --git a/src/web/src/components/community/channel-member-view-model.test.ts b/src/web/src/components/community/channel-member-view-model.test.ts
index 94e176e26..c56695dde 100644
--- a/src/web/src/components/community/channel-member-view-model.test.ts
+++ b/src/web/src/components/community/channel-member-view-model.test.ts
@@ -17,6 +17,8 @@ const mocks = vi.hoisted(() => ({
removeChannelMember: vi.fn(),
addThreadParticipant: vi.fn(),
removeThreadParticipant: vi.fn(),
+ addThreadHookArgs: [] as unknown[][],
+ removeThreadHookArgs: [] as unknown[][],
setMemberRole: vi.fn(),
kickMember: vi.fn(),
}))
@@ -43,8 +45,14 @@ vi.mock("@/hooks/community/use-channel-members", () => ({
useRemoveChannelMember: () => ({ mutateAsync: mocks.removeChannelMember }),
}))
vi.mock("@/hooks/community/use-thread-participants", () => ({
- useAddThreadParticipant: () => ({ mutateAsync: mocks.addThreadParticipant }),
- useRemoveThreadParticipant: () => ({ mutateAsync: mocks.removeThreadParticipant }),
+ useAddThreadParticipant: (...args: unknown[]) => {
+ mocks.addThreadHookArgs.push(args)
+ return { mutateAsync: mocks.addThreadParticipant }
+ },
+ useRemoveThreadParticipant: (...args: unknown[]) => {
+ mocks.removeThreadHookArgs.push(args)
+ return { mutateAsync: mocks.removeThreadParticipant }
+ },
}))
vi.mock("@/hooks/community/mutations", () => ({
useSetMemberRole: () => ({ mutate: mocks.setMemberRole }),
@@ -133,9 +141,39 @@ describe("useChannelMemberViewModel", () => {
mocks.removeChannelMember.mockResolvedValue({})
mocks.addThreadParticipant.mockResolvedValue({})
mocks.removeThreadParticipant.mockResolvedValue({})
+ mocks.addThreadHookArgs = []
+ mocks.removeThreadHookArgs = []
mocks.kickMember.mockResolvedValue({})
})
+ it("scopes forum sidebar participant mutations only to children of a forum", () => {
+ const child = (parentType: string) => props({
+ channelId: "thread_1",
+ currentServer: {
+ categories: [{
+ private: false,
+ channels: [{ id: "parent_1", type: parentType }],
+ }],
+ },
+ channelInServer: null,
+ currentChannelMeta: { name: "Thread", parentChannelId: "parent_1" },
+ isChildChannel: true,
+ isNotifyUnit: true,
+ })
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(renderHarness(child("text")))
+ })
+ expect(mocks.addThreadHookArgs.at(-1)).toEqual(["thread_1", undefined, "viewer_1"])
+ expect(mocks.removeThreadHookArgs.at(-1)).toEqual(["thread_1", "server_1", "viewer_1", false])
+
+ act(() => {
+ renderer!.update(renderHarness(child("forum")))
+ })
+ expect(mocks.addThreadHookArgs.at(-1)).toEqual(["thread_1", "server_1", "viewer_1"])
+ expect(mocks.removeThreadHookArgs.at(-1)).toEqual(["thread_1", "server_1", "viewer_1", true])
+ })
+
afterEach(() => {
vi.clearAllMocks()
})
diff --git a/src/web/src/components/community/channel-member-view-model.tsx b/src/web/src/components/community/channel-member-view-model.tsx
index 176e8b93a..d5b3f8105 100644
--- a/src/web/src/components/community/channel-member-view-model.tsx
+++ b/src/web/src/components/community/channel-member-view-model.tsx
@@ -2,6 +2,7 @@
import { useEffect, useMemo, useState, type ComponentProps, type ReactNode } from "react"
import { toast } from "sonner"
+import { isForum } from "@alook/shared"
import { AddMembersDialog } from "@/components/community/add-members-dialog"
import type { CommunityPanelSheet } from "@/components/community/community-panel-sheet"
import type { Member, Role } from "@/components/community/_types"
@@ -42,7 +43,7 @@ export type ChannelMemberPanelProps = Pick<
type ServerModel = {
categories?: Array<{
private?: number | boolean
- channels: Array<{ id: string }>
+ channels: Array<{ id: string; type?: string }>
}>
} | null | undefined
@@ -135,8 +136,25 @@ export function useChannelMemberViewModel({
)
const addChannelMemberMut = useAddChannelMember(channelId)
const removeChannelMemberMut = useRemoveChannelMember(channelId)
- const addThreadParticipantMut = useAddThreadParticipant(channelId)
- const removeThreadParticipantMut = useRemoveThreadParticipant(channelId, serverId, currentUser.id)
+ const parentChannel = currentChannelMeta?.parentChannelId
+ ? currentServer?.categories
+ ?.flatMap((category) => category.channels)
+ .find((channel) => channel.id === currentChannelMeta.parentChannelId)
+ : null
+ const forumSidebarServerId = isChildChannel && isForum(parentChannel?.type)
+ ? serverId
+ : undefined
+ const addThreadParticipantMut = useAddThreadParticipant(
+ channelId,
+ forumSidebarServerId,
+ currentUser.id,
+ )
+ const removeThreadParticipantMut = useRemoveThreadParticipant(
+ channelId,
+ serverId,
+ currentUser.id,
+ !!forumSidebarServerId,
+ )
const setMemberRoleMut = useSetMemberRole()
const kickMemberMut = useKickMember()
diff --git a/src/web/src/components/community/channel-route.text-scroll-target.test.ts b/src/web/src/components/community/channel-route.text-scroll-target.test.ts
index 034fe91a6..e9d940b96 100644
--- a/src/web/src/components/community/channel-route.text-scroll-target.test.ts
+++ b/src/web/src/components/community/channel-route.text-scroll-target.test.ts
@@ -101,6 +101,9 @@ vi.mock("@/contexts/community/current-user", () => ({
vi.mock("@/hooks/community/use-channel-route-model", () => ({
useChannelRouteModel: () => mockRouteModel,
}))
+vi.mock("@/hooks/community/use-forum-opener-hint", () => ({
+ useForumOpenerHint: () => ({ data: null, isLoading: false }),
+}))
vi.mock("@/hooks/community/use-server-members", () => ({
useServerMembers: () => ({
members: [],
diff --git a/src/web/src/components/community/channel-route.tsx b/src/web/src/components/community/channel-route.tsx
index d6aae428e..6cfb71fad 100644
--- a/src/web/src/components/community/channel-route.tsx
+++ b/src/web/src/components/community/channel-route.tsx
@@ -23,7 +23,7 @@ import {
} from "@/stores/community"
import { useCurrentUser } from "@/contexts/community/current-user"
import { useChannelRouteModel } from "@/hooks/community/use-channel-route-model"
-import { useMessage } from "@/hooks/community/use-message"
+import { useForumOpenerHint } from "@/hooks/community/use-forum-opener-hint"
import { useNotificationSettings } from "@/hooks/community/use-notification-settings"
import { useSetChannelNotif } from "@/hooks/community/mutations"
@@ -65,17 +65,19 @@ export function ChannelRoute({ serverParam, channelId }: { serverParam: string;
isForumPostChild,
isNotifyUnit,
} = routeModel
- const { message: forumPostOpener, isLoading: forumPostOpenerLoading } = useMessage(
- isForumPostChild ? currentChannelMeta?.parentMessageId : null,
+ const forumPostOpener = useForumOpenerHint(
+ serverId,
+ currentChannelMeta?.parentMessageId,
+ isForumPostChild && routeModel.routeHydrated,
)
const channelName = useMemo(() => resolveChannelDisplayName({
- forumPostTitle: isForumPostChild ? forumPostOpener?.content : null,
+ forumPostTitle: isForumPostChild ? forumPostOpener.data?.content : null,
topLevelName: channelInServer?.name,
childChannelName: isForumPostChild ? null : currentChannelMeta?.name,
forumListName: null,
threadListName: null,
fallback: isForumPostChild ? "Post" : "channel",
- }), [channelInServer, currentChannelMeta, forumPostOpener, isForumPostChild])
+ }), [channelInServer, currentChannelMeta, forumPostOpener.data?.content, isForumPostChild])
const memberViewModel = useChannelMemberViewModel({
serverId,
channelId,
@@ -143,7 +145,7 @@ export function ChannelRoute({ serverParam, channelId }: { serverParam: string;
const channelHydrated =
currentChannelId === channelId &&
routeModel.routeHydrated &&
- (!isForumPostChild || !forumPostOpenerLoading)
+ (!isForumPostChild || !forumPostOpener.isLoading)
if (!channelHydrated) {
if (isForum) {
return (
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.ts
index d37706293..985432c91 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
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import type { CommunityMemberJoin, CommunityMemberUpdate } from "@alook/shared"
+import type { CommunityMemberJoin, CommunityMemberLeave, CommunityMemberUpdate } from "@alook/shared"
import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
import { communityKeys } from "@/lib/query-keys"
import {
@@ -15,6 +15,35 @@ beforeEach(resetCommunityWsHarness)
afterEach(cleanupCommunityWsHarness)
describe("useCommunityWs — member events", () => {
+ it("clears the active private route immediately when the viewer leaves the server", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentServerId("srv_1")
+ useCommunityStore.getState().setCurrentChannelId("private_child")
+ useCommunityStore.getState().setCurrentChannelMeta({
+ name: "Private title",
+ parentChannelId: "private_parent",
+ })
+ capturedQueryClient.setQueryData(communityKeys.server("srv_1"), {
+ id: "srv_1",
+ categories: [],
+ })
+
+ capturedOnMessage!({
+ type: "community:member.leave",
+ serverId: "srv_1",
+ userId: "u_me",
+ memberId: "member_me",
+ } satisfies CommunityMemberLeave)
+
+ expect(useCommunityStore.getState()).toMatchObject({
+ currentServerId: null,
+ currentChannelId: null,
+ currentChannelMeta: null,
+ })
+ expect(capturedQueryClient.getQueryState(communityKeys.server("srv_1"))).toBeUndefined()
+ })
+
it("patches the members cache with a join event", async () => {
await mountHook()
capturedQueryClient.setQueryData(communityKeys.members("srv_1"), {
@@ -169,8 +198,15 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
it("adds/removes the viewer's participating child in the forum sidebar", async () => {
await mountHook({ viewerUserId: "u_me" })
- const key = communityKeys.forumSidebarThreadsView("srv_1", null)
+ const { useCommunityStore } = await import("@/stores/community")
+ const key = communityKeys.forumSidebarThreads("srv_1")
capturedQueryClient.setQueryData(key, forumSidebarFixture())
+ useCommunityStore.getState().setCurrentChannelId("post_1")
+ useCommunityStore.getState().setCurrentChannelMeta({
+ name: "Private forum title",
+ parentChannelId: "forum_1",
+ parentMessageId: "opener-post_1",
+ })
capturedOnMessage!({
type: "community:channel.member_remove",
@@ -179,6 +215,7 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
userId: "u_me",
})
expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(key)?.threads).toEqual([])
+ expect(useCommunityStore.getState().currentChannelMeta).toBeNull()
capturedQueryClient.setQueryData(key, forumSidebarFixture([]))
capturedOnMessage!({
@@ -189,4 +226,68 @@ describe("useCommunityWs — channel.member_add/remove → invalidate rosters",
})
expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)
})
+
+ it("does not touch forum resources for a known ordinary text child", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ const baseKey = communityKeys.forumSidebarThreads("srv_1")
+ const retainedKey = communityKeys.forumSidebarRetained("srv_1", "forum_post")
+ const metaKey = communityKeys.channelMeta("srv_1", "text_thread")
+ const hintKey = communityKeys.forumOpenerHint("srv_1", "forum_opener")
+ capturedQueryClient.setQueryData(communityKeys.server("srv_1"), {
+ id: "srv_1",
+ categories: [{
+ id: "cat_1",
+ channels: [{ id: "text_parent", type: "text" }],
+ }],
+ })
+ capturedQueryClient.setQueryData(baseKey, forumSidebarFixture())
+ capturedQueryClient.setQueryData(retainedKey, { id: "forum_post" })
+ capturedQueryClient.setQueryData(metaKey, {
+ id: "text_thread",
+ serverId: "srv_1",
+ parentChannelId: "text_parent",
+ parentMessageId: "text_opener",
+ type: "thread",
+ })
+ capturedQueryClient.setQueryData(hintKey, { id: "forum_opener", content: "Forum title" })
+ const before = {
+ base: capturedQueryClient.getQueryData(baseKey),
+ retained: capturedQueryClient.getQueryData(retainedKey),
+ meta: capturedQueryClient.getQueryData(metaKey),
+ hint: capturedQueryClient.getQueryData(hintKey),
+ }
+
+ capturedOnMessage!({
+ type: "community:channel.member_add",
+ serverId: "srv_1",
+ channelId: "text_thread",
+ userId: "u_me",
+ })
+
+ expect(capturedQueryClient.getQueryData(baseKey)).toBe(before.base)
+ expect(capturedQueryClient.getQueryState(baseKey)?.isInvalidated).toBe(false)
+ expect(capturedQueryClient.getQueryData(retainedKey)).toBe(before.retained)
+ expect(capturedQueryClient.getQueryData(metaKey)).toBe(before.meta)
+ expect(capturedQueryClient.getQueryData(hintKey)).toBe(before.hint)
+
+ useCommunityStore.getState().setCurrentChannelId("text_thread")
+ useCommunityStore.getState().setCurrentChannelMeta({
+ name: "Private title",
+ parentChannelId: "text_parent",
+ })
+ capturedOnMessage!({
+ type: "community:channel.member_remove",
+ serverId: "srv_1",
+ channelId: "text_thread",
+ userId: "u_me",
+ })
+
+ expect(capturedQueryClient.getQueryData(baseKey)).toBe(before.base)
+ expect(capturedQueryClient.getQueryState(baseKey)?.isInvalidated).toBe(false)
+ expect(capturedQueryClient.getQueryData(retainedKey)).toBe(before.retained)
+ expect(capturedQueryClient.getQueryState(metaKey)).toBeUndefined()
+ expect(capturedQueryClient.getQueryData(hintKey)).toBe(before.hint)
+ expect(useCommunityStore.getState().currentChannelMeta).toBeNull()
+ })
})
diff --git a/src/web/src/hooks/community/community-ws/membership-events.ts b/src/web/src/hooks/community/community-ws/membership-events.ts
index e939017b3..7ddb49228 100644
--- a/src/web/src/hooks/community/community-ws/membership-events.ts
+++ b/src/web/src/hooks/community/community-ws/membership-events.ts
@@ -7,6 +7,7 @@ import type {
} from "@alook/shared"
import { communityKeys } from "@/lib/query-keys"
import { useMessageStreamStore } from "@/stores/community/message-stream"
+import { useCommunityStore } from "@/stores/community"
import {
patchCacheJoin,
patchCacheLeave,
@@ -14,9 +15,11 @@ import {
type MembersEnvelope,
} from "@/hooks/community/use-server-members"
import {
- removeForumSidebarThread,
+ grantForumSidebarChild,
+ isKnownNonForumSidebarChannel,
+ removeForumSidebarChildrenForParent,
+ removeForumSidebarThreadExact,
removeForumSidebarUnreadChild,
- type ForumSidebarQueryData,
} from "@/hooks/community/use-forum-sidebar-threads"
import { patchAuthorNameInCache, type PageCache } from "@/hooks/community/community-ws/cache"
import type { MembershipEventContext } from "@/hooks/community/community-ws/handler-context"
@@ -38,7 +41,24 @@ export function handleChannelMemberEvent(
event.type === "community:channel.member_remove" &&
event.userId === viewerUserIdRef.current
) {
- removeForumSidebarUnreadChild(queryClient, event.serverId, event.channelId)
+ const nonForum = isKnownNonForumSidebarChannel(
+ queryClient,
+ event.serverId,
+ event.channelId,
+ )
+ if (!nonForum) {
+ removeForumSidebarUnreadChild(queryClient, event.serverId, event.channelId)
+ removeForumSidebarChildrenForParent(queryClient, event.serverId, event.channelId)
+ removeForumSidebarThreadExact(queryClient, event.serverId, event.channelId)
+ } else {
+ queryClient.removeQueries({
+ queryKey: communityKeys.channelMeta(event.serverId, event.channelId),
+ exact: true,
+ })
+ }
+ if (useCommunityStore.getState().currentChannelId === event.channelId) {
+ useCommunityStore.getState().setCurrentChannelMeta(null)
+ }
useMessageStreamStore.getState().removeScope({
kind: "channel",
id: event.channelId,
@@ -47,19 +67,18 @@ export function handleChannelMemberEvent(
queryClient.removeQueries({ queryKey: communityKeys.channelMessages(event.channelId) })
queryClient.removeQueries({ queryKey: communityKeys.pins(event.channelId) })
queryClient.removeQueries({ queryKey: communityKeys.threads(event.channelId) })
- queryClient.setQueriesData<ForumSidebarQueryData>(
- { queryKey: communityKeys.forumSidebarThreads(event.serverId) },
- (data) => removeForumSidebarThread(data, event.channelId),
- )
} else if (
event.type === "community:channel.member_add" &&
event.userId === viewerUserIdRef.current
) {
- void queryClient.invalidateQueries({
- queryKey: communityKeys.forumSidebarThreads(event.serverId),
- })
+ if (!isKnownNonForumSidebarChannel(queryClient, event.serverId, event.channelId)) {
+ void grantForumSidebarChild(queryClient, event.serverId, event.channelId)
+ }
}
- void queryClient.invalidateQueries({ queryKey: communityKeys.server(event.serverId) })
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.server(event.serverId),
+ exact: true,
+ })
// Refetch the channel roster so an open private-channel Members drawer
// (and the manage-members dialog) reflect the add/remove live.
void queryClient.invalidateQueries({ queryKey: communityKeys.channelMembers(event.channelId) })
@@ -116,6 +135,13 @@ export function handleMemberLeave(
// the user away from the now-forbidden URL.
if (event.userId === viewerUserIdRef.current) {
useMessageStreamStore.getState().removeServer(event.serverId)
+ queryClient.removeQueries({ queryKey: communityKeys.server(event.serverId) })
+ const store = useCommunityStore.getState()
+ if (store.currentServerId === event.serverId) {
+ store.setCurrentChannelMeta(null)
+ store.setCurrentChannelId(null)
+ store.setCurrentServerId(null)
+ }
// Rail LIST only (the layout's eject effect reads it to route the
// kicked viewer away). `exact` so a kick doesn't cascade-refetch
// every server's nested detail subtree.
diff --git a/src/web/src/hooks/community/community-ws/message-events.test.ts b/src/web/src/hooks/community/community-ws/message-events.test.ts
index b5eb5cbbf..d23e7cc90 100644
--- a/src/web/src/hooks/community/community-ws/message-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/message-events.test.ts
@@ -22,10 +22,18 @@ import {
beforeEach(resetCommunityWsHarness)
afterEach(cleanupCommunityWsHarness)
+function seedParent(serverId: string, parentId: string, type: "forum" | "text") {
+ capturedQueryClient.setQueryData(communityKeys.server(serverId), {
+ id: serverId,
+ categories: [{ id: "cat_1", channels: [{ id: parentId, type }] }],
+ })
+}
+
describe("useCommunityWs — message.create", () => {
it("patches a loaded forum-sidebar child activity without a refetch", async () => {
await mountHook()
- const key = communityKeys.forumSidebarThreadsView("srv_1", null)
+ seedParent("srv_1", "forum_1", "forum")
+ const key = communityKeys.forumSidebarThreads("srv_1")
capturedQueryClient.setQueryData(key, forumSidebarFixture())
const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
const event = {
@@ -47,7 +55,8 @@ describe("useCommunityWs — message.create", () => {
it("invalidates the forum-sidebar collection when the active child is not loaded", async () => {
await mountHook()
- const key = communityKeys.forumSidebarThreadsView("srv_1", null)
+ seedParent("srv_1", "forum_1", "forum")
+ const key = communityKeys.forumSidebarThreads("srv_1")
capturedQueryClient.setQueryData(key, forumSidebarFixture([]))
capturedOnMessage!({
@@ -59,6 +68,86 @@ describe("useCommunityWs — message.create", () => {
expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)
})
+ it.each([false, true])(
+ "invalidates canonical base for a retained-only child (active=%s) so it survives route exit",
+ async (active) => {
+ if (active) {
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ channelId: "post_retained" })
+ }
+ await mountHook()
+ seedParent("srv_1", "forum_1", "forum")
+ const key = communityKeys.forumSidebarThreads("srv_1")
+ const retainedKey = communityKeys.forumSidebarRetained("srv_1", "post_retained")
+ capturedQueryClient.setQueryData(key, forumSidebarFixture([]))
+ capturedQueryClient.setQueryData(
+ retainedKey,
+ forumSidebarFixture(["post_retained"]).threads[0],
+ )
+
+ capturedOnMessage!({
+ ...messageCreate("post_retained"),
+ serverId: "srv_1",
+ parentChannelId: "forum_1",
+ } satisfies CommunityMessageCreate)
+
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>["threads"][number]>(
+ retainedKey,
+ )).toMatchObject({
+ activityAt: "2026-07-03T00:00:00.000Z",
+ expiresAt: "2026-07-06T00:00:00.000Z",
+ })
+ expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)
+
+ capturedQueryClient.setQueryData(key, forumSidebarFixture(["post_retained"]))
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(key)
+ ?.threads.some((thread) => thread.id === "post_retained")).toBe(true)
+ },
+ )
+
+ it("does not touch forum resources for ordinary text-thread create or opener edit", async () => {
+ await mountHook()
+ seedParent("s1", "text_parent", "text")
+ const baseKey = communityKeys.forumSidebarThreads("s1")
+ const retainedKey = communityKeys.forumSidebarRetained("s1", "forum_post")
+ const metaKey = communityKeys.channelMeta("s1", "text_thread")
+ const hintKey = communityKeys.forumOpenerHint("s1", "forum_opener")
+ capturedQueryClient.setQueryData(baseKey, forumSidebarFixture())
+ capturedQueryClient.setQueryData(retainedKey, { id: "forum_post" })
+ capturedQueryClient.setQueryData(metaKey, {
+ id: "text_thread",
+ parentChannelId: "text_parent",
+ })
+ capturedQueryClient.setQueryData(hintKey, { id: "forum_opener", content: "Forum title" })
+ const before = [
+ capturedQueryClient.getQueryData(baseKey),
+ capturedQueryClient.getQueryData(retainedKey),
+ capturedQueryClient.getQueryData(metaKey),
+ capturedQueryClient.getQueryData(hintKey),
+ ]
+
+ capturedOnMessage!({
+ ...messageCreate("text_thread"),
+ serverId: "s1",
+ parentChannelId: "text_parent",
+ } satisfies CommunityMessageCreate)
+ capturedOnMessage!({
+ type: "community:message.edited",
+ channelId: "text_thread",
+ messageId: "text_opener",
+ content: "Text title",
+ parentChannelId: "text_parent",
+ } satisfies CommunityMessageEdited)
+
+ expect(capturedQueryClient.getQueryState(baseKey)?.isInvalidated).toBe(false)
+ expect([
+ capturedQueryClient.getQueryData(baseKey),
+ capturedQueryClient.getQueryData(retainedKey),
+ capturedQueryClient.getQueryData(metaKey),
+ capturedQueryClient.getQueryData(hintKey),
+ ]).toEqual(before)
+ })
+
it("writes the channel overlay and leaves the base cache untouched when focused", async () => {
await mountHook()
const { useCommunityStore } = await import("@/stores/community")
@@ -573,6 +662,7 @@ describe("useCommunityWs — DM message.create", () => {
describe("useCommunityWs — message edit refreshes forum opener summary", () => {
it("invalidates the parent thread list for an opener edit, but not for an ordinary reply", async () => {
await mountHook()
+ seedParent("s1", "forum_1", "forum")
const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
const opener: CommunityMessageEdited = {
type: "community:message.edited",
@@ -590,7 +680,7 @@ describe("useCommunityWs — message edit refreshes forum opener summary", () =>
const forumPage = { pages: [{ messages: [{ id: "opener_1", content: "old title" }] }], pageParams: [null] }
capturedQueryClient.setQueryData(allKey, forumPage)
capturedQueryClient.setQueryData(bugKey, forumPage)
- const sidebarKey = communityKeys.forumSidebarThreadsView("s1", null)
+ const sidebarKey = communityKeys.forumSidebarThreads("s1")
capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture())
capturedOnMessage!(opener)
expect(invalidateSpy).toHaveBeenCalledWith({ queryKey: communityKeys.channelMessages("forum_1") })
diff --git a/src/web/src/hooks/community/community-ws/message-events.ts b/src/web/src/hooks/community/community-ws/message-events.ts
index 0372f90cb..fbbfbb29d 100644
--- a/src/web/src/hooks/community/community-ws/message-events.ts
+++ b/src/web/src/hooks/community/community-ws/message-events.ts
@@ -13,10 +13,12 @@ import type { CanonicalMessage } from "@/lib/community/message-stream"
import { useCommunityStore } from "@/stores/community"
import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
import {
+ getForumSidebarBase,
hasForumSidebarThread,
- patchForumSidebarActivity,
- patchForumSidebarTitle,
- type ForumSidebarQueryData,
+ isForumSidebarParent,
+ invalidateForumSidebarBaseExact,
+ patchForumSidebarActivityExact,
+ patchForumSidebarTitleExact,
} from "@/hooks/community/use-forum-sidebar-threads"
import {
applyReactionToCache,
@@ -75,22 +77,24 @@ export function handleMessageCreate(
// message reaches every notify member even when muted; use its
// explicit server/parent metadata to re-rank a loaded row without a
// GET, or refetch when the active post is currently absent/expired.
- if (event.serverId && event.parentChannelId) {
- const key = communityKeys.forumSidebarThreads(event.serverId)
- const cached = queryClient.getQueriesData<ForumSidebarQueryData>({ queryKey: key })
- const loaded = cached.some(([, data]) => hasForumSidebarThread(data, event.channelId))
- if (loaded) {
- queryClient.setQueriesData<ForumSidebarQueryData>(
- { queryKey: key },
- (data) => patchForumSidebarActivity(
- data,
- event.channelId,
- event.parentChannelId!,
- event.message.createdAt,
- ),
- )
- } else {
- void queryClient.invalidateQueries({ queryKey: key })
+ if (
+ event.serverId &&
+ event.parentChannelId &&
+ isForumSidebarParent(queryClient, event.serverId, event.parentChannelId)
+ ) {
+ const canonical = hasForumSidebarThread(
+ getForumSidebarBase(queryClient, event.serverId),
+ event.channelId,
+ )
+ patchForumSidebarActivityExact(
+ queryClient,
+ event.serverId,
+ event.channelId,
+ event.parentChannelId,
+ event.message.createdAt,
+ )
+ if (!canonical) {
+ void invalidateForumSidebarBaseExact(queryClient, event.serverId)
}
}
@@ -281,11 +285,8 @@ export function handleMessageEdited(
queryKey: communityKeys.channelMessages(event.parentChannelId),
})
const serverId = useCommunityStore.getState().currentServerId
- if (serverId) {
- queryClient.setQueriesData<ForumSidebarQueryData>(
- { queryKey: communityKeys.forumSidebarThreads(serverId) },
- (data) => patchForumSidebarTitle(data, event.channelId, event.content),
- )
+ if (serverId && isForumSidebarParent(queryClient, serverId, event.parentChannelId)) {
+ patchForumSidebarTitleExact(queryClient, serverId, event.channelId, event.content)
}
}
}
diff --git a/src/web/src/hooks/community/community-ws/reconnect.test.ts b/src/web/src/hooks/community/community-ws/reconnect.test.ts
index b000e1802..33676703b 100644
--- a/src/web/src/hooks/community/community-ws/reconnect.test.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect.test.ts
@@ -114,6 +114,40 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
).toBe(true)
})
+ it("drops every inactive retained/meta/hint access result before reconnect validation", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentServerId("srv_open")
+ capturedQueryClient.setQueryData(
+ communityKeys.forumSidebarRetained("srv_open", "post-a"),
+ { id: "post-a" },
+ )
+ capturedQueryClient.setQueryData(
+ communityKeys.forumSidebarRetained("srv_open", "post-b"),
+ null,
+ )
+ capturedQueryClient.setQueryData(
+ communityKeys.channelMeta("srv_open", "post-a"),
+ { id: "post-a", verifiedEpoch: 0 },
+ )
+ capturedQueryClient.setQueryData(
+ communityKeys.forumOpenerHint("srv_open", "opener-a"),
+ { id: "opener-a", content: "private title" },
+ )
+
+ capturedOnReconnect!()
+
+ 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([])
+ })
+
it("invalidates the focused DM's messages on reconnect, but NOT its read-state snapshot", async () => {
const { useCommunityStore } = await import("@/stores/community")
useCommunityStore.getState().subscribe({ dmConversationId: "dm_focus" })
diff --git a/src/web/src/hooks/community/community-ws/reconnect.ts b/src/web/src/hooks/community/community-ws/reconnect.ts
index f35f8a181..22c5a1252 100644
--- a/src/web/src/hooks/community/community-ws/reconnect.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect.ts
@@ -1,6 +1,7 @@
import type { QueryClient } from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
import { useCommunityStore } from "@/stores/community"
+import { invalidateForumSidebarBaseExact } from "@/hooks/community/use-forum-sidebar-threads"
/**
* Machines are WS-live-patched with no query refetch (see `use-machines.ts`)
@@ -74,6 +75,17 @@ export function reconcileCommunityWsReconnect(queryClient: QueryClient) {
if (currentServerId) {
void queryClient.invalidateQueries({
queryKey: communityKeys.server(currentServerId),
+ exact: true,
+ })
+ void invalidateForumSidebarBaseExact(queryClient, currentServerId)
+ queryClient.removeQueries({
+ queryKey: communityKeys.forumSidebarRetainedRoot(currentServerId),
+ })
+ queryClient.removeQueries({
+ queryKey: communityKeys.channelMetaRoot(currentServerId),
+ })
+ queryClient.removeQueries({
+ queryKey: communityKeys.forumOpenerHintRoot(currentServerId),
})
}
// Bot audit logs are WS-live-patched into the React Query cache; if
diff --git a/src/web/src/hooks/community/community-ws/social-events.test.ts b/src/web/src/hooks/community/community-ws/social-events.test.ts
index 85bbbdc97..0ace4bfe0 100644
--- a/src/web/src/hooks/community/community-ws/social-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/social-events.test.ts
@@ -8,6 +8,7 @@ import { getMessageOverlay } from "@/stores/community/message-stream"
import { communityKeys } from "@/lib/query-keys"
import type { ServerDetail } from "../use-servers"
import {
+ deriveForumSidebarProjection,
patchForumSidebarUnread,
reconcileForumSidebarUnreadFallbacks,
type ForumSidebarQueryData,
@@ -29,7 +30,7 @@ beforeEach(resetCommunityWsHarness)
afterEach(cleanupCommunityWsHarness)
describe("useCommunityWs — message.create patches channel unread in the open server's cache", () => {
- function serverDetailFixture(channelId: string) {
+ function serverDetailFixture(channelId: string, type = "text") {
return {
id: "srv_open",
name: "Server",
@@ -37,7 +38,7 @@ describe("useCommunityWs — message.create patches channel unread in the open s
icon: null,
ownerId: "u_owner",
categories: [
- { id: "cat_A", name: "Category A", channels: [{ id: channelId, name: "random", active: false, unread: false }] },
+ { id: "cat_A", name: "Category A", channels: [{ id: channelId, name: "random", type, active: false, unread: false }] },
],
}
}
@@ -59,7 +60,7 @@ describe("useCommunityWs — message.create patches channel unread in the open s
it("routes a child unread.bump to its loaded forum-sidebar row instead of the parent forum", async () => {
await mountHook({ viewerUserId: "u_me" })
capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("forum_1"))
- const sidebarKey = communityKeys.forumSidebarThreadsView("srv_open", null)
+ const sidebarKey = communityKeys.forumSidebarThreads("srv_open")
capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture())
capturedOnMessage!(unreadBump("post_1", "u_me", {
@@ -77,11 +78,71 @@ describe("useCommunityWs — message.create patches channel unread in the open s
)?.forumUnreadState?.forum_1?.childIds).toEqual(["post_1"])
})
+ it("keeps an inactive retained-only child on the parent fallback, then transfers it on the activation render", async () => {
+ await mountHook({ viewerUserId: "u_me" })
+ const serverKey = communityKeys.server("srv_open")
+ const baseKey = communityKeys.forumSidebarThreads("srv_open")
+ const retainedKey = communityKeys.forumSidebarRetained("srv_open", "post_extra")
+ capturedQueryClient.setQueryData(serverKey, serverDetailFixture("forum_1", "forum"))
+ capturedQueryClient.setQueryData(baseKey, forumSidebarFixture([
+ "post_1", "post_2", "post_3", "post_4", "post_5",
+ ]))
+ capturedQueryClient.setQueryData(retainedKey, {
+ ...forumSidebarFixture(["post_extra"]).threads[0],
+ })
+
+ capturedOnMessage!(unreadBump("post_extra", "u_me", {
+ serverId: "srv_open",
+ railChannelId: "forum_1",
+ }))
+
+ expect(capturedQueryClient.getQueryData<ServerDetail>(serverKey)
+ ?.categories[0]?.channels[0]?.unread).toBe(true)
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>["threads"][number]>(
+ retainedKey,
+ )?.unread).toBe(false)
+
+ const ownership = capturedQueryClient.getQueryData<ServerDetail>(serverKey)?.forumUnreadState
+ const active = deriveForumSidebarProjection(
+ capturedQueryClient.getQueryData(baseKey),
+ capturedQueryClient.getQueryData(retainedKey),
+ ownership,
+ )
+ expect(active.threads.find((thread) => thread.id === "post_extra")?.unread).toBe(true)
+ expect(active.parentUnread.forum_1).toBe(false)
+ })
+
+ it("keeps a canonical fifth child on the parent fallback when an active extra displaces it", async () => {
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ channelId: "post_extra" })
+ await mountHook({ viewerUserId: "u_me" })
+ const serverKey = communityKeys.server("srv_open")
+ const baseKey = communityKeys.forumSidebarThreads("srv_open")
+ capturedQueryClient.setQueryData(serverKey, serverDetailFixture("forum_1", "forum"))
+ capturedQueryClient.setQueryData(baseKey, forumSidebarFixture([
+ "post_1", "post_2", "post_3", "post_4", "post_5",
+ ]))
+ capturedQueryClient.setQueryData(
+ communityKeys.forumSidebarRetained("srv_open", "post_extra"),
+ forumSidebarFixture(["post_extra"]).threads[0],
+ )
+
+ capturedOnMessage!(unreadBump("post_5", "u_me", {
+ serverId: "srv_open",
+ railChannelId: "forum_1",
+ }))
+
+ expect(capturedQueryClient.getQueryData<ServerDetail>(serverKey)
+ ?.categories[0]?.channels[0]?.unread).toBe(true)
+ expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(baseKey)
+ ?.threads.find((thread) => thread.id === "post_5")?.unread).toBe(false)
+ })
+
it("falls back to the parent forum dot when the child has no locatable sidebar row", async () => {
await mountHook({ viewerUserId: "u_me" })
capturedQueryClient.setQueryData(communityKeys.server("srv_open"), serverDetailFixture("forum_1"))
capturedQueryClient.setQueryData(
- communityKeys.forumSidebarThreadsView("srv_open", null),
+ communityKeys.forumSidebarThreads("srv_open"),
forumSidebarFixture([]),
)
@@ -103,8 +164,8 @@ describe("useCommunityWs — message.create patches channel unread in the open s
it("moves message.create → unread.bump fallback ownership to the refetched child", async () => {
await mountHook({ viewerUserId: "u_me" })
const serverKey = communityKeys.server("srv_open")
- const sidebarKey = communityKeys.forumSidebarThreadsView("srv_open", null)
- capturedQueryClient.setQueryData(serverKey, serverDetailFixture("forum_1"))
+ const sidebarKey = communityKeys.forumSidebarThreads("srv_open")
+ capturedQueryClient.setQueryData(serverKey, serverDetailFixture("forum_1", "forum"))
capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture([]))
capturedOnMessage!({
diff --git a/src/web/src/hooks/community/community-ws/social-events.ts b/src/web/src/hooks/community/community-ws/social-events.ts
index f4dcb17a0..c632b5ddb 100644
--- a/src/web/src/hooks/community/community-ws/social-events.ts
+++ b/src/web/src/hooks/community/community-ws/social-events.ts
@@ -12,11 +12,10 @@ import { useCommunityStore } from "@/stores/community"
import { patchChannelUnread } from "@/hooks/community/server-detail-cache"
import type { ServersResponse, ServerDetail } from "@/hooks/community/use-servers"
import {
- hasForumSidebarThread,
- patchForumSidebarUnread,
+ hasProjectedForumSidebarThread,
+ patchForumSidebarUnreadExact,
recordForumSidebarChildUnread,
setForumSidebarParentUnreadBase,
- type ForumSidebarQueryData,
} from "@/hooks/community/use-forum-sidebar-threads"
import type { SocialEventContext } from "@/hooks/community/community-ws/handler-context"
@@ -42,12 +41,13 @@ export function handleUnreadBump(
const railChannelId = event.railChannelId ?? event.channelId
const targetServerId =
event.serverId ?? useCommunityStore.getState().currentServerId
- const sidebarKey = targetServerId
- ? communityKeys.forumSidebarThreads(targetServerId)
- : null
- const hasChildSidebarRow = !!sidebarKey && event.channelId !== railChannelId &&
- queryClient.getQueriesData<ForumSidebarQueryData>({ queryKey: sidebarKey })
- .some(([, data]) => hasForumSidebarThread(data, event.channelId))
+ const hasChildSidebarRow = !!targetServerId && event.channelId !== railChannelId &&
+ hasProjectedForumSidebarThread(
+ queryClient,
+ targetServerId,
+ event.channelId,
+ sub.channelId,
+ )
const sidebarChannelId = hasChildSidebarRow ? event.channelId : railChannelId
// Suppress the dot for the channel the viewer is actually looking at
// (its unread clears on read anyway) — compare against the ROW being
@@ -58,11 +58,8 @@ export function handleUnreadBump(
// — previously only the open server was patched, so cross-server
// bumps never lit. Absent serverId (DM bump / older frame) → fall
// back to the currently-open server (backward-compatible).
- if (hasChildSidebarRow && sidebarKey) {
- queryClient.setQueriesData<ForumSidebarQueryData>(
- { queryKey: sidebarKey },
- (data) => patchForumSidebarUnread(data, event.channelId, true),
- )
+ if (hasChildSidebarRow && targetServerId) {
+ patchForumSidebarUnreadExact(queryClient, targetServerId, event.channelId, true)
recordForumSidebarChildUnread(
queryClient,
targetServerId!,
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.ts
index a8ac41a7d..5f528946a 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
@@ -142,7 +142,7 @@ describe("useCommunityWs — channel.delete evicts channel-scoped caches", () =>
})
capturedQueryClient.setQueryData(communityKeys.pins("ch_dead"), { pins: [{ id: "p" }] })
capturedQueryClient.setQueryData(communityKeys.threads("ch_dead"), { threads: [{ id: "t" }] })
- const sidebarKey = communityKeys.forumSidebarThreadsView("srv_1", null)
+ const sidebarKey = communityKeys.forumSidebarThreads("srv_1")
capturedQueryClient.setQueryData(sidebarKey, forumSidebarFixture(["ch_dead"]))
const event: CommunityChannelDelete = {
@@ -278,8 +278,19 @@ describe("useCommunityWs — child_create patches parent thread badge with count
it("child_update removes archived sidebar rows and invalidates on reopen", async () => {
await mountHook()
- const key = communityKeys.forumSidebarThreadsView("s1", null)
+ const { useCommunityStore } = await import("@/stores/community")
+ const key = communityKeys.forumSidebarThreads("s1")
+ capturedQueryClient.setQueryData(communityKeys.server("s1"), {
+ id: "s1",
+ categories: [{ id: "cat_1", channels: [{ id: "forum_1", type: "forum" }] }],
+ })
capturedQueryClient.setQueryData(key, forumSidebarFixture(["ch_thread"]))
+ useCommunityStore.getState().setCurrentChannelId("ch_thread")
+ useCommunityStore.getState().setCurrentChannelMeta({
+ name: "Private title",
+ parentChannelId: "forum_1",
+ parentMessageId: "opener-ch_thread",
+ })
capturedOnMessage!({
type: "community:channel.child_update",
@@ -288,6 +299,7 @@ describe("useCommunityWs — child_create patches parent thread badge with count
changes: { archived: true },
} satisfies CommunityChildChannelUpdate)
expect(capturedQueryClient.getQueryData<ReturnType<typeof forumSidebarFixture>>(key)?.threads).toEqual([])
+ expect(useCommunityStore.getState().currentChannelMeta).toBeNull()
capturedOnMessage!({
type: "community:channel.child_update",
@@ -298,6 +310,68 @@ describe("useCommunityWs — child_create patches parent thread badge with count
expect(capturedQueryClient.getQueryState(key)?.isInvalidated).toBe(true)
})
+ it("clears active child metadata synchronously on channel.delete", async () => {
+ await mountHook()
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().setCurrentChannelId("ch_dead")
+ useCommunityStore.getState().setCurrentChannelMeta({
+ name: "Private title",
+ parentChannelId: "forum_1",
+ })
+
+ capturedOnMessage!({
+ type: "community:channel.delete",
+ serverId: "srv_1",
+ channelId: "ch_dead",
+ parentChannelId: "forum_1",
+ } satisfies CommunityChannelDelete)
+
+ expect(useCommunityStore.getState().currentChannelMeta).toBeNull()
+ })
+
+ it("does not touch forum resources for ordinary text-thread updates", async () => {
+ await mountHook()
+ const baseKey = communityKeys.forumSidebarThreads("s1")
+ const retainedKey = communityKeys.forumSidebarRetained("s1", "forum_post")
+ const metaKey = communityKeys.channelMeta("s1", "text_thread")
+ const hintKey = communityKeys.forumOpenerHint("s1", "forum_opener")
+ capturedQueryClient.setQueryData(communityKeys.server("s1"), {
+ id: "s1",
+ categories: [{ id: "cat_1", channels: [{ id: "text_parent", type: "text" }] }],
+ })
+ capturedQueryClient.setQueryData(baseKey, forumSidebarFixture())
+ capturedQueryClient.setQueryData(retainedKey, { id: "forum_post" })
+ capturedQueryClient.setQueryData(metaKey, { id: "text_thread", parentChannelId: "text_parent" })
+ capturedQueryClient.setQueryData(hintKey, { id: "forum_opener", content: "Forum title" })
+ const before = [
+ capturedQueryClient.getQueryData(baseKey),
+ capturedQueryClient.getQueryData(retainedKey),
+ capturedQueryClient.getQueryData(metaKey),
+ capturedQueryClient.getQueryData(hintKey),
+ ]
+
+ for (const changes of [
+ { archived: true },
+ { archived: false },
+ { lastMessageAt: "2026-08-09T00:00:00.000Z" },
+ ]) {
+ capturedOnMessage!({
+ type: "community:channel.child_update",
+ parentChannelId: "text_parent",
+ channelId: "text_thread",
+ changes,
+ } satisfies CommunityChildChannelUpdate)
+ }
+
+ expect(capturedQueryClient.getQueryState(baseKey)?.isInvalidated).toBe(false)
+ expect([
+ capturedQueryClient.getQueryData(baseKey),
+ capturedQueryClient.getQueryData(retainedKey),
+ capturedQueryClient.getQueryData(metaKey),
+ capturedQueryClient.getQueryData(hintKey),
+ ]).toEqual(before)
+ })
+
it("child_update keeps newer thread fields from the current base row when refreshing fallback", async () => {
await mountHook()
const { useCommunityStore } = await import("@/stores/community")
@@ -435,6 +509,10 @@ describe("useCommunityWs — server.delete resets store when focused server dies
const { useCommunityStore } = await import("@/stores/community")
useCommunityStore.getState().setCurrentServerId("srv_doomed")
useCommunityStore.getState().setCurrentChannelId("ch_1")
+ useCommunityStore.getState().setCurrentChannelMeta({
+ name: "Private title",
+ parentChannelId: "private_parent",
+ })
const event: CommunityServerDelete = {
type: "community:server.delete",
@@ -444,6 +522,7 @@ describe("useCommunityWs — server.delete resets store when focused server dies
expect(useCommunityStore.getState().currentServerId).toBeNull()
expect(useCommunityStore.getState().currentChannelId).toBeNull()
+ expect(useCommunityStore.getState().currentChannelMeta).toBeNull()
})
it("does NOT touch the store when a different server is deleted", 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.ts
index 96718a3f8..c7e4b3c5f 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
@@ -20,10 +20,13 @@ import { useCommunityStore } from "@/stores/community"
import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
import type { ServersResponse, ServerDetail } from "@/hooks/community/use-servers"
import {
- patchForumSidebarActivity,
- removeForumSidebarThread,
+ grantForumSidebarChild,
+ isForumSidebarParent,
+ isKnownNonForumSidebarChannel,
+ patchForumSidebarActivityExact,
+ removeForumSidebarChildrenForParent,
+ removeForumSidebarThreadExact,
removeForumSidebarUnreadChild,
- type ForumSidebarQueryData,
} from "@/hooks/community/use-forum-sidebar-threads"
import {
findCachedMessage,
@@ -122,28 +125,37 @@ export function handleChildChannelUpdate(
// indicator if the update carries them.
const changes = event.changes
const sidebarServerId = useCommunityStore.getState().currentServerId
- if (sidebarServerId) {
- const sidebarKey = communityKeys.forumSidebarThreads(sidebarServerId)
+ if (
+ sidebarServerId &&
+ isForumSidebarParent(queryClient, sidebarServerId, event.parentChannelId)
+ ) {
if (changes.archived === true) {
removeForumSidebarUnreadChild(queryClient, sidebarServerId, event.channelId)
- queryClient.setQueriesData<ForumSidebarQueryData>(
- { queryKey: sidebarKey },
- (data) => removeForumSidebarThread(data, event.channelId),
- )
+ removeForumSidebarThreadExact(queryClient, sidebarServerId, event.channelId)
} else if (changes.archived === false) {
- void queryClient.invalidateQueries({ queryKey: sidebarKey })
+ void grantForumSidebarChild(queryClient, sidebarServerId, event.channelId)
} else if (changes.lastMessageAt) {
- queryClient.setQueriesData<ForumSidebarQueryData>(
- { queryKey: sidebarKey },
- (data) => patchForumSidebarActivity(
- data,
- event.channelId,
- event.parentChannelId,
- changes.lastMessageAt!,
- ),
+ patchForumSidebarActivityExact(
+ queryClient,
+ sidebarServerId,
+ event.channelId,
+ event.parentChannelId,
+ changes.lastMessageAt,
)
}
}
+ if (
+ changes.archived === true &&
+ useCommunityStore.getState().currentChannelId === event.channelId
+ ) {
+ useCommunityStore.getState().setCurrentChannelMeta(null)
+ if (sidebarServerId) {
+ queryClient.removeQueries({
+ queryKey: communityKeys.channelMeta(sidebarServerId, event.channelId),
+ exact: true,
+ })
+ }
+ }
if (changes.messageCount !== undefined || changes.name !== undefined) {
queryClient.setQueriesData<PageCache>(
{ queryKey: communityKeys.channelMessages(event.parentChannelId) },
@@ -260,8 +272,9 @@ export function handleServerDelete(
const store = useCommunityStore.getState()
useMessageStreamStore.getState().removeServer(event.serverId)
if (store.currentServerId === event.serverId) {
- store.setCurrentServerId(null)
+ store.setCurrentChannelMeta(null)
store.setCurrentChannelId(null)
+ store.setCurrentServerId(null)
}
}
@@ -281,7 +294,24 @@ export function handleChannelEvent(
// subsequent same-id revive (rare, but the server can reuse ids)
// would surface stale rows.
if (event.type === "community:channel.delete") {
- removeForumSidebarUnreadChild(queryClient, event.serverId, event.channelId)
+ const nonForum = isKnownNonForumSidebarChannel(
+ queryClient,
+ event.serverId,
+ event.channelId,
+ )
+ if (!nonForum) {
+ removeForumSidebarUnreadChild(queryClient, event.serverId, event.channelId)
+ removeForumSidebarChildrenForParent(queryClient, event.serverId, event.channelId)
+ removeForumSidebarThreadExact(queryClient, event.serverId, event.channelId)
+ } else {
+ queryClient.removeQueries({
+ queryKey: communityKeys.channelMeta(event.serverId, event.channelId),
+ exact: true,
+ })
+ }
+ if (useCommunityStore.getState().currentChannelId === event.channelId) {
+ useCommunityStore.getState().setCurrentChannelMeta(null)
+ }
useMessageStreamStore.getState().removeScope({
kind: "channel",
id: event.channelId,
@@ -296,10 +326,6 @@ export function handleChannelEvent(
queryClient.removeQueries({
queryKey: communityKeys.threads(event.channelId),
})
- queryClient.setQueriesData<ForumSidebarQueryData>(
- { queryKey: communityKeys.forumSidebarThreads(event.serverId) },
- (data) => removeForumSidebarThread(data, event.channelId),
- )
// When a child thread is deleted, refresh the
// PARENT's list so the deleted card disappears from the feed on
// every client. Absent on older events / top-level channels.
@@ -316,7 +342,10 @@ export function handleChannelEvent(
})
}
}
- void queryClient.invalidateQueries({ queryKey: communityKeys.server(event.serverId) })
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.server(event.serverId),
+ exact: true,
+ })
}
type CategoryEvent =
@@ -329,7 +358,10 @@ export function handleCategoryEvent(
event: CategoryEvent,
{ queryClient }: StructureTreeEventContext,
) {
- void queryClient.invalidateQueries({ queryKey: communityKeys.server(event.serverId) })
+ void queryClient.invalidateQueries({
+ queryKey: communityKeys.server(event.serverId),
+ exact: true,
+ })
}
export function handleInviteCreate(
diff --git a/src/web/src/hooks/community/community-ws/test-harness.ts b/src/web/src/hooks/community/community-ws/test-harness.ts
index 411192df3..7a8d225e0 100644
--- a/src/web/src/hooks/community/community-ws/test-harness.ts
+++ b/src/web/src/hooks/community/community-ws/test-harness.ts
@@ -116,6 +116,7 @@ async function resetStore() {
useCommunityStore.getState().setCurrentServerId("s1")
const { useCommunityWsStore } = await import("@/stores/community/ws")
useCommunityWsStore.getState().reset()
+ useCommunityWsStore.getState().markAccessConnected()
useMessageStreamStore.getState().resetAll()
const mod = await import("../use-community-ws")
mod._resetActiveSend_forTesting()
@@ -169,19 +170,20 @@ export function forumSidebarFixture(ids = ["post_1"]) {
parentChannelId: "forum_1",
parentMessageId: `opener-${id}`,
activityAt: "2026-08-01T00:00:00.000Z",
- expiresAt: "2026-08-04T00:00:00.000Z",
+ expiresAt: "2099-08-04T00:00:00.000Z",
unread: false,
})),
included: { parentMessages: ids.map((id) => ({ id: `opener-${id}`, content: `title-${id}` })) },
serverNow: "2026-08-01T00:00:00.000Z",
serverClockOffsetMs: 0,
+ verifiedEpoch: 0,
threads: ids.map((id) => ({
id,
parentChannelId: "forum_1",
parentMessageId: `opener-${id}`,
title: `title-${id}`,
activityAt: "2026-08-01T00:00:00.000Z",
- expiresAt: "2026-08-04T00:00:00.000Z",
+ expiresAt: "2099-08-04T00:00:00.000Z",
unread: false,
})),
}
diff --git a/src/web/src/hooks/community/mutations/channels.ts b/src/web/src/hooks/community/mutations/channels.ts
index 6dbc9fb45..8ad2b4ac0 100644
--- a/src/web/src/hooks/community/mutations/channels.ts
+++ b/src/web/src/hooks/community/mutations/channels.ts
@@ -128,7 +128,7 @@ export function useCreateChannel() {
if (ctx?.snapshot) queryClient.setQueryData(communityKeys.server(args.serverId), ctx.snapshot)
},
onSettled: (_data, _err, args) => {
- void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId) })
+ void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })
},
})
}
@@ -156,7 +156,7 @@ export function useMoveChannel() {
})
},
onSuccess: (_data, args) => {
- void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId) })
+ void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })
},
})
}
@@ -171,7 +171,7 @@ export function useDeleteChannel() {
},
onSuccess: (_data, args) => {
if (args.serverId) {
- void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId) })
+ void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })
}
},
})
@@ -243,7 +243,7 @@ export function useCreateCategory() {
if (ctx?.snapshot) queryClient.setQueryData(communityKeys.server(args.serverId), ctx.snapshot)
},
onSettled: (_data, _err, args) => {
- void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId) })
+ void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })
},
})
}
@@ -265,7 +265,7 @@ export function useUpdateCategory() {
})
},
onSuccess: (_data, args) => {
- void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId) })
+ void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })
},
})
}
@@ -302,7 +302,7 @@ export function useDeleteCategory() {
if (ctx?.snapshot) queryClient.setQueryData(communityKeys.server(args.serverId), ctx.snapshot)
},
onSettled: (_data, _err, args) => {
- void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId) })
+ void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })
},
})
}
@@ -359,7 +359,7 @@ export function useReorderCategories() {
})
},
onSuccess: (_data, args) => {
- void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId) })
+ void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })
},
})
}
@@ -376,7 +376,7 @@ export function useReorderChannels() {
})
},
onSuccess: (_data, args) => {
- void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId) })
+ void queryClient.invalidateQueries({ queryKey: communityKeys.server(args.serverId), exact: true })
},
})
}
diff --git a/src/web/src/hooks/community/mutations/forum.test.ts b/src/web/src/hooks/community/mutations/forum.test.ts
index 0bfe7d333..eb021a3fd 100644
--- a/src/web/src/hooks/community/mutations/forum.test.ts
+++ b/src/web/src/hooks/community/mutations/forum.test.ts
@@ -200,7 +200,7 @@ describe("useDeleteForumThread", () => {
capturedQc.setQueryData(communityKeys.channelMessages("forum_1"), { pages: [], pageParams: [] })
capturedQc.setQueryData(communityKeys.forumActivityFeed("forum_1", null), { pages: [], pageParams: [] })
- const sidebarKey = communityKeys.forumSidebarThreadsView("server_1", "p2")
+ const sidebarKey = communityKeys.forumSidebarThreads("server_1")
capturedQc.setQueryData(sidebarKey, {
channels: [], included: { parentMessages: [] }, serverNow: "2026-08-08T00:00:00.000Z",
serverClockOffsetMs: 0,
diff --git a/src/web/src/hooks/community/mutations/forum.ts b/src/web/src/hooks/community/mutations/forum.ts
index f6b83c5a1..6e9dbc4fd 100644
--- a/src/web/src/hooks/community/mutations/forum.ts
+++ b/src/web/src/hooks/community/mutations/forum.ts
@@ -6,9 +6,8 @@ import { communityKeys } from "@/lib/query-keys"
import type { UploadedAttachment } from "@/hooks/community/mutations/uploads"
import type { MentionType } from "@alook/shared"
import {
- removeForumSidebarThread,
+ removeForumSidebarThreadExact,
removeForumSidebarUnreadChild,
- type ForumSidebarQueryData,
} from "@/hooks/community/use-forum-sidebar-threads"
export type CreateForumThreadArgs = {
@@ -117,10 +116,7 @@ export function useDeleteForumThread() {
void queryClient.invalidateQueries({ queryKey: communityKeys.channelMessages(args.forumChannelId) })
void queryClient.invalidateQueries({ queryKey: communityKeys.threads(args.forumChannelId) })
removeForumSidebarUnreadChild(queryClient, args.serverId, args.threadId)
- queryClient.setQueriesData<ForumSidebarQueryData>(
- { queryKey: communityKeys.forumSidebarThreads(args.serverId) },
- (data) => removeForumSidebarThread(data, args.threadId),
- )
+ removeForumSidebarThreadExact(queryClient, args.serverId, args.threadId)
},
})
}
diff --git a/src/web/src/hooks/community/mutations/messages.test.ts b/src/web/src/hooks/community/mutations/messages.test.ts
index 932898967..4a5c5f9ca 100644
--- a/src/web/src/hooks/community/mutations/messages.test.ts
+++ b/src/web/src/hooks/community/mutations/messages.test.ts
@@ -137,6 +137,13 @@ function sidebarData(threadId = "post_1") {
}
}
+function seedParent(type: "forum" | "text", parentId = "forum_1") {
+ capturedQc.setQueryData(communityKeys.server("s1"), {
+ id: "s1",
+ categories: [{ id: "cat_1", channels: [{ id: parentId, type }] }],
+ })
+}
+
beforeEach(() => {
apiFetchMock.mockReset()
toastMock.mockReset()
@@ -202,7 +209,8 @@ describe("useEditMessage", () => {
})
it("patches a loaded forum-sidebar title after the opener edit succeeds", async () => {
- const sidebarKey = communityKeys.forumSidebarThreadsView("s1", "post_1")
+ seedParent("forum")
+ const sidebarKey = communityKeys.forumSidebarThreads("s1")
capturedQc.setQueryData(sidebarKey, sidebarData())
apiFetchMock.mockResolvedValueOnce(undefined)
const mod = await loadMod()
@@ -263,7 +271,8 @@ describe("useSendMessage — happy path", () => {
})
it("re-ranks a loaded participating forum thread from the canonical send timestamp", async () => {
- const sidebarKey = communityKeys.forumSidebarThreadsView("s1", "post_1")
+ seedParent("forum")
+ const sidebarKey = communityKeys.forumSidebarThreads("s1")
capturedQc.setQueryData(sidebarKey, sidebarData())
apiFetchMock.mockResolvedValueOnce({ message: postedMessage("server_id_1", 9) })
const mod = await loadMod()
@@ -285,7 +294,8 @@ describe("useSendMessage — happy path", () => {
})
it("invalidates the sidebar collection when a just-enrolled thread is not loaded", async () => {
- const sidebarKey = communityKeys.forumSidebarThreadsView("s1", null)
+ seedParent("forum")
+ const sidebarKey = communityKeys.forumSidebarThreads("s1")
const empty = { ...sidebarData(), threads: [] }
capturedQc.setQueryData(sidebarKey, empty)
apiFetchMock.mockResolvedValueOnce({ message: postedMessage("server_id_1", 9) })
@@ -302,6 +312,43 @@ describe("useSendMessage — happy path", () => {
expect(capturedQc.getQueryState(sidebarKey)?.isInvalidated).toBe(true)
})
+
+ it("does not touch forum resources when sending in an ordinary text thread", async () => {
+ seedParent("text", "text_parent")
+ const baseKey = communityKeys.forumSidebarThreads("s1")
+ const retainedKey = communityKeys.forumSidebarRetained("s1", "forum_post")
+ const metaKey = communityKeys.channelMeta("s1", "text_thread")
+ const hintKey = communityKeys.forumOpenerHint("s1", "forum_opener")
+ capturedQc.setQueryData(baseKey, sidebarData())
+ capturedQc.setQueryData(retainedKey, { id: "forum_post" })
+ capturedQc.setQueryData(metaKey, { id: "text_thread", parentChannelId: "text_parent" })
+ capturedQc.setQueryData(hintKey, { id: "forum_opener", content: "Forum title" })
+ const before = [
+ capturedQc.getQueryData(baseKey),
+ capturedQc.getQueryData(retainedKey),
+ capturedQc.getQueryData(metaKey),
+ capturedQc.getQueryData(hintKey),
+ ]
+ apiFetchMock.mockResolvedValueOnce({ message: postedMessage("server_id_1", 9) })
+ const mod = await loadMod()
+ mod.useSendMessage()
+
+ await runMutation({
+ serverId: "s1",
+ channelId: "text_thread",
+ forumParentChannelId: "text_parent",
+ content: "hi",
+ author: { id: "u_me", name: "me", avatar: "M" },
+ })
+
+ expect(capturedQc.getQueryState(baseKey)?.isInvalidated).toBe(false)
+ expect([
+ capturedQc.getQueryData(baseKey),
+ capturedQc.getQueryData(retainedKey),
+ capturedQc.getQueryData(metaKey),
+ capturedQc.getQueryData(hintKey),
+ ]).toEqual(before)
+ })
})
describe("useSendMessage — rollback", () => {
diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.ts
index 37617348e..f2789d05a 100644
--- a/src/web/src/hooks/community/mutations/messages.ts
+++ b/src/web/src/hooks/community/mutations/messages.ts
@@ -28,10 +28,12 @@ import type { MessagesPage } from "@/hooks/community/use-messages"
import type { PinsResponse } from "@/hooks/community/use-channel-panels"
import type { MarkedResponse, MessageMarkedResponse } from "@/hooks/community/use-inbox"
import {
+ getForumSidebarBase,
hasForumSidebarThread,
- patchForumSidebarActivity,
- patchForumSidebarTitle,
- type ForumSidebarQueryData,
+ invalidateForumSidebarBaseExact,
+ isForumSidebarParent,
+ patchForumSidebarActivityExact,
+ patchForumSidebarTitleExact,
} from "@/hooks/community/use-forum-sidebar-threads"
import { isBlocked, type MentionType } from "@alook/shared"
@@ -133,9 +135,11 @@ export function useEditMessage() {
onSuccess: (_data, variables) => {
if (variables.forumChannelId) void queryClient.invalidateQueries({ queryKey: communityKeys.channelMessages(variables.forumChannelId) })
if (variables.forumThreadId) {
- queryClient.setQueriesData<ForumSidebarQueryData>(
- { queryKey: communityKeys.forumSidebarThreads(variables.serverId) },
- (data) => patchForumSidebarTitle(data, variables.forumThreadId!, variables.content),
+ patchForumSidebarTitleExact(
+ queryClient,
+ variables.serverId,
+ variables.forumThreadId,
+ variables.content,
)
}
},
@@ -266,22 +270,23 @@ export function useSendMessage() {
}
},
onSuccess: (data, args) => {
- if (args.forumParentChannelId) {
- const key = communityKeys.forumSidebarThreads(args.serverId)
- const cached = queryClient.getQueriesData<ForumSidebarQueryData>({ queryKey: key })
- const loaded = cached.some(([, value]) => hasForumSidebarThread(value, args.channelId))
- if (loaded) {
- queryClient.setQueriesData<ForumSidebarQueryData>(
- { queryKey: key },
- (value) => patchForumSidebarActivity(
- value,
- args.channelId,
- args.forumParentChannelId!,
- data.message.createdAt,
- ),
- )
- } else {
- void queryClient.invalidateQueries({ queryKey: key })
+ if (
+ args.forumParentChannelId &&
+ isForumSidebarParent(queryClient, args.serverId, args.forumParentChannelId)
+ ) {
+ const canonical = hasForumSidebarThread(
+ getForumSidebarBase(queryClient, args.serverId),
+ args.channelId,
+ )
+ patchForumSidebarActivityExact(
+ queryClient,
+ args.serverId,
+ args.channelId,
+ args.forumParentChannelId,
+ data.message.createdAt,
+ )
+ if (!canonical) {
+ void invalidateForumSidebarBaseExact(queryClient, args.serverId)
}
}
if (!args.nonce) return
diff --git a/src/web/src/hooks/community/mutations/servers.test.ts b/src/web/src/hooks/community/mutations/servers.test.ts
index 6bf72f863..aa7f2e720 100644
--- a/src/web/src/hooks/community/mutations/servers.test.ts
+++ b/src/web/src/hooks/community/mutations/servers.test.ts
@@ -75,6 +75,53 @@ describe("useLeaveServer — optimistic + rollback", () => {
const cache = capturedQc.getQueryData<{ servers: { id: string }[] }>(communityKeys.servers())
expect(cache?.servers).toHaveLength(1)
})
+
+ it.each(["leave", "delete"] as const)(
+ "%s success clears the server subtree, stream, and current private route",
+ async (operation) => {
+ apiFetchMock.mockResolvedValueOnce(undefined)
+ const mod = await load()
+ const { useCommunityStore } = await import("@/stores/community")
+ const { useMessageStreamStore } = await import("@/stores/community/message-stream")
+ useCommunityStore.getState().reset()
+ useCommunityStore.getState().setCurrentServerId("srv_1")
+ useCommunityStore.getState().setCurrentChannelId("private_child")
+ useCommunityStore.getState().setCurrentChannelMeta({
+ name: "Private title",
+ parentChannelId: "private_parent",
+ })
+ useMessageStreamStore.getState().dispatch(
+ { kind: "channel", id: "private_child", serverId: "srv_1" },
+ {
+ type: "wsMessage",
+ message: {
+ id: "message_1",
+ type: "chat",
+ authorId: "user_1",
+ authorName: "User",
+ content: "Private content",
+ },
+ },
+ )
+ capturedQc.setQueryData(communityKeys.server("srv_1"), {
+ id: "srv_1",
+ categories: [],
+ })
+ if (operation === "leave") mod.useLeaveServer()
+ else mod.useDeleteServer()
+
+ await runMutation({ serverId: "srv_1" })
+
+ expect(useCommunityStore.getState()).toMatchObject({
+ currentServerId: null,
+ currentChannelId: null,
+ currentChannelMeta: null,
+ })
+ expect(capturedQc.getQueryState(communityKeys.server("srv_1"))).toBeUndefined()
+ expect([...useMessageStreamStore.getState().entries.values()]
+ .some((entry) => entry.scope.serverId === "srv_1")).toBe(false)
+ },
+ )
})
describe("useUpdateServer — rollback on both caches", () => {
diff --git a/src/web/src/hooks/community/mutations/servers.ts b/src/web/src/hooks/community/mutations/servers.ts
index 6c80b66af..dea742c83 100644
--- a/src/web/src/hooks/community/mutations/servers.ts
+++ b/src/web/src/hooks/community/mutations/servers.ts
@@ -5,6 +5,8 @@ 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"
/**
* Server-scoped mutations. `create`/`join` invalidate the rail; `leave`/`delete`
@@ -69,6 +71,15 @@ 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()
return useMutation<void, Error, LeaveServerArgs, { snapshot: ServersResponse | undefined }>({
@@ -87,6 +98,10 @@ export function useLeaveServer() {
onError: (_err, _args, ctx) => {
if (ctx?.snapshot) queryClient.setQueryData(communityKeys.servers(), ctx.snapshot)
},
+ onSuccess: (_data, args) => {
+ queryClient.removeQueries({ queryKey: communityKeys.server(args.serverId) })
+ clearDepartedServer(args.serverId)
+ },
})
}
@@ -108,6 +123,10 @@ export function useDeleteServer() {
onError: (_err, _args, ctx) => {
if (ctx?.snapshot) queryClient.setQueryData(communityKeys.servers(), ctx.snapshot)
},
+ onSuccess: (_data, args) => {
+ queryClient.removeQueries({ queryKey: communityKeys.server(args.serverId) })
+ clearDepartedServer(args.serverId)
+ },
})
}
diff --git a/src/web/src/hooks/community/use-channel-route-model.subscription.test.ts b/src/web/src/hooks/community/use-channel-route-model.subscription.test.ts
new file mode 100644
index 000000000..056b0e34c
--- /dev/null
+++ b/src/web/src/hooks/community/use-channel-route-model.subscription.test.ts
@@ -0,0 +1,105 @@
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { QueryClient } from "@tanstack/react-query"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { useCommunityStore } from "@/stores/community"
+
+const mocks = vi.hoisted(() => ({
+ subscribe: vi.fn(),
+ unsubscribe: vi.fn(),
+ replace: vi.fn(),
+ metaQuery: {
+ data: undefined as undefined | Record<string, unknown>,
+ error: null as unknown,
+ isVerified: false,
+ },
+}))
+
+const queryClient = new QueryClient()
+
+vi.mock("next/navigation", () => ({
+ useRouter: () => ({ replace: mocks.replace }),
+}))
+vi.mock("@tanstack/react-query", async () => {
+ const actual = await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query")
+ return { ...actual, useQueryClient: () => queryClient }
+})
+vi.mock("./use-servers", () => ({
+ useServer: () => ({
+ server: {
+ id: "server-1",
+ categories: [{
+ id: "cat-1",
+ channels: [{ id: "forum-1", name: "Forum", type: "forum" }],
+ }],
+ },
+ }),
+}))
+vi.mock("./use-child-channel-meta", () => ({
+ useChildChannelMeta: () => mocks.metaQuery,
+}))
+vi.mock("./use-community-ws", () => ({
+ communityWsSubscribe: (...args: unknown[]) => mocks.subscribe(...args),
+ communityWsUnsubscribe: (...args: unknown[]) => mocks.unsubscribe(...args),
+}))
+vi.mock("@/lib/api/client", () => ({ toastApiError: vi.fn() }))
+
+import { useChannelRouteModel } from "./use-channel-route-model"
+
+function Harness() {
+ useChannelRouteModel("server-1", "server-1", "post-1")
+ return null
+}
+
+beforeEach(() => {
+ useCommunityStore.getState().reset()
+ mocks.subscribe.mockClear()
+ mocks.unsubscribe.mockClear()
+ mocks.replace.mockClear()
+ mocks.metaQuery = { data: undefined, error: null, isVerified: false }
+})
+
+afterEach(() => {
+ useCommunityStore.getState().reset()
+})
+
+describe("useChannelRouteModel subscription ownership", () => {
+ it("does not unsubscribe/resubscribe when metadata becomes verified", () => {
+ let renderer: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(React.createElement(Harness))
+ })
+ expect(mocks.subscribe).toHaveBeenCalledTimes(1)
+ expect(mocks.unsubscribe).not.toHaveBeenCalled()
+
+ mocks.metaQuery = {
+ data: {
+ id: "post-1",
+ serverId: "server-1",
+ name: "Post",
+ type: "thread",
+ parentChannelId: "forum-1",
+ parentMessageId: "opener-1",
+ creatorId: "user-1",
+ archived: false,
+ activityAt: "2026-08-09T00:00:00.000Z",
+ verifiedEpoch: 0,
+ },
+ error: null,
+ isVerified: true,
+ }
+ act(() => {
+ renderer!.update(React.createElement(Harness))
+ })
+
+ expect(mocks.subscribe).toHaveBeenCalledTimes(1)
+ expect(mocks.unsubscribe).not.toHaveBeenCalled()
+ expect(useCommunityStore.getState().currentChannelMeta).toMatchObject({
+ parentChannelId: "forum-1",
+ parentMessageId: "opener-1",
+ })
+
+ act(() => renderer!.unmount())
+ expect(mocks.unsubscribe).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/src/web/src/hooks/community/use-channel-route-model.test.ts b/src/web/src/hooks/community/use-channel-route-model.test.ts
index 21233d7ae..378c463ff 100644
--- a/src/web/src/hooks/community/use-channel-route-model.test.ts
+++ b/src/web/src/hooks/community/use-channel-route-model.test.ts
@@ -42,6 +42,18 @@ describe("buildChannelRouteModel", () => {
expect(model.routeHydrated).toBe(false)
})
+ it("does not expose same-route cached metadata before the current access epoch settles", () => {
+ const stale = { name: "private title", parentChannelId: "forum1", parentMessageId: "m1", creatorId: "u1" }
+ const model = buildChannelRouteModel(server, stale, "post-a", {
+ channelId: "post-a",
+ settled: false,
+ })
+ expect(model.currentChannelMeta).toBeNull()
+ expect(model.parent).toBeNull()
+ expect(model.isForumPostChild).toBe(false)
+ expect(model.routeHydrated).toBe(false)
+ })
+
it("derives the child subtype only after that child's metadata settles", () => {
const meta = { name: "B", parentChannelId: "forum1", parentMessageId: "m2", creatorId: "u2" }
const model = buildChannelRouteModel(server, meta, "post-b", { channelId: "post-b", settled: true })
diff --git a/src/web/src/hooks/community/use-channel-route-model.ts b/src/web/src/hooks/community/use-channel-route-model.ts
index 2043bffe0..07ce70b61 100644
--- a/src/web/src/hooks/community/use-channel-route-model.ts
+++ b/src/web/src/hooks/community/use-channel-route-model.ts
@@ -1,14 +1,20 @@
"use client"
-import { useEffect, useMemo, useState } from "react"
+import { useEffect, useMemo } from "react"
import { useRouter } from "next/navigation"
+import { useQueryClient } from "@tanstack/react-query"
import { isForum as isForumType } from "@alook/shared"
import { useServer } from "./use-servers"
import { useCommunityStore, useCurrentChannelMeta } from "@/stores/community"
-import { apiFetch, toastApiError } from "@/lib/api/client"
+import { toastApiError } from "@/lib/api/client"
import { isDefinitiveChildMetaFailure } from "@/components/community/eject-server"
import { clearLastChannel, getLastChannel } from "@/lib/community/last-channel"
import { communityWsSubscribe, communityWsUnsubscribe } from "./use-community-ws"
+import { useChildChannelMeta } from "./use-child-channel-meta"
+import {
+ removeForumSidebarThreadExact,
+ removeForumSidebarUnreadChild,
+} from "./use-forum-sidebar-threads"
type Server = ReturnType<typeof useServer>["server"]
type ChannelMeta = ReturnType<typeof useCurrentChannelMeta>
@@ -23,7 +29,7 @@ export function buildChannelRouteModel(
const channel = channels.find((candidate) => candidate.id === channelId) ?? null
const isChild = !channel && !!server?.categories
const metaSettled = !isChild || (metaState?.channelId === channelId && metaState.settled)
- const channelMeta = !isChild || metaState?.channelId === channelId ? currentChannelMeta : null
+ const channelMeta = !isChild || metaSettled ? currentChannelMeta : null
const parent = channelMeta?.parentChannelId
? channels.find((candidate) => candidate.id === channelMeta.parentChannelId) ?? null
: null
@@ -43,12 +49,24 @@ export function buildChannelRouteModel(
export function useChannelRouteModel(serverId: string, serverParam: string, channelId: string) {
const router = useRouter()
+ const queryClient = useQueryClient()
const { server } = useServer(serverId)
const currentChannelMeta = useCurrentChannelMeta()
- const [metaState, setMetaState] = useState<{ channelId: string; settled: boolean } | null>(null)
+ const topLevelChannel = server?.categories
+ ?.flatMap((category) => category.channels)
+ .some((candidate) => candidate.id === channelId)
+ const isChild = !!server?.categories && !topLevelChannel
+ const metaQuery = useChildChannelMeta(serverId, channelId, isChild)
const model = useMemo(
- () => buildChannelRouteModel(server, currentChannelMeta, channelId, metaState),
- [channelId, currentChannelMeta, metaState, server],
+ () => buildChannelRouteModel(
+ server,
+ currentChannelMeta,
+ channelId,
+ isChild
+ ? { channelId, settled: metaQuery.isVerified }
+ : { channelId, settled: true },
+ ),
+ [channelId, currentChannelMeta, isChild, metaQuery.isVerified, server],
)
useEffect(() => {
useCommunityStore.getState().setCurrentChannelId(channelId)
@@ -56,33 +74,26 @@ export function useChannelRouteModel(serverId: string, serverParam: string, chan
}, [channelId])
useEffect(() => {
communityWsSubscribe({ channelId })
- if (!model.isChild) {
- setMetaState({ channelId, settled: true })
+ return () => communityWsUnsubscribe()
+ }, [channelId])
+ useEffect(() => {
+ if (!isChild) {
useCommunityStore.getState().setCurrentChannelMeta(null)
- return () => communityWsUnsubscribe()
+ return
}
- setMetaState({ channelId, settled: false })
- let active = true
- apiFetch<{ name: string; parentChannelId: string | null; parentMessageId: string | null; creatorId: string | null }>(`/api/community/channels/${channelId}`)
- .then((data) => {
- if (!active) return
- useCommunityStore.getState().setCurrentChannelMeta(data)
- setMetaState({ channelId, settled: true })
- })
- .catch((error) => {
- if (!active) return
- useCommunityStore.getState().setCurrentChannelMeta(null)
- if (isDefinitiveChildMetaFailure(error)) {
- if (getLastChannel(serverId) === channelId) clearLastChannel(serverId)
- router.replace(`/c/channels/${serverParam}`)
- } else {
- toastApiError(error, "Failed to load thread")
- }
- })
- return () => {
- active = false
- communityWsUnsubscribe()
+ if (metaQuery.data && metaQuery.isVerified) {
+ useCommunityStore.getState().setCurrentChannelMeta(metaQuery.data)
+ } else if (metaQuery.error || metaQuery.data?.archived) {
+ 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")
+ }
}
- }, [channelId, model.isChild, router, serverId, serverParam])
+ }, [channelId, isChild, metaQuery.data, metaQuery.error, metaQuery.isVerified, queryClient, router, serverId, serverParam])
return model
}
diff --git a/src/web/src/hooks/community/use-child-channel-meta.test.ts b/src/web/src/hooks/community/use-child-channel-meta.test.ts
new file mode 100644
index 000000000..c82c57eca
--- /dev/null
+++ b/src/web/src/hooks/community/use-child-channel-meta.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest"
+import type { ChildChannelMeta } from "./use-forum-sidebar-threads"
+import { isChildChannelMetaVerified } from "./use-child-channel-meta"
+
+const meta = (overrides: Partial<ChildChannelMeta> = {}): ChildChannelMeta => ({
+ id: "post-1",
+ serverId: "server-1",
+ name: "post",
+ type: "thread",
+ parentChannelId: "forum-1",
+ parentMessageId: "opener-1",
+ creatorId: "user-1",
+ archived: false,
+ activityAt: "2026-08-09T00:00:00.000Z",
+ verifiedEpoch: 2,
+ ...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)
+ })
+
+ it("never verifies an archived child payload", () => {
+ expect(isChildChannelMetaVerified(meta({ archived: true }), 2, true)).toBe(false)
+ })
+})
diff --git a/src/web/src/hooks/community/use-child-channel-meta.ts b/src/web/src/hooks/community/use-child-channel-meta.ts
new file mode 100644
index 000000000..a69db1136
--- /dev/null
+++ b/src/web/src/hooks/community/use-child-channel-meta.ts
@@ -0,0 +1,82 @@
+"use client"
+
+import { useQuery } from "@tanstack/react-query"
+import { apiFetch } from "@/lib/api/client"
+import { communityKeys } from "@/lib/query-keys"
+import type {
+ ChildChannelMeta,
+ ForumSidebarQueryData,
+} from "@/hooks/community/use-forum-sidebar-threads"
+import { useCommunityWsStore } from "@/stores/community/ws"
+
+type ChannelMetaPayload = {
+ id: string
+ serverId: string
+ name: string
+ type: string
+ parentChannelId: string | null
+ parentMessageId: string | null
+ creatorId: string | null
+ archived: boolean | number
+ lastMessageAt: string | null
+ createdAt: string
+}
+
+function projectChildMeta(payload: ChannelMetaPayload, verifiedEpoch: number): ChildChannelMeta {
+ if (!payload.parentChannelId || !payload.parentMessageId) {
+ throw new Error("invalid child channel metadata")
+ }
+ return {
+ id: payload.id,
+ serverId: payload.serverId,
+ name: payload.name,
+ type: payload.type,
+ parentChannelId: payload.parentChannelId,
+ parentMessageId: payload.parentMessageId,
+ creatorId: payload.creatorId,
+ archived: payload.archived === true || payload.archived === 1,
+ activityAt: payload.lastMessageAt ?? payload.createdAt,
+ verifiedEpoch,
+ }
+}
+
+export function isChildChannelMetaVerified(
+ meta: ChildChannelMeta | undefined,
+ accessEpoch: number,
+ accessConnected: boolean,
+) {
+ return !!meta && accessConnected && meta.verifiedEpoch === accessEpoch && !meta.archived
+}
+
+export function useChildChannelMeta(
+ serverId: string,
+ channelId: string,
+ 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")),
+ enabled: false,
+ })
+ const query = useQuery<ChildChannelMeta>({
+ queryKey: communityKeys.channelMeta(serverId, channelId),
+ queryFn: async () => {
+ const requestEpoch = useCommunityWsStore.getState().accessEpoch
+ return projectChildMeta(
+ await apiFetch<ChannelMetaPayload>(`/api/community/channels/${channelId}`),
+ requestEpoch,
+ )
+ },
+ enabled: enabled && (
+ (sidebar.isSuccess && sidebar.fetchStatus === "idle") || sidebar.isError
+ ),
+ staleTime: Infinity,
+ gcTime: 5 * 60 * 1000,
+ })
+ return {
+ ...query,
+ isVerified: isChildChannelMetaVerified(query.data, accessEpoch, accessConnected),
+ }
+}
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index dc76a0975..365c34520 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -288,6 +288,8 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
}, [queryClient])
const { send } = useUserWs(handleMessage, {
onReconnect: handleReconnect,
+ onDisconnect: useCommunityWsStore.getState().markAccessDisconnected,
+ onAuthenticated: useCommunityWsStore.getState().markAccessConnected,
requestDaemonStatusOnAuth: false,
})
diff --git a/src/web/src/hooks/community/use-eager-channel-read.ts b/src/web/src/hooks/community/use-eager-channel-read.ts
index ab8b87a02..5734178b8 100644
--- a/src/web/src/hooks/community/use-eager-channel-read.ts
+++ b/src/web/src/hooks/community/use-eager-channel-read.ts
@@ -6,10 +6,9 @@ import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import type { ServersResponse } from "@/hooks/community/use-servers"
import {
- patchForumSidebarUnread,
+ patchForumSidebarUnreadExact,
removeForumSidebarUnreadChild,
setForumSidebarParentUnreadBase,
- type ForumSidebarQueryData,
} from "@/hooks/community/use-forum-sidebar-threads"
/**
@@ -75,10 +74,7 @@ export function useEagerChannelRead({
// could incorrectly re-light its parent from stale local ownership.
if (serverId && isChildChannel) {
removeForumSidebarUnreadChild(queryClient, serverId, channelId)
- queryClient.setQueriesData<ForumSidebarQueryData>(
- { queryKey: communityKeys.forumSidebarThreads(serverId) },
- (data) => patchForumSidebarUnread(data, channelId, false),
- )
+ patchForumSidebarUnreadExact(queryClient, serverId, channelId, false)
} else if (serverId) {
setForumSidebarParentUnreadBase(queryClient, serverId, channelId, false)
}
diff --git a/src/web/src/hooks/community/use-forum-opener-hint.test.ts b/src/web/src/hooks/community/use-forum-opener-hint.test.ts
new file mode 100644
index 000000000..d15dfcc19
--- /dev/null
+++ b/src/web/src/hooks/community/use-forum-opener-hint.test.ts
@@ -0,0 +1,52 @@
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { communityKeys } from "@/lib/query-keys"
+import { useForumOpenerHint } from "./use-forum-opener-hint"
+
+const apiFetchMock = vi.fn()
+vi.mock("@/lib/api/client", () => ({
+ apiFetch: (...args: unknown[]) => apiFetchMock(...args),
+}))
+
+function Capture({ enabled }: { enabled: boolean }) {
+ useForumOpenerHint("server-1", "opener-1", enabled)
+ return null
+}
+
+beforeEach(() => apiFetchMock.mockReset())
+
+describe("useForumOpenerHint", () => {
+ it("does not fetch or authorize content before the route metadata is verified", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ await act(async () => {
+ TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, { enabled: false }),
+ ),
+ )
+ })
+ expect(apiFetchMock).not.toHaveBeenCalled()
+ })
+
+ it("reuses a seeded lightweight hint without a full opener request", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ queryClient.setQueryData(
+ communityKeys.forumOpenerHint("server-1", "opener-1"),
+ { id: "opener-1", content: "Seeded" },
+ )
+ await act(async () => {
+ TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, { enabled: true }),
+ ),
+ )
+ })
+ expect(apiFetchMock).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/hooks/community/use-forum-opener-hint.ts b/src/web/src/hooks/community/use-forum-opener-hint.ts
new file mode 100644
index 000000000..1362083fd
--- /dev/null
+++ b/src/web/src/hooks/community/use-forum-opener-hint.ts
@@ -0,0 +1,26 @@
+"use client"
+
+import { useQuery } from "@tanstack/react-query"
+import { apiFetch } from "@/lib/api/client"
+import { communityKeys } from "@/lib/query-keys"
+import type { ForumOpenerHint } from "@/hooks/community/use-forum-sidebar-threads"
+
+export function useForumOpenerHint(
+ serverId: string,
+ messageId: string | null | undefined,
+ enabled: boolean,
+) {
+ const active = enabled && !!messageId
+ return useQuery<ForumOpenerHint>({
+ queryKey: communityKeys.forumOpenerHint(serverId, messageId ?? "__none__"),
+ queryFn: async () => {
+ const message = await apiFetch<{ id: string; content: string }>(
+ `/api/community/messages/${messageId}`,
+ )
+ return { id: message.id, content: message.content }
+ },
+ enabled: active,
+ staleTime: Infinity,
+ gcTime: 5 * 60 * 1000,
+ })
+}
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.ts
index fb538b3db..d6f84d7c9 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
@@ -4,6 +4,13 @@ import TestRenderer, { act } from "react-test-renderer"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
import {
+ deriveForumSidebarProjection,
+ grantForumSidebarChild,
+ invalidateForumSidebarBaseExact,
+ patchForumSidebarActivityExact,
+ patchForumSidebarTitleExact,
+ removeForumSidebarThreadExact,
+ normalizeForumSidebarEnvelope,
patchForumSidebarActivity,
patchForumSidebarUnread,
projectForumSidebarThreads,
@@ -11,13 +18,16 @@ import {
recordForumSidebarChildUnread,
removeForumSidebarThread,
removeForumSidebarUnreadChild,
+ resolveForumSidebarRouteCandidate,
setForumSidebarParentUnreadBase,
type ForumSidebarQueryData,
+ type ForumSidebarThread,
type ForumSidebarUnreadFallbackState,
type SidebarThreadEnvelope,
useForumSidebarThreads,
} from "./use-forum-sidebar-threads"
import type { ServerDetail } from "./use-servers"
+import { useCommunityWsStore } from "@/stores/community/ws"
const apiFetchMock = vi.fn()
vi.mock("@/lib/api/client", () => ({
@@ -33,6 +43,11 @@ const envelope = (ids: string[]): SidebarThreadEnvelope => ({
activityAt: `2026-08-08T0${index}:00:00.000Z`,
expiresAt: `2026-08-11T0${index}:00:00.000Z`,
unread: index === 0,
+ serverId: "server-1",
+ type: "thread",
+ creatorId: "creator-1",
+ archived: false,
+ createdAt: `2026-08-08T0${index}:00:00.000Z`,
})),
included: {
parentMessages: ids.map((id) => ({ id: `opener-${id}`, content: `title-${id}` })),
@@ -40,11 +55,12 @@ const envelope = (ids: string[]): SidebarThreadEnvelope => ({
serverNow: "2026-08-08T00:00:00.000Z",
})
-function Capture({ retainId, onRender }: {
+function Capture({ retainId, onRender, enabled }: {
retainId: string | null
onRender: (ids: string[]) => void
+ enabled?: boolean
}) {
- const result = useForumSidebarThreads("server-1", retainId)
+ const result = useForumSidebarThreads("server-1", retainId, enabled)
onRender(result.threads.map((thread) => thread.id))
return null
}
@@ -59,10 +75,13 @@ async function waitFor(predicate: () => boolean) {
beforeEach(() => {
apiFetchMock.mockReset()
+ useCommunityWsStore.getState().reset()
+ useCommunityWsStore.getState().markAccessConnected()
})
afterEach(() => {
vi.useRealTimers()
+ useCommunityWsStore.getState().reset()
})
function serverDetail(parentUnread: boolean): ServerDetail {
@@ -254,7 +273,7 @@ describe("useForumSidebarThreads", () => {
it("migrates a missing-child fallback dot to the child after the sidebar refetch", async () => {
apiFetchMock.mockResolvedValue(envelope(["post-missing"]))
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
- const sidebarKey = communityKeys.forumSidebarThreadsView("server-1", null)
+ const sidebarKey = communityKeys.forumSidebarThreads("server-1")
queryClient.setQueryData<ForumSidebarQueryData>(sidebarKey, {
...envelope([]),
threads: [],
@@ -324,9 +343,10 @@ describe("useForumSidebarThreads", () => {
})
expect(renders.at(-1)).toEqual(["thread-1"])
invalidateSpy.mockClear()
+ apiFetchMock.mockRejectedValueOnce(new Error("offline"))
act(() => vi.advanceTimersByTime(10 * 60 * 60 * 1000))
- const key = communityKeys.forumSidebarThreadsView("server-1", null)
+ const key = communityKeys.forumSidebarThreads("server-1")
await act(async () => {
queryClient.setQueryData<ForumSidebarQueryData>(key, (data) =>
patchForumSidebarActivity(
@@ -344,7 +364,99 @@ describe("useForumSidebarThreads", () => {
act(() => vi.advanceTimersByTime(1))
expect(invalidateSpy).toHaveBeenCalledWith({
queryKey: communityKeys.forumSidebarThreads("server-1"),
+ exact: true,
})
+ await act(async () => { await vi.advanceTimersByTimeAsync(0) })
+ expect(queryClient.getQueryData<ForumSidebarQueryData>(key)?.threads).toEqual([])
+ expect(JSON.stringify(queryClient.getQueryData(key))).not.toContain("thread-1")
+ expect(queryClient.getQueryState(
+ communityKeys.channelMeta("server-1", "thread-1"),
+ )).toBeUndefined()
+ expect(queryClient.getQueryState(
+ communityKeys.forumOpenerHint("server-1", "opener-thread-1"),
+ )).toBeUndefined()
+ expect(renders.at(-1)).toEqual([])
+ renderer!.unmount()
+ })
+
+ it("retains a warm canonical route through expiry and offline refresh until navigation and GC", async () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date("2026-08-08T00:00:00.000Z"))
+ apiFetchMock.mockRejectedValue(new Error("offline"))
+ const source = envelope(["canonical-a"])
+ source.channels[0]!.expiresAt = "2026-08-08T00:00:00.100Z"
+ const normalized = normalizeForumSidebarEnvelope({
+ ...source,
+ canonicalChannels: source.channels,
+ retainedChannel: null,
+ }, null, 0)
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ queryClient.setQueryData(communityKeys.server("server-1"), serverDetail(false))
+ queryClient.setQueryData(
+ communityKeys.forumSidebarThreads("server-1"),
+ { ...normalized.base, verifiedEpoch: 0 },
+ )
+
+ 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 vi.advanceTimersByTimeAsync(0)
+ })
+ expect(renders.at(-1)).toEqual(["canonical-a"])
+
+ await act(async () => {
+ renderer!.update(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, {
+ retainId: "canonical-a",
+ onRender: (ids) => renders.push(ids),
+ }),
+ ),
+ )
+ await vi.advanceTimersByTimeAsync(0)
+ })
+ const retainedKey = communityKeys.forumSidebarRetained("server-1", "canonical-a")
+ expect(queryClient.getQueryData<ForumSidebarThread>(retainedKey)?.id).toBe("canonical-a")
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(126)
+ })
+ expect(queryClient.getQueryData<ForumSidebarQueryData>(
+ communityKeys.forumSidebarThreads("server-1"),
+ )?.threads).toEqual([])
+ expect(renders.at(-1)).toEqual(["canonical-a"])
+
+ await act(async () => {
+ renderer!.update(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, {
+ retainId: null,
+ onRender: (ids) => renders.push(ids),
+ }),
+ ),
+ )
+ await vi.advanceTimersByTimeAsync(0)
+ })
+ expect(renders.at(-1)).toEqual([])
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync((5 * 60 * 1000) + 1)
+ })
+ expect(queryClient.getQueryState(retainedKey)).toBeUndefined()
renderer!.unmount()
})
@@ -420,3 +532,701 @@ describe("useForumSidebarThreads", () => {
expect(patchForumSidebarUnread(data, "thread-1", false)?.threads[0]?.unread).toBe(false)
})
})
+
+describe("forum sidebar Stage B resources", () => {
+ it("does not retain known top-level routes and keeps an unknown direct child candidate", () => {
+ expect(resolveForumSidebarRouteCandidate("general", ["general", "forum"])).toBeNull()
+ expect(resolveForumSidebarRouteCandidate("post-1", ["general", "forum"])).toBe("post-1")
+ expect(resolveForumSidebarRouteCandidate("post-1", null)).toBeNull()
+ })
+
+ it("uses one cold combined request and seeds sibling resources before base settles", async () => {
+ const canonical = envelope(["base-1"])
+ const retained = envelope(["retained-1"])
+ apiFetchMock.mockResolvedValue({
+ ...canonical,
+ canonicalChannels: canonical.channels,
+ retainedChannel: retained.channels[0],
+ included: {
+ parentMessages: [
+ ...canonical.included.parentMessages,
+ ...retained.included.parentMessages,
+ ],
+ },
+ })
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, { retainId: "retained-1", onRender: () => undefined }),
+ ),
+ )
+ })
+ await waitFor(() => queryClient.getQueryState(
+ communityKeys.forumSidebarThreads("server-1"),
+ )?.status === "success")
+
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+ expect(apiFetchMock.mock.calls[0]?.[0]).toContain("retainId=retained-1")
+ expect(queryClient.getQueryData(
+ communityKeys.forumSidebarRetained("server-1", "retained-1"),
+ )).toMatchObject({ id: "retained-1" })
+ expect(queryClient.getQueryData(
+ communityKeys.channelMeta("server-1", "retained-1"),
+ )).toMatchObject({ id: "retained-1" })
+ expect(queryClient.getQueryData(
+ communityKeys.forumOpenerHint("server-1", "opener-retained-1"),
+ )).toEqual({ id: "opener-retained-1", content: "title-retained-1" })
+ renderer!.unmount()
+ })
+
+ it("does not restart the first request when enablement and the route candidate arrive together", async () => {
+ let resolveRequest: ((value: SidebarThreadEnvelope) => void) | undefined
+ apiFetchMock.mockImplementation(() => new Promise((resolve) => { resolveRequest = resolve }))
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const tree = (retainId: string | null, enabled: boolean) => React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, {
+ retainId,
+ enabled,
+ onRender: () => undefined,
+ }),
+ )
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(tree(null, false))
+ })
+ await act(async () => {
+ renderer!.update(tree("retained-1", true))
+ await new Promise((resolve) => setTimeout(resolve, 10))
+ })
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+ expect(apiFetchMock.mock.calls[0]?.[0]).toContain("retainId=retained-1")
+
+ const canonical = envelope(["base-1"])
+ const retained = envelope(["retained-1"])
+ await act(async () => resolveRequest?.({
+ ...canonical,
+ canonicalChannels: canonical.channels,
+ retainedChannel: retained.channels[0],
+ included: {
+ parentMessages: [
+ ...canonical.included.parentMessages,
+ ...retained.included.parentMessages,
+ ],
+ },
+ }))
+ renderer!.unmount()
+ })
+
+ it("shares one cold request across an asynchronous StrictMode-style remount", async () => {
+ let resolveRequest: ((value: SidebarThreadEnvelope) => void) | undefined
+ apiFetchMock.mockImplementation(() => new Promise((resolve) => { resolveRequest = resolve }))
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const renders: string[][] = []
+ const tree = () => React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, {
+ retainId: "retained-1",
+ onRender: (ids) => renders.push(ids),
+ }),
+ )
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(tree())
+ })
+ await waitFor(() => apiFetchMock.mock.calls.length === 1)
+ act(() => renderer!.unmount())
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 10))
+ renderer = TestRenderer.create(tree())
+ })
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+
+ const canonical = envelope(["base-1"])
+ const retained = envelope(["retained-1"])
+ await act(async () => resolveRequest?.({
+ ...canonical,
+ canonicalChannels: canonical.channels,
+ retainedChannel: retained.channels[0],
+ included: {
+ parentMessages: [
+ ...canonical.included.parentMessages,
+ ...retained.included.parentMessages,
+ ],
+ },
+ }))
+ await waitFor(() => renders.at(-1)?.includes("retained-1") ?? false)
+
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+ expect(queryClient.getQueryData(
+ communityKeys.channelMeta("server-1", "retained-1"),
+ )).toMatchObject({ id: "retained-1" })
+ renderer!.unmount()
+ })
+
+ it("does not seed resources when an unmounted consumer loses the response race", async () => {
+ let resolveRequest: ((value: SidebarThreadEnvelope) => void) | undefined
+ apiFetchMock.mockImplementation(() => new Promise((resolve) => { resolveRequest = resolve }))
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, { retainId: "retained-1", onRender: () => undefined }),
+ ),
+ )
+ })
+ await waitFor(() => apiFetchMock.mock.calls.length === 1)
+ const canonical = envelope(["base-1"])
+ const retained = envelope(["retained-1"])
+ await act(async () => {
+ renderer!.unmount()
+ resolveRequest?.({
+ ...canonical,
+ canonicalChannels: canonical.channels,
+ retainedChannel: retained.channels[0],
+ included: {
+ parentMessages: [
+ ...canonical.included.parentMessages,
+ ...retained.included.parentMessages,
+ ],
+ },
+ })
+ await Promise.resolve()
+ })
+
+ expect(queryClient.getQueryData(
+ communityKeys.forumSidebarThreads("server-1"),
+ )).toBeUndefined()
+ expect(queryClient.getQueriesData({
+ queryKey: communityKeys.channelMetaRoot("server-1"),
+ })).toEqual([])
+ expect(queryClient.getQueriesData({
+ queryKey: communityKeys.forumOpenerHintRoot("server-1"),
+ })).toEqual([])
+ })
+
+ it("does not relabel an old in-flight response with a newer access epoch", async () => {
+ let resolveRequest: ((value: SidebarThreadEnvelope) => void) | undefined
+ apiFetchMock.mockImplementation(() => new Promise((resolve) => { resolveRequest = resolve }))
+ 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(() => apiFetchMock.mock.calls.length === 1)
+
+ await act(async () => {
+ useCommunityWsStore.getState().markAccessDisconnected()
+ useCommunityWsStore.getState().markAccessConnected()
+ resolveRequest?.(envelope(["base-1"]))
+ })
+ await waitFor(() => queryClient.getQueryState(
+ communityKeys.forumSidebarThreads("server-1"),
+ )?.status === "success")
+
+ expect(queryClient.getQueryData<ForumSidebarQueryData>(
+ communityKeys.forumSidebarThreads("server-1"),
+ )?.verifiedEpoch).toBe(0)
+ expect(useCommunityWsStore.getState().accessEpoch).toBe(1)
+ expect(renders.at(-1)).toEqual([])
+ renderer!.unmount()
+ })
+
+ it("replays a title patch that lands while the canonical request is in flight", async () => {
+ let resolveRequest: ((value: SidebarThreadEnvelope) => void) | undefined
+ apiFetchMock.mockImplementation(() => new Promise((resolve) => { resolveRequest = resolve }))
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, { retainId: null, onRender: () => undefined }),
+ ),
+ )
+ })
+ patchForumSidebarTitleExact(queryClient, "server-1", "base-1", "live title")
+ await act(async () => resolveRequest?.(envelope(["base-1"])))
+ await waitFor(() => queryClient.getQueryState(
+ communityKeys.forumSidebarThreads("server-1"),
+ )?.status === "success")
+
+ expect(queryClient.getQueryData<ForumSidebarQueryData>(
+ communityKeys.forumSidebarThreads("server-1"),
+ )?.threads[0]?.title).toBe("live title")
+ expect(queryClient.getQueryData(
+ communityKeys.forumOpenerHint("server-1", "opener-base-1"),
+ )).toEqual({ id: "opener-base-1", content: "live title" })
+ renderer!.unmount()
+ })
+
+ it("replays in-flight activity into the exact metadata seed", async () => {
+ let resolveRequest: ((value: SidebarThreadEnvelope) => void) | undefined
+ apiFetchMock.mockImplementation(() => new Promise((resolve) => { resolveRequest = resolve }))
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, { retainId: null, onRender: () => undefined }),
+ ),
+ )
+ })
+ patchForumSidebarActivityExact(
+ queryClient,
+ "server-1",
+ "base-1",
+ "forum-1",
+ "2026-08-09T00:00:00.000Z",
+ )
+ await act(async () => resolveRequest?.(envelope(["base-1"])))
+ await waitFor(() => queryClient.getQueryState(
+ communityKeys.forumSidebarThreads("server-1"),
+ )?.status === "success")
+
+ expect(queryClient.getQueryData<ForumSidebarQueryData>(
+ communityKeys.forumSidebarThreads("server-1"),
+ )?.threads[0]?.activityAt).toBe("2026-08-09T00:00:00.000Z")
+ expect(queryClient.getQueryData(
+ communityKeys.channelMeta("server-1", "base-1"),
+ )).toMatchObject({ activityAt: "2026-08-09T00:00:00.000Z" })
+ renderer!.unmount()
+ })
+
+ it("does not let a delayed response revive removed metadata or opener hints", async () => {
+ let resolveRequest: ((value: SidebarThreadEnvelope) => void) | undefined
+ apiFetchMock.mockImplementation(() => new Promise((resolve) => { resolveRequest = resolve }))
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, { retainId: null, onRender: () => undefined }),
+ ),
+ )
+ })
+ removeForumSidebarThreadExact(queryClient, "server-1", "base-1")
+ await act(async () => resolveRequest?.(envelope(["base-1"])))
+ await waitFor(() => queryClient.getQueryState(
+ communityKeys.forumSidebarThreads("server-1"),
+ )?.status === "success")
+
+ expect(queryClient.getQueryData<ForumSidebarQueryData>(
+ communityKeys.forumSidebarThreads("server-1"),
+ )?.threads).toEqual([])
+ expect(queryClient.getQueryData(
+ communityKeys.channelMeta("server-1", "base-1"),
+ )).toBeUndefined()
+ expect(queryClient.getQueryData(
+ communityKeys.forumOpenerHint("server-1", "opener-base-1"),
+ )).toBeUndefined()
+ renderer!.unmount()
+ })
+
+ it("restarts a cold request when the route candidate changes", async () => {
+ let resolveFirst: ((value: SidebarThreadEnvelope) => void) | undefined
+ let resolveSecond: ((value: SidebarThreadEnvelope) => void) | undefined
+ apiFetchMock
+ .mockImplementationOnce(() => new Promise((resolve) => { resolveFirst = resolve }))
+ .mockImplementationOnce(() => new Promise((resolve) => { resolveSecond = resolve }))
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, { retainId: null, onRender: () => undefined }),
+ ),
+ )
+ })
+ await waitFor(() => apiFetchMock.mock.calls.length === 1)
+ await act(async () => {
+ renderer!.update(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, { retainId: "post-b", onRender: () => undefined }),
+ ),
+ )
+ })
+ await waitFor(() => apiFetchMock.mock.calls.length === 2)
+ const first = envelope(["base-a"])
+ const secondBase = envelope(["base-a"])
+ const secondRetained = envelope(["post-b"])
+ await act(async () => resolveFirst?.(first))
+ await act(async () => resolveSecond?.({
+ ...secondBase,
+ canonicalChannels: secondBase.channels,
+ retainedChannel: secondRetained.channels[0],
+ included: {
+ parentMessages: [
+ ...secondBase.included.parentMessages,
+ ...secondRetained.included.parentMessages,
+ ],
+ },
+ }))
+ await waitFor(() => queryClient.getQueryData<ForumSidebarThread | null>(
+ communityKeys.forumSidebarRetained("server-1", "post-b"),
+ )?.id === "post-b")
+
+ expect(apiFetchMock.mock.calls[1]?.[0]).toContain("retainId=post-b")
+ expect(queryClient.getQueryData<ForumSidebarThread | null>(
+ communityKeys.forumSidebarRetained("server-1", "post-b"),
+ )?.id).toBe("post-b")
+ renderer!.unmount()
+ })
+
+ it("clears an exact negative retained result on a grant without touching siblings", async () => {
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(communityKeys.forumSidebarRetained("server-1", "post-1"), null)
+ queryClient.setQueryData(
+ communityKeys.forumSidebarRetained("server-1", "post-2"),
+ { id: "post-2" },
+ )
+
+ await grantForumSidebarChild(queryClient, "server-1", "post-1")
+
+ expect(queryClient.getQueryState(
+ communityKeys.forumSidebarRetained("server-1", "post-1"),
+ )).toBeUndefined()
+ expect(queryClient.getQueryData(
+ communityKeys.forumSidebarRetained("server-1", "post-2"),
+ )).toEqual({ id: "post-2" })
+ })
+
+ it("clears stale metadata and opener content when the retained candidate is unauthorized", async () => {
+ apiFetchMock.mockResolvedValue({
+ ...envelope([]),
+ canonicalChannels: [],
+ retainedChannel: null,
+ })
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ queryClient.setQueryData(communityKeys.server("server-1"), {
+ ...serverDetail(true),
+ forumUnreadState: {
+ "forum-1": { baseUnread: true, childIds: ["private-post"] },
+ },
+ })
+ queryClient.setQueryData<ForumSidebarUnreadFallbackState>(
+ communityKeys.forumSidebarUnreadFallbacks("server-1"),
+ { "forum-1": { baseUnread: true, childIds: ["private-post"] } },
+ )
+ queryClient.setQueryData(
+ communityKeys.forumSidebarRetained("server-1", "private-post"),
+ {
+ ...projectForumSidebarThreads(envelope(["private-post"]))[0],
+ parentMessageId: "private-opener",
+ },
+ )
+ queryClient.setQueryData(
+ communityKeys.channelMeta("server-1", "private-post"),
+ {
+ id: "private-post",
+ serverId: "server-1",
+ name: "Private post",
+ type: "thread",
+ parentChannelId: "forum-1",
+ parentMessageId: "private-opener",
+ creatorId: "user-1",
+ archived: false,
+ activityAt: "2026-08-08T00:00:00.000Z",
+ verifiedEpoch: 0,
+ },
+ )
+ queryClient.setQueryData(
+ communityKeys.forumOpenerHint("server-1", "private-opener"),
+ { id: "private-opener", content: "Private title" },
+ )
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, { retainId: "private-post", onRender: () => undefined }),
+ ),
+ )
+ })
+ await waitFor(() => queryClient.getQueryState(
+ communityKeys.forumSidebarThreads("server-1"),
+ )?.status === "success")
+
+ expect(queryClient.getQueryData(
+ communityKeys.forumSidebarRetained("server-1", "private-post"),
+ )).toBeNull()
+ expect(queryClient.getQueryState(
+ communityKeys.channelMeta("server-1", "private-post"),
+ )).toBeUndefined()
+ expect(queryClient.getQueryState(
+ communityKeys.forumOpenerHint("server-1", "private-opener"),
+ )).toBeUndefined()
+ expect(queryClient.getQueryData<ServerDetail>(
+ communityKeys.server("server-1"),
+ )?.forumUnreadState?.["forum-1"]).toEqual({ baseUnread: true, childIds: [] })
+ expect(parentUnread(queryClient)).toBe(true)
+ expect(queryClient.getQueryData<ForumSidebarUnreadFallbackState>(
+ communityKeys.forumSidebarUnreadFallbacks("server-1"),
+ )).toEqual({})
+ renderer!.unmount()
+ })
+
+ it("force-restarts an in-flight request on grant instead of reusing its negative response", async () => {
+ let resolveFirst: ((value: SidebarThreadEnvelope) => void) | undefined
+ let resolveSecond: ((value: SidebarThreadEnvelope) => void) | undefined
+ apiFetchMock
+ .mockImplementationOnce(() => new Promise((resolve) => { resolveFirst = resolve }))
+ .mockImplementationOnce(() => new Promise((resolve) => { resolveSecond = resolve }))
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, { retainId: "post-granted", onRender: () => undefined }),
+ ),
+ )
+ })
+ await waitFor(() => apiFetchMock.mock.calls.length === 1)
+ act(() => { void grantForumSidebarChild(queryClient, "server-1", "post-granted") })
+ await waitFor(() => apiFetchMock.mock.calls.length === 2)
+
+ const granted = envelope(["post-granted"])
+ await act(async () => resolveSecond?.({
+ ...granted,
+ canonicalChannels: granted.channels,
+ retainedChannel: granted.channels[0],
+ }))
+ await waitFor(() => queryClient.getQueryData<ForumSidebarQueryData>(
+ communityKeys.forumSidebarThreads("server-1"),
+ )?.threads[0]?.id === "post-granted")
+ await act(async () => resolveFirst?.({
+ ...envelope([]),
+ canonicalChannels: [],
+ retainedChannel: null,
+ }))
+
+ expect(apiFetchMock).toHaveBeenCalledTimes(2)
+ expect(queryClient.getQueryData<ForumSidebarQueryData>(
+ communityKeys.forumSidebarThreads("server-1"),
+ )?.threads.map((thread) => thread.id)).toEqual(["post-granted"])
+ expect(queryClient.getQueryData(
+ communityKeys.channelMeta("server-1", "post-granted"),
+ )).toMatchObject({ id: "post-granted", verifiedEpoch: 0 })
+ renderer!.unmount()
+ })
+
+ it("force-restarts an old-epoch request before reconnect validation", async () => {
+ let resolveFirst: ((value: SidebarThreadEnvelope) => void) | undefined
+ let resolveSecond: ((value: SidebarThreadEnvelope) => void) | undefined
+ apiFetchMock
+ .mockImplementationOnce(() => new Promise((resolve) => { resolveFirst = resolve }))
+ .mockImplementationOnce(() => new Promise((resolve) => { resolveSecond = resolve }))
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, { retainId: null, onRender: () => undefined }),
+ ),
+ )
+ })
+ await waitFor(() => apiFetchMock.mock.calls.length === 1)
+ await act(async () => {
+ useCommunityWsStore.getState().markAccessDisconnected()
+ useCommunityWsStore.getState().markAccessConnected()
+ void invalidateForumSidebarBaseExact(queryClient, "server-1")
+ })
+ await waitFor(() => apiFetchMock.mock.calls.length === 2)
+
+ await act(async () => resolveSecond?.(envelope(["epoch-1"])))
+ await waitFor(() => queryClient.getQueryData<ForumSidebarQueryData>(
+ communityKeys.forumSidebarThreads("server-1"),
+ )?.threads[0]?.id === "epoch-1")
+ await act(async () => resolveFirst?.(envelope(["epoch-0"])))
+
+ expect(queryClient.getQueryData<ForumSidebarQueryData>(
+ communityKeys.forumSidebarThreads("server-1"),
+ )).toMatchObject({
+ verifiedEpoch: 1,
+ threads: [expect.objectContaining({ id: "epoch-1" })],
+ })
+ expect(queryClient.getQueryState(
+ communityKeys.channelMeta("server-1", "epoch-0"),
+ )).toBeUndefined()
+ renderer!.unmount()
+ })
+
+ it("normalizes one canonical base plus one exact retained resource", () => {
+ const source = {
+ ...envelope(["base-1", "base-2"]),
+ canonicalChannels: envelope(["base-1", "base-2"]).channels,
+ retainedChannel: envelope(["retained-1"]).channels[0],
+ included: {
+ parentMessages: [
+ { id: "opener-base-1", content: "Base 1" },
+ { id: "opener-base-2", content: "Base 2" },
+ { id: "opener-retained-1", content: "Retained 1" },
+ ],
+ },
+ }
+
+ const normalized = normalizeForumSidebarEnvelope(source, "retained-1", 0)
+
+ expect(normalized.base.threads.map((thread) => thread.id)).toEqual(["base-1", "base-2"])
+ expect(normalized.retained?.id).toBe("retained-1")
+ expect(normalized.channelMetas["retained-1"]).toMatchObject({
+ id: "retained-1",
+ parentMessageId: "opener-retained-1",
+ })
+ expect(normalized.openerHints["opener-retained-1"]).toEqual({
+ id: "opener-retained-1",
+ content: "Retained 1",
+ })
+ expect(normalized.openerHints["opener-retained-1"]).not.toHaveProperty("authorId")
+ expect(JSON.stringify(normalized.base)).not.toContain("retained-1")
+ expect(JSON.stringify(normalized.base)).not.toContain("Retained 1")
+ })
+
+ it("removes a child and opener from every exact resource without raw base residue", () => {
+ const source = envelope(["base-1"])
+ const normalized = normalizeForumSidebarEnvelope({
+ ...source,
+ canonicalChannels: source.channels,
+ retainedChannel: null,
+ }, null, 0)
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(communityKeys.forumSidebarThreads("server-1"), normalized.base)
+ queryClient.setQueryData(
+ communityKeys.forumSidebarRetained("server-1", "base-1"),
+ normalized.base.threads[0],
+ )
+ queryClient.setQueryData(
+ communityKeys.channelMeta("server-1", "base-1"),
+ normalized.channelMetas["base-1"],
+ )
+ queryClient.setQueryData(
+ communityKeys.forumOpenerHint("server-1", "opener-base-1"),
+ normalized.openerHints["opener-base-1"],
+ )
+
+ removeForumSidebarThreadExact(queryClient, "server-1", "base-1")
+
+ expect(JSON.stringify(queryClient.getQueryData(
+ communityKeys.forumSidebarThreads("server-1"),
+ ))).not.toContain("base-1")
+ expect(queryClient.getQueryState(
+ communityKeys.forumSidebarRetained("server-1", "base-1"),
+ )).toBeUndefined()
+ expect(queryClient.getQueryState(
+ communityKeys.channelMeta("server-1", "base-1"),
+ )).toBeUndefined()
+ expect(queryClient.getQueryState(
+ communityKeys.forumOpenerHint("server-1", "opener-base-1"),
+ )).toBeUndefined()
+ })
+
+ it("keeps a positive retained resource but does not duplicate a canonical child", () => {
+ const source = {
+ ...envelope(["base-1"]),
+ canonicalChannels: envelope(["base-1"]).channels,
+ retainedChannel: envelope(["base-1"]).channels[0],
+ }
+
+ const normalized = normalizeForumSidebarEnvelope(source, "base-1", 0)
+ expect(normalized.retained?.id).toBe("base-1")
+ expect(deriveForumSidebarProjection(
+ normalized.base,
+ normalized.retained,
+ {},
+ Date.parse("2026-08-08T00:00:00.000Z"),
+ ).threads.map((thread) => thread.id)).toEqual(["base-1"])
+ })
+
+ it("derives child and parent unread from one ownership snapshot", () => {
+ const source = envelope(["base-1", "base-2"])
+ const normalized = normalizeForumSidebarEnvelope({
+ ...source,
+ canonicalChannels: source.channels,
+ retainedChannel: envelope(["retained-1"]).channels[0],
+ }, "retained-1", 0)
+ const ownership = {
+ "forum-1": {
+ baseUnread: false,
+ childIds: ["base-2", "retained-1"],
+ },
+ }
+
+ const active = deriveForumSidebarProjection(
+ normalized.base,
+ normalized.retained,
+ ownership,
+ Date.parse("2026-08-08T01:00:00.000Z"),
+ 2,
+ )
+ expect(active.threads.map((thread) => [thread.id, thread.unread])).toEqual([
+ ["retained-1", true],
+ ["base-1", false],
+ ])
+ expect(active.parentUnread["forum-1"]).toBe(true)
+
+ const inactive = deriveForumSidebarProjection(
+ normalized.base,
+ null,
+ ownership,
+ Date.parse("2026-08-08T01:00:00.000Z"),
+ 2,
+ )
+ expect(inactive.threads.map((thread) => [thread.id, thread.unread])).toEqual([
+ ["base-1", false],
+ ["base-2", true],
+ ])
+ expect(inactive.parentUnread["forum-1"]).toBe(true)
+ })
+
+ it("prunes expired base rows before a refresh can succeed", () => {
+ const source = envelope(["expired", "fresh"])
+ source.channels[0]!.expiresAt = "2026-08-08T00:30:00.000Z"
+ source.channels[1]!.expiresAt = "2026-08-08T02:00:00.000Z"
+ const normalized = normalizeForumSidebarEnvelope({
+ ...source,
+ canonicalChannels: source.channels,
+ retainedChannel: null,
+ }, null, 0)
+
+ const projection = deriveForumSidebarProjection(
+ normalized.base,
+ null,
+ {},
+ Date.parse("2026-08-08T01:00:00.000Z"),
+ )
+ expect(projection.threads.map((thread) => thread.id)).toEqual(["fresh"])
+ })
+})
diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.ts
index 54aff3a13..e789e0ec7 100644
--- a/src/web/src/hooks/community/use-forum-sidebar-threads.ts
+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.ts
@@ -1,11 +1,12 @@
"use client"
-import { useEffect } from "react"
-import { keepPreviousData, useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query"
+import { useEffect, useMemo, useRef } from "react"
+import { useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
import { patchChannelUnread } from "@/hooks/community/server-detail-cache"
import type { ServerDetail } from "@/hooks/community/use-servers"
+import { useCommunityWsStore } from "@/stores/community/ws"
export type ForumSidebarThread = {
id: string
@@ -26,25 +27,91 @@ export type SidebarThreadEnvelope = {
activityAt: string
expiresAt: string
unread: boolean
+ serverId?: string
+ type?: string
+ creatorId?: string | null
+ archived?: boolean | number
+ lastMessageAt?: string | null
+ createdAt?: string
}>
+ canonicalChannels?: SidebarThreadEnvelope["channels"]
+ retainedChannel?: SidebarThreadEnvelope["channels"][number] | null
included: {
parentMessages: Array<{ id: string; content: string }>
}
serverNow: string
}
-export type ForumSidebarQueryData = SidebarThreadEnvelope & {
+export type ForumSidebarQueryData = {
threads: ForumSidebarThread[]
- /** Server clock minus client clock, captured when this envelope arrived. */
+ verifiedEpoch: number
+ serverNow: string
serverClockOffsetMs: number
}
+export type ChildChannelMeta = {
+ id: string
+ serverId: string
+ name: string
+ type: string
+ parentChannelId: string
+ parentMessageId: string
+ creatorId: string | null
+ archived: boolean
+ activityAt: string
+ verifiedEpoch: number
+}
+
+export type ForumOpenerHint = { id: string; content: string }
+
+export type NormalizedForumSidebarEnvelope = {
+ base: ForumSidebarQueryData
+ retained: ForumSidebarThread | null
+ channelMetas: Record<string, ChildChannelMeta>
+ openerHints: Record<string, ForumOpenerHint>
+}
+
+export function resolveForumSidebarRouteCandidate(
+ channelId: string | null,
+ topLevelChannelIds: Iterable<string> | null,
+) {
+ if (!channelId || !topLevelChannelIds) return null
+ return new Set(topLevelChannelIds).has(channelId) ? null : channelId
+}
+
+type InflightDelta = {
+ activity: Map<string, { parentChannelId: string; activityAt: string }>
+ titles: Map<string, string>
+ unread: Map<string, boolean>
+ removed: Set<string>
+}
+
+type InflightRecord = {
+ promise: Promise<NormalizedForumSidebarEnvelope>
+ delta: InflightDelta
+ candidate: string | null
+ controller: AbortController
+ signals: Set<AbortSignal>
+ abortTimer: ReturnType<typeof setTimeout> | null
+}
+
+const inflight = new Map<string, InflightRecord>()
+
+function recordInflightDelta(
+ serverId: string,
+ update: (delta: InflightDelta) => void,
+) {
+ const record = inflight.get(serverId)
+ if (record) update(record.delta)
+}
+
export type ForumSidebarUnreadFallbackState = Record<string, {
baseUnread: boolean
childIds: string[]
}>
const SIDEBAR_ACTIVITY_WINDOW_MS = 72 * 60 * 60 * 1000
+const STRICT_MODE_ABORT_GRACE_MS = 50
function parentUnread(cache: ServerDetail | undefined, parentChannelId: string): boolean {
return !!cache?.categories.some((category) =>
@@ -245,7 +312,7 @@ export function patchForumSidebarActivity(
return { ...data, threads }
}
-export function patchForumSidebarTitle(
+function patchForumSidebarTitle(
data: ForumSidebarQueryData | undefined,
threadId: string,
title: string,
@@ -293,8 +360,531 @@ export function projectForumSidebarThreads(data: SidebarThreadEnvelope): ForumSi
})
}
-export function useForumSidebarThreads(serverId: string, retainId: string | null) {
+function projectChannels(
+ channels: SidebarThreadEnvelope["channels"],
+ parentMessages: SidebarThreadEnvelope["included"]["parentMessages"],
+): ForumSidebarThread[] {
+ return projectForumSidebarThreads({
+ channels,
+ included: { parentMessages },
+ serverNow: "",
+ })
+}
+
+function childMeta(
+ channel: SidebarThreadEnvelope["channels"][number],
+): ChildChannelMeta | null {
+ if (
+ !channel.serverId || !channel.type || !channel.parentChannelId ||
+ !channel.parentMessageId
+ ) return null
+ return {
+ id: channel.id,
+ serverId: channel.serverId,
+ name: channel.name,
+ type: channel.type,
+ parentChannelId: channel.parentChannelId,
+ parentMessageId: channel.parentMessageId,
+ creatorId: channel.creatorId ?? null,
+ archived: channel.archived === true || channel.archived === 1,
+ activityAt: channel.activityAt,
+ verifiedEpoch: -1,
+ }
+}
+
+export function normalizeForumSidebarEnvelope(
+ envelope: SidebarThreadEnvelope,
+ retainId: string | null,
+ serverClockOffsetOverride?: number,
+): NormalizedForumSidebarEnvelope {
+ const canonicalChannels = envelope.canonicalChannels ?? envelope.channels
+ const threads = projectChannels(canonicalChannels, envelope.included.parentMessages)
+ const serverNowMs = Date.parse(envelope.serverNow)
+ const base: ForumSidebarQueryData = {
+ threads,
+ serverNow: envelope.serverNow,
+ verifiedEpoch: -1,
+ serverClockOffsetMs: serverClockOffsetOverride ??
+ (Number.isFinite(serverNowMs) ? serverNowMs - Date.now() : 0),
+ }
+ const retainedChannel = retainId && envelope.retainedChannel?.id === retainId
+ ? envelope.retainedChannel
+ : null
+ const retained = retainedChannel
+ ? projectChannels([retainedChannel], envelope.included.parentMessages)[0] ?? null
+ : null
+ const channelMetas: Record<string, ChildChannelMeta> = {}
+ for (const channel of retainedChannel
+ ? [...canonicalChannels, retainedChannel]
+ : canonicalChannels) {
+ const meta = childMeta(channel)
+ if (meta) channelMetas[meta.id] = meta
+ }
+ const openerHints = Object.fromEntries(
+ envelope.included.parentMessages.map(({ id, content }) => [id, { id, content }]),
+ )
+ return { base, retained, channelMetas, openerHints }
+}
+
+export function deriveForumSidebarProjection(
+ base: ForumSidebarQueryData | undefined,
+ activeExtra: ForumSidebarThread | null | undefined,
+ ownership: ServerDetail["forumUnreadState"] | undefined,
+ nowMs = Date.now(),
+ limitPerParent = 5,
+) {
+ if (!base) return { threads: [] as ForumSidebarThread[], parentUnread: {} as Record<string, boolean> }
+ const serverNowMs = nowMs + base.serverClockOffsetMs
+ let threads = base.threads.filter((thread) => {
+ const expiresAt = Date.parse(thread.expiresAt)
+ return !Number.isFinite(expiresAt) || expiresAt > serverNowMs
+ })
+ if (activeExtra && !threads.some((thread) => thread.id === activeExtra.id)) {
+ const siblings = threads.filter((thread) => thread.parentChannelId === activeExtra.parentChannelId)
+ const otherParents = threads.filter((thread) => thread.parentChannelId !== activeExtra.parentChannelId)
+ threads = [...otherParents, ...siblings.slice(0, Math.max(0, limitPerParent - 1)), activeExtra]
+ .sort((a, b) => {
+ if (a.parentChannelId !== b.parentChannelId) return a.parentChannelId < b.parentChannelId ? -1 : 1
+ if (a.activityAt !== b.activityAt) return a.activityAt > b.activityAt ? -1 : 1
+ return a.id === b.id ? 0 : a.id > b.id ? -1 : 1
+ })
+ }
+ const renderedIds = new Set(threads.map((thread) => thread.id))
+ threads = threads.map((thread) => ({
+ ...thread,
+ unread: ownership?.[thread.parentChannelId]?.childIds.includes(thread.id) ?? thread.unread,
+ }))
+ const parentUnread: Record<string, boolean> = {}
+ for (const [parentId, state] of Object.entries(ownership ?? {})) {
+ parentUnread[parentId] = state.baseUnread || state.childIds.some((id) => !renderedIds.has(id))
+ }
+ return { threads, parentUnread }
+}
+
+export function getForumSidebarBase(queryClient: QueryClient, serverId: string) {
+ return queryClient.getQueryData<ForumSidebarQueryData>(
+ communityKeys.forumSidebarThreads(serverId),
+ )
+}
+
+function getForumSidebarRetained(
+ queryClient: QueryClient,
+ serverId: string,
+ childId: string,
+) {
+ return queryClient.getQueryData<ForumSidebarThread | null>(
+ communityKeys.forumSidebarRetained(serverId, childId),
+ )
+}
+
+export function hasProjectedForumSidebarThread(
+ queryClient: QueryClient,
+ serverId: string,
+ childId: string,
+ activeChildId: string | null | undefined,
+) {
+ const access = useCommunityWsStore.getState()
+ const base = getForumSidebarBase(queryClient, serverId)
+ if (
+ !access.accessConnected ||
+ !base ||
+ base.verifiedEpoch !== access.accessEpoch
+ ) return false
+ const activeExtra = activeChildId
+ ? getForumSidebarRetained(queryClient, serverId, activeChildId)
+ : null
+ const ownership = queryClient.getQueryData<ServerDetail>(
+ communityKeys.server(serverId),
+ )?.forumUnreadState
+ return deriveForumSidebarProjection(base, activeExtra, ownership)
+ .threads.some((thread) => thread.id === childId)
+}
+
+export function isKnownNonForumSidebarChannel(
+ queryClient: QueryClient,
+ serverId: string,
+ channelId: string,
+) {
+ const server = queryClient.getQueryData<ServerDetail>(communityKeys.server(serverId))
+ const topLevel = server?.categories
+ .flatMap((category) => category.channels)
+ .find((channel) => channel.id === channelId)
+ if (topLevel) return topLevel.type !== "forum"
+ const meta = queryClient.getQueryData<ChildChannelMeta>(
+ communityKeys.channelMeta(serverId, channelId),
+ )
+ if (!meta) return false
+ const parent = server?.categories
+ .flatMap((category) => category.channels)
+ .find((channel) => channel.id === meta.parentChannelId)
+ return !!parent && parent.type !== "forum"
+}
+
+export function isForumSidebarParent(
+ queryClient: QueryClient,
+ serverId: string,
+ parentChannelId: string,
+) {
+ return queryClient.getQueryData<ServerDetail>(communityKeys.server(serverId))
+ ?.categories.some((category) => category.channels.some(
+ (channel) => channel.id === parentChannelId && channel.type === "forum",
+ )) ?? false
+}
+
+function patchRetained(
+ queryClient: QueryClient,
+ serverId: string,
+ childId: string,
+ patch: (thread: ForumSidebarThread) => ForumSidebarThread,
+) {
+ queryClient.setQueryData<ForumSidebarThread | null | undefined>(
+ communityKeys.forumSidebarRetained(serverId, childId),
+ (thread) => thread ? patch(thread) : thread,
+ )
+}
+
+export function patchForumSidebarActivityExact(
+ queryClient: QueryClient,
+ serverId: string,
+ childId: string,
+ parentChannelId: string,
+ activityAt: string,
+) {
+ recordInflightDelta(serverId, (delta) => {
+ delta.activity.set(childId, { parentChannelId, activityAt })
+ })
+ queryClient.setQueryData<ForumSidebarQueryData | undefined>(
+ communityKeys.forumSidebarThreads(serverId),
+ (data) => patchForumSidebarActivity(data, childId, parentChannelId, activityAt),
+ )
+ patchRetained(queryClient, serverId, childId, (thread) => ({
+ ...thread,
+ activityAt,
+ expiresAt: new Date(Date.parse(activityAt) + SIDEBAR_ACTIVITY_WINDOW_MS).toISOString(),
+ }))
+ queryClient.setQueryData<ChildChannelMeta | undefined>(
+ communityKeys.channelMeta(serverId, childId),
+ (meta) => meta ? { ...meta, activityAt } : meta,
+ )
+}
+
+export function patchForumSidebarTitleExact(
+ queryClient: QueryClient,
+ serverId: string,
+ childId: string,
+ title: string,
+) {
+ recordInflightDelta(serverId, (delta) => {
+ delta.titles.set(childId, title)
+ })
+ queryClient.setQueryData<ForumSidebarQueryData | undefined>(
+ communityKeys.forumSidebarThreads(serverId),
+ (data) => patchForumSidebarTitle(data, childId, title),
+ )
+ patchRetained(queryClient, serverId, childId, (thread) => ({ ...thread, title }))
+ const meta = queryClient.getQueryData<ChildChannelMeta>(communityKeys.channelMeta(serverId, childId))
+ if (meta) {
+ queryClient.setQueryData<ForumOpenerHint | undefined>(
+ communityKeys.forumOpenerHint(serverId, meta.parentMessageId),
+ (hint) => hint ? { ...hint, content: title } : hint,
+ )
+ }
+}
+
+export function patchForumSidebarUnreadExact(
+ queryClient: QueryClient,
+ serverId: string,
+ childId: string,
+ unread: boolean,
+) {
+ recordInflightDelta(serverId, (delta) => {
+ delta.unread.set(childId, unread)
+ })
+ queryClient.setQueryData<ForumSidebarQueryData | undefined>(
+ communityKeys.forumSidebarThreads(serverId),
+ (data) => patchForumSidebarUnread(data, childId, unread),
+ )
+ patchRetained(queryClient, serverId, childId, (thread) => ({ ...thread, unread }))
+}
+
+export function removeForumSidebarThreadExact(
+ queryClient: QueryClient,
+ serverId: string,
+ childId: string,
+) {
+ const meta = queryClient.getQueryData<ChildChannelMeta>(
+ communityKeys.channelMeta(serverId, childId),
+ )
+ const parentMessageId = meta?.parentMessageId ??
+ getForumSidebarRetained(queryClient, serverId, childId)?.parentMessageId ??
+ getForumSidebarBase(queryClient, serverId)?.threads
+ .find((thread) => thread.id === childId)?.parentMessageId
+ recordInflightDelta(serverId, (delta) => {
+ delta.removed.add(childId)
+ })
+ queryClient.setQueryData<ForumSidebarQueryData | undefined>(
+ communityKeys.forumSidebarThreads(serverId),
+ (data) => removeForumSidebarThread(data, childId),
+ )
+ queryClient.removeQueries({
+ queryKey: communityKeys.forumSidebarRetained(serverId, childId),
+ exact: true,
+ })
+ queryClient.removeQueries({
+ queryKey: communityKeys.channelMeta(serverId, childId),
+ exact: true,
+ })
+ if (parentMessageId) {
+ queryClient.removeQueries({
+ queryKey: communityKeys.forumOpenerHint(serverId, parentMessageId),
+ exact: true,
+ })
+ }
+}
+
+export function removeForumSidebarChildrenForParent(
+ queryClient: QueryClient,
+ serverId: string,
+ parentChannelId: string,
+) {
+ const childIds = new Set(
+ getForumSidebarBase(queryClient, serverId)?.threads
+ .filter((thread) => thread.parentChannelId === parentChannelId)
+ .map((thread) => thread.id) ?? [],
+ )
+ for (const [, meta] of queryClient.getQueriesData<ChildChannelMeta>({
+ queryKey: communityKeys.channelMetaRoot(serverId),
+ })) {
+ if (meta?.parentChannelId === parentChannelId) childIds.add(meta.id)
+ }
+ for (const [, thread] of queryClient.getQueriesData<ForumSidebarThread | null>({
+ queryKey: communityKeys.forumSidebarRetainedRoot(serverId),
+ })) {
+ if (thread?.parentChannelId === parentChannelId) childIds.add(thread.id)
+ }
+ for (const childId of childIds) {
+ removeForumSidebarUnreadChild(queryClient, serverId, childId)
+ removeForumSidebarThreadExact(queryClient, serverId, childId)
+ }
+}
+
+export function invalidateForumSidebarBaseExact(queryClient: QueryClient, serverId: string) {
+ const pending = inflight.get(serverId)
+ if (pending) {
+ if (pending.abortTimer !== null) globalThis.clearTimeout(pending.abortTimer)
+ pending.controller.abort()
+ inflight.delete(serverId)
+ }
+ const queryKey = communityKeys.forumSidebarThreads(serverId)
+ void queryClient.cancelQueries({ queryKey, exact: true })
+ return queryClient.invalidateQueries({
+ queryKey,
+ exact: true,
+ })
+}
+
+export function grantForumSidebarChild(
+ queryClient: QueryClient,
+ serverId: string,
+ childId: string,
+) {
+ recordInflightDelta(serverId, (delta) => {
+ delta.removed.delete(childId)
+ })
+ void queryClient.cancelQueries({
+ queryKey: communityKeys.forumSidebarRetained(serverId, childId),
+ exact: true,
+ })
+ queryClient.removeQueries({
+ queryKey: communityKeys.forumSidebarRetained(serverId, childId),
+ exact: true,
+ })
+ queryClient.removeQueries({
+ queryKey: communityKeys.channelMeta(serverId, childId),
+ exact: true,
+ })
+ return invalidateForumSidebarBaseExact(queryClient, serverId)
+}
+
+function sidebarUrl(serverId: string, retainId: string | null) {
+ const params = new URLSearchParams({
+ type: "thread",
+ parentType: "forum",
+ participating: "true",
+ activeWithin: "72h",
+ limitPerParent: "5",
+ include: "parentMessage",
+ })
+ if (retainId) params.set("retainId", retainId)
+ return `/api/community/servers/${serverId}/channels?${params.toString()}`
+}
+
+function attachInflightSignal(
+ serverId: string,
+ record: InflightRecord,
+ signal?: AbortSignal,
+) {
+ if (!signal || record.signals.has(signal)) return
+ if (record.abortTimer !== null) {
+ globalThis.clearTimeout(record.abortTimer)
+ record.abortTimer = null
+ }
+ record.signals.add(signal)
+ const release = () => {
+ record.signals.delete(signal)
+ if (record.signals.size > 0 || record.abortTimer !== null) return
+ record.abortTimer = globalThis.setTimeout(() => {
+ record.abortTimer = null
+ if (inflight.get(serverId) === record && record.signals.size === 0) {
+ record.controller.abort()
+ }
+ }, STRICT_MODE_ABORT_GRACE_MS)
+ }
+ if (signal.aborted) release()
+ else signal.addEventListener("abort", release, { once: true })
+}
+
+function fetchForumSidebar(serverId: string, retainId: string | null, signal?: AbortSignal) {
+ const pending = inflight.get(serverId)
+ if (pending?.candidate === retainId && !pending.controller.signal.aborted) {
+ attachInflightSignal(serverId, pending, signal)
+ return pending.promise
+ }
+ if (pending) {
+ if (pending.abortTimer !== null) globalThis.clearTimeout(pending.abortTimer)
+ pending.controller.abort()
+ inflight.delete(serverId)
+ }
+ const controller = new AbortController()
+ const delta: InflightDelta = {
+ activity: new Map(),
+ titles: new Map(),
+ unread: new Map(),
+ removed: new Set(),
+ }
+ const request = apiFetch<SidebarThreadEnvelope>(sidebarUrl(serverId, retainId), {
+ signal: controller.signal,
+ })
+ .then((envelope) => normalizeForumSidebarEnvelope(envelope, retainId))
+ .then((normalized) => {
+ let base: ForumSidebarQueryData | undefined = normalized.base
+ let retained = normalized.retained
+ const channelMetas = { ...normalized.channelMetas }
+ const openerHints = { ...normalized.openerHints }
+ for (const [childId, update] of delta.activity) {
+ base = patchForumSidebarActivity(
+ base,
+ childId,
+ update.parentChannelId,
+ update.activityAt,
+ )
+ if (retained?.id === childId) {
+ retained = {
+ ...retained,
+ activityAt: update.activityAt,
+ expiresAt: new Date(
+ Date.parse(update.activityAt) + SIDEBAR_ACTIVITY_WINDOW_MS,
+ ).toISOString(),
+ }
+ }
+ if (channelMetas[childId]) {
+ channelMetas[childId] = {
+ ...channelMetas[childId],
+ activityAt: update.activityAt,
+ }
+ }
+ }
+ for (const [childId, title] of delta.titles) {
+ base = patchForumSidebarTitle(base, childId, title)
+ if (retained?.id === childId) retained = { ...retained, title }
+ const meta = channelMetas[childId]
+ if (meta && openerHints[meta.parentMessageId]) {
+ openerHints[meta.parentMessageId] = {
+ ...openerHints[meta.parentMessageId],
+ content: title,
+ }
+ }
+ }
+ for (const [childId, unread] of delta.unread) {
+ base = patchForumSidebarUnread(base, childId, unread)
+ if (retained?.id === childId) retained = { ...retained, unread }
+ }
+ for (const childId of delta.removed) {
+ const meta = channelMetas[childId]
+ if (meta) delete openerHints[meta.parentMessageId]
+ delete channelMetas[childId]
+ base = removeForumSidebarThread(base, childId)
+ if (retained?.id === childId) retained = null
+ }
+ return {
+ ...normalized,
+ base: base ?? normalized.base,
+ retained,
+ channelMetas,
+ openerHints,
+ }
+ })
+ .finally(() => {
+ const current = inflight.get(serverId)
+ if (current?.promise !== request) return
+ if (current.abortTimer !== null) globalThis.clearTimeout(current.abortTimer)
+ inflight.delete(serverId)
+ })
+ const record: InflightRecord = {
+ promise: request,
+ delta,
+ candidate: retainId,
+ controller,
+ signals: new Set(),
+ abortTimer: null,
+ }
+ inflight.set(serverId, record)
+ attachInflightSignal(serverId, record, signal)
+ return request
+}
+
+function seedForumSidebarResources(
+ queryClient: QueryClient,
+ serverId: string,
+ normalized: NormalizedForumSidebarEnvelope,
+ verifiedEpoch: number,
+ retainId: string | null,
+) {
+ if (
+ retainId &&
+ !normalized.retained &&
+ !hasForumSidebarThread(normalized.base, retainId)
+ ) {
+ removeForumSidebarUnreadChild(queryClient, serverId, retainId)
+ removeForumSidebarThreadExact(queryClient, serverId, retainId)
+ }
+ for (const meta of Object.values(normalized.channelMetas)) {
+ queryClient.setQueryData(
+ communityKeys.channelMeta(serverId, meta.id),
+ { ...meta, verifiedEpoch },
+ )
+ }
+ for (const hint of Object.values(normalized.openerHints)) {
+ queryClient.setQueryData(communityKeys.forumOpenerHint(serverId, hint.id), hint)
+ }
+}
+
+function throwIfConsumerAborted(signal: AbortSignal) {
+ if (!signal.aborted) return
+ const error = new Error("Aborted")
+ error.name = "AbortError"
+ throw error
+}
+
+export function useForumSidebarThreads(
+ serverId: string,
+ retainId: string | null,
+ enabled = true,
+) {
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
// not change. This is essential for access/archive/participation removal:
@@ -305,43 +895,77 @@ export function useForumSidebarThreads(serverId: string, retainId: string | null
enabled: false,
})
const query = useQuery({
- queryKey: communityKeys.forumSidebarThreadsView(serverId, retainId),
- enabled: !!serverId,
- // `retainId` is part of the key because the server may return an otherwise
- // expired/non-top-five active thread. Keep the prior projection visible
- // while that neighboring view loads so route changes never collapse the
- // sidebar to an empty list for a frame.
- placeholderData: keepPreviousData,
- queryFn: async () => {
- const params = new URLSearchParams({
- type: "thread",
- parentType: "forum",
- participating: "true",
- activeWithin: "72h",
- limitPerParent: "5",
- include: "parentMessage",
- })
- if (retainId) params.set("retainId", retainId)
- const envelope = await apiFetch<SidebarThreadEnvelope>(
- `/api/community/servers/${serverId}/channels?${params.toString()}`,
+ queryKey: communityKeys.forumSidebarThreads(serverId),
+ enabled: !!serverId && enabled,
+ staleTime: Infinity,
+ queryFn: async ({ signal }) => {
+ const requestEpoch = useCommunityWsStore.getState().accessEpoch
+ const normalized = await fetchForumSidebar(serverId, retainId, signal)
+ throwIfConsumerAborted(signal)
+ seedForumSidebarResources(queryClient, serverId, normalized, requestEpoch, retainId)
+ if (retainId) {
+ queryClient.setQueryData(
+ communityKeys.forumSidebarRetained(serverId, retainId),
+ normalized.retained,
+ )
+ }
+ return { ...normalized.base, verifiedEpoch: requestEpoch }
+ },
+ })
+ useEffect(() => {
+ if (previousRetainId.current === retainId) return
+ previousRetainId.current = retainId
+ if (query.fetchStatus !== "fetching") return
+ if (inflight.get(serverId)?.candidate === retainId) return
+ void queryClient.cancelQueries({
+ queryKey: communityKeys.forumSidebarThreads(serverId),
+ exact: true,
+ }).then(() => invalidateForumSidebarBaseExact(queryClient, serverId))
+ }, [query.fetchStatus, queryClient, retainId, serverId])
+ useEffect(() => {
+ if (!retainId) return
+ const canonical = query.data?.threads.find((thread) => thread.id === retainId)
+ if (!canonical) return
+ const key = communityKeys.forumSidebarRetained(serverId, retainId)
+ if (queryClient.getQueryState(key)?.status === "success") return
+ queryClient.setQueryData(key, canonical)
+ }, [query.data, queryClient, retainId, serverId])
+ const retainedKey = communityKeys.forumSidebarRetained(serverId, retainId ?? "__none__")
+ const retainedState = queryClient.getQueryState<ForumSidebarThread | null>(retainedKey)
+ const retainIsCanonical = !!retainId && hasForumSidebarThread(query.data, retainId)
+ const retainedQuery = useQuery<ForumSidebarThread | null>({
+ queryKey: retainedKey,
+ enabled: enabled && !!retainId && query.isSuccess && query.fetchStatus === "idle" &&
+ !retainIsCanonical && retainedState?.status !== "success",
+ staleTime: Infinity,
+ gcTime: 5 * 60 * 1000,
+ queryFn: async ({ signal }) => {
+ const requestEpoch = useCommunityWsStore.getState().accessEpoch
+ const normalized = await fetchForumSidebar(serverId, retainId, signal)
+ throwIfConsumerAborted(signal)
+ seedForumSidebarResources(queryClient, serverId, normalized, requestEpoch, retainId)
+ queryClient.setQueryData(
+ communityKeys.forumSidebarThreads(serverId),
+ { ...normalized.base, verifiedEpoch: requestEpoch },
)
- const serverNowMs = Date.parse(envelope.serverNow)
- return {
- ...envelope,
- threads: projectForumSidebarThreads(envelope),
- serverClockOffsetMs: Number.isFinite(serverNowMs) ? serverNowMs - Date.now() : 0,
- } satisfies ForumSidebarQueryData
+ return normalized.retained
},
})
+ const baseIsVerified = accessConnected && query.data?.verifiedEpoch === accessEpoch
+ const projection = useMemo(() => deriveForumSidebarProjection(
+ baseIsVerified ? query.data : undefined,
+ baseIsVerified ? retainedQuery.data : null,
+ serverDetailQuery.data?.forumUnreadState,
+ ), [baseIsVerified, query.data, retainedQuery.data, serverDetailQuery.data?.forumUnreadState])
useEffect(() => {
if (!query.data) return
reconcileForumSidebarUnreadFallbacks(
queryClient,
serverId,
- query.data.threads.map((thread) => thread.id),
+ projection.threads.map((thread) => thread.id),
)
- }, [query.data, queryClient, serverDetailQuery.data?.forumUnreadState, serverId])
+ }, [projection.threads, query.data, queryClient, serverDetailQuery.data?.forumUnreadState, serverId])
// Expire rows against the server's clock without polling. The currently
// retained route is deliberately excluded: it remains visible until the
@@ -351,19 +975,32 @@ export function useForumSidebarThreads(serverId: string, retainId: string | null
if (!data) return
const serverNowMs = Date.now() + data.serverClockOffsetMs
const nextExpiry = data.threads
- .filter((thread) => thread.id !== retainId)
.map((thread) => Date.parse(thread.expiresAt))
.filter((expiresAt) => Number.isFinite(expiresAt))
.sort((a, b) => a - b)[0]
if (nextExpiry === undefined) return
const timeout = globalThis.setTimeout(() => {
- void queryClient.invalidateQueries({ queryKey: communityKeys.forumSidebarThreads(serverId) })
+ const current = getForumSidebarBase(queryClient, serverId)
+ const currentServerNow = Date.now() + (current?.serverClockOffsetMs ?? 0)
+ for (const thread of current?.threads ?? []) {
+ if (Date.parse(thread.expiresAt) > currentServerNow) continue
+ if (thread.id === retainId) {
+ queryClient.setQueryData<ForumSidebarQueryData | undefined>(
+ communityKeys.forumSidebarThreads(serverId),
+ (value) => removeForumSidebarThread(value, thread.id),
+ )
+ } else {
+ removeForumSidebarThreadExact(queryClient, serverId, thread.id)
+ }
+ }
+ void invalidateForumSidebarBaseExact(queryClient, serverId)
}, Math.max(0, nextExpiry - serverNowMs) + 25)
return () => globalThis.clearTimeout(timeout)
}, [query.data, queryClient, retainId, serverId])
return {
...query,
- threads: query.data?.threads ?? [],
+ threads: projection.threads,
+ parentUnread: projection.parentUnread,
}
}
diff --git a/src/web/src/hooks/community/use-thread-participants.test.ts b/src/web/src/hooks/community/use-thread-participants.test.ts
index b5a4255ca..c9d356d50 100644
--- a/src/web/src/hooks/community/use-thread-participants.test.ts
+++ b/src/web/src/hooks/community/use-thread-participants.test.ts
@@ -52,7 +52,7 @@ beforeEach(() => {
describe("useRemoveThreadParticipant", () => {
it("removes the child from every sidebar view when the viewer leaves", async () => {
- const key = communityKeys.forumSidebarThreadsView("server_1", "post_1")
+ const key = communityKeys.forumSidebarThreads("server_1")
queryClient.setQueryData(key, sidebarData())
const { useRemoveThreadParticipant } = await import("./use-thread-participants")
useRemoveThreadParticipant("post_1", "server_1", "viewer_1")
@@ -68,7 +68,7 @@ describe("useRemoveThreadParticipant", () => {
})
it("keeps the viewer's sidebar row when the creator removes someone else", async () => {
- const key = communityKeys.forumSidebarThreadsView("server_1", null)
+ const key = communityKeys.forumSidebarThreads("server_1")
queryClient.setQueryData(key, sidebarData())
const { useRemoveThreadParticipant } = await import("./use-thread-participants")
useRemoveThreadParticipant("post_1", "server_1", "viewer_1")
@@ -78,4 +78,48 @@ describe("useRemoveThreadParticipant", () => {
expect(queryClient.getQueryData<ReturnType<typeof sidebarData>>(key)?.threads).toHaveLength(1)
})
+
+ it("does not revalidate the viewer's forum access when adding someone else", async () => {
+ const key = communityKeys.forumSidebarThreads("server_1")
+ queryClient.setQueryData(key, sidebarData())
+ const { useAddThreadParticipant } = await import("./use-thread-participants")
+ useAddThreadParticipant("post_1", "server_1", "viewer_1")
+
+ const result = await config.mutationFn("other_1")
+ config.onSuccess?.(result, "other_1")
+
+ expect(queryClient.getQueryState(key)?.isInvalidated).toBe(false)
+ expect(queryClient.getQueryData<ReturnType<typeof sidebarData>>(key)?.threads).toHaveLength(1)
+ })
+
+ it("does not touch forum sidebar resources for an ordinary text thread", async () => {
+ const baseKey = communityKeys.forumSidebarThreads("server_1")
+ const retainedKey = communityKeys.forumSidebarRetained("server_1", "forum_post")
+ const metaKey = communityKeys.channelMeta("server_1", "text_thread")
+ const hintKey = communityKeys.forumOpenerHint("server_1", "opener_1")
+ queryClient.setQueryData(baseKey, sidebarData())
+ queryClient.setQueryData(retainedKey, { id: "forum_post" })
+ queryClient.setQueryData(metaKey, { id: "text_thread", parentChannelId: "text_parent" })
+ queryClient.setQueryData(hintKey, { id: "opener_1", content: "Title" })
+ const before = {
+ base: queryClient.getQueryData(baseKey),
+ retained: queryClient.getQueryData(retainedKey),
+ meta: queryClient.getQueryData(metaKey),
+ hint: queryClient.getQueryData(hintKey),
+ }
+ const { useAddThreadParticipant, useRemoveThreadParticipant } = await import("./use-thread-participants")
+
+ useAddThreadParticipant("text_thread", undefined, "viewer_1")
+ let result = await config.mutationFn("viewer_1")
+ config.onSuccess?.(result, "viewer_1")
+ useRemoveThreadParticipant("text_thread", "server_1", "viewer_1", false)
+ result = await config.mutationFn("viewer_1")
+ config.onSuccess?.(result, "viewer_1")
+
+ expect(queryClient.getQueryData(baseKey)).toBe(before.base)
+ expect(queryClient.getQueryState(baseKey)?.isInvalidated).toBe(false)
+ expect(queryClient.getQueryData(retainedKey)).toBe(before.retained)
+ expect(queryClient.getQueryState(metaKey)).toBeUndefined()
+ expect(queryClient.getQueryData(hintKey)).toBe(before.hint)
+ })
})
diff --git a/src/web/src/hooks/community/use-thread-participants.ts b/src/web/src/hooks/community/use-thread-participants.ts
index 779636696..ad1fa8cc5 100644
--- a/src/web/src/hooks/community/use-thread-participants.ts
+++ b/src/web/src/hooks/community/use-thread-participants.ts
@@ -3,10 +3,11 @@
import { useMutation, useQueryClient } from "@tanstack/react-query"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
+import { useCommunityStore } from "@/stores/community"
import {
- removeForumSidebarThread,
+ grantForumSidebarChild,
+ removeForumSidebarThreadExact,
removeForumSidebarUnreadChild,
- type ForumSidebarQueryData,
} from "@/hooks/community/use-forum-sidebar-threads"
// The participant READ hook was retired: the post/thread member panel now reads
@@ -16,7 +17,11 @@ import {
// channelMembers cache the panel now reads (NOT the old threadParticipants key).
/** Any participant adds a parent-channel member to the thread/post. */
-export function useAddThreadParticipant(channelId: string) {
+export function useAddThreadParticipant(
+ channelId: string,
+ serverId?: string,
+ viewerUserId?: string,
+) {
const qc = useQueryClient()
return useMutation({
mutationFn: (userId: string) =>
@@ -24,14 +29,22 @@ export function useAddThreadParticipant(channelId: string) {
method: "POST",
body: JSON.stringify({ userId }),
}),
- onSuccess: () => {
+ onSuccess: (_data, userId) => {
void qc.invalidateQueries({ queryKey: communityKeys.channelMembers(channelId) })
+ if (serverId && userId === viewerUserId) {
+ void grantForumSidebarChild(qc, serverId, channelId)
+ }
},
})
}
/** Leave a thread/post (remove your own participation, or the creator removes someone). */
-export function useRemoveThreadParticipant(channelId: string, serverId?: string, viewerUserId?: string) {
+export function useRemoveThreadParticipant(
+ channelId: string,
+ serverId?: string,
+ viewerUserId?: string,
+ forumSidebar = !!serverId,
+) {
const qc = useQueryClient()
return useMutation({
mutationFn: (userId: string) =>
@@ -42,11 +55,18 @@ export function useRemoveThreadParticipant(channelId: string, serverId?: string,
onSuccess: (_data, userId) => {
void qc.invalidateQueries({ queryKey: communityKeys.channelMembers(channelId) })
if (serverId && userId === viewerUserId) {
- removeForumSidebarUnreadChild(qc, serverId, channelId)
- qc.setQueriesData<ForumSidebarQueryData>(
- { queryKey: communityKeys.forumSidebarThreads(serverId) },
- (data) => removeForumSidebarThread(data, channelId),
- )
+ if (forumSidebar) {
+ removeForumSidebarUnreadChild(qc, serverId, channelId)
+ removeForumSidebarThreadExact(qc, serverId, channelId)
+ } else {
+ qc.removeQueries({
+ queryKey: communityKeys.channelMeta(serverId, channelId),
+ exact: true,
+ })
+ }
+ if (useCommunityStore.getState().currentChannelId === channelId) {
+ useCommunityStore.getState().setCurrentChannelMeta(null)
+ }
}
},
})
diff --git a/src/web/src/lib/query-keys.test.ts b/src/web/src/lib/query-keys.test.ts
index e4171a7c8..89fe2dbbc 100644
--- a/src/web/src/lib/query-keys.test.ts
+++ b/src/web/src/lib/query-keys.test.ts
@@ -31,9 +31,19 @@ describe("communityKeys", () => {
expect(communityKeys.presence("s1")).toEqual([...server, "presence"])
expect(communityKeys.auditLog("s1")).toEqual([...server, "audit-log"])
expect(communityKeys.invites("s1")).toEqual([...server, "invites"])
- const sidebar = [...server, "forum-sidebar-threads"]
+ const sidebar = [...server, "forum-sidebar-base"]
expect(communityKeys.forumSidebarThreads("s1")).toEqual(sidebar)
- expect(communityKeys.forumSidebarThreadsView("s1", "post_1")).toEqual([...sidebar, "post_1"])
+ expect(communityKeys.forumSidebarRetained("s1", "post_1")).toEqual([
+ ...server, "forum-sidebar-retained", "post_1",
+ ])
+ expect(communityKeys.channelMeta("s1", "post_1")).toEqual([
+ ...server, "channel-meta", "post_1",
+ ])
+ expect(communityKeys.forumOpenerHint("s1", "message_1")).toEqual([
+ ...server, "forum-opener-hint", "message_1",
+ ])
+ expect(communityKeys.forumSidebarRetained("s1", "post_1").slice(0, -2))
+ .toEqual(server)
expect(communityKeys.forumSidebarUnreadFallbacks("s1")).toEqual([
...server, "forum-sidebar-unread-fallbacks",
])
diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.ts
index 52edc1d36..e056b5590 100644
--- a/src/web/src/lib/query-keys.ts
+++ b/src/web/src/lib/query-keys.ts
@@ -21,9 +21,19 @@ export const communityKeys = {
server: (serverId: string) =>
[...communityKeys.servers(), serverId] as const,
forumSidebarThreads: (serverId: string) =>
- [...communityKeys.server(serverId), "forum-sidebar-threads"] as const,
- forumSidebarThreadsView: (serverId: string, retainId: string | null) =>
- [...communityKeys.forumSidebarThreads(serverId), retainId] as const,
+ [...communityKeys.server(serverId), "forum-sidebar-base"] as const,
+ forumSidebarRetainedRoot: (serverId: string) =>
+ [...communityKeys.server(serverId), "forum-sidebar-retained"] as const,
+ forumSidebarRetained: (serverId: string, childId: string) =>
+ [...communityKeys.forumSidebarRetainedRoot(serverId), childId] as const,
+ channelMetaRoot: (serverId: string) =>
+ [...communityKeys.server(serverId), "channel-meta"] as const,
+ channelMeta: (serverId: string, channelId: string) =>
+ [...communityKeys.channelMetaRoot(serverId), channelId] as const,
+ forumOpenerHintRoot: (serverId: string) =>
+ [...communityKeys.server(serverId), "forum-opener-hint"] as const,
+ forumOpenerHint: (serverId: string, messageId: string) =>
+ [...communityKeys.forumOpenerHintRoot(serverId), messageId] as const,
forumSidebarUnreadFallbacks: (serverId: string) =>
[...communityKeys.server(serverId), "forum-sidebar-unread-fallbacks"] as const,
diff --git a/src/web/src/lib/use-user-ws.test.ts b/src/web/src/lib/use-user-ws.test.ts
index b72bd4391..a19155623 100644
--- a/src/web/src/lib/use-user-ws.test.ts
+++ b/src/web/src/lib/use-user-ws.test.ts
@@ -215,6 +215,34 @@ describe("useUserWs", () => {
expect(onMsg).not.toHaveBeenCalled()
})
+ it("opens the access gate only after auth.ok", async () => {
+ setupTokenFetch()
+
+ const onAuthenticated = vi.fn()
+ await mountHook(vi.fn(), { onAuthenticated, requestDaemonStatusOnAuth: false })
+
+ const ws = MockWebSocket.instances[0]
+ ws.simulateOpen()
+ expect(onAuthenticated).not.toHaveBeenCalled()
+
+ ws.simulateMessage({ type: "auth.ok" })
+ expect(onAuthenticated).toHaveBeenCalledTimes(1)
+ })
+
+ it("does not reopen access when a stale socket delivers auth.ok after cleanup", async () => {
+ setupTokenFetch()
+
+ const onAuthenticated = vi.fn()
+ await mountHook(vi.fn(), { onAuthenticated, requestDaemonStatusOnAuth: false })
+ const ws = MockWebSocket.instances[0]
+ ws.simulateOpen()
+ effectCleanup?.()
+
+ ws.simulateMessage({ type: "auth.ok" })
+
+ expect(onAuthenticated).not.toHaveBeenCalled()
+ })
+
it("uses the latest option on the original socket without changing connect identity", async () => {
setupTokenFetch()
diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.ts
index 9d67e565d..6f2ea2e1a 100644
--- a/src/web/src/lib/use-user-ws.ts
+++ b/src/web/src/lib/use-user-ws.ts
@@ -20,6 +20,8 @@ export type WsMessageIncoming = WsMessage & { [key: string]: unknown }
export type UseUserWsOptions = {
onReconnect?: () => void
+ onDisconnect?: () => void
+ onAuthenticated?: () => void
requestDaemonStatusOnAuth?: boolean
}
@@ -31,6 +33,8 @@ export function useUserWs(
const reconnectDelay = useRef(WS_RECONNECT_INIT)
const onMessageRef = useRef(onMessage)
const onReconnectRef = useRef(options?.onReconnect)
+ const onDisconnectRef = useRef(options?.onDisconnect)
+ const onAuthenticatedRef = useRef(options?.onAuthenticated)
const requestDaemonStatusOnAuthRef = useRef(options?.requestDaemonStatusOnAuth ?? true)
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const hasConnectedBeforeRef = useRef(false)
@@ -47,6 +51,11 @@ export function useUserWs(
onReconnectRef.current = options?.onReconnect
}, [options?.onReconnect])
+ useEffect(() => {
+ onDisconnectRef.current = options?.onDisconnect
+ onAuthenticatedRef.current = options?.onAuthenticated
+ }, [options?.onAuthenticated, options?.onDisconnect])
+
useEffect(() => {
requestDaemonStatusOnAuthRef.current = options?.requestDaemonStatusOnAuth ?? true
}, [options?.requestDaemonStatusOnAuth])
@@ -106,6 +115,7 @@ export function useUserWs(
wsRef.current = ws
ws.onopen = () => {
+ if (ws !== wsRef.current || generation !== connectionGenerationRef.current) return
reconnectDelay.current = WS_RECONNECT_INIT
ws.send(JSON.stringify({ type: "auth", token: authToken }))
@@ -128,10 +138,12 @@ export function useUserWs(
}
ws.onmessage = (e) => {
+ if (ws !== wsRef.current || generation !== connectionGenerationRef.current) return
lastMessageAtRef.current = Date.now()
try {
const msg = JSON.parse(e.data)
if (msg.type === "auth.ok") {
+ onAuthenticatedRef.current?.()
if (requestDaemonStatusOnAuthRef.current) {
ws.send(JSON.stringify({ type: "check_daemon_status" }))
}
@@ -145,6 +157,7 @@ export function useUserWs(
ws.onclose = () => {
if (ws !== wsRef.current) return
+ onDisconnectRef.current?.()
if (pingIntervalRef.current) { clearInterval(pingIntervalRef.current); pingIntervalRef.current = null }
if (livenessIntervalRef.current) { clearInterval(livenessIntervalRef.current); livenessIntervalRef.current = null }
scheduleReconnect(generation)
diff --git a/src/web/src/stores/community/ws.test.ts b/src/web/src/stores/community/ws.test.ts
index ca2e33906..261686b91 100644
--- a/src/web/src/stores/community/ws.test.ts
+++ b/src/web/src/stores/community/ws.test.ts
@@ -11,6 +11,20 @@ beforeEach(() => {
})
describe("useCommunityWsStore", () => {
+ it("fails closed until the websocket is authenticated and advances epochs on disconnect", () => {
+ expect(useCommunityWsStore.getState()).toMatchObject({
+ accessConnected: false,
+ accessEpoch: 0,
+ })
+ useCommunityWsStore.getState().markAccessConnected()
+ expect(useCommunityWsStore.getState().accessConnected).toBe(true)
+ useCommunityWsStore.getState().markAccessDisconnected()
+ expect(useCommunityWsStore.getState()).toMatchObject({
+ accessConnected: false,
+ accessEpoch: 1,
+ })
+ })
+
it("starts with empty presence + seen sets", () => {
const s = useCommunityWsStore.getState()
expect(s.onlineUserIds.size).toBe(0)
diff --git a/src/web/src/stores/community/ws.ts b/src/web/src/stores/community/ws.ts
index 09e96e2e9..3ee4c9080 100644
--- a/src/web/src/stores/community/ws.ts
+++ b/src/web/src/stores/community/ws.ts
@@ -49,6 +49,8 @@ export type BotAuditEventEntry = {
type UserStatus = { emoji: string | null; text: string | null }
export type CommunityWsStoreState = {
+ accessEpoch: number
+ accessConnected: boolean
/**
* Everyone online right now — human or bot. The server pushes
* `community:presence.update` identically for both (see
@@ -98,6 +100,8 @@ export type CommunityWsStoreState = {
markSeenMessage: (id: string) => void
setUserStatus: (userId: string, emoji: string | null, text: string | null) => void
resetUserStatuses: () => void
+ markAccessDisconnected: () => void
+ markAccessConnected: () => void
pushBotAuditEvent: (event: BotAuditEventEntry) => void
reset: () => void
}
@@ -105,7 +109,10 @@ export type CommunityWsStoreState = {
const initialState = (): Pick<
CommunityWsStoreState,
"onlineUserIds" | "seenMessageIds" | "userStatuses" | "botAuditEvents"
+ | "accessEpoch" | "accessConnected"
> => ({
+ accessEpoch: 0,
+ accessConnected: false,
onlineUserIds: new Set(),
seenMessageIds: new Set(),
userStatuses: new Map(),
@@ -174,6 +181,13 @@ export const useCommunityWsStore = create<CommunityWsStoreState>((set, get) => (
set({ userStatuses: new Map() })
},
+ markAccessDisconnected: () => set((state) => ({
+ accessEpoch: state.accessEpoch + 1,
+ accessConnected: false,
+ })),
+
+ markAccessConnected: () => set({ accessConnected: true }),
+
pushBotAuditEvent: (event) => {
const current = get().botAuditEvents
const perBot = current.get(event.botId) ?? []
diff --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.ts
new file mode 100644
index 000000000..25dd5d9e9
--- /dev/null
+++ b/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts
@@ -0,0 +1,122 @@
+import { test, expect } from "./_fixtures/community-fixture"
+import { tid } from "./_fixtures/testids"
+import { seedChannel, seedForumThread, seedServer } from "./_fixtures/seed"
+
+function isSidebarRequest(url: string, serverId: string): boolean {
+ const parsed = new URL(url)
+ return parsed.pathname === `/api/community/servers/${serverId}/channels`
+ && parsed.searchParams.get("participating") === "true"
+}
+
+function isExactChannelRequest(url: string, channelId: string): boolean {
+ return new URL(url).pathname === `/api/community/channels/${channelId}`
+}
+
+function isExactMessageRequest(url: string): boolean {
+ return /^\/api\/community\/messages\/[^/]+$/.test(new URL(url).pathname)
+}
+
+function isChannelMessagesRequest(url: string, channelId: string): boolean {
+ return new URL(url).pathname === `/api/community/channels/${channelId}/messages`
+}
+
+test.describe.serial("forum sidebar Stage B request shape", () => {
+ let serverId: string
+ let forumId: string
+ let threadId: string
+ let textAId: string
+ let textBId: string
+ let forumTitle: string
+
+ test.beforeAll(async () => {
+ serverId = await seedServer("alice", `Sidebar ${Date.now()}`)
+ forumId = await seedChannel("alice", serverId, "forum", "forum")
+ textAId = await seedChannel("alice", serverId, "text-a")
+ textBId = await seedChannel("alice", serverId, "text-b")
+ forumTitle = `Retained ${Date.now()}`
+ threadId = await seedForumThread("alice", forumId, forumTitle, "post body")
+ })
+
+ test("a cold direct child and hard refresh use one combined GET with no exact meta/opener GETs", async ({ asUser }) => {
+ const { page } = await asUser("alice")
+ const requests: string[] = []
+ const successfulResponses: string[] = []
+ page.on("request", (request) => {
+ if (request.method() === "GET") requests.push(request.url())
+ })
+ page.on("response", (response) => {
+ if (response.request().method() === "GET" && response.ok()) {
+ successfulResponses.push(response.url())
+ }
+ })
+
+ const initialCombined = page.waitForResponse((response) =>
+ response.ok() && isSidebarRequest(response.url(), serverId),
+ )
+ await page.goto(`/c/channels/${serverId}/${threadId}`)
+ await initialCombined
+ 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 })
+ await expect(page.locator('[data-slot="skeleton"]')).toHaveCount(0)
+
+ expect(requests.filter((url) => isSidebarRequest(url, serverId))).toHaveLength(1)
+ expect(new URL(requests.find((url) => isSidebarRequest(url, serverId))!).searchParams.get("retainId"))
+ .toBe(threadId)
+ expect(requests.filter((url) => isExactChannelRequest(url, threadId))).toHaveLength(0)
+ expect(requests.filter(isExactMessageRequest)).toHaveLength(0)
+ const coldMessageRequests = requests.filter((url) => isChannelMessagesRequest(url, threadId))
+ 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()
+ }
+
+ requests.length = 0
+ successfulResponses.length = 0
+ const refreshCombined = page.waitForResponse((response) =>
+ response.ok() && isSidebarRequest(response.url(), serverId),
+ )
+ await page.reload({ waitUntil: "commit" })
+ await refreshCombined
+ await expect(page.getByRole("heading", { name: forumTitle })).toBeVisible({ timeout: 20_000 })
+ await expect(page.getByText("post body", { exact: true })).toBeVisible({ timeout: 20_000 })
+ await expect(page.locator('[data-slot="skeleton"]')).toHaveCount(0)
+ await page.waitForTimeout(2_000)
+
+ expect(requests.filter((url) => isSidebarRequest(url, serverId))).toHaveLength(1)
+ expect(new URL(requests.find((url) => isSidebarRequest(url, serverId))!).searchParams.get("retainId"))
+ .toBe(threadId)
+ 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()
+ }
+ })
+
+ test("switching between top-level channels reuses the warm canonical base", async ({ asUser }) => {
+ const { page } = await asUser("alice")
+ const requests: string[] = []
+ page.on("request", (request) => {
+ if (request.method() === "GET") requests.push(request.url())
+ })
+
+ const initialCombined = page.waitForResponse((response) =>
+ response.ok() && isSidebarRequest(response.url(), serverId),
+ )
+ await page.goto(`/c/channels/${serverId}/${textAId}`)
+ await initialCombined
+ await expect(page.getByTestId(tid.channelRow(textBId))).toBeVisible({ timeout: 20_000 })
+
+ requests.length = 0
+ await page.getByTestId(tid.channelRow(textBId)).click()
+ await page.waitForURL(new RegExp(`${textBId}(?:\\?|$)`), { timeout: 20_000, waitUntil: "commit" })
+ await expect(page.getByTestId(tid.channelRow(textBId))).toBeVisible()
+ await page.waitForTimeout(300)
+
+ expect(requests.filter((url) => isSidebarRequest(url, serverId))).toHaveLength(0)
+ })
+})