Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): restore flat channel routes (#514)

Genera5fa1c254899
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
deleted file mode 100644
index f2039bdf4..000000000
--- a/src/web/src/app/c/channels/[serverId]/[channelId]/[childChannelId]/page.tsx
+++ /dev/null
@@ -1,3 +0,0 @@
-export default function ChildChannelPage() {
- return null
-}
diff --git a/src/web/src/app/c/channels/[serverId]/page.tsx b/src/web/src/app/c/channels/[serverId]/page.tsx
index e437af2bd..fcf38a110 100644
--- a/src/web/src/app/c/channels/[serverId]/page.tsx
+++ b/src/web/src/app/c/channels/[serverId]/page.tsx
@@ -27,8 +27,8 @@ export default function ServerDefaultPage() {
useEffect(() => {
if (breakpoint !== "desktop" || !currentServer) return
const allChannels = currentServer.categories.flatMap((cat) => cat.channels)
- // Restore the remembered route leaf, including canonical parent/child
- // leaves, or use the first top-level channel when there is no memory.
+ // Restore one remembered channel id, or use the first top-level channel
+ // when there is no valid memory.
const target = pickServerLandingChannel(
allChannels.map((c) => c.id),
getLastChannel(serverId),
diff --git a/src/web/src/app/c/channels/layout.tsx b/src/web/src/app/c/channels/layout.tsx
index 96b3d6812..58423aacb 100644
--- a/src/web/src/app/c/channels/layout.tsx
+++ b/src/web/src/app/c/channels/layout.tsx
@@ -13,7 +13,7 @@ import { patchChannelUnread } from "@/hooks/community/server-detail-cache"
import type { ServerDetail } from "@/hooks/community/use-servers"
import { ShellFrame } from "@/components/community/shell/shell-frame"
import {
- childChannelHref,
+ channelHref,
serverModalMarkerCleanupHref,
} from "@/lib/community/community-route"
import { useBreakpoint } from "@/hooks/use-mobile"
@@ -71,18 +71,11 @@ import {
} from "@/hooks/community/mutations"
export default function ServerLayout({ children }: { children: ReactNode }) {
- const params = useParams<{ serverId: string; channelId?: string; childChannelId?: string }>()
+ const params = useParams<{ serverId: string; channelId?: string }>()
const searchParams = useSearchParams()
const pathname = usePathname()
const serverId = decodeURIComponent(params.serverId)
- const routeChannelId = params.childChannelId
- ? decodeURIComponent(params.childChannelId)
- : params.channelId
- ? decodeURIComponent(params.channelId)
- : null
- const routeParentChannelId = params.childChannelId && params.channelId
- ? decodeURIComponent(params.channelId)
- : undefined
+ const routeChannelId = params.channelId ? decodeURIComponent(params.channelId) : null
const hasChannel = !!routeChannelId
const breakpoint = useBreakpoint()
@@ -323,7 +316,7 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
// trusts the cache unconditionally, so both directions must write to it.
markSwitch("channel", id)
cancelPendingNavigation()
- useCommunityStore.getState().uiHandlers.navigatePath?.(`/c/channels/${serverId}/${id}`)
+ useCommunityStore.getState().uiHandlers.navigatePath?.(channelHref(serverId, id))
channelTree.markRead(id)
const hasChildFallback = setForumSidebarParentUnreadBase(
queryClient,
@@ -339,22 +332,18 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
}
}, [cancelPendingNavigation, channelTree, queryClient, serverId])
- const setActiveForumThread = useCallback((parentId: string, id: string) => {
+ const setActiveForumThread = useCallback((_parentId: string, id: string) => {
markSwitch("channel", id)
cancelPendingNavigation()
useCommunityStore.getState().uiHandlers.navigatePath?.(
- childChannelHref(serverId, parentId, id),
+ channelHref(serverId, id),
)
removeForumSidebarUnreadChild(queryClient, serverId, id)
patchForumSidebarUnreadExact(queryClient, serverId, id, false)
}, [cancelPendingNavigation, queryClient, serverId])
const prefetchChannel = useCallback(
- (id: string, parentId?: string) => router.prefetch(
- parentId
- ? childChannelHref(serverId, parentId, id)
- : `/c/channels/${serverId}/${id}`,
- ),
+ (id: string, _parentId?: string) => router.prefetch(channelHref(serverId, id)),
[router, serverId],
)
@@ -585,7 +574,6 @@ export default function ServerLayout({ children }: { children: ReactNode }) {
<ChannelRoute
key={`${serverId}/${routeChannelId}`}
serverParam={params.serverId}
- parentChannelId={routeParentChannelId}
channelId={routeChannelId}
/>
)
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 19cb38fd5..953906ca1 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
@@ -1,41 +1,42 @@
-import { readFileSync } from "node:fs"
+import { existsSync, readFileSync } from "node:fs"
import { describe, expect, it } from "vitest"
const readSource = (relativePath: string) =>
readFileSync(new URL(relativePath, import.meta.url), "utf8")
describe("adaptive navigation cutover contracts", () => {
- it("uses canonical parent-aware routes for known child entries and prefetches", () => {
+ it("uses the one flat route builder while preserving parent-aware sidebar callbacks", () => {
const contextSheet = readSource("../messages/message-context-sheet.tsx")
const layout = readSource("../../../app/c/channels/layout.tsx")
const sidebar = readSource("./channel-sidebar.tsx")
expect(contextSheet).toContain(
- "router.push(childChannelHref(serverId, channelId, threadId))",
+ "push(channelHref(serverId, threadId))",
)
expect(contextSheet).not.toContain(
- "router.push(`/c/channels/${serverId}/${threadId}`)",
+ "child" + "ChannelHref",
)
- expect(layout).toContain("childChannelHref(serverId, parentId, id)")
+ expect(layout).toContain("channelHref(serverId, id)")
+ expect(sidebar).toContain("onSelectForumThread?.(parentId, thread.id)")
expect(sidebar).toContain("prefetchChannel?.(thread.id, parentId)")
})
- it("keeps one channel subtree mounted across flat-to-nested canonicalization", () => {
+ it("keeps the layout as the one channel subtree owner and removes the nested leaf", () => {
const layout = readSource("../../../app/c/channels/layout.tsx")
const flatPage = readSource("../../../app/c/channels/[serverId]/[channelId]/page.tsx")
- const nestedPage = readSource(
+ const nestedPage = new URL(
"../../../app/c/channels/[serverId]/[channelId]/[childChannelId]/page.tsx",
+ import.meta.url,
)
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")
- }
+ expect(layout).not.toContain("parentChannelId={routeParent" + "ChannelId}")
+ expect(flatPage).toContain("return null")
+ expect(flatPage).not.toContain("<ChannelRoute")
+ expect(existsSync(nestedPage)).toBe(false)
})
it("autofocuses message composers only after desktop is known", () => {
diff --git a/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts b/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts
index 8767db9b2..6d7f4d0e1 100644
--- a/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts
+++ b/src/web/src/components/community/channels/channel-route.text-scroll-target.test.ts
@@ -7,8 +7,18 @@ import { MessageList } from "../messages/message-list"
import { useChannelMemberViewModel } from "../members/channel-member-view-model"
import { useChannelMessageFeed } from "@/hooks/community/use-channel-message-feed"
-const { mockRouteModel, mockMemberViewModel, mockRouter } = vi.hoisted(() => ({
+const {
+ mockRouteModel,
+ mockMemberViewModel,
+ mockRouter,
+ mockUiHandlers,
+ mockBreakpoint,
+ mockHeaderBack,
+} = vi.hoisted(() => ({
mockRouter: { push: vi.fn(), replace: vi.fn(), back: vi.fn() },
+ mockUiHandlers: { replacePath: vi.fn(), goBackMobile: vi.fn() },
+ mockBreakpoint: { value: "desktop" as "desktop" | "mobile" },
+ mockHeaderBack: { current: undefined as undefined | (() => void) },
mockRouteModel: {
server: {
id: "server_1",
@@ -48,9 +58,12 @@ vi.mock("next/navigation", () => ({
}))
vi.mock("sonner", () => ({ toast: vi.fn() }))
vi.mock("@/lib/api/client", () => ({ apiFetch: vi.fn(), toastApiError: vi.fn() }))
-vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop" }))
+vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => mockBreakpoint.value }))
vi.mock("@/components/community/channels/channel-header", () => ({
- ChannelHeader: () => null,
+ ChannelHeader: ({ onBack }: { onBack?: () => void }) => {
+ if (onBack) mockHeaderBack.current = onBack
+ return null
+ },
ChannelHeaderSkeleton: () => null,
}))
vi.mock("@/components/community/messages/message-list", () => ({ MessageList: vi.fn(() => null) }))
@@ -66,7 +79,8 @@ vi.mock("@/components/community/members/channel-member-view-model", () => ({
useChannelMemberViewModel: vi.fn(() => mockMemberViewModel),
}))
vi.mock("@/components/community/channels/channel-shell", () => ({
- ChannelShell: ({ body }: { body: React.ReactNode }) => body,
+ ChannelShell: ({ header, body }: { header: React.ReactNode; body: React.ReactNode }) =>
+ React.createElement(React.Fragment, null, header, body),
}))
vi.mock("@/components/community/shell/community-panel-sheet", () => ({ CommunityPanelSheet: () => null }))
vi.mock("@/components/community/messages/message-context-sheet", () => ({ MessageContextSheet: () => null }))
@@ -92,7 +106,7 @@ vi.mock("@/stores/community", () => {
return {
useCommunityStore,
useCurrentChannelId: () => "channel_1",
- useUiHandlers: () => ({}),
+ useUiHandlers: () => mockUiHandlers,
useTypingUsersForScope: () => [],
useTypingNamesForScope: () => ({}),
}
@@ -218,6 +232,8 @@ describe("ChannelRoute message surface ownership", () => {
beforeEach(() => {
vi.useFakeTimers()
mockedMessageList.mockClear()
+ mockBreakpoint.value = "desktop"
+ mockHeaderBack.current = undefined
Object.assign(mockRouteModel, {
server: {
id: "server_1",
@@ -333,10 +349,44 @@ describe("ChannelRoute message surface ownership", () => {
isChildChannel: true,
}))
expect(mockRouter.replace).toHaveBeenLastCalledWith(
- "/c/channels/server_1/parent_1/channel_1?msg=m_target&keep=1",
+ "/c/channels/server_1/channel_1?keep=1",
+ { scroll: false },
)
})
+ it("derives a mobile child Back destination from fetched parent metadata", () => {
+ configureThreadRoute()
+ mockBreakpoint.value = "mobile"
+ mockedUseChannelMessageFeed.mockImplementation(() => feed({ anchorInCache: true }))
+
+ act(() => {
+ TestRenderer.create(
+ React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" }),
+ )
+ })
+ act(() => mockHeaderBack.current?.())
+
+ expect(mockUiHandlers.replacePath).toHaveBeenCalledWith(
+ "/c/channels/server_1/parent_1",
+ )
+ expect(mockUiHandlers.goBackMobile).not.toHaveBeenCalled()
+ })
+
+ it("uses the shell mobile Back handler for a top-level channel", () => {
+ mockBreakpoint.value = "mobile"
+ mockedUseChannelMessageFeed.mockImplementation(() => feed())
+
+ act(() => {
+ TestRenderer.create(
+ React.createElement(ChannelRoute, { serverParam: "server_1", channelId: "channel_1" }),
+ )
+ })
+ act(() => mockHeaderBack.current?.())
+
+ expect(mockUiHandlers.goBackMobile).toHaveBeenCalledOnce()
+ expect(mockUiHandlers.replacePath).not.toHaveBeenCalled()
+ })
+
it("keeps a child target through warm cache and 5000ms until MessageList consumes it", () => {
configureThreadRoute()
let childFeed = feed({ messages: [{ id: "m_unrelated" }], anchorInCache: true })
diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsx
index 7c0833783..4076bfdef 100644
--- a/src/web/src/components/community/channels/channel-route.tsx
+++ b/src/web/src/components/community/channels/channel-route.tsx
@@ -27,7 +27,7 @@ import { useChannelRouteModel } from "@/hooks/community/use-channel-route-model"
import { useForumOpenerHint } from "@/hooks/community/use-forum-opener-hint"
import { useNotificationSettings } from "@/hooks/community/use-notification-settings"
import { useSetChannelNotif } from "@/hooks/community/mutations"
-import { childChannelHref, removeCommunityParam } from "@/lib/community/community-route"
+import { channelHref, removeCommunityParam } from "@/lib/community/community-route"
/**
* /c/channels/:serverId/:channelId
@@ -36,14 +36,9 @@ import { childChannelHref, removeCommunityParam } from "@/lib/community/communit
* - Text channel: MessageList + Composer + right panels
* - Child thread opened via URL: child-channel view (breadcrumb + list)
*/
-export function ChannelRoute({
- serverParam,
- channelId,
- parentChannelId: routeParentChannelId,
-}: {
+export function ChannelRoute({ serverParam, channelId }: {
serverParam: string
channelId: string
- parentChannelId?: string
}) {
const router = useRouter()
const searchParams = useSearchParams()
@@ -52,11 +47,8 @@ export function ChannelRoute({
// memory) so re-entering the server restores here instead of the default.
// Pure localStorage write; failures are swallowed in the helper.
useEffect(() => {
- setLastChannel(
- serverId,
- routeParentChannelId ? `${routeParentChannelId}/${channelId}` : channelId,
- )
- }, [serverId, channelId, routeParentChannelId])
+ setLastChannel(serverId, channelId)
+ }, [serverId, channelId])
// Cross-channel "jump to message" target, captured ONCE at mount from `?msg=`.
// `ChannelView` is keyed by `serverId/channelId`, so a fresh jump remounts and
// re-reads this. The param is stripped from the URL right after (below) so a
@@ -124,7 +116,14 @@ export function ChannelRoute({
const channelNotif = notifs.channel
const { mutate: setChannelNotif } = useSetChannelNotif()
- const goBack = useCallback(() => { uiHandlers.goBackMobile?.() }, [uiHandlers])
+ const goBack = useCallback(() => {
+ const parentChannelId = currentChannelMeta?.parentChannelId
+ if (isChildChannel && parentChannelId) {
+ uiHandlers.replacePath?.(channelHref(serverParam, parentChannelId))
+ return
+ }
+ uiHandlers.goBackMobile?.()
+ }, [currentChannelMeta?.parentChannelId, isChildChannel, serverParam, uiHandlers])
const setNotificationLevel = useCallback((level: ChannelNotifLevel) => {
setChannelNotif({ channelId, level }, {
onError: (error) => toastApiError(error, "Failed to update notification level"),
@@ -137,38 +136,20 @@ export function ChannelRoute({
useEffect(() => {
if (!jumpTargetId) return
const search = searchParams.toString()
- const routePath = routeParentChannelId
- ? childChannelHref(serverParam, routeParentChannelId, channelId)
- : `/c/channels/${serverParam}/${channelId}`
+ const routePath = channelHref(serverParam, channelId)
const href = `${routePath}${search ? `?${search}` : ""}`
router.replace(removeCommunityParam(href, "msg"), { scroll: false })
// eslint-disable-next-line react-hooks/exhaustive-deps -- run once for this mount's jump
}, [])
- useEffect(() => {
- const parentChannelId = currentChannelMeta?.parentChannelId
- if (!isChildChannel || routeParentChannelId || !parentChannelId) return
- const search = searchParams.toString()
- const routePath = childChannelHref(serverParam, parentChannelId, channelId)
- router.replace(`${routePath}${search ? `?${search}` : ""}`)
- }, [
- channelId,
- currentChannelMeta?.parentChannelId,
- isChildChannel,
- routeParentChannelId,
- router,
- searchParams,
- serverParam,
- ])
-
const enterThread = useCallback((id: string) => {
// No eager read PUT here — the thread page's `useEagerChannelRead` fires it
// on mount AFTER its read-state snapshot latches, so the "New" divider
// still anchors to the pre-open pointer. A PUT here would race the snapshot.
useCommunityStore.getState().uiHandlers.navigatePath?.(
- childChannelHref(serverParam, channelId, id),
+ channelHref(serverParam, id),
)
- }, [channelId, serverParam])
+ }, [serverParam])
const openProfile = useCallback<OpenProfile>((name, e, discriminator, userId) => {
uiHandlers.openProfile?.(name, e, discriminator, userId)
diff --git a/src/web/src/components/community/messages/message-channel-controller-state.test.ts b/src/web/src/components/community/messages/message-channel-controller-state.test.ts
index 85532faf8..75c401b11 100644
--- a/src/web/src/components/community/messages/message-channel-controller-state.test.ts
+++ b/src/web/src/components/community/messages/message-channel-controller-state.test.ts
@@ -341,7 +341,7 @@ describe("useMessageChannelController", () => {
})
it("consumes seq on the current canonical child route and preserves other query state", () => {
- mocks.pathname = "/c/channels/server_1/parent_1/channel_1"
+ mocks.pathname = "/c/channels/server_1/channel_1"
mocks.seq = "7"
act(() => {
TestRenderer.create(React.createElement(Probe, { value: props() }))
@@ -351,7 +351,7 @@ describe("useMessageChannelController", () => {
serverId: "server_1", channelId: "channel_1", label: "general", seq: 7,
})
expect(mocks.router.replace).toHaveBeenCalledWith(
- "/c/channels/server_1/parent_1/channel_1?keep=1",
+ "/c/channels/server_1/channel_1?keep=1",
{ scroll: false },
)
})
diff --git a/src/web/src/components/community/messages/message-context-sheet.navigation.test.ts b/src/web/src/components/community/messages/message-context-sheet.navigation.test.ts
new file mode 100644
index 000000000..65a333466
--- /dev/null
+++ b/src/web/src/components/community/messages/message-context-sheet.navigation.test.ts
@@ -0,0 +1,121 @@
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const mocks = vi.hoisted(() => ({
+ push: vi.fn(),
+ close: vi.fn(),
+ openThread: undefined as undefined | ((threadId: string) => void),
+}))
+
+vi.mock("next/navigation", () => ({
+ useParams: () => ({ serverId: "server_1" }),
+ useRouter: () => ({ push: mocks.push }),
+}))
+vi.mock("@tanstack/react-query", () => ({
+ useQuery: () => ({
+ data: {
+ notFound: false,
+ anchorId: "message_1",
+ messages: [{
+ id: "message_1",
+ seq: 1,
+ type: "chat",
+ authorId: "author_1",
+ authorName: "Author",
+ content: "Message",
+ createdAt: "2026-08-20T00:00:00.000Z",
+ thread: { id: "child_1", name: "Child", messageCount: 1 },
+ }],
+ },
+ isLoading: false,
+ isError: false,
+ }),
+ useQueryClient: () => ({ setQueryData: vi.fn() }),
+}))
+vi.mock("@/components/ui/sheet", () => ({
+ Sheet: ({ children }: { children: React.ReactNode }) => children,
+ SheetContent: ({ children }: { children: React.ReactNode }) => children,
+ SheetHeader: ({ children }: { children: React.ReactNode }) => children,
+ SheetTitle: ({ children }: { children: React.ReactNode }) => children,
+}))
+vi.mock("@/components/ui/sheet-resize-handle", () => ({
+ useSheetResize: () => ({
+ width: 420,
+ onPointerDown: vi.fn(),
+ onPointerMove: vi.fn(),
+ onPointerUp: vi.fn(),
+ }),
+ SheetResizeHandle: () => null,
+}))
+vi.mock("./message-row", () => ({
+ MessageRow: ({ onOpenThread }: { onOpenThread: (threadId: string) => void }) => {
+ mocks.openThread = onOpenThread
+ return null
+ },
+}))
+vi.mock("./message-share-dialog", () => ({ MessageShareDialog: () => null }))
+vi.mock("../channels/channel-icon", () => ({ ChannelIcon: () => null }))
+vi.mock("@/components/ui/skeleton", () => ({ Skeleton: () => null }))
+vi.mock("../dividers", () => ({ DateDivider: () => null }))
+vi.mock("@/contexts/community/current-user", () => ({
+ useCurrentUser: () => ({ id: "viewer_1" }),
+}))
+vi.mock("@/stores/community", () => ({ useUiHandlers: () => ({}) }))
+vi.mock("@/hooks/use-hover-capable", () => ({ useHoverCapable: () => true }))
+vi.mock("@/hooks/community/mutations", () => ({
+ usePinMessage: () => ({ mutate: vi.fn() }),
+ useUnpinMessage: () => ({ mutate: vi.fn() }),
+ useCreateThread: () => ({ mutateAsync: vi.fn() }),
+ useToggleMark: () => vi.fn(),
+}))
+vi.mock("sonner", () => ({ toast: vi.fn() }))
+vi.mock("@/lib/api/client", () => ({ apiFetch: vi.fn(), toastApiError: vi.fn() }))
+
+import {
+ MessageContextSheet,
+ openMessageContextThread,
+} from "./message-context-sheet"
+
+describe("MessageContextSheet thread navigation", () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.openThread = undefined
+ })
+
+ it("opens a rendered channel thread by its flat child id and closes the sheet", () => {
+ act(() => {
+ TestRenderer.create(React.createElement(MessageContextSheet, {
+ open: false,
+ onOpenChange: mocks.close,
+ channelId: "parent_1",
+ targetSeq: 1,
+ }))
+ })
+ act(() => mocks.openThread?.("child_1"))
+
+ expect(mocks.push).toHaveBeenCalledWith("/c/channels/server_1/child_1")
+ expect(mocks.close).toHaveBeenCalledWith(false)
+ })
+
+ it("does not navigate from a DM or without a server route", () => {
+ const push = vi.fn()
+ const close = vi.fn()
+
+ expect(openMessageContextThread({
+ type: "dm",
+ serverId: "server_1",
+ threadId: "child_1",
+ push,
+ close,
+ })).toBe(false)
+ expect(openMessageContextThread({
+ type: "channel",
+ threadId: "child_1",
+ push,
+ close,
+ })).toBe(false)
+ expect(push).not.toHaveBeenCalled()
+ expect(close).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/web/src/components/community/messages/message-context-sheet.tsx b/src/web/src/components/community/messages/message-context-sheet.tsx
index c3ed098b9..663b927bd 100644
--- a/src/web/src/components/community/messages/message-context-sheet.tsx
+++ b/src/web/src/components/community/messages/message-context-sheet.tsx
@@ -21,7 +21,7 @@ import { usePinMessage, useUnpinMessage, useCreateThread, useToggleMark } from "
import type { FileAttachment, ImagePreview, MessagesPage, Msg, Reaction, RenderMsg } from "@/lib/community/models/message"
import type { OpenProfile } from "@/components/community/social/profile-types"
import { useHoverCapable } from "@/hooks/use-hover-capable"
-import { childChannelHref } from "@/lib/community/community-route"
+import { channelHref } from "@/lib/community/community-route"
export type ReplyTarget = { id: string; authorName: string; text: string }
@@ -32,6 +32,25 @@ const CONTEXT_LIMIT = 11
type ScopeType = "channel" | "dm"
+export function openMessageContextThread({
+ type,
+ serverId,
+ threadId,
+ push,
+ close,
+}: {
+ type: ScopeType
+ serverId?: string
+ threadId: string
+ push: (href: string) => void
+ close: () => void
+}): boolean {
+ if (type === "dm" || !serverId) return false
+ push(channelHref(serverId, threadId))
+ close()
+ return true
+}
+
// A DM (type=dm) and a thread are channel rows in the same id-space, so both
// resolve through the one canonical door — no per-type URL fork. `type` is kept
// in the signatures for call-site clarity but no longer branches the path.
@@ -311,12 +330,14 @@ export function MessageContextSheet({
// Sheet's Reply-style handoff: navigate the main window to the thread and
// close the sheet in the same gesture. Falls back to a no-op in the DM
// case (threads live inside channels, not DMs).
- if (type === "dm") return
- const serverId = routeParams?.serverId
- if (!serverId) return
- router.push(childChannelHref(serverId, channelId, threadId))
- onOpenChange(false)
- }, [type, router, routeParams, channelId, onOpenChange])
+ openMessageContextThread({
+ type,
+ serverId: routeParams?.serverId,
+ threadId,
+ push: router.push,
+ close: () => onOpenChange(false),
+ })
+ }, [type, router, routeParams, onOpenChange])
const onPreviewImage = useCallback((image: ImagePreview) => {
uiHandlers.previewImage?.(image)
diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts
index c3a4eb465..3da78a47a 100644
--- a/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts
+++ b/src/web/src/components/community/shell/use-shell-inbox-controller.test.ts
@@ -115,7 +115,7 @@ describe("useShellInboxController", () => {
expect(hook.order).toEqual(["watch", "read", "cancel", "push"])
expect(mocks.watch).toHaveBeenCalledWith("channel:child")
expect(mocks.readForum).toHaveBeenCalledWith({ parentChannelId: "forum", openerMessageId: "opener" })
- expect(hook.pushed.at(-1)).toBe("/c/channels/s1/forum/child")
+ expect(hook.pushed.at(-1)).toBe("/c/channels/s1/child")
hook.order.length = 0
await act(async () => hook.current.popoverProps.onOpenMention?.({ id: "m1" } as never))
@@ -144,7 +144,7 @@ describe("useShellInboxController", () => {
m: { seq: 8 },
} as never))
expect(mocks.watch).toHaveBeenLastCalledWith("marked:mk-child")
- expect(hook.pushed.at(-1)).toBe("/c/channels/s1/parent1/child1?seq=8")
+ expect(hook.pushed.at(-1)).toBe("/c/channels/s1/child1?seq=8")
await act(async () => hook.current.popoverProps.onOpenMarked?.({
id: "mk2",
diff --git a/src/web/src/components/community/shell/use-shell-inbox-controller.ts b/src/web/src/components/community/shell/use-shell-inbox-controller.ts
index 11c4cd3c1..dbd1b4d03 100644
--- a/src/web/src/components/community/shell/use-shell-inbox-controller.ts
+++ b/src/web/src/components/community/shell/use-shell-inbox-controller.ts
@@ -2,7 +2,7 @@
import { useCallback, useState, type ComponentProps } from "react"
import { communityKeys } from "@/lib/query-keys"
-import { childChannelHref } from "@/lib/community/community-route"
+import { channelHref } from "@/lib/community/community-route"
import type { Marked } from "@/lib/community/models/inbox"
import { useInboxUnreads, useInboxMentions, useInboxMarked } from "@/hooks/community/use-inbox"
import { useInboxAutoCollapse } from "@/hooks/community/use-inbox-auto-collapse"
@@ -45,14 +45,12 @@ export function useShellInboxController({
const openServerChannel = useCallback((
serverId: string,
channelId: string,
- parentChannelId?: string,
+ _parentChannelId?: string,
watchKey: string = `channel:${channelId}`,
) => {
watchInboxItem(watchKey)
cancelPendingNavigation()
- router.push(parentChannelId
- ? childChannelHref(serverId, parentChannelId, channelId)
- : `/c/channels/${serverId}/${channelId}`)
+ router.push(channelHref(serverId, channelId))
}, [cancelPendingNavigation, router, watchInboxItem])
const openForumThread = useCallback((
@@ -64,7 +62,7 @@ export function useShellInboxController({
watchInboxItem(`channel:${childChannelId}`)
readForumThreadFromInbox({ parentChannelId, openerMessageId })
cancelPendingNavigation()
- router.push(childChannelHref(serverId, parentChannelId, childChannelId))
+ router.push(channelHref(serverId, childChannelId))
}, [cancelPendingNavigation, readForumThreadFromInbox, router, watchInboxItem])
const openMarked = useCallback((marked: Marked) => {
@@ -72,9 +70,7 @@ export function useShellInboxController({
cancelPendingNavigation()
const seqQuery = marked.m.seq != null ? `?seq=${marked.m.seq}` : ""
if (marked.serverId) {
- const channelPath = marked.parentChannelId
- ? childChannelHref(marked.serverId, marked.parentChannelId, marked.channelId)
- : `/c/channels/${marked.serverId}/${marked.channelId}`
+ const channelPath = channelHref(marked.serverId, marked.channelId)
router.push(`${channelPath}${seqQuery}`)
} else {
router.push(`/c/me/${marked.channelId}${seqQuery}`)
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
index 056b0e34c..081fbe95b 100644
--- 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
@@ -8,6 +8,8 @@ const mocks = vi.hoisted(() => ({
subscribe: vi.fn(),
unsubscribe: vi.fn(),
replace: vi.fn(),
+ clearLastChannel: vi.fn(),
+ lastChannel: null as string | null,
metaQuery: {
data: undefined as undefined | Record<string, unknown>,
error: null as unknown,
@@ -43,6 +45,10 @@ vi.mock("./use-community-ws", () => ({
communityWsUnsubscribe: (...args: unknown[]) => mocks.unsubscribe(...args),
}))
vi.mock("@/lib/api/client", () => ({ toastApiError: vi.fn() }))
+vi.mock("@/lib/community/last-channel", () => ({
+ getLastChannel: () => mocks.lastChannel,
+ clearLastChannel: (...args: unknown[]) => mocks.clearLastChannel(...args),
+}))
import { useChannelRouteModel } from "./use-channel-route-model"
@@ -56,6 +62,8 @@ beforeEach(() => {
mocks.subscribe.mockClear()
mocks.unsubscribe.mockClear()
mocks.replace.mockClear()
+ mocks.clearLastChannel.mockClear()
+ mocks.lastChannel = null
mocks.metaQuery = { data: undefined, error: null, isVerified: false }
})
@@ -102,4 +110,37 @@ describe("useChannelRouteModel subscription ownership", () => {
act(() => renderer!.unmount())
expect(mocks.unsubscribe).toHaveBeenCalledTimes(1)
})
+
+ it("clears an exact flat last-channel value when verified metadata is archived", () => {
+ mocks.lastChannel = "post-1"
+ mocks.metaQuery = {
+ data: {
+ id: "post-1",
+ serverId: "server-1",
+ name: "Post",
+ type: "thread",
+ parentChannelId: "forum-1",
+ parentMessageId: "opener-1",
+ creatorId: "user-1",
+ archived: true,
+ activityAt: "2026-08-09T00:00:00.000Z",
+ verifiedEpoch: 0,
+ },
+ error: null,
+ isVerified: true,
+ }
+ let renderer: TestRenderer.ReactTestRenderer
+
+ act(() => {
+ renderer = TestRenderer.create(React.createElement(Harness))
+ })
+
+ expect(mocks.clearLastChannel).toHaveBeenCalledWith("server-1")
+ expect(mocks.replace).toHaveBeenCalledWith("/c/channels/server-1")
+ expect(mocks.subscribe).toHaveBeenCalledTimes(1)
+ expect(mocks.unsubscribe).not.toHaveBeenCalled()
+
+ act(() => renderer!.unmount())
+ expect(mocks.unsubscribe).toHaveBeenCalledTimes(1)
+ })
})
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 8457629cc..89cece2ae 100644
--- a/src/web/src/hooks/community/use-channel-route-model.ts
+++ b/src/web/src/hooks/community/use-channel-route-model.ts
@@ -87,10 +87,7 @@ export function useChannelRouteModel(serverId: string, serverParam: string, chan
removeForumSidebarUnreadChild(queryClient, serverId, channelId)
removeForumSidebarThreadExact(queryClient, serverId, channelId)
const lastChannel = getLastChannel(serverId)
- if (
- lastChannel === channelId ||
- lastChannel?.endsWith(`/${channelId}`)
- ) {
+ if (lastChannel === channelId) {
clearLastChannel(serverId)
}
router.replace(`/c/channels/${serverParam}`)
diff --git a/src/web/src/lib/community/community-route.test.ts b/src/web/src/lib/community/community-route.test.ts
index d519f2737..8b4a7641d 100644
--- a/src/web/src/lib/community/community-route.test.ts
+++ b/src/web/src/lib/community/community-route.test.ts
@@ -1,7 +1,6 @@
import { describe, expect, it } from "vitest"
import {
channelHref,
- childChannelHref,
removeCommunityParam,
resolveCommunityRoute,
serverModalMarkerCleanupHref,
@@ -16,17 +15,14 @@ describe("community route", () => {
["/c/me/dm_1", "detail", "/c/me"],
["/c/channels/server_1", "list", null],
["/c/channels/server_1/channel_1", "detail", "/c/channels/server_1"],
- ["/c/channels/server_1/parent_1/child_1", "detail", "/c/channels/server_1/parent_1"],
])("classifies %s", (pathname, surface, parentPath) => {
expect(resolveCommunityRoute(pathname)).toEqual({ surface, parentPath })
})
- it("builds root, top-level, and canonical child hrefs", () => {
+ it("builds top-level and child hrefs through the same flat channel builder", () => {
expect(serverRootHref("server_1")).toBe("/c/channels/server_1")
expect(channelHref("server_1", "channel_1")).toBe("/c/channels/server_1/channel_1")
- expect(childChannelHref("server_1", "parent_1", "child_1")).toBe(
- "/c/channels/server_1/parent_1/child_1",
- )
+ expect(channelHref("server_1", "child_1")).toBe("/c/channels/server_1/child_1")
})
it("removes one query key while preserving the rest and the hash", () => {
diff --git a/src/web/src/lib/community/community-route.ts b/src/web/src/lib/community/community-route.ts
index 9669e96c4..7b39a6507 100644
--- a/src/web/src/lib/community/community-route.ts
+++ b/src/web/src/lib/community/community-route.ts
@@ -18,12 +18,6 @@ export function resolveCommunityRoute(pathname: string): CommunityRoute {
if (segments[1] === "channels" && segments[2]) {
const serverRoot = `/c/channels/${segments[2]}`
if (segments.length === 3) return { surface: "list", parentPath: null }
- if (segments.length >= 5) {
- return {
- surface: "detail",
- parentPath: `${serverRoot}/${segments[3]}`,
- }
- }
return { surface: "detail", parentPath: serverRoot }
}
@@ -38,14 +32,6 @@ export function channelHref(serverId: string, channelId: string): string {
return `${serverRootHref(serverId)}/${channelId}`
}
-export function childChannelHref(
- serverId: string,
- parentChannelId: string,
- childChannelId: string,
-): string {
- return `${channelHref(serverId, parentChannelId)}/${childChannelId}`
-}
-
export function removeCommunityParam(href: string, key: string): string {
return updateHrefSearchParams(href, (searchParams) => {
searchParams.delete(key)
diff --git a/src/web/src/lib/community/last-channel.test.ts b/src/web/src/lib/community/last-channel.test.ts
index bb9674101..165964a01 100644
--- a/src/web/src/lib/community/last-channel.test.ts
+++ b/src/web/src/lib/community/last-channel.test.ts
@@ -47,6 +47,19 @@ describe("last-channel", () => {
expect(getLastChannel("srv_1")).toBe("ch_2")
})
+ it("clears a deployed parent/child value on read", () => {
+ storage[lastChannelKey("srv_1")] = "parent_1/child_1"
+ expect(getLastChannel("srv_1")).toBeNull()
+ expect(storage[lastChannelKey("srv_1")]).toBeUndefined()
+ })
+
+ it("rejects a future slash write and clears the prior valid value", () => {
+ setLastChannel("srv_1", "child_1")
+ setLastChannel("srv_1", "parent_1/child_1")
+ expect(getLastChannel("srv_1")).toBeNull()
+ expect(storage[lastChannelKey("srv_1")]).toBeUndefined()
+ })
+
it("returns null (never throws) when localStorage.getItem throws", () => {
vi.stubGlobal("localStorage", {
getItem: vi.fn(() => {
@@ -127,9 +140,9 @@ describe("pickServerLandingChannel", () => {
})
describe("pickServerLandingHref", () => {
- it("restores a canonical parent/child leaf", () => {
+ it("rejects a superseded parent/child leaf and falls back safely", () => {
expect(pickServerLandingHref("srv_1", ["ch_1"], "forum_1/post_1")).toBe(
- "/c/channels/srv_1/forum_1/post_1",
+ "/c/channels/srv_1/ch_1",
)
})
diff --git a/src/web/src/lib/community/last-channel.ts b/src/web/src/lib/community/last-channel.ts
index 2986bfe3f..e0aa401ef 100644
--- a/src/web/src/lib/community/last-channel.ts
+++ b/src/web/src/lib/community/last-channel.ts
@@ -3,8 +3,8 @@
// were; this remembers, per browser, the last channel/post opened in each
// server so the server-landing page can restore to it.
//
-// Deliberately narrow: it stores ONLY the route leaf (a serverId -> channelId or
-// parentId/channelId map), never scroll position or read-to-seq — those are
+// Deliberately narrow: it stores ONLY one channel id per server, never scroll
+// position or read-to-seq — those are
// server read-state, a separate concern this must not touch. localStorage-only
// (no backend, no daemon, no cross-device sync). Pure guarded wrappers (SSR +
// privacy-mode safe) mirroring `composer-draft.ts` — any failure degrades to
@@ -23,11 +23,22 @@ export function lastChannelKey(serverId: string): string {
}
export function getLastChannel(serverId: string): string | null {
- return readNavigationMemory(lastChannelKey(serverId))
+ const key = lastChannelKey(serverId)
+ const channelId = readNavigationMemory(key)
+ if (channelId?.includes("/")) {
+ clearNavigationMemory(key)
+ return null
+ }
+ return channelId
}
export function setLastChannel(serverId: string, channelId: string): void {
- writeNavigationMemory(lastChannelKey(serverId), channelId)
+ const key = lastChannelKey(serverId)
+ if (channelId.includes("/")) {
+ clearNavigationMemory(key)
+ return
+ }
+ writeNavigationMemory(key, channelId)
}
/**
@@ -65,7 +76,7 @@ export function pickServerLandingChannel(
channelIds: readonly string[],
last: string | null,
): string | undefined {
- if (last !== null) return last
+ if (last !== null && !last.includes("/")) return last
return channelIds[0]
}
diff --git a/src/web/src/lib/community/models/inbox.ts b/src/web/src/lib/community/models/inbox.ts
index d7e76bf4d..eaddf21cd 100644
--- a/src/web/src/lib/community/models/inbox.ts
+++ b/src/web/src/lib/community/models/inbox.ts
@@ -34,8 +34,8 @@ export type Marked = {
// For a server message this is the channel id; for a DM it's the DM channel
// id, which is also the frontend `/c/me/<id>` route param.
channelId: string
- // Child-channel marks include their canonical parent route segment. Optional
- // for backward compatibility with older cached marked-feed payloads.
+ // Legacy cached payloads may include the parent for read/grouping metadata.
+ // Flat channel navigation never encodes it as a route segment.
parentChannelId?: string | null
m: Msg
}
diff --git a/src/web/src/test/architecture/community-channel-route-contract.test.ts b/src/web/src/test/architecture/community-channel-route-contract.test.ts
new file mode 100644
index 000000000..ed3bd3b7e
--- /dev/null
+++ b/src/web/src/test/architecture/community-channel-route-contract.test.ts
@@ -0,0 +1,64 @@
+import { existsSync, readdirSync, readFileSync } from "node:fs"
+import { extname, join, relative } from "node:path"
+import { fileURLToPath } from "node:url"
+import { describe, expect, it } from "vitest"
+
+const SRC_ROOT = fileURLToPath(new URL("../../", import.meta.url))
+const THIS_TEST = fileURLToPath(import.meta.url)
+const REMOVED_ROUTE = join(
+ SRC_ROOT,
+ "app/c/channels/[serverId]/[channelId]/[childChannelId]",
+)
+const REMOVED_PATH_TEST = join(SRC_ROOT, "test/e2e-ui/08-mobile.spec.ts")
+const NESTED_CHANNEL_PATH = /\/c\/channels\/[^/?\s"'`\[\]]+\/[^/?\s"'`\[\]]+\/[^/?\s"'`\[\]]+/g
+
+function sources(root: string): string[] {
+ return readdirSync(root, { withFileTypes: true }).flatMap((entry) => {
+ const path = join(root, entry.name)
+ if (entry.isDirectory()) return sources(path)
+ return [".ts", ".tsx"].includes(extname(path)) ? [path] : []
+ })
+}
+
+describe("flat Community channel route contract", () => {
+ it("removes the nested route entry and superseded route helpers", () => {
+ expect(existsSync(REMOVED_ROUTE)).toBe(false)
+
+ const forbidden = sources(SRC_ROOT)
+ .filter((path) => path !== THIS_TEST)
+ .flatMap((path) => {
+ const source = readFileSync(path, "utf8")
+ return ["child" + "ChannelHref", "routeParent" + "ChannelId"]
+ .filter((token) => source.includes(token))
+ .map((token) => ({ path: relative(SRC_ROOT, path), token }))
+ })
+ expect(forbidden).toEqual([])
+ })
+
+ it("allows one nested URL only in the removed-path rejection journey", () => {
+ const occurrences = sources(SRC_ROOT)
+ .filter((path) => path !== THIS_TEST)
+ .flatMap((path) => {
+ const source = readFileSync(path, "utf8")
+ return [...source.matchAll(NESTED_CHANNEL_PATH)]
+ .map((match) => ({ path, literal: match[0] }))
+ })
+
+ expect(occurrences.map(({ path, literal }) => ({
+ path: relative(SRC_ROOT, path),
+ literal,
+ }))).toEqual([{
+ path: relative(SRC_ROOT, REMOVED_PATH_TEST),
+ literal: "/c/channels/${serverId}/${channelId}/${childChannelId}",
+ }])
+ })
+
+ it("keeps last-channel memory flat on both reads and writes", () => {
+ const source = readFileSync(
+ join(SRC_ROOT, "lib/community/last-channel.ts"),
+ "utf8",
+ )
+ expect(source.match(/includes\("\/"\)/g)).toHaveLength(3)
+ expect(source).toContain("clearNavigationMemory(key)")
+ })
+})
diff --git a/src/web/src/test/e2e-ui/08-mobile.spec.ts b/src/web/src/test/e2e-ui/08-mobile.spec.ts
index cdd2fb003..f41a43fa4 100644
--- a/src/web/src/test/e2e-ui/08-mobile.spec.ts
+++ b/src/web/src/test/e2e-ui/08-mobile.spec.ts
@@ -97,20 +97,35 @@ test.describe.serial("mobile layout", () => {
await expect(page.getByTestId(tid.composerInput)).toBeVisible()
})
- test("canonical child detail consumes seq without dropping route or other URL state", async ({ asUser }) => {
+ test("flat child detail consumes seq without dropping route or other URL state", async ({ asUser }) => {
const { page } = await asUser("alice")
await page.goto(
- `/c/channels/${serverId}/${channelId}/${childChannelId}?seq=1&keep=child-seq`,
+ `/c/channels/${serverId}/${childChannelId}?seq=1&keep=child-seq`,
)
await expect.poll(() => new URL(page.url()).pathname).toBe(
- `/c/channels/${serverId}/${channelId}/${childChannelId}`,
+ `/c/channels/${serverId}/${childChannelId}`,
)
await expect.poll(() => new URL(page.url()).searchParams.has("seq")).toBe(false)
expect(new URL(page.url()).searchParams.get("keep")).toBe("child-seq")
await expect(page.getByRole("dialog").getByText("mobile child seq target")).toBeVisible()
})
+ test("a flat child derives Header Back from parent metadata", async ({ asUser }) => {
+ const { page } = await asUser("alice")
+ await page.goto(`/c/channels/${serverId}/${childChannelId}`)
+ await expect(
+ page.getByRole("banner").getByText("mobile-child", { exact: true }),
+ ).toBeVisible()
+
+ const historyLength = await page.evaluate(() => history.length)
+ await page.getByRole("button", { name: "Back" }).click()
+ await expect.poll(() => new URL(page.url()).pathname).toBe(
+ `/c/channels/${serverId}/${channelId}`,
+ )
+ expect(await page.evaluate(() => history.length)).toBe(historyLength)
+ })
+
test("Marked opens a child message on its canonical route without losing context", async ({ asUser }) => {
const { page } = await asUser("alice")
await page.goto("/c/me")
@@ -119,12 +134,39 @@ test.describe.serial("mobile layout", () => {
await page.getByText("mobile child seq target", { exact: true }).click()
await expect.poll(() => new URL(page.url()).pathname).toBe(
- `/c/channels/${serverId}/${channelId}/${childChannelId}`,
+ `/c/channels/${serverId}/${childChannelId}`,
)
await expect.poll(() => new URL(page.url()).searchParams.has("seq")).toBe(false)
await expect(page.getByRole("dialog").getByText("mobile child seq target")).toBeVisible()
})
+ test("rejects the removed nested route and clears nested last-channel memory", async ({ asUser }) => {
+ const { page } = await asUser("alice")
+ const response = await page.goto(
+ `/c/channels/${serverId}/${channelId}/${childChannelId}`,
+ )
+ expect(response?.status()).toBe(404)
+
+ await page.goto("/c/me")
+ await page.evaluate(
+ ([key, value]) => localStorage.setItem(key, value),
+ [`community:lastChannel:${serverId}`, `${channelId}/${childChannelId}`],
+ )
+ await page.setViewportSize({ width: 900, height: 844 })
+ await page.goto(`/c/channels/${serverId}`)
+ await expect.poll(() => {
+ const segments = new URL(page.url()).pathname.split("/").filter(Boolean)
+ return segments.length === 4 ? segments.at(-1) : null
+ }).not.toBeNull()
+ const selectedChannelId = new URL(page.url()).pathname.split("/").at(-1)
+ expect(selectedChannelId).not.toBe(childChannelId)
+ await expect(page.getByTestId(tid.composerInput)).toBeVisible()
+ await expect.poll(() => page.evaluate(
+ (key) => localStorage.getItem(key),
+ `community:lastChannel:${serverId}`,
+ )).toBe(selectedChannelId)
+ })
+
test("server-root modal markers are one-shot on mobile", async ({ asUser }) => {
for (const marker of ["settings", "invite"]) {
const { page } = await asUser("alice")
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 47c69d7d1..7f9bf7712 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
@@ -81,9 +81,8 @@ test.describe.serial("forum sidebar Stage B request shape", () => {
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 expect.poll(() => new URL(page.url()).pathname).toBe(
+ `/c/channels/${serverId}/${threadId}`,
)
await page.waitForTimeout(500)
expect(anchorRouteRequests).toBe(1)
@@ -91,7 +90,9 @@ test.describe.serial("forum sidebar Stage B request shape", () => {
releaseFirstAnchor()
}
await Promise.all([initialCombined, initialNewest, initialAnchored])
- await page.waitForURL(new RegExp(threadId), { timeout: 20_000, waitUntil: "commit" })
+ await expect.poll(() => new URL(page.url()).pathname).toBe(
+ `/c/channels/${serverId}/${threadId}`,
+ )
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)
@@ -121,6 +122,9 @@ test.describe.serial("forum sidebar Stage B request shape", () => {
)
await page.reload({ waitUntil: "commit" })
await refreshCombined
+ await expect.poll(() => new URL(page.url()).pathname).toBe(
+ `/c/channels/${serverId}/${threadId}`,
+ )
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)
@@ -148,7 +152,7 @@ test.describe.serial("forum sidebar Stage B request shape", () => {
.toBe(refreshSuccessfulMessageResponses.length)
})
- test("natural flat-route canonicalization preserves one settled message load", async ({ asUser }) => {
+ test("a flat child route preserves one settled message load", async ({ asUser }) => {
const { page } = await asUser("alice")
const successfulResponses: string[] = []
page.on("response", (response) => {
@@ -158,9 +162,8 @@ test.describe.serial("forum sidebar Stage B request shape", () => {
})
await page.goto(`/c/channels/${serverId}/${threadId}`)
- await page.waitForURL(
- new RegExp(`/c/channels/${serverId}/${forumId}/${threadId}(?:\\?|$)`),
- { timeout: 20_000, waitUntil: "commit" },
+ await expect.poll(() => new URL(page.url()).pathname).toBe(
+ `/c/channels/${serverId}/${threadId}`,
)
await expect(page.getByRole("heading", { name: forumTitle })).toBeVisible({ timeout: 20_000 })
await expect(page.getByText("post body", { exact: true })).toBeVisible({ timeout: 20_000 })
@@ -176,7 +179,7 @@ test.describe.serial("forum sidebar Stage B request shape", () => {
.toBeLessThanOrEqual(1)
})
- test("switching between top-level channels reuses the warm canonical base", async ({ asUser }) => {
+ test("sidebar top-level and child navigation reuse the warm flat base", async ({ asUser }) => {
const { page } = await asUser("alice")
const requests: string[] = []
page.on("request", (request) => {
@@ -189,6 +192,7 @@ test.describe.serial("forum sidebar Stage B request shape", () => {
await page.goto(`/c/channels/${serverId}/${textAId}`)
await initialCombined
await expect(page.getByTestId(tid.channelRow(textBId))).toBeVisible({ timeout: 20_000 })
+ await expect(page.getByTestId(tid.forumSidebarThread(threadId))).toBeVisible({ timeout: 20_000 })
requests.length = 0
await page.getByTestId(tid.channelRow(textBId)).click()
@@ -197,5 +201,22 @@ test.describe.serial("forum sidebar Stage B request shape", () => {
await page.waitForTimeout(300)
expect(requests.filter((url) => isSidebarRequest(url, serverId))).toHaveLength(0)
+
+ requests.length = 0
+ await page.getByTestId(tid.forumSidebarThread(threadId)).click()
+ await expect.poll(() => new URL(page.url()).pathname).toBe(
+ `/c/channels/${serverId}/${threadId}`,
+ )
+ await expect(page.getByRole("heading", { name: forumTitle })).toBeVisible({ timeout: 20_000 })
+ expect(requests.filter((url) => isSidebarRequest(url, serverId))).toHaveLength(0)
+
+ await page.goBack()
+ await expect.poll(() => new URL(page.url()).pathname).toBe(
+ `/c/channels/${serverId}/${textBId}`,
+ )
+ await page.goForward()
+ await expect.poll(() => new URL(page.url()).pathname).toBe(
+ `/c/channels/${serverId}/${threadId}`,
+ )
})
})