Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): decouple thread routes from forum sidebar (#563)

Gener0fecd62dbd39
diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsx
index 79aeffbe8..e3973931b 100644
--- a/src/web/src/app/c/channels/layout.tsx
+++ b/src/web/src/app/c/channels/layout.tsx
@@ -121,10 +121,17 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
return isForum(parent?.type) ? currentChannelId : null
}, [currentChannelId, currentChannelMeta?.parentChannelId, currentServer])
const sidebarRouteCandidate = useMemo(() => {
- const topLevelIds = currentServer?.categories
- ?.flatMap((category) => category.channels.map((channel) => channel.id)) ?? null
- return resolveForumSidebarRouteCandidate(routeChannelId, topLevelIds)
- }, [routeChannelId, currentServer])
+ const topLevelChannels = currentServer?.categories
+ ?.flatMap((category) => category.channels) ?? null
+ const parent = currentChannelId === routeChannelId && currentChannelMeta?.parentChannelId
+ ? topLevelChannels?.find((channel) => channel.id === currentChannelMeta.parentChannelId)
+ : null
+ return resolveForumSidebarRouteCandidate(
+ routeChannelId,
+ topLevelChannels?.map((channel) => channel.id) ?? null,
+ isForum(parent?.type),
+ )
+ }, [currentChannelId, currentChannelMeta?.parentChannelId, currentServer, routeChannelId])
const forumSidebar = useForumSidebarThreads(
serverId,
sidebarRouteCandidate,
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
index 05c0a47b6..902226da3 100644
--- a/src/web/src/hooks/community/use-child-channel-meta.test.ts
+++ b/src/web/src/hooks/community/use-child-channel-meta.test.ts
@@ -1,6 +1,17 @@
-import { describe, expect, it } from "vitest"
+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 type { ChildChannelMeta } from "./use-forum-sidebar-threads"
-import { pickRenderableChildMeta } from "./use-child-channel-meta"
+import { communityKeys } from "@/lib/query-keys"
+import { useCommunityWsStore } from "@/stores/community/ws"
+
+const apiFetchMock = vi.hoisted(() => vi.fn())
+vi.mock("@/lib/api/client", () => ({
+ apiFetch: (...args: unknown[]) => apiFetchMock(...args),
+}))
+
+import { pickRenderableChildMeta, useChildChannelMeta } from "./use-child-channel-meta"
const meta = (overrides: Partial<ChildChannelMeta> = {}): ChildChannelMeta => ({
id: "post-1",
@@ -16,6 +27,37 @@ const meta = (overrides: Partial<ChildChannelMeta> = {}): ChildChannelMeta => ({
...overrides,
})
+async function waitFor(predicate: () => boolean) {
+ for (let i = 0; i < 40 && !predicate(); i++) {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 5))
+ })
+ }
+}
+
+function Capture() {
+ useChildChannelMeta("server-1", "post-1", true)
+ return null
+}
+
+beforeEach(() => {
+ apiFetchMock.mockReset()
+ apiFetchMock.mockResolvedValue({
+ id: "post-1",
+ serverId: "server-1",
+ name: "post",
+ type: "thread",
+ parentChannelId: "forum-1",
+ parentMessageId: "opener-1",
+ creatorId: "user-1",
+ archived: false,
+ lastMessageAt: "2026-08-09T00:00:00.000Z",
+ createdAt: "2026-08-08T00:00:00.000Z",
+ })
+ useCommunityWsStore.getState().reset()
+ useCommunityWsStore.getState().markAccessConnected()
+})
+
describe("child channel metadata stale rendering", () => {
it("keeps a previously authorized snapshot renderable across a WS epoch", () => {
const trusted = meta({ verifiedEpoch: 2 })
@@ -34,4 +76,26 @@ describe("child channel metadata stale rendering", () => {
3,
)).toBeUndefined()
})
+
+ it("starts exact metadata loading without waiting for the forum sidebar", async () => {
+ 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),
+ ),
+ )
+ })
+ await waitFor(() => apiFetchMock.mock.calls.length === 1)
+
+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/post-1")
+ expect(queryClient.getQueryData(
+ communityKeys.channelMeta("server-1", "post-1"),
+ )).toMatchObject({ id: "post-1", parentChannelId: "forum-1" })
+ renderer!.unmount()
+ })
})
diff --git a/src/web/src/hooks/community/use-child-channel-meta.ts b/src/web/src/hooks/community/use-child-channel-meta.ts
index 406e0cf42..02c85de7d 100644
--- a/src/web/src/hooks/community/use-child-channel-meta.ts
+++ b/src/web/src/hooks/community/use-child-channel-meta.ts
@@ -4,10 +4,7 @@ import { useQuery } from "@tanstack/react-query"
import { useEffect, useState } from "react"
import { apiFetch } from "@/lib/api/client"
import { communityKeys } from "@/lib/query-keys"
-import type {
- ChildChannelMeta,
- ForumSidebarQueryData,
-} from "@/hooks/community/use-forum-sidebar-threads"
+import type { ChildChannelMeta } from "@/hooks/community/use-forum-sidebar-threads"
import { useCommunityWsStore } from "@/stores/community/ws"
type ChannelMetaPayload = {
@@ -57,11 +54,6 @@ export function useChildChannelMeta(
enabled: boolean,
) {
const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)
- 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 () => {
@@ -71,9 +63,7 @@ export function useChildChannelMeta(
requestEpoch,
)
},
- enabled: enabled && (
- (sidebar.isSuccess && sidebar.fetchStatus === "idle") || sidebar.isError
- ),
+ enabled,
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 fd37d33c1..34f41bcdf 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
@@ -372,12 +372,12 @@ describe("useForumSidebarThreads", () => {
await act(async () => { await vi.advanceTimersByTimeAsync(1) })
expect(queryClient.getQueryData<ForumSidebarQueryData>(key)?.threads).toEqual([])
expect(JSON.stringify(queryClient.getQueryData(key))).not.toContain("thread-1")
- expect(queryClient.getQueryState(
+ expect(queryClient.getQueryData(
communityKeys.channelMeta("server-1", "thread-1"),
- )).toBeUndefined()
- expect(queryClient.getQueryState(
+ )).toMatchObject({ id: "thread-1", parentChannelId: "forum-1" })
+ expect(queryClient.getQueryData(
communityKeys.forumOpenerHint("server-1", "opener-thread-1"),
- )).toBeUndefined()
+ )).toEqual({ id: "opener-thread-1", content: "title-thread-1" })
expect(renders.at(-1)).toEqual([])
renderer!.unmount()
})
@@ -537,10 +537,12 @@ describe("useForumSidebarThreads", () => {
})
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("retains only child routes whose exact metadata confirms a forum parent", () => {
+ expect(resolveForumSidebarRouteCandidate("general", ["general", "forum"], true)).toBeNull()
+ expect(resolveForumSidebarRouteCandidate("post-1", ["general", "forum"], true)).toBe("post-1")
+ expect(resolveForumSidebarRouteCandidate("thread-1", ["general", "forum"], false)).toBeNull()
+ expect(resolveForumSidebarRouteCandidate("post-1", ["general", "forum"], null)).toBeNull()
+ expect(resolveForumSidebarRouteCandidate("post-1", null, true)).toBeNull()
})
it("requires positive forum ownership evidence", () => {
@@ -1083,7 +1085,7 @@ describe("forum sidebar Stage B resources", () => {
)).toEqual({ id: "post-2" })
})
- it("clears stale metadata and opener content when the retained candidate is unauthorized", async () => {
+ it("clears a negative retained projection without deleting exact route metadata", async () => {
apiFetchMock.mockResolvedValue({
...envelope([]),
canonicalChannels: [],
@@ -1143,12 +1145,12 @@ describe("forum sidebar Stage B resources", () => {
expect(queryClient.getQueryData(
communityKeys.forumSidebarRetained("server-1", "private-post"),
)).toBeNull()
- expect(queryClient.getQueryState(
+ expect(queryClient.getQueryData(
communityKeys.channelMeta("server-1", "private-post"),
- )).toBeUndefined()
- expect(queryClient.getQueryState(
+ )).toMatchObject({ id: "private-post", parentChannelId: "forum-1" })
+ expect(queryClient.getQueryData(
communityKeys.forumOpenerHint("server-1", "private-opener"),
- )).toBeUndefined()
+ )).toEqual({ id: "private-opener", content: "Private title" })
expect(queryClient.getQueryData<ServerDetail>(
communityKeys.server("server-1"),
)?.forumUnreadState?.["forum-1"]).toEqual({ baseUnread: true, childIds: [] })
@@ -1159,6 +1161,68 @@ describe("forum sidebar Stage B resources", () => {
renderer!.unmount()
})
+ it("settles an active negative retained query without restarting it", async () => {
+ apiFetchMock.mockResolvedValue({
+ ...envelope([]),
+ canonicalChannels: [],
+ retainedChannel: null,
+ })
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const accessEpoch = useCommunityWsStore.getState().accessEpoch
+ const base = normalizeForumSidebarEnvelope(envelope([]), null).base
+ queryClient.setQueryData(
+ communityKeys.forumSidebarThreads("server-1"),
+ { ...base, verifiedEpoch: accessEpoch },
+ )
+ 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: accessEpoch,
+ },
+ )
+ 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.forumSidebarRetained("server-1", "private-post"),
+ )?.status === "success")
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 50))
+ })
+
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+ expect(queryClient.getQueryData(
+ communityKeys.forumSidebarRetained("server-1", "private-post"),
+ )).toBeNull()
+ expect(queryClient.getQueryData(
+ communityKeys.channelMeta("server-1", "private-post"),
+ )).toMatchObject({ id: "private-post", parentChannelId: "forum-1" })
+ expect(queryClient.getQueryData(
+ communityKeys.forumOpenerHint("server-1", "private-opener"),
+ )).toEqual({ id: "private-opener", content: "Private title" })
+ 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
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 ae17ef568..cd4068d4f 100644
--- a/src/web/src/hooks/community/use-forum-sidebar-threads.ts
+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.ts
@@ -79,8 +79,9 @@ export type NormalizedForumSidebarEnvelope = {
export function resolveForumSidebarRouteCandidate(
channelId: string | null,
topLevelChannelIds: Iterable<string> | null,
+ parentIsForum: boolean | null | undefined,
) {
- if (!channelId || !topLevelChannelIds) return null
+ if (!channelId || !topLevelChannelIds || !parentIsForum) return null
return new Set(topLevelChannelIds).has(channelId) ? null : channelId
}
@@ -645,17 +646,7 @@ export function removeForumSidebarThreadExact(
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,
- })
+ removeForumSidebarProjectionExact(queryClient, serverId, childId)
queryClient.removeQueries({
queryKey: communityKeys.channelMeta(serverId, childId),
exact: true,
@@ -668,6 +659,32 @@ export function removeForumSidebarThreadExact(
}
}
+export function removeForumSidebarProjectionExact(
+ queryClient: QueryClient,
+ serverId: string,
+ childId: string,
+) {
+ removeForumSidebarBaseProjectionExact(queryClient, serverId, childId)
+ queryClient.removeQueries({
+ queryKey: communityKeys.forumSidebarRetained(serverId, childId),
+ exact: true,
+ })
+}
+
+function removeForumSidebarBaseProjectionExact(
+ queryClient: QueryClient,
+ serverId: string,
+ childId: string,
+) {
+ recordInflightDelta(serverId, (delta) => {
+ delta.removed.add(childId)
+ })
+ queryClient.setQueryData<ForumSidebarQueryData | undefined>(
+ communityKeys.forumSidebarThreads(serverId),
+ (data) => removeForumSidebarThread(data, childId),
+ )
+}
+
/** Undo only the in-flight removal tombstone after an optimistic HTTP failure. */
export function restoreForumSidebarThreadInflight(
serverId: string,
@@ -894,7 +911,9 @@ function seedForumSidebarResources(
hasForumSidebarOwnershipEvidence(queryClient, serverId, retainId)
) {
removeForumSidebarUnreadChild(queryClient, serverId, retainId)
- removeForumSidebarThreadExact(queryClient, serverId, retainId)
+ // The retained query owns its negative result. Removing that active query
+ // here makes `retained=null` immediately eligible to refetch in a loop.
+ removeForumSidebarBaseProjectionExact(queryClient, serverId, retainId)
}
for (const meta of Object.values(normalized.channelMetas)) {
queryClient.setQueryData(
@@ -1037,7 +1056,7 @@ export function useForumSidebarThreads(
(value) => removeForumSidebarThread(value, thread.id),
)
} else {
- removeForumSidebarThreadExact(queryClient, serverId, thread.id)
+ removeForumSidebarProjectionExact(queryClient, serverId, thread.id)
}
}
void invalidateForumSidebarBaseExact(queryClient, serverId)
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 c9d356d50..4b3d21847 100644
--- a/src/web/src/hooks/community/use-thread-participants.test.ts
+++ b/src/web/src/hooks/community/use-thread-participants.test.ts
@@ -53,7 +53,9 @@ beforeEach(() => {
describe("useRemoveThreadParticipant", () => {
it("removes the child from every sidebar view when the viewer leaves", async () => {
const key = communityKeys.forumSidebarThreads("server_1")
+ const metaKey = communityKeys.channelMeta("server_1", "post_1")
queryClient.setQueryData(key, sidebarData())
+ queryClient.setQueryData(metaKey, { id: "post_1", parentChannelId: "forum_1" })
const { useRemoveThreadParticipant } = await import("./use-thread-participants")
useRemoveThreadParticipant("post_1", "server_1", "viewer_1")
@@ -65,6 +67,7 @@ describe("useRemoveThreadParticipant", () => {
{ method: "DELETE" },
)
expect(queryClient.getQueryData<ReturnType<typeof sidebarData>>(key)?.threads).toEqual([])
+ expect(queryClient.getQueryData(metaKey)).toEqual({ id: "post_1", parentChannelId: "forum_1" })
})
it("keeps the viewer's sidebar row when the creator removes someone else", async () => {
@@ -119,7 +122,7 @@ describe("useRemoveThreadParticipant", () => {
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(metaKey)).toBe(before.meta)
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 ad1fa8cc5..f2ec592e1 100644
--- a/src/web/src/hooks/community/use-thread-participants.ts
+++ b/src/web/src/hooks/community/use-thread-participants.ts
@@ -3,10 +3,9 @@
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 {
grantForumSidebarChild,
- removeForumSidebarThreadExact,
+ removeForumSidebarProjectionExact,
removeForumSidebarUnreadChild,
} from "@/hooks/community/use-forum-sidebar-threads"
@@ -57,15 +56,7 @@ export function useRemoveThreadParticipant(
if (serverId && userId === viewerUserId) {
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)
+ removeForumSidebarProjectionExact(qc, serverId, channelId)
}
}
},
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
index 2d2298fce..9e49a6e9f 100644
--- a/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts
+++ b/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts
@@ -1,6 +1,16 @@
-import { test, expect } from "./_fixtures/community-fixture"
+import type { Page } from "@playwright/test"
+import { test, expect, userId } from "./_fixtures/community-fixture"
+import { sendMessage } from "./_fixtures/actions"
import { tid } from "./_fixtures/testids"
-import { seedChannel, seedForumThread, seedServer } from "./_fixtures/seed"
+import {
+ seedCategory,
+ seedChannel,
+ seedForumThread,
+ seedJoinServer,
+ seedMessage,
+ seedServer,
+ seedThread,
+} from "./_fixtures/seed"
function isSidebarRequest(url: string, serverId: string): boolean {
const parsed = new URL(url)
@@ -12,14 +22,51 @@ 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`
}
+async function installRouteStabilityProbe(page: Page): Promise<void> {
+ await page.addInitScript((composerShellTestId) => {
+ const target = window as typeof window & {
+ __routeStability?: { mounts: number; losses: number; present: boolean }
+ }
+ target.__routeStability = { mounts: 0, losses: 0, present: false }
+ const sample = () => {
+ const state = target.__routeStability!
+ const present = !!document.querySelector(`[data-testid="${composerShellTestId}"]`)
+ if (present && !state.present) state.mounts += 1
+ if (!present && state.present) state.losses += 1
+ state.present = present
+ }
+ const observe = () => {
+ if (!document.documentElement) {
+ globalThis.setTimeout(observe, 0)
+ return
+ }
+ new MutationObserver(sample).observe(document.documentElement, {
+ childList: true,
+ subtree: true,
+ })
+ sample()
+ }
+ observe()
+ }, tid.channelComposerShell)
+}
+
+async function routeStability(page: Page) {
+ return page.evaluate(() => (window as typeof window & {
+ __routeStability: { mounts: number; losses: number; present: boolean }
+ }).__routeStability)
+}
+
+async function participantUserIds(page: Page, channelId: string): Promise<string[]> {
+ const response = await page.request.get(`/api/community/channels/${channelId}/members`)
+ expect(response.status()).toBe(200)
+ const payload = await response.json() as { members: Array<{ userId: string }> }
+ return payload.members.map((member) => member.userId)
+}
+
test.describe.serial("forum sidebar Stage B request shape", () => {
let serverId: string
let forumId: string
@@ -27,17 +74,23 @@ test.describe.serial("forum sidebar Stage B request shape", () => {
let textAId: string
let textBId: string
let forumTitle: string
+ let ordinaryThreadId: 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")
+ const categoryId = await seedCategory("alice", serverId, "Grouped")
+ forumId = await seedChannel("alice", serverId, "forum", "forum", categoryId)
+ textAId = await seedChannel("alice", serverId, "text-a", undefined, categoryId)
+ textBId = await seedChannel("alice", serverId, "text-b", undefined, categoryId)
+ await seedJoinServer("alice", "bob", serverId)
+ await seedJoinServer("alice", "carol", serverId)
forumTitle = `Retained ${Date.now()}`
threadId = await seedForumThread("alice", forumId, forumTitle, "post body")
+ const parentMessageId = await seedMessage("alice", textAId, "ordinary thread opener")
+ ordinaryThreadId = await seedThread("alice", parentMessageId, "ordinary thread")
})
- test("a cold direct child and hard refresh use one combined GET with no exact meta/opener GETs", async ({ asUser }) => {
+ test("a cold direct child and hard refresh keep exact route metadata bounded", async ({ asUser }) => {
const { page } = await asUser("alice")
const requests: string[] = []
const successfulResponses: string[] = []
@@ -97,11 +150,14 @@ test.describe.serial("forum sidebar Stage B request shape", () => {
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 coldSidebarRequests = requests.filter((url) => isSidebarRequest(url, serverId))
+ expect(coldSidebarRequests.length).toBeGreaterThanOrEqual(1)
+ expect(coldSidebarRequests.length).toBeLessThanOrEqual(2)
+ expect(coldSidebarRequests.every((url) => {
+ const retainId = new URL(url).searchParams.get("retainId")
+ return retainId === null || retainId === threadId
+ })).toBe(true)
+ expect(successfulResponses.filter((url) => isExactChannelRequest(url, threadId))).toHaveLength(1)
const coldMessageRequests = requests.filter((url) => isChannelMessagesRequest(url, threadId))
const coldSuccessfulMessageResponses = successfulResponses.filter((url) =>
isChannelMessagesRequest(url, threadId),
@@ -130,11 +186,10 @@ test.describe.serial("forum sidebar Stage B request shape", () => {
await expect(page.locator('[data-slot="skeleton"]')).toHaveCount(0)
await page.waitForTimeout(2_000) // late exact-channel/message fetch exclusion window
- 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 refreshSidebarRequests = requests.filter((url) => isSidebarRequest(url, serverId))
+ expect(refreshSidebarRequests.length).toBeGreaterThanOrEqual(1)
+ expect(refreshSidebarRequests.length).toBeLessThanOrEqual(2)
+ expect(successfulResponses.filter((url) => isExactChannelRequest(url, threadId))).toHaveLength(1)
const refreshMessageRequests = requests.filter((url) => isChannelMessagesRequest(url, threadId))
expect(refreshMessageRequests.length).toBeGreaterThanOrEqual(1)
const refreshSuccessfulMessageResponses = successfulResponses.filter((url) =>
@@ -179,6 +234,122 @@ test.describe.serial("forum sidebar Stage B request shape", () => {
.toBeLessThanOrEqual(1)
})
+ test("a non-participant keeps a grouped forum route after retained null arrives", async ({ asUser }) => {
+ const { page } = await asUser("bob")
+ await installRouteStabilityProbe(page)
+ const successfulResponses: string[] = []
+ const sidebarResponses: Array<{ url: string; retainedChannel: unknown }> = []
+ await page.route(`**/api/community/servers/${serverId}/channels?**`, async (route) => {
+ if (!isSidebarRequest(route.request().url(), serverId)) {
+ await route.continue()
+ return
+ }
+ await new Promise((resolve) => setTimeout(resolve, 750))
+ await route.continue()
+ })
+ page.on("response", async (response) => {
+ if (response.request().method() !== "GET" || !response.ok()) return
+ successfulResponses.push(response.url())
+ if (!isSidebarRequest(response.url(), serverId)) return
+ const payload = await response.json() as { retainedChannel: unknown }
+ sidebarResponses.push({ url: response.url(), retainedChannel: payload.retainedChannel })
+ })
+
+ expect(await participantUserIds(page, threadId)).not.toContain(userId("bob"))
+ await page.goto(`/c/channels/${serverId}/${threadId}`)
+ await expect(page.getByTestId(tid.channelComposerShell)).toBeVisible({ timeout: 20_000 })
+ await expect(page.getByText("post body", { exact: true })).toBeVisible({ timeout: 20_000 })
+ await expect.poll(() => sidebarResponses.some(({ url }) =>
+ new URL(url).searchParams.get("retainId") === threadId,
+ )).toBe(true)
+ await page.waitForTimeout(2_000)
+
+ const retainedResponses = sidebarResponses.filter(({ url }) =>
+ new URL(url).searchParams.get("retainId") === threadId
+ )
+ expect(retainedResponses).toHaveLength(1)
+ expect(retainedResponses[0]?.retainedChannel).toBeNull()
+ expect(successfulResponses.filter((url) => isExactChannelRequest(url, threadId))).toHaveLength(1)
+ expect(await routeStability(page)).toEqual({ mounts: 1, losses: 0, present: true })
+ expect(await participantUserIds(page, threadId)).not.toContain(userId("bob"))
+
+ const reply = `bob joins ${Date.now()}`
+ await sendMessage(page, reply)
+ await expect(page.getByText(reply, { exact: true })).toBeVisible({ timeout: 20_000 })
+ await expect.poll(async () => participantUserIds(page, threadId)).toContain(userId("bob"))
+ })
+
+ test("a non-participant warm forum-card click settles one negative retained request", async ({ asUser }) => {
+ const { page } = await asUser("carol")
+ await installRouteStabilityProbe(page)
+ const successfulResponses: string[] = []
+ const sidebarResponses: Array<{ url: string; retainedChannel: unknown }> = []
+ page.on("response", async (response) => {
+ if (response.request().method() !== "GET" || !response.ok()) return
+ successfulResponses.push(response.url())
+ if (!isSidebarRequest(response.url(), serverId)) return
+ const payload = await response.json() as { retainedChannel: unknown }
+ sidebarResponses.push({ url: response.url(), retainedChannel: payload.retainedChannel })
+ })
+
+ await page.goto(`/c/channels/${serverId}/${forumId}`)
+ const card = page.getByTestId(tid.forumThreadCard(threadId))
+ await expect(card).toBeVisible({ timeout: 20_000 })
+ await page.waitForTimeout(300)
+ sidebarResponses.length = 0
+ successfulResponses.length = 0
+
+ await card.click()
+ await expect.poll(() => new URL(page.url()).pathname).toBe(
+ `/c/channels/${serverId}/${threadId}`,
+ )
+ await expect(page.getByTestId(tid.channelComposerShell)).toBeVisible({ timeout: 20_000 })
+ await expect(page.getByText("post body", { exact: true })).toBeVisible({ timeout: 20_000 })
+ await expect.poll(() => sidebarResponses.filter(({ url }) =>
+ new URL(url).searchParams.get("retainId") === threadId,
+ ).length).toBe(1)
+ await page.waitForTimeout(2_000)
+
+ const retainedResponses = sidebarResponses.filter(({ url }) =>
+ new URL(url).searchParams.get("retainId") === threadId
+ )
+ expect(retainedResponses).toHaveLength(1)
+ expect(retainedResponses[0]?.retainedChannel).toBeNull()
+ expect(successfulResponses.filter((url) => isExactChannelRequest(url, threadId))).toHaveLength(1)
+ expect(await routeStability(page)).toEqual({ mounts: 1, losses: 0, present: true })
+ expect(await participantUserIds(page, threadId)).not.toContain(userId("carol"))
+ })
+
+ test("a grouped ordinary thread never asks the forum sidebar to retain it", async ({ asUser }) => {
+ const { page } = await asUser("bob")
+ await installRouteStabilityProbe(page)
+ const successfulResponses: string[] = []
+ const requests: 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())
+ }
+ })
+
+ expect(await participantUserIds(page, ordinaryThreadId)).not.toContain(userId("bob"))
+ await page.goto(`/c/channels/${serverId}/${ordinaryThreadId}`)
+ await expect(page.getByTestId(tid.channelComposerShell)).toBeVisible({ timeout: 20_000 })
+ await expect(page.getByText("ordinary thread opener", { exact: true })).toBeVisible({ timeout: 20_000 })
+ await page.waitForTimeout(2_000)
+
+ expect(successfulResponses.filter((url) => isExactChannelRequest(url, ordinaryThreadId)))
+ .toHaveLength(1)
+ expect(requests.filter((url) =>
+ isSidebarRequest(url, serverId)
+ && new URL(url).searchParams.get("retainId") === ordinaryThreadId
+ )).toHaveLength(0)
+ expect(await routeStability(page)).toEqual({ mounts: 1, losses: 0, present: true })
+ expect(await participantUserIds(page, ordinaryThreadId)).not.toContain(userId("bob"))
+ })
+
test("sidebar top-level and child navigation reuse the warm flat base", async ({ asUser }) => {
const { page } = await asUser("alice")
const requests: string[] = []