Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

perf(web): accelerate inbox conversation navigation (#695)

Gener710ca15b545c
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.ts b/src/web/src/app/api/community/channels/[id]/messages/route.ts
index 6c68a1fd9..b8e463a83 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/route.ts
@@ -82,6 +82,13 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
// old dm/[id]/messages route (which passed isDm:true explicitly).
const isDm = resolved.value.isDm
const isForum = resolved.value.target.kind === "forum"
+ // Transport-only proof for inbox navigation. The client validates this
+ // receipt against the requested target before any page reaches TanStack's
+ // cache; it must never be persisted as part of MessagesPage.
+ const surfaceReceipt = {
+ channelId,
+ surfaceKind: resolved.value.target.kind,
+ }
// TODO(route-disc): unify the two response projections.
// Auth/pagination-scope already single-source (one mask, one channel-scoped set);
@@ -138,7 +145,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
)
const { messages, latestSeq } = await enrichMessages(db, userId, { channelId, isDm, isForum }, items)
- return writeJSON({ messages, hasMoreOlder, hasMoreNewer, olderCursor, newerCursor, latestSeq })
+ return writeJSON({ messages, hasMoreOlder, hasMoreNewer, olderCursor, newerCursor, latestSeq, surfaceReceipt })
}
if (since) {
@@ -150,7 +157,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
})
const { items, hasMoreNewer, newerCursor, hasMoreOlder, olderCursor } = buildSinceResponse(rows, pageSize)
const { messages, latestSeq } = await enrichMessages(db, userId, { channelId, isDm, isForum }, items)
- return writeJSON({ messages, hasMoreNewer, newerCursor, hasMoreOlder, olderCursor, latestSeq })
+ return writeJSON({ messages, hasMoreNewer, newerCursor, hasMoreOlder, olderCursor, latestSeq, surfaceReceipt })
}
const rows = await queries.communityMessage.listMessages(db, {
@@ -162,7 +169,7 @@ export const GET = withCommunityActor(async (req: NextRequest, ctx) => {
const { items, hasMore, cursor: nextCursor } = buildPaginatedResponse(rows, pageSize)
const { messages, latestSeq } = await enrichMessages(db, userId, { channelId, isDm, isForum }, items.slice().reverse())
- return writeJSON({ messages, hasMore, cursor: nextCursor, latestSeq })
+ return writeJSON({ messages, hasMore, cursor: nextCursor, latestSeq, surfaceReceipt })
})
/**
diff --git a/src/web/src/app/c/me/[dmId]/page.test.ts b/src/web/src/app/c/me/[dmId]/page.test.ts
index 265655d7f..a61376784 100644
--- a/src/web/src/app/c/me/[dmId]/page.test.ts
+++ b/src/web/src/app/c/me/[dmId]/page.test.ts
@@ -7,7 +7,9 @@ describe("DM page loading ownership", () => {
expect(source).toContain("fullFramePending: !hasDm && dmsLoading")
expect(source).toContain("notFound: !hasDm && !dmsLoading")
expect(source).toContain("messageBodyLoading: hasDm && (")
- expect(source).toContain("readSnapshotFetching ||\n messagesLoading")
+ expect(source).not.toContain("readSnapshotFetching ||\n messagesLoading")
+ expect(source).toContain("waitForAnchor: true")
+ expect(source).toContain("if (navigationBlocked)")
expect(source).toContain("if (loadingOwnership.fullFramePending)")
expect(source).toContain("<DmHeader\n")
expect(source).toContain("<Composer\n")
diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsx
index 050574de8..dbdc6a93a 100644
--- a/src/web/src/app/c/me/[dmId]/page.tsx
+++ b/src/web/src/app/c/me/[dmId]/page.tsx
@@ -69,13 +69,11 @@ function resolveDmLoadingOwnership({
hasDm,
dmsLoading,
currentChannelMatches,
- readSnapshotFetching,
messagesLoading,
}: {
hasDm: boolean
dmsLoading: boolean
currentChannelMatches: boolean
- readSnapshotFetching: boolean
messagesLoading: boolean
}) {
return {
@@ -83,7 +81,6 @@ function resolveDmLoadingOwnership({
notFound: !hasDm && !dmsLoading,
messageBodyLoading: hasDm && (
!currentChannelMatches ||
- readSnapshotFetching ||
messagesLoading
),
}
@@ -142,7 +139,7 @@ function DmView() {
// gate treats `undefined` as "not-yet-decided" and stays disabled, so we
// don't fire a newest-mode fetch that would immediately be superseded.
const {
- messages,
+ messages: fetchedMessages,
isLoading: messagesLoading,
hasMoreOlder: hasMoreMessages,
hasMoreNewer: hasMoreNewerMessages,
@@ -156,11 +153,21 @@ function DmView() {
isPending: messagesPending,
isError: messagesError,
refetch: refetchMessages,
+ navigationBlocked,
} = useDmMessages(dmId, {
lastReadMessageId: readSnapshotFetching
? undefined
: (readSnapshot?.lastReadMessageId ?? null),
+ // Inbox clicks already start the canonical messages/read requests in
+ // parallel before routing. Keep the mounted DM route anchor-first so
+ // direct, sidebar, Back, and Forward navigation retain their frozen read
+ // pointer instead of briefly owning a newest request.
+ waitForAnchor: true,
+ reconcileLateAnchor: true,
+ revalidateOnMount: true,
+ viewerUserId: currentUser.id,
})
+ const messages = fetchedMessages
// Cross-navigation deep-link: a Marked-tab row for a DM message navigates
// here with `?seq=<n>` and we open the context sheet on that message. Read
@@ -441,10 +448,13 @@ function DmView() {
hasDm: !!dm,
dmsLoading,
currentChannelMatches: currentChannelId === dmId,
- readSnapshotFetching,
messagesLoading,
})
+ if (navigationBlocked) {
+ return <DmLoadingFrame reserveBackSlot={bp === "mobile"} />
+ }
+
if (loadingOwnership.fullFramePending) {
return <DmLoadingFrame reserveBackSlot={bp === "mobile"} />
}
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 9993e1ab0..82c8342b8 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
@@ -69,6 +69,10 @@ vi.mock("next/navigation", () => ({
usePathname: () => "/c/channels/server_1/channel_1",
useSearchParams: () => new URLSearchParams(mockSearchParams.value),
}))
+vi.mock("@tanstack/react-query", () => ({ useQueryClient: () => ({}) }))
+vi.mock("@/lib/community/conversation-navigation-proof", () => ({
+ useConversationNavigationGate: () => ({ required: false, allowed: true }),
+}))
vi.mock("sonner", () => ({ toast: vi.fn() }))
vi.mock("@/lib/api/client", () => ({ apiFetch: vi.fn(), toastApiError: vi.fn() }))
vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => mockBreakpoint.value }))
diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsx
index ce5f8baaf..7a58fd043 100644
--- a/src/web/src/components/community/channels/channel-route.tsx
+++ b/src/web/src/components/community/channels/channel-route.tsx
@@ -35,6 +35,9 @@ import {
useThreadOpenerRouteGate,
} from "@/hooks/community/thread-opener-read-handoff"
import { useThreadSplitMode } from "@/hooks/community/use-thread-split-mode"
+import { useQueryClient } from "@tanstack/react-query"
+import { useCommunityWsStore } from "@/stores/community/ws"
+import { useConversationNavigationGate } from "@/lib/community/conversation-navigation-proof"
const THREAD_VIEW_PARAM = "threadView"
@@ -65,6 +68,14 @@ export function ChannelRoute({ serverParam, channelId }: {
// refresh/back doesn't re-trigger the jump; this frozen copy still drives the
// anchor + scroll for this mount.
const [jumpTargetId] = useState<string | null>(() => searchParams.get("msg"))
+ const queryClient = useQueryClient()
+ const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)
+ const navigationGate = useConversationNavigationGate(
+ queryClient,
+ currentUser.id,
+ channelId,
+ accessEpoch,
+ )
const uiHandlers = useUiHandlers()
const currentChannelId = useCurrentChannelId()
const routeModel = useChannelRouteModel(serverId, serverParam, channelId, currentUser.id)
@@ -185,7 +196,8 @@ export function ChannelRoute({ serverParam, channelId }: {
const channelHydrated =
currentChannelId === channelId &&
routeModel.routeHydrated &&
- (!isForumPostChild || !forumPostOpener.isLoading)
+ (!isForumPostChild || !forumPostOpener.isLoading) &&
+ navigationGate.allowed
if (!channelHydrated) {
if (isForum) {
return (
diff --git a/src/web/src/components/community/shell/shell-frame-types.ts b/src/web/src/components/community/shell/shell-frame-types.ts
index 319c4b745..c0cc21242 100644
--- a/src/web/src/components/community/shell/shell-frame-types.ts
+++ b/src/web/src/components/community/shell/shell-frame-types.ts
@@ -14,6 +14,7 @@ export type ShellFrameProps = {
export type ShellRouter = {
push: (href: string) => void
+ pushImmediate?: (href: string) => void
replace: (href: string) => void
prefetch: (href: string) => void
}
diff --git a/src/web/src/components/community/shell/shell-frame.test.ts b/src/web/src/components/community/shell/shell-frame.test.ts
index f7bb7dacd..1ad1b6b2c 100644
--- a/src/web/src/components/community/shell/shell-frame.test.ts
+++ b/src/web/src/components/community/shell/shell-frame.test.ts
@@ -66,6 +66,12 @@ vi.mock("@/stores/community", () => ({
getState: () => ({ registerUiHandlers: mocks.registerUiHandlers }),
}),
}))
+vi.mock("@/stores/community/ws", () => ({
+ useCommunityWsStore: (selector: (state: { accessEpoch: number }) => unknown) => selector({ accessEpoch: 0 }),
+}))
+vi.mock("@/contexts/community/current-user", () => ({
+ useCurrentUser: () => ({ id: "viewer" }),
+}))
vi.mock("./use-shell-rail-controller", () => ({
useShellRailController: (options: unknown) => {
mocks.railOptions(options)
@@ -156,7 +162,7 @@ describe("ShellFrame orchestration", () => {
renderer = TestRenderer.create(createElement(ShellFrame, sourceProps))
})
expect(renderer.root.findByType("shell-frame-view").props.checkpoint).toMatchObject({
- surface: "detail",
+ surface: "list",
targetHref: "/c/channels/s1",
main: { kind: "keep" },
})
@@ -218,7 +224,7 @@ describe("ShellFrame orchestration", () => {
const view = renderer.root.findByType("shell-frame-view")
expect(view.props.checkpoint).toMatchObject({
mode: "warm-scope",
- surface: "detail",
+ surface: "list",
targetHref: "/c/channels/s2",
main: { kind: "keep" },
})
diff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsx
index 99f998232..d6fe2e51b 100644
--- a/src/web/src/components/community/shell/shell-frame.tsx
+++ b/src/web/src/components/community/shell/shell-frame.tsx
@@ -13,6 +13,8 @@ import {
} from "@/lib/community/community-route"
import { communityKeys } from "@/lib/query-keys"
import { useCommunityStore } from "@/stores/community"
+import { useCommunityWsStore } from "@/stores/community/ws"
+import { useCurrentUser } from "@/contexts/community/current-user"
import { ShellFrameView } from "./shell-frame-view"
import { useShellRailController } from "./use-shell-rail-controller"
import { useShellProfileController } from "./use-shell-profile-controller"
@@ -33,6 +35,8 @@ export function ShellFrame(props: ShellFrameProps) {
onOpenActiveServerInvite,
} = props
const queryClient = useQueryClient()
+ const currentUser = useCurrentUser()
+ const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)
const breakpoint = useBreakpoint()
const onboardingState = useCommunityOnboarding()
const initialCommittedFrame: CommunityCommittedFrame = {
@@ -98,6 +102,8 @@ export function ShellFrame(props: ShellFrameProps) {
publishedHref: navigation.publishedHref,
navigationPending: navigation.navigationPending,
pendingHref: navigation.pendingHref,
+ viewerId: currentUser.id,
+ accessEpoch,
})
const goBackMobile = useCallback(() => {
if (route.parentPath) navigation.replace(route.parentPath)
diff --git a/src/web/src/components/community/shell/use-community-navigation-controller.test.ts b/src/web/src/components/community/shell/use-community-navigation-controller.test.ts
index 1e553e48d..9bd079d05 100644
--- a/src/web/src/components/community/shell/use-community-navigation-controller.test.ts
+++ b/src/web/src/components/community/shell/use-community-navigation-controller.test.ts
@@ -10,11 +10,20 @@ const mocks = vi.hoisted(() => ({
push: vi.fn(),
replace: vi.fn(),
prefetch: vi.fn(),
+ cancelProof: vi.fn(),
+ queryClient: {},
frame: {
current: null as CommunityCommittedFrame | null,
},
}))
+vi.mock("@tanstack/react-query", () => ({
+ useQueryClient: () => mocks.queryClient,
+}))
+vi.mock("@/lib/community/conversation-navigation-proof", () => ({
+ cancelActiveConversationNavigationProof: (...args: unknown[]) => mocks.cancelProof(...args),
+}))
+
vi.mock("next/navigation", () => ({
usePathname: () => mocks.pathname.current,
useSearchParams: () => mocks.search.current,
@@ -56,6 +65,7 @@ describe("useCommunityNavigationController", () => {
mocks.push.mockReset()
mocks.replace.mockReset()
mocks.prefetch.mockReset()
+ mocks.cancelProof.mockReset()
mocks.frame.current = { ...normalizeCommunityHref("/c/me"), revision: 0 }
const windowTarget = new EventTarget() as EventTarget & { navigation: EventTarget }
windowTarget.navigation = new EventTarget()
@@ -73,6 +83,7 @@ describe("useCommunityNavigationController", () => {
expect(mocks.push).toHaveBeenCalledWith("/c/me/friends")
expect(hook.current.navigationPending).toBe(true)
expect(hook.current.pendingHref).toBe("/c/me/friends")
+ expect(mocks.cancelProof).toHaveBeenCalledWith(mocks.queryClient)
mocks.pathname.current = "/c/me/friends"
await hook.rerender()
@@ -116,6 +127,7 @@ describe("useCommunityNavigationController", () => {
expect(mocks.replace).toHaveBeenCalledWith("/c/channels/s1")
expect(mocks.push).not.toHaveBeenCalled()
expect(hook.current.pendingHref).toBe("/c/channels/s1")
+ expect(mocks.cancelProof).toHaveBeenCalledWith(mocks.queryClient)
})
it("keeps a same-server root intent pending until the exact root frame commits", async () => {
@@ -155,6 +167,8 @@ describe("useCommunityNavigationController", () => {
expect(hook.current.pendingHref).toBeNull()
expect(mocks.replace).not.toHaveBeenCalled()
expect(mocks.push).toHaveBeenCalledTimes(1)
+ expect(mocks.cancelProof).toHaveBeenCalledTimes(2)
+ await hook.unmount()
})
it("commits only the latest async destination", async () => {
@@ -179,6 +193,17 @@ describe("useCommunityNavigationController", () => {
expect(mocks.push).toHaveBeenCalledTimes(1)
expect(mocks.push).toHaveBeenCalledWith("/c/channels/s2/c2")
expect(hook.current.pendingHref).toBe("/c/channels/s2/c2")
+ expect(mocks.cancelProof).toHaveBeenCalledTimes(2)
+ })
+
+ it("settles an async resolver that returns the published destination", async () => {
+ const hook = await renderController()
+ await expect(act(async () => (
+ hook.current.resolveAndPush(async () => "/c/me")
+ ))).resolves.toBe(true)
+ expect(hook.current.navigationPending).toBe(false)
+ expect(hook.current.pendingHref).toBeNull()
+ expect(mocks.push).not.toHaveBeenCalled()
})
it("clears pending destination state on cancellation and async failure", async () => {
@@ -205,5 +230,13 @@ describe("useCommunityNavigationController", () => {
expect(mocks.push).not.toHaveBeenCalled()
expect(hook.current.navigationPending).toBe(false)
expect(hook.current.pendingHref).toBeNull()
+ expect(mocks.cancelProof).not.toHaveBeenCalled()
+ })
+
+ it("preserves the proof begun by an Inbox child handler", async () => {
+ const hook = await renderController()
+ await act(async () => hook.current.pushImmediate("/c/channels/s1/c1"))
+ expect(mocks.push).toHaveBeenCalledWith("/c/channels/s1/c1")
+ expect(mocks.cancelProof).not.toHaveBeenCalled()
})
})
diff --git a/src/web/src/components/community/shell/use-community-navigation-controller.ts b/src/web/src/components/community/shell/use-community-navigation-controller.ts
index 03253ef28..58894a944 100644
--- a/src/web/src/components/community/shell/use-community-navigation-controller.ts
+++ b/src/web/src/components/community/shell/use-community-navigation-controller.ts
@@ -1,7 +1,9 @@
"use client"
import { useCallback, useEffect, useRef, useState } from "react"
+import { flushSync } from "react-dom"
import { usePathname, useRouter, useSearchParams } from "next/navigation"
+import { useQueryClient } from "@tanstack/react-query"
import {
commitLatestNavigationIntent,
createNavigationIntentGate,
@@ -14,12 +16,14 @@ import {
type CommunityCommittedFrame,
} from "@/lib/community/community-route"
import type { ShellRouter } from "./shell-frame-types"
+import { cancelActiveConversationNavigationProof } from "@/lib/community/conversation-navigation-proof"
export type CommunityNavigationController = {
publishedHref: string
navigationPending: boolean
pendingHref: string | null
push: (href: string) => void
+ pushImmediate: (href: string) => void
replace: (href: string) => void
prefetch: (href: string) => void
resolveAndPush: (resolve: () => Promise<string>) => Promise<boolean>
@@ -34,6 +38,7 @@ export function useCommunityNavigationController(
const searchParams = useSearchParams()
const search = searchParams.toString()
const publishedHref = search ? `${pathname}?${search}` : pathname
+ const queryClient = useQueryClient()
const gateRef = useRef(createNavigationIntentGate())
const pendingBaselineRevisionRef = useRef(committedFrame.revision)
const pendingBaselineLeafRef = useRef(committedFrame.leafKey)
@@ -42,9 +47,10 @@ export function useCommunityNavigationController(
const cancelPendingNavigation = useCallback(() => {
supersedeNavigationIntent(gateRef.current)
+ cancelActiveConversationNavigationProof(queryClient)
setNavigationPending(false)
setPendingHref(null)
- }, [])
+ }, [queryClient])
useEffect(() => {
if (pendingHref === null) return
@@ -74,24 +80,41 @@ export function useCommunityNavigationController(
const push = useCallback((href: string) => {
if (href === publishedHref) return
supersedeNavigationIntent(gateRef.current)
+ cancelActiveConversationNavigationProof(queryClient)
pendingBaselineRevisionRef.current = committedFrame.revision
pendingBaselineLeafRef.current = committedFrame.leafKey
setNavigationPending(true)
setPendingHref(href)
router.push(href)
+ }, [committedFrame.leafKey, committedFrame.revision, publishedHref, queryClient, router])
+
+ const pushImmediate = useCallback((href: string) => {
+ if (href === publishedHref) return
+ supersedeNavigationIntent(gateRef.current)
+ pendingBaselineRevisionRef.current = committedFrame.revision
+ pendingBaselineLeafRef.current = committedFrame.leafKey
+ // Inbox promises a target checkpoint on the next paint. Publish it before
+ // Next starts the RSC transition instead of leaving it in the event batch.
+ flushSync(() => {
+ setNavigationPending(true)
+ setPendingHref(href)
+ })
+ router.push(href)
}, [committedFrame.leafKey, committedFrame.revision, publishedHref, router])
const replace = useCallback((href: string) => {
if (href === publishedHref) return
supersedeNavigationIntent(gateRef.current)
+ cancelActiveConversationNavigationProof(queryClient)
pendingBaselineRevisionRef.current = committedFrame.revision
pendingBaselineLeafRef.current = committedFrame.leafKey
setNavigationPending(true)
setPendingHref(href)
router.replace(href)
- }, [committedFrame.leafKey, committedFrame.revision, publishedHref, router])
+ }, [committedFrame.leafKey, committedFrame.revision, publishedHref, queryClient, router])
const resolveAndPush = useCallback(async (resolve: () => Promise<string>) => {
+ cancelActiveConversationNavigationProof(queryClient)
pendingBaselineRevisionRef.current = committedFrame.revision
pendingBaselineLeafRef.current = committedFrame.leafKey
setNavigationPending(true)
@@ -111,13 +134,14 @@ export function useCommunityNavigationController(
setPendingHref(null)
throw error
}
- }, [committedFrame.leafKey, committedFrame.revision, publishedHref, router])
+ }, [committedFrame.leafKey, committedFrame.revision, publishedHref, queryClient, router])
return {
publishedHref,
navigationPending,
pendingHref,
push,
+ pushImmediate,
replace,
prefetch: router.prefetch,
resolveAndPush,
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 b134b51a3..0941675b2 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
@@ -15,6 +15,8 @@ const mocks = vi.hoisted(() => ({
armOpener: vi.fn(),
clearOpener: vi.fn(),
terminateOpener: vi.fn(),
+ cancelProof: vi.fn(),
+ warmup: vi.fn(),
begin: vi.fn(),
submitted: vi.fn(),
rollback: vi.fn(),
@@ -91,6 +93,12 @@ vi.mock("@/hooks/community/mutations", () => ({
vi.mock("@/hooks/community/use-dm-route-verification", () => ({
startDmRouteVerification: (...args: unknown[]) => mocks.verifyDm(...args),
}))
+vi.mock("@/lib/community/conversation-navigation-warmup", () => ({
+ startConversationNavigationWarmup: (...args: unknown[]) => mocks.warmup(...args),
+}))
+vi.mock("@/lib/community/conversation-navigation-proof", () => ({
+ cancelConversationNavigationProof: (...args: unknown[]) => mocks.cancelProof(...args),
+}))
vi.mock("@/hooks/community/thread-opener-read-handoff", () => ({
armThreadOpenerReadHandoff: (...args: unknown[]) => mocks.armOpener(...args),
clearThreadOpenerReadHandoff: (...args: unknown[]) => mocks.clearOpener(...args),
@@ -169,6 +177,8 @@ describe("useShellInboxController", () => {
mocks.armOpener,
mocks.clearOpener,
mocks.terminateOpener,
+ mocks.cancelProof,
+ mocks.warmup,
mocks.begin,
mocks.submitted,
mocks.rollback,
@@ -197,6 +207,7 @@ describe("useShellInboxController", () => {
order.push("verify")
return Promise.resolve("present")
})
+ mocks.warmup.mockReturnValue(99)
})
it("keeps Marked lazy and latches it after first selection", async () => {
@@ -302,7 +313,7 @@ describe("useShellInboxController", () => {
order.length = 0
await act(async () => hook.current.popoverProps.onOpenMention?.(mention))
expect(order).toEqual(["project", "cancel", "clear", "push", "submitted"])
- expect(hook.pushed).toEqual(["/c/channels/s1/c1"])
+ expect(hook.pushed).toEqual(["/c/channels/s1/c1?msg=msg1"])
})
it("closes Marked without creating a projection", async () => {
@@ -312,12 +323,41 @@ describe("useShellInboxController", () => {
id: "mk1",
serverId: "s1",
channelId: "c1",
- m: { seq: 7 },
+ m: { id: "message-7", seq: 7 },
} as never))
expect(order).toEqual(["close", "cancel", "clear", "push"])
+ expect(hook.pushed).toEqual(["/c/channels/s1/c1?seq=7"])
+ expect(mocks.warmup).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
+ href: "/c/channels/s1/c1?seq=7",
+ anchorMessageId: "message-7",
+ }), undefined)
expect(mocks.begin).not.toHaveBeenCalled()
})
+ it("keeps the exact seq target for a DM Marked row", async () => {
+ const hook = await renderController()
+ await act(async () => hook.current.popoverProps.onOpenMarked?.({
+ id: "mk-dm",
+ serverId: null,
+ channelId: "dm1",
+ m: { id: "dm-message", seq: 9 },
+ } as never))
+ expect(hook.pushed).toEqual(["/c/me/dm1?seq=9"])
+ })
+
+ it("cancels the Marked proof and reopens Inbox when navigation throws", async () => {
+ const error = new Error("push failed")
+ const hook = await renderController(undefined, () => { throw error })
+ await expect(act(async () => hook.current.popoverProps.onOpenMarked?.({
+ id: "mk1",
+ serverId: "s1",
+ channelId: "c1",
+ m: { id: "message-7", seq: 7 },
+ } as never))).rejects.toThrow("push failed")
+ expect(mocks.cancelProof).toHaveBeenCalledWith(expect.anything(), 99)
+ expect(mocks.onOpenChange).toHaveBeenCalledWith(true)
+ })
+
it("rolls back and reopens the latest projection when push throws", async () => {
const error = new Error("push failed")
const hook = await renderController(undefined, () => { throw error })
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 93f72d689..0e661279a 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
@@ -29,6 +29,9 @@ import {
armThreadOpenerReadHandoff,
clearThreadOpenerReadHandoff,
} from "@/hooks/community/thread-opener-read-handoff"
+import { startConversationNavigationWarmup } from "@/lib/community/conversation-navigation-warmup"
+import type { ConversationNavigationTarget } from "@/lib/community/conversation-navigation-proof"
+import { cancelConversationNavigationProof } from "@/lib/community/conversation-navigation-proof"
type UnreadChannel = UnreadServer["channels"][number]
type UnreadChild = UnreadChannel["children"][number]
@@ -40,6 +43,8 @@ type Options = {
publishedHref: string
navigationPending: boolean
pendingHref: string | null
+ viewerId: string
+ accessEpoch: number
}
export function useShellInboxController({
@@ -49,7 +54,13 @@ export function useShellInboxController({
publishedHref,
navigationPending,
pendingHref,
+ viewerId,
+ accessEpoch,
}: Options) {
+ const pushInboxHref = useCallback((href: string) => {
+ if (router.pushImmediate) router.pushImmediate(href)
+ else router.push(href)
+ }, [router])
const inboxUnreads = useInboxUnreads()
const inboxMentions = useInboxMentions()
const unreadFeed = inboxUnreads.servers
@@ -87,18 +98,25 @@ export function useShellInboxController({
const pushProjected = useCallback((
target: InboxRowTarget,
destinationHref: string,
+ warmup: Omit<ConversationNavigationTarget, "href" | "viewerId">,
prepare?: () => string | void,
afterPush?: () => void,
) => {
const epoch = inbox.beginProjection(target, destinationHref)
cancelPendingNavigation()
clearThreadOpenerReadHandoff(queryClient)
+ const proofEpoch = startConversationNavigationWarmup(queryClient, {
+ ...warmup,
+ href: destinationHref,
+ viewerId,
+ }, accessEpoch)
let pushedHref = destinationHref
try {
pushedHref = prepare?.() ?? destinationHref
- router.push(pushedHref)
+ pushInboxHref(pushedHref)
if (inbox.markProjectionSubmitted(epoch)) afterPush?.()
} catch (error) {
+ cancelConversationNavigationProof(queryClient, proofEpoch)
const nonce = new URLSearchParams(pushedHref.split("?")[1] ?? "")
.get("inboxThreadOpener")
if (nonce) terminateThreadOpenerReservationHandoff(queryClient, nonce)
@@ -108,7 +126,7 @@ export function useShellInboxController({
}
throw error
}
- }, [cancelPendingNavigation, inbox, queryClient, router])
+ }, [accessEpoch, cancelPendingNavigation, inbox, pushInboxHref, queryClient, viewerId])
const openServerChannel = useCallback((
server: UnreadServer,
@@ -123,17 +141,31 @@ export function useShellInboxController({
const previousOpen = inbox.closeWithoutProjection()
cancelPendingNavigation()
clearThreadOpenerReadHandoff(queryClient)
+ const proofEpoch = startConversationNavigationWarmup(queryClient, {
+ href,
+ viewerId,
+ channelId: channel.channelId,
+ serverId: server.serverId,
+ scopeKind: "channel",
+ expectedSurfaceKind: channel.type === "forum" ? "forum" : "channel",
+ }, accessEpoch)
try {
- router.push(href)
+ pushInboxHref(href)
} catch (error) {
+ cancelConversationNavigationProof(queryClient, proofEpoch)
cancelPendingNavigation()
inbox.onOpenChange(previousOpen)
throw error
}
return
}
- pushProjected(target, href)
- }, [cancelPendingNavigation, inbox, pushProjected, queryClient, router])
+ pushProjected(target, href, {
+ channelId: channel.channelId,
+ serverId: server.serverId,
+ scopeKind: "channel",
+ expectedSurfaceKind: channel.type === "forum" ? "forum" : "channel",
+ })
+ }, [accessEpoch, cancelPendingNavigation, inbox, pushInboxHref, pushProjected, queryClient, viewerId])
const openThread = useCallback((
server: UnreadServer,
@@ -142,7 +174,12 @@ export function useShellInboxController({
) => {
const target = inboxThreadRowTarget(server, parent, child)
const href = channelHref(server.serverId, child.channelId)
- pushProjected(target, href, () => (
+ pushProjected(target, href, {
+ channelId: child.channelId,
+ serverId: server.serverId,
+ scopeKind: "channel",
+ expectedSurfaceKind: "thread",
+ }, () => (
child.openerMessageId
&& child.openerUnread === true
&& child.openerSeq !== undefined
@@ -165,20 +202,35 @@ export function useShellInboxController({
const href = marked.serverId
? `${channelHref(marked.serverId, marked.channelId)}${seqQuery}`
: `/c/me/${marked.channelId}${seqQuery}`
+ const proofEpoch = startConversationNavigationWarmup(queryClient, {
+ href,
+ viewerId,
+ channelId: marked.channelId,
+ ...(marked.serverId ? { serverId: marked.serverId } : {}),
+ scopeKind: marked.serverId ? "channel" : "dm",
+ ...(marked.serverId ? { anchorMessageId: marked.m.id } : {}),
+ ...(!marked.serverId ? { expectedSurfaceKind: "dm" as const } : {}),
+ }, accessEpoch)
try {
- router.push(href)
+ pushInboxHref(href)
} catch (error) {
+ cancelConversationNavigationProof(queryClient, proofEpoch)
cancelPendingNavigation()
inbox.onOpenChange(previousOpen)
throw error
}
- }, [cancelPendingNavigation, inbox, queryClient, router])
+ }, [accessEpoch, cancelPendingNavigation, inbox, pushInboxHref, queryClient, viewerId])
const openDm = useCallback((dm: UnreadDm) => {
const dmId = dm.channelId
pushProjected(
inboxDmRowTarget(dm),
`/c/me/${dmId}`,
+ {
+ channelId: dmId,
+ scopeKind: "dm",
+ expectedSurfaceKind: "dm",
+ },
() => {
queryClient.setQueryData(
communityKeys.dms(),
@@ -196,7 +248,13 @@ export function useShellInboxController({
const openMention = useCallback((mention: Mention) => {
const target = inboxMentionRowTarget(mention)
if (!target || !mention.serverId || !mention.channelId) return
- pushProjected(target, channelHref(mention.serverId, mention.channelId))
+ const href = `${channelHref(mention.serverId, mention.channelId)}?msg=${mention.m.id}`
+ pushProjected(target, href, {
+ channelId: mention.channelId,
+ serverId: mention.serverId,
+ scopeKind: "channel",
+ anchorMessageId: mention.m.id,
+ })
}, [pushProjected])
const popoverProps: ComponentProps<typeof InboxPopover> = {
diff --git a/src/web/src/hooks/community/use-channel-message-feed.ts b/src/web/src/hooks/community/use-channel-message-feed.ts
index 5182b67b5..7a0101e77 100644
--- a/src/web/src/hooks/community/use-channel-message-feed.ts
+++ b/src/web/src/hooks/community/use-channel-message-feed.ts
@@ -27,9 +27,15 @@ export function useChannelMessageFeed({
? undefined
: (readSnapshot?.lastReadMessageId ?? null),
anchorMessageId,
+ // Ordinary direct/sidebar mounts keep the established anchor-first
+ // contract. Inbox clicks get their independent newest/read/detail
+ // concurrency from startConversationNavigationWarmup before this route
+ // mounts; widening the route hook itself to newest-first changes every
+ // navigation source and can replace the read-centered window.
waitForAnchor: true,
reconcileLateAnchor: true,
revalidateOnMount: true,
+ viewerUserId,
})
const { newDividerBefore, anchorFound } = useMemo(() => {
if (!readSnapshot) return { newDividerBefore: undefined, anchorFound: false }
diff --git a/src/web/src/hooks/community/use-messages.test.ts b/src/web/src/hooks/community/use-messages.test.ts
index 5d6445ea5..bce455c3e 100644
--- a/src/web/src/hooks/community/use-messages.test.ts
+++ b/src/web/src/hooks/community/use-messages.test.ts
@@ -1,5 +1,7 @@
import { describe, it, expect, vi, beforeEach } from "vitest"
-import { QueryClient, type InfiniteData } from "@tanstack/react-query"
+import { createElement } from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { QueryClient, QueryClientProvider, type InfiniteData } from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
import type { Msg } from "@/lib/community/models/message"
@@ -75,6 +77,26 @@ describe("channelMessagesQueryFn — url per mode", () => {
})
describe("channelMessagesQueryFn — queryClient integration", () => {
+ it("validates the transport receipt before returning a cache-safe page", async () => {
+ const { channelMessagesQueryFn } = await loadHook()
+ const onSurfaceReceipt = vi.fn()
+ apiFetchMock.mockResolvedValueOnce({
+ messages: [],
+ hasMore: false,
+ surfaceReceipt: { channelId: "ch_1", surfaceKind: "channel" },
+ })
+
+ const page = await channelMessagesQueryFn("ch_1", null, { onSurfaceReceipt })({
+ pageParam: { mode: "newest" },
+ })
+
+ expect(onSurfaceReceipt).toHaveBeenCalledWith({
+ channelId: "ch_1",
+ surfaceKind: "channel",
+ })
+ expect(page).not.toHaveProperty("surfaceReceipt")
+ })
+
it("passes TanStack's AbortSignal to apiFetch", async () => {
const { channelMessagesQueryFn } = await loadHook()
const controller = new AbortController()
@@ -120,6 +142,26 @@ describe("channelMessagesQueryFn — queryClient integration", () => {
})
describe("dmMessagesQueryFn", () => {
+ it("strips the authoritative receipt before QueryClient storage", async () => {
+ const { dmMessagesQueryFn } = await loadHook()
+ apiFetchMock.mockResolvedValueOnce({
+ messages: [],
+ hasMore: false,
+ surfaceReceipt: { channelId: "dm_1", surfaceKind: "dm" },
+ })
+ const qc = new QueryClient()
+ const key = communityKeys.dmMessages("dm_1")
+
+ await qc.fetchInfiniteQuery({
+ queryKey: key,
+ queryFn: dmMessagesQueryFn("dm_1"),
+ initialPageParam: { mode: "newest" } as const,
+ })
+
+ const data = qc.getQueryData<InfiniteData<Record<string, unknown>>>(key)
+ expect(data?.pages[0]).not.toHaveProperty("surfaceReceipt")
+ })
+
it("passes TanStack's AbortSignal to apiFetch", async () => {
const { dmMessagesQueryFn } = await loadHook()
const controller = new AbortController()
@@ -174,6 +216,51 @@ describe("dmMessagesQueryFn", () => {
})
})
+describe("message hooks — canonical receipt forwarding", () => {
+ it("records transport receipts for mounted Channel and DM queries", async () => {
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true
+ const { useDmMessages, useMessages } = await loadHook()
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ })
+ apiFetchMock.mockImplementation(async (url: string) => ({
+ messages: [],
+ hasMore: false,
+ latestSeq: 0,
+ surfaceReceipt: url.includes("ch_receipt")
+ ? { channelId: "ch_receipt", surfaceKind: "channel" }
+ : { channelId: "dm_receipt", surfaceKind: "dm" },
+ }))
+
+ function CaptureReceipts() {
+ useMessages("ch_receipt", {
+ serverId: "server",
+ lastReadMessageId: null,
+ })
+ useDmMessages("dm_receipt", { lastReadMessageId: null })
+ return null
+ }
+
+ let renderer: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ createElement(CaptureReceipts),
+ ))
+ })
+ await act(async () => {
+ await vi.waitFor(() => {
+ expect(queryClient.getQueryState(communityKeys.channelMessages("ch_receipt"))?.status)
+ .toBe("success")
+ expect(queryClient.getQueryState(communityKeys.dmMessages("dm_receipt"))?.status)
+ .toBe("success")
+ })
+ })
+ act(() => renderer!.unmount())
+ })
+})
+
describe("messageMatchesTag", () => {
it("keeps untagged live rows out of tagged forum variants", async () => {
const { messageMatchesTag } = await loadHook()
diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.ts
index a2d669227..70dc166ec 100644
--- a/src/web/src/hooks/community/use-messages.ts
+++ b/src/web/src/hooks/community/use-messages.ts
@@ -21,6 +21,13 @@ import {
type MessageScope,
} from "@/lib/community/message-stream"
import { useMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
+import { useCommunityWsStore } from "@/stores/community/ws"
+import {
+ commitConversationNavigationProof,
+ recordConversationNavigationReceipt,
+ useConversationNavigationGate,
+} from "@/lib/community/conversation-navigation-proof"
+import type { MessageSurfaceReceipt } from "@/lib/community/conversation-navigation-proof"
/**
* Fetches paginated messages for a community channel.
@@ -42,6 +49,27 @@ import { useMessageOverlay, useMessageStreamStore } from "@/stores/community/mes
*/
export type { MessagesPage, MessagesPageParam } from "@/lib/community/models/message"
+export type { MessageSurfaceReceipt } from "@/lib/community/conversation-navigation-proof"
+
+type MessagesTransportPage = MessagesPage & {
+ surfaceReceipt?: MessageSurfaceReceipt
+}
+
+type MessagesTransportOptions = {
+ onSurfaceReceipt?: (receipt: MessageSurfaceReceipt) => void
+}
+
+function isMessageSurfaceReceipt(value: unknown): value is MessageSurfaceReceipt {
+ if (!value || typeof value !== "object") return false
+ const receipt = value as Partial<MessageSurfaceReceipt>
+ return typeof receipt.channelId === "string" && (
+ receipt.surfaceKind === "channel" ||
+ receipt.surfaceKind === "thread" ||
+ receipt.surfaceKind === "forum" ||
+ receipt.surfaceKind === "dm"
+ )
+}
+
function buildMessagesUrl(base: string, pageParam: MessagesPageParam, tag?: string | null): string {
const params = new URLSearchParams()
if (tag) params.set("tag", tag)
@@ -65,8 +93,25 @@ function buildMessagesUrl(base: string, pageParam: MessagesPageParam, tag?: stri
return qs ? `${base}?${qs}` : base
}
+async function fetchMessagesTransport(
+ url: string,
+ signal: AbortSignal | undefined,
+ options: MessagesTransportOptions | undefined,
+): Promise<MessagesPage> {
+ const transport = await apiFetchProfiles<MessagesTransportPage>(
+ url,
+ (page) => messageProfilePatches(page.messages),
+ signal ? { signal } : undefined,
+ )
+ const { surfaceReceipt, ...page } = transport
+ if (isMessageSurfaceReceipt(surfaceReceipt)) {
+ options?.onSurfaceReceipt?.(surfaceReceipt)
+ }
+ return page
+}
+
export const channelMessagesQueryFn =
- (channelId: string, tag?: string | null) =>
+ (channelId: string, tag?: string | null, options?: MessagesTransportOptions) =>
async ({
pageParam,
signal,
@@ -79,15 +124,11 @@ export const channelMessagesQueryFn =
pageParam,
tag,
)
- return apiFetchProfiles<MessagesPage>(
- url,
- (page) => messageProfilePatches(page.messages),
- signal ? { signal } : undefined,
- )
+ return fetchMessagesTransport(url, signal, options)
}
export const dmMessagesQueryFn =
- (dmId: string) =>
+ (dmId: string, options?: MessagesTransportOptions) =>
async ({
pageParam,
signal,
@@ -99,11 +140,7 @@ export const dmMessagesQueryFn =
`/api/community/channels/${dmId}/messages`,
pageParam,
)
- return apiFetchProfiles<MessagesPage>(
- url,
- (page) => messageProfilePatches(page.messages),
- signal ? { signal } : undefined,
- )
+ return fetchMessagesTransport(url, signal, options)
}
export function messageMatchesTag(message: Msg, tag?: string | null): boolean {
@@ -237,9 +274,12 @@ type MessagesReturn = Omit<UseInfiniteQueryResult<PageCache, Error>, "isLoading"
// below, which also folds in `!anchorResolved` so a disabled query (still
// waiting on the anchor snapshot) reports loading too.
isLoading: boolean
+ navigationBlocked: boolean
}
type MessagesOpts = {
+ /** Viewer identity used only by the ephemeral inbox-navigation paint gate. */
+ viewerUserId?: string
/** Server-side message-tag filter. Null/undefined means the complete set. */
tag?: string | null
/**
@@ -622,6 +662,7 @@ function useMessagesInner(
// painting can't strand the viewport at the top. A cold channel (empty
// cache) still shows the skeleton.
isLoading: query.isLoading || (!anchorResolved && messages.length === 0),
+ navigationBlocked: false,
messages,
latestSeq,
hasMoreOlder,
@@ -651,13 +692,23 @@ export function useMessages(
channelId: string | null,
opts: ChannelMessagesOpts,
): MessagesReturn {
+ const queryClient = useQueryClient()
+ const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)
const queryKey = useMemo(() => {
const baseKey = communityKeys.channelMessages(channelId ?? "__none__")
return opts.tag ? [...baseKey, "tag", opts.tag] as const : baseKey
}, [channelId, opts.tag])
const queryFn = useMemo(
- () => channelMessagesQueryFn(channelId ?? "__none__", opts.tag),
- [channelId, opts.tag],
+ () => channelMessagesQueryFn(channelId ?? "__none__", opts.tag, {
+ onSurfaceReceipt: (receipt) => {
+ recordConversationNavigationReceipt(
+ queryClient,
+ receipt,
+ accessEpoch,
+ )
+ },
+ }),
+ [accessEpoch, channelId, opts.tag, queryClient],
)
const base = useMessagesInner(
channelId,
@@ -689,7 +740,23 @@ export function useMessages(
messageMatchesTag(message, opts.tag)),
[canonicalBase, opts.tag, overlay],
)
- return { ...base, messages }
+ useEffect(() => {
+ if (!channelId || base.data === undefined) return
+ commitConversationNavigationProof(queryClient, channelId, accessEpoch)
+ }, [accessEpoch, base.data, base.dataUpdatedAt, channelId, queryClient])
+ const navigationGate = useConversationNavigationGate(
+ queryClient,
+ opts.viewerUserId ?? "__none__",
+ channelId ?? "__none__",
+ accessEpoch,
+ )
+ const gated = navigationGate.required && !navigationGate.allowed
+ return {
+ ...base,
+ messages: gated ? [] : messages,
+ isLoading: base.isLoading || gated,
+ navigationBlocked: gated,
+ }
}
/**
@@ -699,13 +766,23 @@ export function useDmMessages(
dmId: string | null,
opts?: MessagesOpts,
): MessagesReturn {
+ const queryClient = useQueryClient()
+ const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)
const queryKey = useMemo(
() => communityKeys.dmMessages(dmId ?? "__none__"),
[dmId],
)
const queryFn = useMemo(
- () => dmMessagesQueryFn(dmId ?? "__none__"),
- [dmId],
+ () => dmMessagesQueryFn(dmId ?? "__none__", {
+ onSurfaceReceipt: (receipt) => {
+ recordConversationNavigationReceipt(
+ queryClient,
+ receipt,
+ accessEpoch,
+ )
+ },
+ }),
+ [accessEpoch, dmId, queryClient],
)
const base = useMessagesInner(
dmId,
@@ -735,5 +812,21 @@ export function useDmMessages(
() => materializeMessageStream(canonicalBase, overlay),
[canonicalBase, overlay],
)
- return { ...base, messages }
+ useEffect(() => {
+ if (!dmId || base.data === undefined) return
+ commitConversationNavigationProof(queryClient, dmId, accessEpoch)
+ }, [accessEpoch, base.data, base.dataUpdatedAt, dmId, queryClient])
+ const navigationGate = useConversationNavigationGate(
+ queryClient,
+ opts?.viewerUserId ?? "__none__",
+ dmId ?? "__none__",
+ accessEpoch,
+ )
+ const gated = navigationGate.required && !navigationGate.allowed
+ return {
+ ...base,
+ messages: gated ? [] : messages,
+ isLoading: base.isLoading || gated,
+ navigationBlocked: gated,
+ }
}
diff --git a/src/web/src/hooks/community/use-servers.test.ts b/src/web/src/hooks/community/use-servers.test.ts
index ad8f76f6b..b02464df4 100644
--- a/src/web/src/hooks/community/use-servers.test.ts
+++ b/src/web/src/hooks/community/use-servers.test.ts
@@ -296,6 +296,34 @@ describe("useServer / serverQueryFn", () => {
], forumUnreadState: {} })
})
+ it("passes the navigation AbortSignal to every server-detail resource", async () => {
+ const identity = {
+ id: "srv_signal",
+ name: "Signal",
+ discriminator: "0001",
+ description: "",
+ icon: null,
+ ownerId: "u_1",
+ }
+ apiFetchMock.mockImplementation(async (url: string) => {
+ if (url === "/api/community/servers") return { servers: [identity] }
+ if (url.endsWith("/categories")) return { categories: [] }
+ if (url.endsWith("/channels")) return { channels: [] }
+ if (url.endsWith("/unreads")) return { channelIds: [] }
+ throw new Error(`unexpected ${url}`)
+ })
+ const controller = new AbortController()
+ const { serverQueryFn } = await import("./use-servers")
+ await serverQueryFn(new QueryClient(), "srv_signal", controller.signal)()
+
+ for (const path of ["categories", "channels", "unreads"]) {
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ `/api/community/servers/srv_signal/${path}`,
+ { signal: controller.signal },
+ )
+ }
+ })
+
it("resolves cold server detail without joining an in-flight rail replacement", async () => {
let releaseRail!: (value: {
servers: Array<{
diff --git a/src/web/src/hooks/community/use-servers.ts b/src/web/src/hooks/community/use-servers.ts
index 76c3b6f1a..98dacc10e 100644
--- a/src/web/src/hooks/community/use-servers.ts
+++ b/src/web/src/hooks/community/use-servers.ts
@@ -211,25 +211,30 @@ type UnreadResponse = {
async function resolveServerIdentity(
queryClient: QueryClient,
serverId: string,
+ signal?: AbortSignal,
): Promise<Server | undefined> {
const cached = queryClient
.getQueryData<ServersResponse>(communityKeys.servers())
?.servers.find((server) => server.id === serverId)
if (cached) return cached
- const fetched = await serversQueryFn()
+ const fetched = await serversQueryFn({ signal } as QueryFunctionContext)
return fetched.servers.find((server) => server.id === serverId)
}
export const serverQueryFn = (
queryClient: QueryClient,
serverId: string,
+ signal?: AbortSignal,
) => async (): Promise<ServerDetail> => {
+ const fetchResource = <T,>(path: string) => signal
+ ? apiFetch<T>(path, { signal })
+ : apiFetch<T>(path)
const [server, categoryData, channelData, unreadData] = await Promise.all([
- resolveServerIdentity(queryClient, serverId),
- apiFetch<{ categories: Array<Omit<Category, "channels"> & { serverId?: string }> }>(`/api/community/servers/${serverId}/categories`),
- apiFetch<{ channels: RawChannel[] }>(`/api/community/servers/${serverId}/channels`),
- apiFetch<UnreadResponse>(`/api/community/servers/${serverId}/unreads`),
+ resolveServerIdentity(queryClient, serverId, signal),
+ fetchResource<{ categories: Array<Omit<Category, "channels"> & { serverId?: string }> }>(`/api/community/servers/${serverId}/categories`),
+ fetchResource<{ channels: RawChannel[] }>(`/api/community/servers/${serverId}/channels`),
+ fetchResource<UnreadResponse>(`/api/community/servers/${serverId}/unreads`),
])
if (unreadData.stale) throw new Error("stale D1 read")
if (!server) throw new Error("server not found")
diff --git a/src/web/src/lib/community/community-route.test.ts b/src/web/src/lib/community/community-route.test.ts
index ce4fba6db..556ad747b 100644
--- a/src/web/src/lib/community/community-route.test.ts
+++ b/src/web/src/lib/community/community-route.test.ts
@@ -166,11 +166,11 @@ describe("community route", () => {
targetReady: true,
})).toEqual({
mode: "same-scope-leaf",
- surface: "list",
+ surface: "detail",
targetHref: "/c/channels/s1/c1",
rail: { kind: "keep" },
sidebar: { kind: "keep" },
- main: { kind: "keep" },
+ main: { kind: "target-skeleton", href: "/c/channels/s1/c1" },
})
})
diff --git a/src/web/src/lib/community/community-route.ts b/src/web/src/lib/community/community-route.ts
index f9b22f13b..5ef35738d 100644
--- a/src/web/src/lib/community/community-route.ts
+++ b/src/web/src/lib/community/community-route.ts
@@ -295,6 +295,8 @@ export function resolveCommunityCheckpointPlan({
}
const target = normalizeCommunityHref(targetHref)
+ const targetMainKind = resolveCommunityModulePlan(target.href).main.kind
+ const isConversationTarget = targetMainKind === "server-conversation" || targetMainKind === "dm"
if (target.scope.kind === "unknown" || target.leafKey === committedFrame.leafKey) {
return committedPlan(committedFrame, target.href)
}
@@ -302,11 +304,13 @@ export function resolveCommunityCheckpointPlan({
if (communityScopeEqual(committedFrame.scope, target.scope)) {
return {
mode: "same-scope-leaf",
- surface: committedFrame.surface,
+ surface: target.surface,
targetHref: target.href,
rail: { kind: "keep" },
sidebar: { kind: "keep" },
- main: { kind: "keep" },
+ main: isConversationTarget
+ ? { kind: "target-skeleton", href: target.href }
+ : { kind: "keep" },
}
}
@@ -314,6 +318,10 @@ export function resolveCommunityCheckpointPlan({
return {
...committedPlan(committedFrame, target.href),
mode: "warm-scope",
+ surface: target.surface,
+ main: isConversationTarget
+ ? { kind: "target-skeleton", href: target.href }
+ : { kind: "keep" },
}
}
diff --git a/src/web/src/lib/community/conversation-navigation-proof.test.ts b/src/web/src/lib/community/conversation-navigation-proof.test.ts
new file mode 100644
index 000000000..0cc28995b
--- /dev/null
+++ b/src/web/src/lib/community/conversation-navigation-proof.test.ts
@@ -0,0 +1,289 @@
+import { createElement } from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { renderToString } from "react-dom/server"
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
+import { QueryClient } from "@tanstack/react-query"
+import { communityKeys } from "@/lib/query-keys"
+import {
+ beginConversationNavigationProof,
+ cancelActiveConversationNavigationProof,
+ cancelConversationNavigationProof,
+ commitConversationNavigationProof,
+ failConversationNavigationProof,
+ getConversationNavigationProof,
+ isCurrentConversationNavigation,
+ recordConversationNavigationReceipt,
+ recoverConversationNavigationProof,
+ registerConversationNavigationRecovery,
+ useConversationNavigationGate,
+} from "./conversation-navigation-proof"
+
+const target = {
+ href: "/c/channels/s1/c1",
+ viewerId: "viewer",
+ channelId: "c1",
+ serverId: "s1",
+ scopeKind: "channel" as const,
+ expectedSurfaceKind: "channel" as const,
+}
+
+describe("conversation navigation proof", () => {
+ beforeEach(() => {
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true
+ })
+
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it("aborts and fences A when B supersedes it", () => {
+ const queryClient = new QueryClient()
+ const a = beginConversationNavigationProof(queryClient, target, 3)
+ const b = beginConversationNavigationProof(queryClient, {
+ ...target,
+ href: "/c/channels/s1/c2",
+ channelId: "c2",
+ }, 3)
+
+ expect(a.signal.aborted).toBe(true)
+ expect(b.signal.aborted).toBe(false)
+ expect(isCurrentConversationNavigation(queryClient, a.epoch, 3)).toBe(false)
+ expect(isCurrentConversationNavigation(queryClient, b.epoch, 3)).toBe(true)
+ expect(recordConversationNavigationReceipt(
+ queryClient,
+ { channelId: "c1", surfaceKind: "channel" },
+ 3,
+ a.epoch,
+ )).toBe(false)
+ expect(getConversationNavigationProof(queryClient)).toMatchObject({
+ epoch: b.epoch,
+ status: "warming",
+ target: { channelId: "c2" },
+ })
+ })
+
+ it("accepts only a matching fresh canonical surface receipt", () => {
+ const queryClient = new QueryClient()
+ const proof = beginConversationNavigationProof(queryClient, target, 7)
+
+ expect(recordConversationNavigationReceipt(
+ queryClient,
+ { channelId: "c1", surfaceKind: "dm" },
+ 7,
+ proof.epoch,
+ )).toBe(false)
+ expect(recordConversationNavigationReceipt(
+ queryClient,
+ { channelId: "c1", surfaceKind: "channel" },
+ 8,
+ proof.epoch,
+ )).toBe(false)
+ expect(recordConversationNavigationReceipt(
+ queryClient,
+ { channelId: "c1", surfaceKind: "channel" },
+ 7,
+ proof.epoch,
+ )).toBe(true)
+ expect(getConversationNavigationProof(queryClient)?.status).toBe("verified")
+ expect(commitConversationNavigationProof(queryClient, "c1", 7)).toBe(true)
+ expect(getConversationNavigationProof(queryClient)?.status).toBe("proven")
+ })
+
+ it("accepts forum authority, ignores duplicate receipts, and rejects wrong targets", () => {
+ const queryClient = new QueryClient()
+ const proof = beginConversationNavigationProof(queryClient, target, 2)
+
+ expect(recordConversationNavigationReceipt(
+ queryClient,
+ { channelId: "other", surfaceKind: "forum" },
+ 2,
+ proof.epoch,
+ )).toBe(false)
+ expect(recordConversationNavigationReceipt(
+ queryClient,
+ { channelId: "c1", surfaceKind: "forum" },
+ 2,
+ proof.epoch,
+ )).toBe(true)
+ expect(recordConversationNavigationReceipt(
+ queryClient,
+ { channelId: "c1", surfaceKind: "forum" },
+ 2,
+ proof.epoch,
+ )).toBe(true)
+ expect(commitConversationNavigationProof(queryClient, "c1", 2)).toBe(false)
+ expect(getConversationNavigationProof(queryClient)?.status).toBe("forum")
+ })
+
+ it("supports DM supersession and exact active-proof cancellation", async () => {
+ const queryClient = new QueryClient()
+ const cancel = vi.spyOn(queryClient, "cancelQueries")
+ const dmTarget = {
+ ...target,
+ href: "/c/me/d1",
+ channelId: "d1",
+ serverId: undefined,
+ scopeKind: "dm" as const,
+ expectedSurfaceKind: "dm" as const,
+ }
+ const first = beginConversationNavigationProof(queryClient, dmTarget, 1)
+ expect(cancelActiveConversationNavigationProof(new QueryClient())).toBe(false)
+ expect(cancelConversationNavigationProof(queryClient, first.epoch + 1)).toBeUndefined()
+ expect(cancelActiveConversationNavigationProof(queryClient)).toBe(true)
+ await vi.waitFor(() => expect(cancel).toHaveBeenCalledWith({
+ queryKey: communityKeys.dmMessages("d1"),
+ }))
+ expect(first.signal.aborted).toBe(true)
+ expect(getConversationNavigationProof(queryClient)).toBeNull()
+ expect(recordConversationNavigationReceipt(
+ queryClient,
+ { channelId: "d1", surfaceKind: "dm" },
+ 1,
+ first.epoch,
+ )).toBe(false)
+ })
+
+ it("cancels the prior DM query when a new proof supersedes it", async () => {
+ const queryClient = new QueryClient()
+ const cancel = vi.spyOn(queryClient, "cancelQueries")
+ const dmTarget = {
+ ...target,
+ href: "/c/me/d1",
+ channelId: "d1",
+ serverId: undefined,
+ scopeKind: "dm" as const,
+ expectedSurfaceKind: "dm" as const,
+ }
+ beginConversationNavigationProof(queryClient, dmTarget, 1)
+ beginConversationNavigationProof(queryClient, target, 1)
+
+ await vi.waitFor(() => expect(cancel).toHaveBeenCalledWith({
+ queryKey: communityKeys.dmMessages("d1"),
+ }))
+ })
+
+ it("cannot reuse an Inbox proof after ordinary navigation supersedes it", () => {
+ const queryClient = new QueryClient()
+ const inboxA = beginConversationNavigationProof(queryClient, target, 4)
+ expect(cancelActiveConversationNavigationProof(queryClient)).toBe(true)
+ expect(recordConversationNavigationReceipt(
+ queryClient,
+ { channelId: "c1", surfaceKind: "channel" },
+ 4,
+ inboxA.epoch,
+ )).toBe(false)
+ expect(getConversationNavigationProof(queryClient)).toBeNull()
+ })
+
+ it("registers and fences recovery by proof epoch", () => {
+ const queryClient = new QueryClient()
+ const first = beginConversationNavigationProof(queryClient, target, 3)
+ const restart = vi.fn()
+ expect(registerConversationNavigationRecovery(
+ queryClient,
+ first.epoch + 1,
+ restart,
+ )).toBe(false)
+ expect(registerConversationNavigationRecovery(queryClient, first.epoch, restart)).toBe(true)
+ expect(recoverConversationNavigationProof(queryClient, first.epoch, 3)).toBe(false)
+
+ failConversationNavigationProof(queryClient, first.epoch + 1, 3, false)
+ failConversationNavigationProof(queryClient, first.epoch, 3, false)
+ expect(recoverConversationNavigationProof(queryClient, first.epoch, 3)).toBe(true)
+ expect(restart).toHaveBeenCalledWith(3, 1)
+
+ const second = beginConversationNavigationProof(queryClient, target, 4, 1)
+ expect(recoverConversationNavigationProof(queryClient, first.epoch, 4)).toBe(false)
+ expect(registerConversationNavigationRecovery(queryClient, second.epoch, restart)).toBe(true)
+ expect(recoverConversationNavigationProof(queryClient, second.epoch, 5)).toBe(true)
+ expect(restart).toHaveBeenLastCalledWith(5, 0)
+ })
+
+ it("makes definitive denial terminal and clears recovery", () => {
+ const queryClient = new QueryClient()
+ const proof = beginConversationNavigationProof(queryClient, target, 6)
+ const restart = vi.fn()
+ registerConversationNavigationRecovery(queryClient, proof.epoch, restart)
+ failConversationNavigationProof(queryClient, proof.epoch, 6, true)
+
+ expect(proof.signal.aborted).toBe(true)
+ expect(getConversationNavigationProof(queryClient)?.status).toBe("denied")
+ expect(recoverConversationNavigationProof(queryClient, proof.epoch, 7)).toBe(false)
+ expect(restart).not.toHaveBeenCalled()
+ })
+
+ it("recovers access drift immediately and transient failure after bounded backoff", async () => {
+ vi.useFakeTimers()
+ const queryClient = new QueryClient()
+ const restart = vi.fn()
+ const proof = beginConversationNavigationProof(queryClient, target, 7)
+ registerConversationNavigationRecovery(queryClient, proof.epoch, restart)
+ let latestGate: { required: boolean; allowed: boolean } | undefined
+
+ function Gate({ accessEpoch }: { accessEpoch: number }) {
+ latestGate = useConversationNavigationGate(queryClient, "viewer", "c1", accessEpoch)
+ return null
+ }
+
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(Gate, { accessEpoch: 8 }))
+ })
+ expect(latestGate).toEqual({ required: true, allowed: false })
+ expect(restart).toHaveBeenCalledWith(8, 0)
+
+ const retry = beginConversationNavigationProof(queryClient, target, 8, 2)
+ registerConversationNavigationRecovery(queryClient, retry.epoch, restart)
+ failConversationNavigationProof(queryClient, retry.epoch, 8, false)
+ await act(async () => {
+ renderer.update(createElement(Gate, { accessEpoch: 8 }))
+ })
+ expect(restart).toHaveBeenCalledTimes(1)
+ await act(async () => {
+ vi.advanceTimersByTime(999)
+ })
+ expect(restart).toHaveBeenCalledTimes(1)
+ await act(async () => {
+ vi.advanceTimersByTime(1)
+ })
+ expect(restart).toHaveBeenLastCalledWith(8, 3)
+ await act(async () => renderer.unmount())
+ })
+
+ it("consumes successful proof after the first authorized paint", async () => {
+ const queryClient = new QueryClient()
+ const proof = beginConversationNavigationProof(queryClient, target, 9)
+ recordConversationNavigationReceipt(
+ queryClient,
+ { channelId: "c1", surfaceKind: "channel" },
+ 9,
+ proof.epoch,
+ )
+ commitConversationNavigationProof(queryClient, "c1", 9)
+ const gates: Array<{ required: boolean; allowed: boolean }> = []
+
+ function Gate() {
+ gates.push(useConversationNavigationGate(queryClient, "viewer", "c1", 9))
+ return null
+ }
+
+ let renderer!: TestRenderer.ReactTestRenderer
+ await act(async () => {
+ renderer = TestRenderer.create(createElement(Gate))
+ })
+ expect(gates).toContainEqual({ required: true, allowed: true })
+ expect(getConversationNavigationProof(queryClient)).toBeNull()
+ await act(async () => renderer.unmount())
+ })
+
+ it("keeps the server snapshot proof-free", () => {
+ const queryClient = new QueryClient()
+
+ function Gate() {
+ const gate = useConversationNavigationGate(queryClient, "viewer", "c1", 1)
+ return createElement("span", null, `${gate.required}:${gate.allowed}`)
+ }
+
+ expect(renderToString(createElement(Gate))).toContain("false:true")
+ })
+})
diff --git a/src/web/src/lib/community/conversation-navigation-proof.ts b/src/web/src/lib/community/conversation-navigation-proof.ts
new file mode 100644
index 000000000..14bf44cbf
--- /dev/null
+++ b/src/web/src/lib/community/conversation-navigation-proof.ts
@@ -0,0 +1,295 @@
+"use client"
+
+import { useEffect, useSyncExternalStore } from "react"
+import type { QueryClient } from "@tanstack/react-query"
+import { communityKeys } from "@/lib/query-keys"
+
+export type MessageSurfaceReceipt = {
+ channelId: string
+ surfaceKind: "channel" | "thread" | "forum" | "dm"
+}
+
+export type ConversationNavigationTarget = {
+ href: string
+ viewerId: string
+ channelId: string
+ serverId?: string
+ scopeKind: "channel" | "dm"
+ expectedSurfaceKind?: MessageSurfaceReceipt["surfaceKind"]
+ anchorMessageId?: string
+}
+
+type ProofStatus = "warming" | "verified" | "proven" | "forum" | "denied" | "failed"
+
+export type ConversationNavigationProof = {
+ epoch: number
+ accessEpoch: number
+ recoveryAttempt: number
+ target: ConversationNavigationTarget
+ status: ProofStatus
+}
+
+type ConversationNavigationRecovery = (
+ accessEpoch: number,
+ recoveryAttempt: number,
+) => void
+
+type ProofStore = {
+ nextEpoch: number
+ activeEpoch: number
+ activeAccessEpoch: number
+ activeTarget: ConversationNavigationTarget | null
+ proof: ConversationNavigationProof | null
+ controller: AbortController | null
+ recovery: { epoch: number; restart: ConversationNavigationRecovery } | null
+ listeners: Set<() => void>
+}
+
+const stores = new WeakMap<QueryClient, ProofStore>()
+
+function getStore(queryClient: QueryClient): ProofStore {
+ let store = stores.get(queryClient)
+ if (!store) {
+ store = {
+ nextEpoch: 0,
+ activeEpoch: 0,
+ activeAccessEpoch: 0,
+ activeTarget: null,
+ proof: null,
+ controller: null,
+ recovery: null,
+ listeners: new Set(),
+ }
+ stores.set(queryClient, store)
+ }
+ return store
+}
+
+function publish(store: ProofStore, proof: ConversationNavigationProof | null) {
+ store.proof = proof
+ for (const listener of store.listeners) listener()
+}
+
+export function beginConversationNavigationProof(
+ queryClient: QueryClient,
+ target: ConversationNavigationTarget,
+ accessEpoch: number,
+ recoveryAttempt = 0,
+): { epoch: number; signal: AbortSignal } {
+ const store = getStore(queryClient)
+ if (store.activeTarget) {
+ const previousKey = store.activeTarget.scopeKind === "dm"
+ ? communityKeys.dmMessages(store.activeTarget.channelId)
+ : communityKeys.channelMessages(store.activeTarget.channelId)
+ void queryClient.cancelQueries({ queryKey: previousKey })
+ }
+ store.controller?.abort()
+ const controller = new AbortController()
+ const epoch = ++store.nextEpoch
+ store.activeEpoch = epoch
+ store.activeAccessEpoch = accessEpoch
+ store.activeTarget = target
+ store.controller = controller
+ store.recovery = null
+ publish(store, { epoch, accessEpoch, recoveryAttempt, target, status: "warming" })
+ return { epoch, signal: controller.signal }
+}
+
+export function registerConversationNavigationRecovery(
+ queryClient: QueryClient,
+ epoch: number,
+ restart: ConversationNavigationRecovery,
+) {
+ const store = getStore(queryClient)
+ if (store.activeEpoch !== epoch || store.proof?.epoch !== epoch) return false
+ store.recovery = { epoch, restart }
+ return true
+}
+
+export function recoverConversationNavigationProof(
+ queryClient: QueryClient,
+ epoch: number,
+ accessEpoch: number,
+) {
+ const store = getStore(queryClient)
+ const proof = store.proof
+ const recovery = store.recovery
+ if (
+ !proof ||
+ proof.epoch !== epoch ||
+ proof.status === "denied" ||
+ (proof.status !== "failed" && proof.accessEpoch === accessEpoch) ||
+ !recovery ||
+ recovery.epoch !== epoch
+ ) return false
+ const recoveryAttempt = proof.accessEpoch === accessEpoch
+ ? proof.recoveryAttempt + 1
+ : 0
+ recovery.restart(accessEpoch, recoveryAttempt)
+ return true
+}
+
+export function isCurrentConversationNavigation(
+ queryClient: QueryClient,
+ epoch: number,
+ accessEpoch: number,
+): boolean {
+ const store = getStore(queryClient)
+ return store.activeEpoch === epoch && store.activeAccessEpoch === accessEpoch
+}
+
+export function recordConversationNavigationReceipt(
+ queryClient: QueryClient,
+ receipt: MessageSurfaceReceipt,
+ accessEpoch: number,
+ epoch?: number,
+): boolean {
+ const store = getStore(queryClient)
+ const proof = store.proof
+ if (
+ !proof ||
+ proof.status === "denied" ||
+ (epoch !== undefined && proof.epoch !== epoch) ||
+ proof.accessEpoch !== accessEpoch ||
+ proof.target.channelId !== receipt.channelId ||
+ (proof.target.scopeKind === "dm"
+ ? receipt.surfaceKind !== "dm"
+ : receipt.surfaceKind === "dm")
+ ) {
+ return false
+ }
+ if (proof.status === "proven" || proof.status === "verified" || proof.status === "forum") {
+ return true
+ }
+ publish(store, {
+ ...proof,
+ status: receipt.surfaceKind === "forum" ? "forum" : "verified",
+ })
+ return true
+}
+
+export function commitConversationNavigationProof(
+ queryClient: QueryClient,
+ channelId: string,
+ accessEpoch: number,
+) {
+ const store = getStore(queryClient)
+ const proof = store.proof
+ if (
+ proof?.status !== "verified" ||
+ proof.target.channelId !== channelId ||
+ proof.accessEpoch !== accessEpoch
+ ) return false
+ publish(store, { ...proof, status: "proven" })
+ return true
+}
+
+export function failConversationNavigationProof(
+ queryClient: QueryClient,
+ epoch: number,
+ accessEpoch: number,
+ definitive: boolean,
+) {
+ const store = getStore(queryClient)
+ const proof = store.proof
+ if (proof?.epoch !== epoch || proof.accessEpoch !== accessEpoch) return
+ if (definitive) {
+ store.controller?.abort()
+ store.activeEpoch = ++store.nextEpoch
+ store.recovery = null
+ }
+ publish(store, { ...proof, status: definitive ? "denied" : "failed" })
+}
+
+function consumeConversationNavigationProof(
+ queryClient: QueryClient,
+ epoch: number,
+) {
+ const store = getStore(queryClient)
+ if (store.proof?.epoch !== epoch) return
+ store.recovery = null
+ publish(store, null)
+}
+
+export function cancelConversationNavigationProof(
+ queryClient: QueryClient,
+ epoch: number,
+) {
+ const store = getStore(queryClient)
+ if (store.activeEpoch !== epoch) return
+ if (store.activeTarget) {
+ const queryKey = store.activeTarget.scopeKind === "dm"
+ ? communityKeys.dmMessages(store.activeTarget.channelId)
+ : communityKeys.channelMessages(store.activeTarget.channelId)
+ void queryClient.cancelQueries({ queryKey })
+ }
+ store.controller?.abort()
+ store.controller = null
+ store.recovery = null
+ store.activeEpoch = ++store.nextEpoch
+ store.activeTarget = null
+ publish(store, null)
+}
+
+export function cancelActiveConversationNavigationProof(queryClient: QueryClient) {
+ const store = getStore(queryClient)
+ if (!store.proof) return false
+ cancelConversationNavigationProof(queryClient, store.activeEpoch)
+ return true
+}
+
+export function getConversationNavigationProof(
+ queryClient: QueryClient,
+): ConversationNavigationProof | null {
+ return getStore(queryClient).proof
+}
+
+export function useConversationNavigationGate(
+ queryClient: QueryClient,
+ viewerId: string,
+ channelId: string,
+ accessEpoch: number,
+): { required: boolean; allowed: boolean } {
+ const store = getStore(queryClient)
+ const proof = useSyncExternalStore(
+ (listener) => {
+ store.listeners.add(listener)
+ return () => store.listeners.delete(listener)
+ },
+ () => store.proof,
+ () => null,
+ )
+ const matching = proof?.target.viewerId === viewerId
+ && proof.target.channelId === channelId
+ const required = matching === true
+ const allowed = !required || (
+ proof.accessEpoch === accessEpoch
+ && (proof.status === "proven" || proof.status === "forum")
+ )
+
+ useEffect(() => {
+ if (!proof || !matching || proof.status === "denied") return
+ if (proof.accessEpoch !== accessEpoch) {
+ recoverConversationNavigationProof(queryClient, proof.epoch, accessEpoch)
+ return
+ }
+ if (proof.status !== "failed") return
+ const delay = Math.min(250 * (2 ** proof.recoveryAttempt), 5_000)
+ const timeout = setTimeout(() => {
+ recoverConversationNavigationProof(queryClient, proof.epoch, accessEpoch)
+ }, delay)
+ return () => clearTimeout(timeout)
+ }, [accessEpoch, matching, proof, queryClient])
+
+ useEffect(() => {
+ if (
+ !proof ||
+ !matching ||
+ (proof.status !== "proven" && proof.status !== "forum") ||
+ proof.accessEpoch !== accessEpoch
+ ) return
+ consumeConversationNavigationProof(queryClient, proof.epoch)
+ }, [accessEpoch, matching, proof, queryClient])
+
+ return { required, allowed }
+}
diff --git a/src/web/src/lib/community/conversation-navigation-warmup.test.ts b/src/web/src/lib/community/conversation-navigation-warmup.test.ts
new file mode 100644
index 000000000..39bb61730
--- /dev/null
+++ b/src/web/src/lib/community/conversation-navigation-warmup.test.ts
@@ -0,0 +1,297 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { QueryClient } from "@tanstack/react-query"
+import { ApiError } from "@/lib/errors"
+import { communityKeys } from "@/lib/query-keys"
+import {
+ getConversationNavigationProof,
+ recoverConversationNavigationProof,
+} from "./conversation-navigation-proof"
+import { startConversationNavigationWarmup } from "./conversation-navigation-warmup"
+
+type SurfaceKind = "channel" | "thread" | "forum" | "dm"
+type Page = { messages: never[]; hasMore: boolean }
+
+const mocks = vi.hoisted(() => ({
+ requests: [] as Array<{
+ channelId: string
+ kind: "channel" | "dm"
+ pageParam: unknown
+ signal: AbortSignal | undefined
+ receipt: (value: { channelId: string; surfaceKind: SurfaceKind }) => void
+ resolve: (value: Page) => void
+ reject: (error: unknown) => void
+ }>,
+ reads: [] as Array<{
+ url: string
+ signal: AbortSignal | undefined
+ resolve: (value: { lastReadMessageId: string | null; lastReadAt: string | null; lastReadSeq: number }) => void
+ reject: (error: unknown) => void
+ }>,
+ servers: [] as Array<{
+ serverId: string
+ signal: AbortSignal | undefined
+ resolve: (value: { id: string }) => void
+ reject: (error: unknown) => void
+ }>,
+ removeScope: vi.fn(),
+ apiFetch: vi.fn(),
+}))
+
+vi.mock("@/hooks/community/use-messages", () => ({
+ channelMessagesQueryFn: (
+ channelId: string,
+ _tag: null,
+ options: { onSurfaceReceipt: (value: { channelId: string; surfaceKind: SurfaceKind }) => void },
+ ) => ({ pageParam, signal }: { pageParam: unknown; signal?: AbortSignal }) => new Promise((resolve, reject) => {
+ mocks.requests.push({
+ channelId,
+ kind: "channel",
+ pageParam,
+ signal,
+ receipt: options.onSurfaceReceipt,
+ resolve: resolve as (value: Page) => void,
+ reject,
+ })
+ }),
+ dmMessagesQueryFn: (
+ channelId: string,
+ options: { onSurfaceReceipt: (value: { channelId: string; surfaceKind: SurfaceKind }) => void },
+ ) => ({ pageParam, signal }: { pageParam: unknown; signal?: AbortSignal }) => new Promise((resolve, reject) => {
+ mocks.requests.push({
+ channelId,
+ kind: "dm",
+ pageParam,
+ signal,
+ receipt: options.onSurfaceReceipt,
+ resolve: resolve as (value: Page) => void,
+ reject,
+ })
+ }),
+}))
+vi.mock("@/hooks/community/use-servers", () => ({
+ serverQueryFn: (_queryClient: unknown, serverId: string, signal?: AbortSignal) => () => (
+ new Promise((resolve, reject) => {
+ mocks.servers.push({
+ serverId,
+ signal,
+ resolve: resolve as (value: { id: string }) => void,
+ reject,
+ })
+ })
+ ),
+}))
+vi.mock("@/lib/api/client", () => ({
+ apiFetch: (url: string, options?: { signal?: AbortSignal }) => {
+ mocks.apiFetch(url, options)
+ return new Promise((resolve, reject) => {
+ mocks.reads.push({
+ url,
+ signal: options?.signal,
+ resolve: resolve as (value: {
+ lastReadMessageId: string | null
+ lastReadAt: string | null
+ lastReadSeq: number
+ }) => void,
+ reject,
+ })
+ })
+ },
+}))
+vi.mock("@/stores/community/message-stream", () => ({
+ useMessageStreamStore: { getState: () => ({ removeScope: mocks.removeScope }) },
+}))
+
+const target = (channelId: string) => ({
+ href: `/c/channels/s1/${channelId}`,
+ viewerId: "viewer",
+ channelId,
+ serverId: "s1",
+ scopeKind: "channel" as const,
+})
+
+describe("conversation navigation warmup", () => {
+ beforeEach(() => {
+ mocks.requests.length = 0
+ mocks.reads.length = 0
+ mocks.servers.length = 0
+ mocks.removeScope.mockReset()
+ mocks.apiFetch.mockReset()
+ })
+
+ it("starts canonical work in parallel and prevents superseded A from seeding", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ startConversationNavigationWarmup(queryClient, target("a"), 4)
+ startConversationNavigationWarmup(queryClient, target("b"), 4)
+ expect(mocks.requests.map((request) => request.channelId)).toEqual(["a", "b"])
+ expect(mocks.apiFetch).toHaveBeenCalledTimes(2)
+ expect(mocks.servers).toHaveLength(2)
+ expect(mocks.requests[0]!.signal?.aborted).toBe(true)
+ expect(mocks.reads[0]!.signal?.aborted).toBe(true)
+ expect(mocks.servers[0]!.signal?.aborted).toBe(true)
+
+ mocks.requests[0]!.receipt({ channelId: "a", surfaceKind: "channel" })
+ mocks.requests[0]!.resolve({ messages: [], hasMore: false })
+ mocks.requests[1]!.receipt({ channelId: "b", surfaceKind: "channel" })
+ mocks.requests[1]!.resolve({ messages: [], hasMore: false })
+ await vi.waitFor(() => {
+ expect(queryClient.getQueryData(communityKeys.channelMessages("b"))).toBeDefined()
+ })
+
+ expect(queryClient.getQueryData(communityKeys.channelMessages("a"))).toBeUndefined()
+ expect(getConversationNavigationProof(queryClient)).toMatchObject({
+ status: "proven",
+ target: { channelId: "b" },
+ })
+ })
+
+ it("clears target caches and overlays on definitive denial", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ queryClient.setQueryData(communityKeys.channelMessages("denied"), { stale: true })
+ queryClient.setQueryData(communityKeys.channelReadStateSnapshot("denied"), { stale: true })
+ queryClient.setQueryData(communityKeys.channelMeta("s1", "denied"), { stale: true })
+ startConversationNavigationWarmup(queryClient, target("denied"), 9)
+ mocks.requests[0]!.reject(new ApiError("not found", 404))
+ await vi.waitFor(() => {
+ expect(getConversationNavigationProof(queryClient)?.status).toBe("denied")
+ })
+
+ expect(queryClient.getQueryData(communityKeys.channelMessages("denied"))).toBeUndefined()
+ expect(queryClient.getQueryData(communityKeys.channelReadStateSnapshot("denied"))).toBeUndefined()
+ expect(queryClient.getQueryData(communityKeys.channelMeta("s1", "denied"))).toBeUndefined()
+ expect(mocks.removeScope).toHaveBeenCalledWith({
+ kind: "channel",
+ id: "denied",
+ serverId: "s1",
+ })
+ expect(getConversationNavigationProof(queryClient)?.status).toBe("denied")
+ expect(mocks.reads[0]!.signal?.aborted).toBe(true)
+ expect(mocks.servers[0]!.signal?.aborted).toBe(true)
+
+ mocks.reads[0]!.resolve({ lastReadMessageId: "late", lastReadAt: null, lastReadSeq: 1 })
+ mocks.servers[0]!.resolve({ id: "late" })
+ await Promise.resolve()
+ expect(queryClient.getQueryData(communityKeys.channelReadStateSnapshot("denied"))).toBeUndefined()
+ expect(queryClient.getQueryData(communityKeys.server("s1"))).toBeUndefined()
+ })
+
+ it("clears DM caches and overlay without starting server detail on denial", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const dmTarget = {
+ href: "/c/me/d1",
+ viewerId: "viewer",
+ channelId: "d1",
+ scopeKind: "dm" as const,
+ expectedSurfaceKind: "dm" as const,
+ }
+ queryClient.setQueryData(communityKeys.dmMessages("d1"), { stale: true })
+ queryClient.setQueryData(communityKeys.dmReadStateSnapshot("d1"), { stale: true })
+ queryClient.setQueryData(communityKeys.dmRouteVerification("d1"), "present")
+ startConversationNavigationWarmup(queryClient, dmTarget, 2)
+ expect(mocks.requests[0]).toMatchObject({ kind: "dm", pageParam: { mode: "newest" } })
+ expect(mocks.servers).toHaveLength(0)
+ mocks.requests[0]!.reject(new ApiError("forbidden", 403))
+ await vi.waitFor(() => {
+ expect(getConversationNavigationProof(queryClient)?.status).toBe("denied")
+ })
+
+ expect(queryClient.getQueryData(communityKeys.dmMessages("d1"))).toBeUndefined()
+ expect(queryClient.getQueryData(communityKeys.dmReadStateSnapshot("d1"))).toBeUndefined()
+ expect(queryClient.getQueryData(communityKeys.dmRouteVerification("d1"))).toBeUndefined()
+ expect(mocks.removeScope).toHaveBeenCalledWith({ kind: "dm", id: "d1" })
+ expect(mocks.reads[0]!.signal?.aborted).toBe(true)
+ mocks.reads[0]!.resolve({ lastReadMessageId: "late", lastReadAt: null, lastReadSeq: 8 })
+ await Promise.resolve()
+ expect(queryClient.getQueryData(communityKeys.dmReadStateSnapshot("d1"))).toBeUndefined()
+ })
+
+ it("commits a successful DM receipt", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ startConversationNavigationWarmup(queryClient, {
+ href: "/c/me/d2",
+ viewerId: "viewer",
+ channelId: "d2",
+ scopeKind: "dm",
+ expectedSurfaceKind: "dm",
+ }, 3)
+ mocks.requests[0]!.receipt({ channelId: "d2", surfaceKind: "dm" })
+ mocks.requests[0]!.resolve({ messages: [], hasMore: false })
+ await vi.waitFor(() => {
+ expect(getConversationNavigationProof(queryClient)?.status).toBe("proven")
+ })
+ })
+
+ it("restarts canonical messages after transient failure without exposing stale cache", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const key = communityKeys.channelMessages("retry")
+ queryClient.setQueryData(key, { pages: [{ messages: [{ id: "stale" }] }], pageParams: [] })
+ const epoch = startConversationNavigationWarmup(queryClient, target("retry"), 5)
+ mocks.requests[0]!.reject(new Error("network"))
+ await vi.waitFor(() => {
+ expect(getConversationNavigationProof(queryClient)?.status).toBe("failed")
+ })
+ expect(queryClient.getQueryData(key)).toBeDefined()
+
+ expect(recoverConversationNavigationProof(queryClient, epoch, 5)).toBe(true)
+ expect(mocks.requests).toHaveLength(2)
+ mocks.requests[1]!.receipt({ channelId: "retry", surfaceKind: "channel" })
+ mocks.requests[1]!.resolve({ messages: [], hasMore: false })
+ await vi.waitFor(() => {
+ expect(getConversationNavigationProof(queryClient)).toMatchObject({
+ accessEpoch: 5,
+ recoveryAttempt: 1,
+ status: "proven",
+ })
+ })
+ })
+
+ it("restarts response-to-commit access drift and accepts only the new proof", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const firstEpoch = startConversationNavigationWarmup(queryClient, target("epoch"), 7)
+ mocks.requests[0]!.receipt({ channelId: "epoch", surfaceKind: "channel" })
+ expect(getConversationNavigationProof(queryClient)?.status).toBe("verified")
+
+ expect(recoverConversationNavigationProof(queryClient, firstEpoch, 8)).toBe(true)
+ expect(mocks.requests[0]!.signal?.aborted).toBe(true)
+ mocks.requests[0]!.resolve({ messages: [], hasMore: false })
+ mocks.requests[1]!.receipt({ channelId: "epoch", surfaceKind: "forum" })
+ mocks.requests[1]!.resolve({ messages: [], hasMore: false })
+ await vi.waitFor(() => {
+ expect(getConversationNavigationProof(queryClient)).toMatchObject({
+ accessEpoch: 8,
+ recoveryAttempt: 0,
+ status: "forum",
+ })
+ })
+ })
+
+ it("uses the exact anchor and seeds current read and server results", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ startConversationNavigationWarmup(queryClient, {
+ ...target("anchor"),
+ anchorMessageId: "m1",
+ }, 3)
+ expect(mocks.requests[0]!.pageParam).toEqual({ mode: "anchor", anchor: "m1" })
+ mocks.requests[0]!.receipt({ channelId: "anchor", surfaceKind: "thread" })
+ mocks.requests[0]!.resolve({ messages: [], hasMore: false })
+ mocks.reads[0]!.resolve({ lastReadMessageId: "m0", lastReadAt: null, lastReadSeq: 4 })
+ mocks.servers[0]!.resolve({ id: "s1" })
+ await vi.waitFor(() => {
+ expect(queryClient.getQueryData(communityKeys.channelReadStateSnapshot("anchor"))).toMatchObject({
+ lastReadSeq: 4,
+ })
+ expect(queryClient.getQueryData(communityKeys.server("s1"))).toEqual({ id: "s1" })
+ })
+ })
+
+ it("ignores auxiliary failures while canonical proof succeeds", async () => {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ startConversationNavigationWarmup(queryClient, target("aux"), 4)
+ mocks.reads[0]!.reject(new Error("read transient"))
+ mocks.servers[0]!.reject(new Error("detail transient"))
+ mocks.requests[0]!.receipt({ channelId: "aux", surfaceKind: "channel" })
+ mocks.requests[0]!.resolve({ messages: [], hasMore: false })
+ await vi.waitFor(() => {
+ expect(getConversationNavigationProof(queryClient)?.status).toBe("proven")
+ })
+ })
+})
diff --git a/src/web/src/lib/community/conversation-navigation-warmup.ts b/src/web/src/lib/community/conversation-navigation-warmup.ts
new file mode 100644
index 000000000..660a437d0
--- /dev/null
+++ b/src/web/src/lib/community/conversation-navigation-warmup.ts
@@ -0,0 +1,124 @@
+"use client"
+
+import { type QueryClient } from "@tanstack/react-query"
+import { apiFetch } from "@/lib/api/client"
+import { ApiError } from "@/lib/errors"
+import { communityKeys } from "@/lib/query-keys"
+import type { MessagesPageParam } from "@/lib/community/models/message"
+import { channelMessagesQueryFn, dmMessagesQueryFn } from "@/hooks/community/use-messages"
+import { serverQueryFn, type ServerDetail } from "@/hooks/community/use-servers"
+import { useMessageStreamStore } from "@/stores/community/message-stream"
+import {
+ beginConversationNavigationProof,
+ commitConversationNavigationProof,
+ failConversationNavigationProof,
+ isCurrentConversationNavigation,
+ recordConversationNavigationReceipt,
+ registerConversationNavigationRecovery,
+ type ConversationNavigationTarget,
+} from "./conversation-navigation-proof"
+
+type ReadSnapshot = {
+ lastReadMessageId: string | null
+ lastReadAt: string | null
+ lastReadSeq: number
+}
+
+function isDefinitiveAccessFailure(error: unknown): boolean {
+ return error instanceof ApiError && (error.status === 403 || error.status === 404)
+}
+
+function clearDeniedTarget(queryClient: QueryClient, target: ConversationNavigationTarget) {
+ const messagesKey = target.scopeKind === "dm"
+ ? communityKeys.dmMessages(target.channelId)
+ : communityKeys.channelMessages(target.channelId)
+ const readKey = target.scopeKind === "dm"
+ ? communityKeys.dmReadStateSnapshot(target.channelId)
+ : communityKeys.channelReadStateSnapshot(target.channelId)
+ queryClient.removeQueries({ queryKey: messagesKey })
+ queryClient.removeQueries({ queryKey: readKey })
+ if (target.serverId) {
+ queryClient.removeQueries({ queryKey: communityKeys.channelMeta(target.serverId, target.channelId) })
+ } else {
+ queryClient.removeQueries({ queryKey: communityKeys.dmRouteVerification(target.channelId) })
+ }
+ useMessageStreamStore.getState().removeScope(
+ target.scopeKind === "dm"
+ ? { kind: "dm", id: target.channelId }
+ : { kind: "channel", id: target.channelId, serverId: target.serverId! },
+ )
+}
+
+export function startConversationNavigationWarmup(
+ queryClient: QueryClient,
+ target: ConversationNavigationTarget,
+ accessEpoch: number,
+ recoveryAttempt = 0,
+) {
+ const { epoch, signal } = beginConversationNavigationProof(
+ queryClient,
+ target,
+ accessEpoch,
+ recoveryAttempt,
+ )
+ registerConversationNavigationRecovery(queryClient, epoch, (nextAccessEpoch, nextAttempt) => {
+ startConversationNavigationWarmup(queryClient, target, nextAccessEpoch, nextAttempt)
+ })
+ const pageParam: MessagesPageParam = target.anchorMessageId
+ ? { mode: "anchor", anchor: target.anchorMessageId }
+ : { mode: "newest" }
+ const messagesKey = target.scopeKind === "dm"
+ ? communityKeys.dmMessages(target.channelId)
+ : communityKeys.channelMessages(target.channelId)
+ const queryFn = target.scopeKind === "dm"
+ ? dmMessagesQueryFn(target.channelId, {
+ onSurfaceReceipt: (receipt) => {
+ recordConversationNavigationReceipt(queryClient, receipt, accessEpoch, epoch)
+ },
+ })
+ : channelMessagesQueryFn(target.channelId, null, {
+ onSurfaceReceipt: (receipt) => {
+ recordConversationNavigationReceipt(queryClient, receipt, accessEpoch, epoch)
+ },
+ })
+
+ void queryClient.fetchInfiniteQuery({
+ queryKey: messagesKey,
+ queryFn,
+ initialPageParam: pageParam,
+ // A persisted/memory-warm page is only a hint. Force this click-owned
+ // query through the canonical door so a fresh receipt is always emitted.
+ staleTime: 0,
+ })
+ .then(() => {
+ if (!isCurrentConversationNavigation(queryClient, epoch, accessEpoch)) return
+ commitConversationNavigationProof(queryClient, target.channelId, accessEpoch)
+ })
+ .catch((error) => {
+ if (signal.aborted) return
+ const definitive = isDefinitiveAccessFailure(error)
+ if (definitive) clearDeniedTarget(queryClient, target)
+ failConversationNavigationProof(queryClient, epoch, accessEpoch, definitive)
+ })
+
+ const readKey = target.scopeKind === "dm"
+ ? communityKeys.dmReadStateSnapshot(target.channelId)
+ : communityKeys.channelReadStateSnapshot(target.channelId)
+ void apiFetch<ReadSnapshot>(`/api/community/channels/${target.channelId}/read-state`, { signal })
+ .then((snapshot) => {
+ if (!isCurrentConversationNavigation(queryClient, epoch, accessEpoch)) return
+ queryClient.setQueryData(readKey, snapshot)
+ })
+ .catch(() => undefined)
+
+ if (target.serverId) {
+ void serverQueryFn(queryClient, target.serverId, signal)()
+ .then((detail) => {
+ if (!isCurrentConversationNavigation(queryClient, epoch, accessEpoch)) return
+ queryClient.setQueryData<ServerDetail>(communityKeys.server(target.serverId!), detail)
+ })
+ .catch(() => undefined)
+ }
+
+ return epoch
+}
diff --git a/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts b/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts
index b8fff5df3..fe4ed5f50 100644
--- a/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts
+++ b/src/web/src/test/e2e-ui/38-community-navigation-checkpoint-matrix.spec.ts
@@ -28,7 +28,7 @@ function channelHeader(page: Page, name: string) {
return page.getByRole("banner").getByText(name, { exact: true })
}
-test("community checkpoint keeps the committed frame live until navigation commits", async ({ asUser }) => {
+test("community checkpoint shows target pending for detail and keeps list surfaces stable", async ({ asUser }) => {
test.setTimeout(120_000)
const stamp = Date.now()
const serverId = await seedServer("alice", `Frame Gate ${stamp}`)
@@ -59,11 +59,11 @@ test("community checkpoint keeps the committed frame live until navigation commi
const leafGate = await holdRoute(page, `/c/channels/${serverId}/${channelB}`)
await page.getByTestId(tid.channelRow(channelB)).click({ noWaitAfter: true })
await expect.poll(leafGate.held).toBeGreaterThan(0)
- await expect(page.getByLabel("Loading conversation")).toHaveCount(0)
- await expect(channelHeader(page, channelAName)).toBeVisible()
+ await expect(page.getByLabel("Loading conversation")).toBeVisible()
+ await expect(channelHeader(page, channelAName)).toHaveCount(0)
await page.waitForTimeout(150)
- await expect(page.getByLabel("Loading conversation")).toHaveCount(0)
- await expect(channelHeader(page, channelAName)).toBeVisible()
+ await expect(page.getByLabel("Loading conversation")).toBeVisible()
+ await expect(channelHeader(page, channelAName)).toHaveCount(0)
await leafGate.release()
await expect(channelHeader(page, channelBName)).toBeVisible({ timeout: 30_000 })
diff --git a/src/web/src/test/e2e-ui/perf/inbox-navigation.perf.ts b/src/web/src/test/e2e-ui/perf/inbox-navigation.perf.ts
new file mode 100644
index 000000000..9eac6f612
--- /dev/null
+++ b/src/web/src/test/e2e-ui/perf/inbox-navigation.perf.ts
@@ -0,0 +1,292 @@
+import { test, expect, type APIRequestContext, type BrowserContext, type Page } from "@playwright/test"
+import { mkdirSync, readFileSync, writeFileSync } from "node:fs"
+import { resolve } from "node:path"
+import { DEV_PASSWORD } from "@alook/shared"
+import { tid } from "../_fixtures/testids"
+
+const BASE_URL = process.env.ALOOK_SERVER_URL || "http://localhost:3000"
+const ARTIFACTS_DIR = resolve(__dirname, "..", "..", "..", "..", "perf-artifacts")
+const MANIFEST_PATH = resolve(ARTIFACTS_DIR, "seed-manifest.json")
+const TRACE_PATH = resolve(ARTIFACTS_DIR, "inbox-navigation-trace.json")
+
+type Manifest = {
+ owner: { email: string; userId: string }
+ servers: Array<{ id: string; channels: Array<{ id: string }> }>
+}
+
+type Sample = {
+ surface: "channel" | "dm"
+ targetId: string
+ cache: "cold" | "warm"
+ clickToTargetMs: number
+ nextFramePending: boolean
+ forbiddenCachedTextVisibleBeforeProof: boolean
+ requestStartsMs: Record<string, number[]>
+ clickOwnedStartsMs: {
+ messages: number
+ readState: number
+ rsc: number
+ detail: Record<string, number>
+ }
+ observerRefetchStartsMs: {
+ messages: number[]
+ readState: number[]
+ }
+}
+
+const CLICK_OWNED_START_BUDGET_MS = 150
+
+async function authenticate(context: BrowserContext, email: string, name?: string) {
+ let response = await context.request.post(`${BASE_URL}/api/auth/sign-in/email`, {
+ data: { email, password: DEV_PASSWORD },
+ })
+ if (!response.ok()) {
+ response = await context.request.post(`${BASE_URL}/api/auth/sign-up/email`, {
+ data: { name: name ?? email.split("@")[0], email, password: DEV_PASSWORD },
+ })
+ }
+ expect(response.ok(), `authenticate ${email}`).toBe(true)
+}
+
+async function postJson<T>(request: APIRequestContext, path: string, data?: unknown): Promise<T> {
+ const response = await request.post(`${BASE_URL}${path}`, { data })
+ expect(response.ok(), `POST ${path} (${response.status()})`).toBe(true)
+ return response.json() as Promise<T>
+}
+
+async function measureInboxClick({
+ page,
+ rowTestId,
+ targetText,
+ cachedText,
+ surface,
+ cache,
+ targetId,
+ detailPaths = [],
+}: {
+ page: Page
+ rowTestId: string
+ targetText: string
+ cachedText?: string
+ surface: Sample["surface"]
+ cache: Sample["cache"]
+ targetId: string
+ detailPaths?: string[]
+}): Promise<Sample> {
+ await page.getByTestId(tid.inboxTrigger).click()
+ const row = page.getByTestId(rowTestId)
+ await expect(row).toBeVisible({ timeout: 20_000 })
+ await page.evaluate(() => performance.clearResourceTimings())
+ const clickTs = await row.evaluate((element, pendingTestId) => {
+ const started = performance.now()
+ performance.mark("inbox-navigation-click")
+ ;(window as unknown as Record<string, Promise<boolean>>).__inboxPendingFrame = new Promise((resolvePending) => {
+ requestAnimationFrame(() => resolvePending(
+ document.querySelector(`[data-testid="${pendingTestId}"]`) !== null,
+ ))
+ })
+ ;(element as HTMLElement).click()
+ return started
+ }, tid.pendingMain(surface === "channel" ? "server-conversation" : "dm"))
+ const nextFramePending = await page.evaluate(() => (
+ (window as unknown as Record<string, Promise<boolean>>).__inboxPendingFrame
+ ))
+ let forbiddenCachedTextVisibleBeforeProof = false
+ if (cachedText) {
+ await page.waitForTimeout(40)
+ forbiddenCachedTextVisibleBeforeProof = await page.getByText(cachedText, { exact: true }).isVisible()
+ }
+ await expect(page.getByText(targetText, { exact: true })).toBeVisible({ timeout: 20_000 })
+ const result = await page.evaluate(({ clickTs }) => {
+ const requestStartsMs: Record<string, number[]> = {}
+ for (const entry of performance.getEntriesByType("resource") as PerformanceResourceTiming[]) {
+ const url = new URL(entry.name)
+ if (!url.pathname.includes("/api/community/") && !url.searchParams.has("_rsc")) continue
+ const path = `${url.pathname}${url.searchParams.has("_rsc") ? "?_rsc" : ""}`
+ const starts = requestStartsMs[path] ?? []
+ starts.push(Math.round((entry.startTime - clickTs) * 10) / 10)
+ requestStartsMs[path] = starts
+ }
+ return {
+ clickToTargetMs: Math.round((performance.now() - clickTs) * 10) / 10,
+ requestStartsMs,
+ }
+ }, { clickTs })
+ const startsFor = (match: (path: string) => boolean) => Object.entries(result.requestStartsMs)
+ .filter(([path]) => match(path))
+ .flatMap(([, starts]) => starts)
+ .filter((start) => start >= 0)
+ .sort((a, b) => a - b)
+ const messageStarts = startsFor((path) => (
+ path === `/api/community/channels/${targetId}/messages`
+ ))
+ const readStarts = startsFor((path) => (
+ path === `/api/community/channels/${targetId}/read-state`
+ ))
+ const rscStarts = startsFor((path) => path.includes(targetId) && path.endsWith("?_rsc"))
+ const detailStarts = Object.fromEntries(detailPaths.map((path) => [
+ path,
+ startsFor((candidate) => candidate === path)[0] ?? Number.POSITIVE_INFINITY,
+ ]))
+ const clickOwnedStartsMs = {
+ messages: messageStarts[0] ?? Number.POSITIVE_INFINITY,
+ readState: readStarts[0] ?? Number.POSITIVE_INFINITY,
+ rsc: rscStarts[0] ?? Number.POSITIVE_INFINITY,
+ detail: detailStarts,
+ }
+ return {
+ surface,
+ targetId,
+ cache,
+ nextFramePending,
+ forbiddenCachedTextVisibleBeforeProof,
+ ...result,
+ clickOwnedStartsMs,
+ observerRefetchStartsMs: {
+ messages: messageStarts.slice(1),
+ readState: readStarts.slice(1),
+ },
+ }
+}
+
+test.skip(process.env.PERF_INBOX_NAVIGATION !== "1", "run explicitly with PERF_INBOX_NAVIGATION=1")
+
+test("Inbox Channel/DM navigation fixed trace", async ({ browser }) => {
+ const manifest = JSON.parse(readFileSync(MANIFEST_PATH, "utf8")) as Manifest
+ expect(manifest.servers.length).toBeGreaterThan(1)
+ const origin = manifest.servers[0]!.channels[0]!
+ const targetServer = manifest.servers[1]!
+ const targetChannel = targetServer.channels[0]!
+ const owner = await browser.newContext()
+ const peer = await browser.newContext()
+ await authenticate(owner, manifest.owner.email)
+ const stamp = `${Date.now()}-${process.pid}`
+ await authenticate(peer, `perf-peer-${stamp}@alook.test`, `perf-peer-${stamp}`)
+
+ const invite = await postJson<{ invite: { token: string } }>(
+ owner.request,
+ `/api/community/servers/${targetServer.id}/invites`,
+ {},
+ )
+ await postJson(peer.request, `/api/community/invites/${invite.invite.token}/join`)
+ const friendship = await postJson<{ id?: string; friendship?: { id: string } }>(
+ peer.request,
+ "/api/community/friends/request",
+ { userId: manifest.owner.userId },
+ )
+ const friendshipId = friendship.id ?? friendship.friendship?.id
+ expect(friendshipId).toBeTruthy()
+ await postJson(owner.request, `/api/community/friends/${friendshipId}/accept`)
+ const dm = await postJson<{ conversation: { id: string } }>(peer.request, "/api/community/channels", {
+ type: "dm",
+ userId: manifest.owner.userId,
+ })
+
+ const page = await owner.newPage()
+ await page.route("**/*", async (route) => {
+ const request = route.request()
+ const url = new URL(request.url())
+ const isTargetRsc = url.searchParams.has("_rsc") && (
+ url.pathname.includes(targetChannel.id) || url.pathname.includes(dm.conversation.id)
+ )
+ const isTargetMessages = request.method() === "GET" && (
+ url.pathname === `/api/community/channels/${targetChannel.id}/messages` ||
+ url.pathname === `/api/community/channels/${dm.conversation.id}/messages`
+ )
+ if (isTargetRsc || isTargetMessages) await new Promise((resolveDelay) => setTimeout(resolveDelay, 120))
+ await route.continue()
+ })
+ await page.goto(`${BASE_URL}/c/channels/${manifest.servers[0]!.id}/${origin.id}`)
+ await expect(page.getByTestId(tid.messageScroller)).toBeVisible({ timeout: 20_000 })
+
+ const samples: Sample[] = []
+ const channelColdText = `inbox channel cold ${stamp}`
+ await postJson(peer.request, `/api/community/channels/${targetChannel.id}/messages`, { content: channelColdText })
+ await page.reload()
+ await expect(page.getByTestId(tid.messageScroller)).toBeVisible({ timeout: 20_000 })
+ samples.push(await measureInboxClick({
+ page,
+ rowTestId: tid.inboxUnreadChannel(targetChannel.id),
+ targetText: channelColdText,
+ surface: "channel",
+ cache: "cold",
+ targetId: targetChannel.id,
+ detailPaths: [
+ `/api/community/servers/${targetServer.id}/categories`,
+ `/api/community/servers/${targetServer.id}/channels`,
+ `/api/community/servers/${targetServer.id}/unreads`,
+ ],
+ }))
+ await page.goBack()
+ await expect(page).toHaveURL(new RegExp(origin.id))
+ const channelWarmText = `inbox channel warm ${stamp}`
+ await postJson(peer.request, `/api/community/channels/${targetChannel.id}/messages`, { content: channelWarmText })
+ await page.reload()
+ await expect(page.getByTestId(tid.messageScroller)).toBeVisible({ timeout: 20_000 })
+ samples.push(await measureInboxClick({
+ page,
+ rowTestId: tid.inboxUnreadChannel(targetChannel.id),
+ targetText: channelWarmText,
+ cachedText: channelColdText,
+ surface: "channel",
+ cache: "warm",
+ targetId: targetChannel.id,
+ detailPaths: [
+ `/api/community/servers/${targetServer.id}/categories`,
+ `/api/community/servers/${targetServer.id}/channels`,
+ `/api/community/servers/${targetServer.id}/unreads`,
+ ],
+ }))
+
+ await page.goBack()
+ await expect(page).toHaveURL(new RegExp(origin.id))
+ const dmColdText = `inbox dm cold ${stamp}`
+ await postJson(peer.request, `/api/community/channels/${dm.conversation.id}/messages`, { content: dmColdText })
+ await page.reload()
+ await expect(page.getByTestId(tid.messageScroller)).toBeVisible({ timeout: 20_000 })
+ samples.push(await measureInboxClick({
+ page,
+ rowTestId: tid.inboxUnreadDm(dm.conversation.id),
+ targetText: dmColdText,
+ surface: "dm",
+ cache: "cold",
+ targetId: dm.conversation.id,
+ }))
+ await page.goBack()
+ await expect(page).toHaveURL(new RegExp(origin.id))
+ const dmWarmText = `inbox dm warm ${stamp}`
+ await postJson(peer.request, `/api/community/channels/${dm.conversation.id}/messages`, { content: dmWarmText })
+ await page.reload()
+ await expect(page.getByTestId(tid.messageScroller)).toBeVisible({ timeout: 20_000 })
+ samples.push(await measureInboxClick({
+ page,
+ rowTestId: tid.inboxUnreadDm(dm.conversation.id),
+ targetText: dmWarmText,
+ cachedText: dmColdText,
+ surface: "dm",
+ cache: "warm",
+ targetId: dm.conversation.id,
+ }))
+
+ mkdirSync(ARTIFACTS_DIR, { recursive: true })
+ writeFileSync(TRACE_PATH, JSON.stringify({ capturedAt: new Date().toISOString(), samples }, null, 2))
+
+ for (const sample of samples) {
+ expect(sample.nextFramePending, JSON.stringify(sample)).toBe(true)
+ expect(sample.forbiddenCachedTextVisibleBeforeProof).toBe(false)
+ if (sample.cache === "warm") expect(sample.clickToTargetMs).toBeLessThanOrEqual(1_500)
+ const clickOwnedStarts = [
+ sample.clickOwnedStartsMs.messages,
+ sample.clickOwnedStartsMs.readState,
+ sample.clickOwnedStartsMs.rsc,
+ ...Object.values(sample.clickOwnedStartsMs.detail),
+ ]
+ expect(clickOwnedStarts.every(Number.isFinite), JSON.stringify(sample)).toBe(true)
+ expect(Math.max(...clickOwnedStarts), JSON.stringify(sample))
+ .toBeLessThanOrEqual(CLICK_OWNED_START_BUDGET_MS)
+ expect(Math.max(...clickOwnedStarts) - Math.min(...clickOwnedStarts), JSON.stringify(sample))
+ .toBeLessThanOrEqual(CLICK_OWNED_START_BUDGET_MS)
+ }
+
+ await Promise.all([owner.close(), peer.close()])
+})
diff --git a/src/web/src/test/e2e-ui/perf/switch.perf.ts b/src/web/src/test/e2e-ui/perf/switch.perf.ts
index b8f0599be..f6d5f7309 100644
--- a/src/web/src/test/e2e-ui/perf/switch.perf.ts
+++ b/src/web/src/test/e2e-ui/perf/switch.perf.ts
@@ -121,10 +121,15 @@ const INPAGE_SETUP = `
let unchangedFrames = 0;
let observedFrames = 0;
const sample = () => {
+ observedFrames += 1;
const root = document.querySelector('[data-testid="${tid.messageScroller}"]');
const content = root?.firstElementChild;
if (!root || !content) {
- reject(new Error('message scroller geometry target disappeared'));
+ if (observedFrames >= 120) {
+ reject(new Error('target message scroller did not mount'));
+ return;
+ }
+ requestAnimationFrame(sample);
return;
}
const rootRect = root.getBoundingClientRect();
@@ -132,7 +137,6 @@ const INPAGE_SETUP = `
const current = [rootRect.width, rootRect.height, contentRect.width, contentRect.height, root.scrollHeight].join(':');
unchangedFrames = current === previous ? unchangedFrames + 1 : 0;
previous = current;
- observedFrames += 1;
if (window.__PERF_RESIZES__.length > 0 && unchangedFrames >= 1) {
resolve();
return;