Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): preserve channel route across canonicalization (#513)

Gustavo Ye28091f00177e
diff --git a/src/web/src/app/c/channels/[serverId]/[channelId]/[childChannelId]/page.tsx b/src/web/src/app/c/channels/[serverId]/[channelId]/[childChannelId]/page.tsx
index 33e148271..f2039bdf4 100644
--- a/src/web/src/app/c/channels/[serverId]/[channelId]/[childChannelId]/page.tsx
+++ b/src/web/src/app/c/channels/[serverId]/[channelId]/[childChannelId]/page.tsx
@@ -1,21 +1,3 @@
-"use client"
-
-import { useParams } from "next/navigation"
-import { ChannelRoute } from "@/components/community/channels/channel-route"
-
export default function ChildChannelPage() {
- const params = useParams<{
- serverId: string
- channelId: string
- childChannelId: string
- }>()
- const key = `${params.serverId}/${params.channelId}/${params.childChannelId}`
- return (
- <ChannelRoute
- key={key}
- serverParam={params.serverId}
- parentChannelId={params.channelId}
- channelId={params.childChannelId}
- />
- )
+ return null
}
diff --git a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
index 3fb3aafb2..a43f3f40c 100644
--- a/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
+++ b/src/web/src/app/c/channels/[serverId]/[channelId]/page.tsx
@@ -1,10 +1,3 @@
-"use client"
-
-import { useParams } from "next/navigation"
-import { ChannelRoute } from "@/components/community/channels/channel-route"
-
export default function ChannelPage() {
- const params = useParams<{ serverId: string; channelId: string }>()
- const key = `${params.serverId}/${params.channelId}`
- return <ChannelRoute key={key} serverParam={params.serverId} channelId={params.channelId} />
+ return null
}
diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsx
index 601894532..96b3d6812 100644
--- a/src/web/src/app/c/channels/layout.tsx
+++ b/src/web/src/app/c/channels/layout.tsx
@@ -18,6 +18,7 @@ import {
} from "@/lib/community/community-route"
import { useBreakpoint } from "@/hooks/use-mobile"
import { ChannelSidebar } from "@/components/community/channels/channel-sidebar"
+import { ChannelRoute } from "@/components/community/channels/channel-route"
import { ServerSettings } from "@/components/community/settings/server-settings"
import { ImageCropDialog } from "@/components/community/image-crop-dialog"
import { validateIconSourceFile } from "@/lib/community/image-crop"
@@ -79,6 +80,9 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
: params.channelId
? decodeURIComponent(params.channelId)
: null
+ const routeParentChannelId = params.childChannelId && params.channelId
+ ? decodeURIComponent(params.channelId)
+ : undefined
const hasChannel = !!routeChannelId
const breakpoint = useBreakpoint()
@@ -576,6 +580,17 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
/>
)
+ const content = routeChannelId
+ ? (
+ <ChannelRoute
+ key={`${serverId}/${routeChannelId}`}
+ serverParam={params.serverId}
+ parentChannelId={routeParentChannelId}
+ channelId={routeChannelId}
+ />
+ )
+ : children
+
return (
<ShellFrame
view="server"
@@ -585,7 +600,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
onOpenActiveServerSettings={onSidebarOpenSettings}
onOpenActiveServerInvite={onRailOpenActiveInvite}
>
- {children}
+ {content}
</ShellFrame>
)
}
diff --git a/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.ts b/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.ts
index a30a4f366..19cb38fd5 100644
--- a/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.ts
+++ b/src/web/src/components/community/channels/adaptive-navigation-cutover.contract.test.ts
@@ -20,6 +20,24 @@ describe("adaptive navigation cutover contracts", () => {
expect(sidebar).toContain("prefetchChannel?.(thread.id, parentId)")
})
+ it("keeps one channel subtree mounted across flat-to-nested canonicalization", () => {
+ const layout = readSource("../../../app/c/channels/layout.tsx")
+ const flatPage = readSource("../../../app/c/channels/[serverId]/[channelId]/page.tsx")
+ const nestedPage = readSource(
+ "../../../app/c/channels/[serverId]/[channelId]/[childChannelId]/page.tsx",
+ )
+
+ expect(layout).toContain(
+ 'import { ChannelRoute } from "@/components/community/channels/channel-route"',
+ )
+ expect(layout).toContain("key={`${serverId}/${routeChannelId}`}")
+ expect(layout).toContain("parentChannelId={routeParentChannelId}")
+ for (const routePage of [flatPage, nestedPage]) {
+ expect(routePage).toContain("return null")
+ expect(routePage).not.toContain("<ChannelRoute")
+ }
+ })
+
it("autofocuses message composers only after desktop is known", () => {
const dmPage = readSource("../../../app/c/me/[dmId]/page.tsx")
const textSurface = readSource("./text-channel-surface.tsx")
diff --git a/src/web/src/hooks/community/use-messages.anchor-revalidation.test.ts b/src/web/src/hooks/community/use-messages.anchor-revalidation.test.ts
index 0b805c922..a07e6d2b9 100644
--- a/src/web/src/hooks/community/use-messages.anchor-revalidation.test.ts
+++ b/src/web/src/hooks/community/use-messages.anchor-revalidation.test.ts
@@ -46,7 +46,222 @@ async function waitForSettled(predicate: () => boolean, tries = 40) {
}
}
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>((done) => { resolve = done })
+ return { promise, resolve }
+}
+
describe("useMessages — Fix 3 anchor re-validation", () => {
+ it("shares one pending anchor repair across an asynchronous route remount", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const key = communityKeys.channelMessages("ch_remount")
+ queryClient.setQueryData(key, {
+ pages: [{
+ messages: [{ id: "m_newest", seq: 2, createdAt: "2026-08-20T00:00:02.000Z" }],
+ hasMoreOlder: true,
+ hasMoreNewer: false,
+ }],
+ pageParams: [{ mode: "newest" }],
+ })
+
+ const anchor = deferred<{
+ messages: Array<{ id: string; seq: number; createdAt: string }>
+ hasMoreOlder: boolean
+ hasMoreNewer: boolean
+ }>()
+ apiFetchMock.mockReturnValue(anchor.promise)
+
+ const firstRenders: string[][] = []
+ let first!: TestRenderer.ReactTestRenderer
+ act(() => {
+ first = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, {
+ onRender: (ids) => { firstRenders.push(ids) },
+ channelId: "ch_remount",
+ lastReadMessageId: "m_anchor",
+ }),
+ ),
+ )
+ })
+ await waitForSettled(() => apiFetchMock.mock.calls.length === 1)
+
+ act(() => { first.unmount() })
+ const remountedRenders: string[][] = []
+ let remounted!: TestRenderer.ReactTestRenderer
+ act(() => {
+ remounted = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, {
+ onRender: (ids) => { remountedRenders.push(ids) },
+ channelId: "ch_remount",
+ lastReadMessageId: "m_anchor",
+ }),
+ ),
+ )
+ })
+ await flush()
+
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/channels/ch_remount/messages?anchor=m_anchor",
+ )
+
+ anchor.resolve({
+ messages: [{ id: "m_anchor", seq: 1, createdAt: "2026-08-20T00:00:01.000Z" }],
+ hasMoreOlder: false,
+ hasMoreNewer: true,
+ })
+ await waitForSettled(() => remountedRenders.at(-1)?.includes("m_anchor") === true)
+
+ expect(firstRenders.every((ids) => ids.length > 0)).toBe(true)
+ expect(remountedRenders.every((ids) => ids.length > 0)).toBe(true)
+ expect(remountedRenders.at(-1)).toEqual(["m_anchor", "m_newest"])
+ act(() => { remounted.unmount() })
+ })
+
+ it("keeps settled observer remounts on the ordinary revalidation contract", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const key = communityKeys.channelMessages("ch_settled_remount")
+ queryClient.setQueryData(key, {
+ pages: [{
+ messages: [{ id: "m_newest", seq: 2, createdAt: "2026-08-20T00:00:02.000Z" }],
+ hasMoreOlder: true,
+ hasMoreNewer: false,
+ }],
+ pageParams: [{ mode: "newest" }],
+ })
+
+ const repairedPage = {
+ messages: [{ id: "m_anchor", seq: 1, createdAt: "2026-08-20T00:00:01.000Z" }],
+ hasMoreOlder: false,
+ hasMoreNewer: true,
+ }
+ const anchor = deferred<typeof repairedPage>()
+ apiFetchMock.mockReturnValue(anchor.promise)
+
+ let first!: TestRenderer.ReactTestRenderer
+ act(() => {
+ first = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, {
+ onRender: () => undefined,
+ channelId: "ch_settled_remount",
+ lastReadMessageId: "m_anchor",
+ }),
+ ),
+ )
+ })
+ await waitForSettled(() => apiFetchMock.mock.calls.length === 1)
+ anchor.resolve(repairedPage)
+ await waitForSettled(() => (
+ queryClient.getQueryData<{
+ pageParams: Array<{ mode: string; anchor?: string }>
+ }>(key)?.pageParams[0]?.anchor === "m_anchor"
+ ))
+ act(() => { first.unmount() })
+
+ apiFetchMock.mockResolvedValue(repairedPage)
+ let remounted!: TestRenderer.ReactTestRenderer
+ act(() => {
+ remounted = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, {
+ onRender: () => undefined,
+ channelId: "ch_settled_remount",
+ lastReadMessageId: "m_anchor",
+ }),
+ ),
+ )
+ })
+ await flush()
+
+ expect(apiFetchMock.mock.calls.map(([url]) => url)).toEqual([
+ "/api/community/channels/ch_settled_remount/messages?anchor=m_anchor",
+ "/api/community/channels/ch_settled_remount/messages?anchor=m_anchor",
+ ])
+ act(() => { remounted.unmount() })
+ })
+
+ it("keeps different anchor identities on independent requests", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const key = communityKeys.channelMessages("ch_distinct")
+ queryClient.setQueryData(key, {
+ pages: [{
+ messages: [{ id: "m_newest", seq: 3, createdAt: "2026-08-20T00:00:03.000Z" }],
+ hasMoreOlder: true,
+ hasMoreNewer: false,
+ }],
+ pageParams: [{ mode: "newest" }],
+ })
+
+ const firstAnchor = deferred<{
+ messages: never[]
+ hasMoreOlder: boolean
+ hasMoreNewer: boolean
+ }>()
+ const secondAnchor = deferred<{
+ messages: never[]
+ hasMoreOlder: boolean
+ hasMoreNewer: boolean
+ }>()
+ apiFetchMock.mockImplementation((url: string) => (
+ url.endsWith("anchor=m_anchor_a") ? firstAnchor.promise : secondAnchor.promise
+ ))
+
+ let first!: TestRenderer.ReactTestRenderer
+ act(() => {
+ first = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, {
+ onRender: () => undefined,
+ channelId: "ch_distinct",
+ lastReadMessageId: "m_anchor_a",
+ }),
+ ),
+ )
+ })
+ await waitForSettled(() => apiFetchMock.mock.calls.length === 1)
+ act(() => { first.unmount() })
+
+ let second!: TestRenderer.ReactTestRenderer
+ act(() => {
+ second = TestRenderer.create(
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(Capture, {
+ onRender: () => undefined,
+ channelId: "ch_distinct",
+ lastReadMessageId: "m_anchor_b",
+ }),
+ ),
+ )
+ })
+ await waitForSettled(() => apiFetchMock.mock.calls.length === 2)
+
+ expect(apiFetchMock.mock.calls.map(([url]) => url)).toEqual([
+ "/api/community/channels/ch_distinct/messages?anchor=m_anchor_a",
+ "/api/community/channels/ch_distinct/messages?anchor=m_anchor_b",
+ ])
+
+ firstAnchor.resolve({ messages: [], hasMoreOlder: false, hasMoreNewer: false })
+ secondAnchor.resolve({ messages: [], hasMoreOlder: false, hasMoreNewer: false })
+ await flush()
+ act(() => { second.unmount() })
+ })
+
it("fresh cache with a drifted anchor: merges the new anchor page into the already-loaded history instead of discarding it", async () => {
// `staleTime: Infinity` — without this, mounting a new observer over
// already-cached data triggers TanStack's own implicit refetch-on-mount
diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.ts
index 093095a40..00a7d7956 100644
--- a/src/web/src/hooks/community/use-messages.ts
+++ b/src/web/src/hooks/community/use-messages.ts
@@ -5,6 +5,7 @@ import {
useQueryClient,
type UseInfiniteQueryResult,
type InfiniteData,
+ type QueryClient,
} from "@tanstack/react-query"
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { apiFetch } from "@/lib/api/client"
@@ -147,6 +148,35 @@ const ANCHOR_CACHE_FRESHNESS_MS = 30_000
type PageCache = InfiniteData<MessagesPage, MessagesPageParam>
+const inflightAnchorRepairs = new WeakMap<
+ QueryClient,
+ Map<string, Promise<MessagesPage>>
+>()
+
+function fetchSharedAnchorRepair(
+ queryClient: QueryClient,
+ requestKey: string,
+ fetchPage: () => Promise<MessagesPage>,
+): Promise<MessagesPage> {
+ let requests = inflightAnchorRepairs.get(queryClient)
+ const pending = requests?.get(requestKey)
+ if (pending) return pending
+
+ if (!requests) {
+ requests = new Map()
+ inflightAnchorRepairs.set(queryClient, requests)
+ }
+ const request = fetchPage()
+ requests.set(requestKey, request)
+ const release = () => {
+ if (requests.get(requestKey) !== request) return
+ requests.delete(requestKey)
+ if (requests.size === 0) inflightAnchorRepairs.delete(queryClient)
+ }
+ void request.then(release, release)
+ return request
+}
+
function cacheHasAnchorPage(
cache: PageCache | undefined,
anchorId: string | null,
@@ -449,7 +479,12 @@ function useMessagesInner(
// - STALE cache (cross-session IDB hydration): the loaded window is
// untrustworthy, so REPLACE it with just the fresh anchor page.
const anchorPageParam: MessagesPageParam = { mode: "anchor", anchor: anchorId }
- queryFn({ pageParam: anchorPageParam })
+ const anchorRequestKey = JSON.stringify([queryKey, anchorPageParam])
+ fetchSharedAnchorRepair(
+ queryClient,
+ anchorRequestKey,
+ () => queryFn({ pageParam: anchorPageParam }),
+ )
.then((page) => {
// Re-check right before the swap — a concurrent send/WS update or a
// second re-anchor attempt in the interim shouldn't be clobbered by
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 295e4d398..47c69d7d1 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
@@ -41,6 +41,23 @@ test.describe.serial("forum sidebar Stage B request shape", () => {
const { page } = await asUser("alice")
const requests: string[] = []
const successfulResponses: string[] = []
+ let releaseFirstAnchor!: () => void
+ const firstAnchorGate = new Promise<void>((resolve) => { releaseFirstAnchor = resolve })
+ let anchorRouteRequests = 0
+ await page.route("**/api/community/channels/**/messages**", async (route) => {
+ const url = route.request().url()
+ if (
+ route.request().method() !== "GET"
+ || !isChannelMessagesRequest(url, threadId)
+ || !new URL(url).searchParams.has("anchor")
+ ) {
+ await route.continue()
+ return
+ }
+ anchorRouteRequests += 1
+ if (anchorRouteRequests === 1) await firstAnchorGate
+ await route.continue()
+ })
page.on("request", (request) => {
if (request.method() === "GET") requests.push(request.url())
})
@@ -61,7 +78,18 @@ test.describe.serial("forum sidebar Stage B request shape", () => {
if (!response.ok() || !isChannelMessagesRequest(response.url(), threadId)) return false
return new URL(response.url()).searchParams.has("anchor")
})
- await page.goto(`/c/channels/${serverId}/${threadId}`)
+ try {
+ await page.goto(`/c/channels/${serverId}/${threadId}`)
+ await expect.poll(() => anchorRouteRequests, { timeout: 20_000 }).toBeGreaterThan(0)
+ await page.waitForURL(
+ new RegExp(`/c/channels/${serverId}/${forumId}/${threadId}(?:\\?|$)`),
+ { timeout: 20_000, waitUntil: "commit" },
+ )
+ await page.waitForTimeout(500)
+ expect(anchorRouteRequests).toBe(1)
+ } finally {
+ releaseFirstAnchor()
+ }
await Promise.all([initialCombined, initialNewest, initialAnchored])
await page.waitForURL(new RegExp(threadId), { timeout: 20_000, waitUntil: "commit" })
await expect(page.getByRole("heading", { name: forumTitle })).toBeVisible({ timeout: 20_000 })
@@ -82,6 +110,7 @@ test.describe.serial("forum sidebar Stage B request shape", () => {
.toHaveLength(1)
expect(coldSuccessfulMessageResponses.filter((url) => new URL(url).searchParams.has("anchor")))
.toHaveLength(1)
+ expect(anchorRouteRequests).toBe(1)
expect(new Set(coldSuccessfulMessageResponses).size).toBe(coldSuccessfulMessageResponses.length)
expect(coldMessageRequests.length).toBeGreaterThanOrEqual(coldSuccessfulMessageResponses.length)
@@ -119,6 +148,34 @@ test.describe.serial("forum sidebar Stage B request shape", () => {
.toBe(refreshSuccessfulMessageResponses.length)
})
+ test("natural flat-route canonicalization preserves one settled message load", async ({ asUser }) => {
+ const { page } = await asUser("alice")
+ const successfulResponses: string[] = []
+ page.on("response", (response) => {
+ if (response.request().method() === "GET" && response.ok()) {
+ successfulResponses.push(response.url())
+ }
+ })
+
+ await page.goto(`/c/channels/${serverId}/${threadId}`)
+ await page.waitForURL(
+ new RegExp(`/c/channels/${serverId}/${forumId}/${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)
+ await page.waitForTimeout(2_000)
+
+ const messageResponses = successfulResponses.filter((url) =>
+ isChannelMessagesRequest(url, threadId),
+ )
+ expect(messageResponses.filter((url) => new URL(url).searchParams.has("anchor")))
+ .toHaveLength(1)
+ expect(messageResponses.filter((url) => !new URL(url).searchParams.has("anchor")).length)
+ .toBeLessThanOrEqual(1)
+ })
+
test("switching between top-level channels reuses the warm canonical base", async ({ asUser }) => {
const { page } = await asUser("alice")
const requests: string[] = []