Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(web): decouple cached conversation presentation (#1086)
Gener91d878840ad1
diff --git a/src/shared/src/db/queries/community/channel.ts b/src/shared/src/db/queries/community/channel.tsindex c4b196179..a15806a37 100644--- a/src/shared/src/db/queries/community/channel.ts+++ b/src/shared/src/db/queries/community/channel.ts@@ -549,6 +549,7 @@ export async function listChildChannelsByParentMessageIds(db: Database,parentChannelId: string,parentMessageIds: string[],+ type: string | null = "thread",) {if (parentMessageIds.length === 0) return [];return (@@ -559,9 +560,10 @@ export async function listChildChannelsByParentMessageIds(.from(communityChannel).where(and(eq(communityChannel.parentChannelId, parentChannelId),- eq(communityChannel.type, "thread"),+ type === null ? undefined : eq(communityChannel.type, type),inArray(communityChannel.parentMessageId, ids),))+ .orderBy(...(type === null ? [desc(communityChannel.lastMessageAt)] : []))))).flat();diff --git a/src/shared/test/queries/community-channel-threads.test.ts b/src/shared/test/queries/community-channel-threads.test.tsindex 90979bbc3..1d4f19cd8 100644--- a/src/shared/test/queries/community-channel-threads.test.ts+++ b/src/shared/test/queries/community-channel-threads.test.ts@@ -3,7 +3,7 @@ import { drizzle } from "drizzle-orm/better-sqlite3";import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";import type { Database } from "../../src/db";import {- createThreadChannel,+ createThreadChannel, listChildChannelsByParentMessageIds,} from "../../src/db/queries/community/channel";/**@@ -175,4 +175,19 @@ describe("createThreadChannel against real SQLite", () => {name: "Thread from a real query",});});+ it("bounds message enrichment to parent and page IDs while retaining ordinary legacy types and archived indicators", async () => {+ const insert = sqlite.prepare("INSERT INTO community_channel (id, server_id, type, parent_channel_id, parent_message_id, archived, last_message_at, created_at) VALUES (?, 'server_1', ?, ?, ?, ?, ?, 'now')");+ insert.run("current", "thread", "parent_1", "page_1", 0, "3");+ insert.run("archived", "thread", "parent_1", "page_1", 1, "1");+ insert.run("legacy", "text", "parent_1", "page_2", 0, "2");+ insert.run("off_page", "thread", "parent_1", "other_message", 0, "4");+ insert.run("foreign_parent", "thread", "another_parent", "page_1", 0, "5");+ const rows = await listChildChannelsByParentMessageIds(db, "parent_1", ["page_1", "page_2"], null);+ expect(rows.map(row => row.id)).toEqual(["current", "legacy", "archived"]);+ expect((await listChildChannelsByParentMessageIds(db, "parent_1", ["page_1", "page_2"])).map(row => row.id).sort()).toEqual(["archived", "current"]);+ const select = vi.spyOn(db, "select");+ expect(await listChildChannelsByParentMessageIds(db, "parent_1", [], null)).toEqual([]);+ expect(select).not.toHaveBeenCalled();+ });+});diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.test.tsindex 42245c583..593f0ecae 100644--- a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts+++ b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts@@ -88,6 +88,7 @@ vi.mock("@alook/shared", async () => {getChannel: (...a: unknown[]) => mockGetChannel(...a),resolveChannelByNameForMember: (...a: unknown[]) => mockResolveChannelByNameForMember(...a),listChildChannels: (...a: unknown[]) => mockListChildChannels(...a),+ listChildChannelsByParentMessageIds: (...a: unknown[]) => mockListChildChannels(...a),isChannelPrivate: (...a: unknown[]) => mockIsChannelPrivate(...a),getPrivateChannelAudienceUserIds: (...a: unknown[]) => mockGetPrivateChannelAudienceUserIds(...a),createChannel: (...a: unknown[]) => mockCreateChannel(...a),@@ -1189,7 +1190,7 @@ describe("GET /api/community/channels/[id]/messages", () => {expect(mockListByMessageIds).toHaveBeenCalledTimes(1)expect(mockListReactionsByMessageIds).toHaveBeenCalledTimes(1)expect(mockGetMessagesByIdsInScope).toHaveBeenCalledTimes(1)- expect(mockListChildChannels).toHaveBeenCalledTimes(1)+ expect(mockListChildChannels).toHaveBeenCalledExactlyOnceWith(expect.anything(), "c1", ["m-1"], null)expect(mockGetLatestMessageSeq).toHaveBeenCalledTimes(1)})diff --git a/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.ts b/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.tsindex 883b98b20..c9ac8ea71 100644--- a/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.ts+++ b/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.ts@@ -48,6 +48,7 @@ vi.mock("sonner", () => ({ toast: vi.fn() }))vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop" }))vi.mock("@/components/community/channels/dm-header", () => ({DmHeader: ({ dm }: { dm: { name: string } }) => React.createElement("div", { "data-testid": "dm-header" }, dm.name),+ DmHeaderSkeleton: () => React.createElement("div", { "data-testid": "dm-identity-pending" }),}))vi.mock("@/components/community/channels/dm-loading-frame", () => ({DmLoadingFrame: () => React.createElement("div", { "data-testid": "dm-loading" }),@@ -193,8 +194,8 @@ describe("DM notification dismissal readiness", () => {it.each([["resolved", [{ id: "dm_1", userId: "peer_1", name: "Peer", avatar: "P" }], false, false, true],["blocked", [{ id: "dm_1", userId: "peer_1", name: "Peer", avatar: "P" }], false, true, false],- ["pending", [], true, false, false],- ["notFound", [], false, false, false],+ ["pending", [], true, false, true],+ ["notFound", [], false, false, true],] as const)("passes the exact %s readiness state to dismissal", (_state,dms,diff --git a/src/web/src/app/c/me/[dmId]/page.test.ts b/src/web/src/app/c/me/[dmId]/page.test.tsindex 8d0d58f09..43353470f 100644--- a/src/web/src/app/c/me/[dmId]/page.test.ts+++ b/src/web/src/app/c/me/[dmId]/page.test.ts@@ -12,7 +12,7 @@ describe("DM page loading ownership", () => {expect(source).toContain("useDmMessages(dmId")expect(source).toContain("if (!dm && !metadata.revoked && !metadata.denied && !dmBlocked && navigationBlocked && !initialLoadError")expect(source).toContain('metadata.status === "retryable-error"')- expect(source).toContain("if (loadingOwnership.fullFramePending)")+ expect(source).toContain("if (!historyAllowed && loadingOwnership.fullFramePending)")expect(source).toContain("<DmHeader\n")expect(source).toContain("<Composer\n")expect(source).toContain("<ConversationFooterShell\n")@@ -28,13 +28,13 @@ describe("DM page loading ownership", () => {expect(messageListProps).toContain("typingUsers")expect(source).not.toContain('data-onboarding-name={dm.name} className="shrink-0"')expect(source).toContain("loading={!historyAllowed || loadingOwnership.messageBodyLoading}")- expect(source).toContain("!historyAllowed ? <ComposerSkeleton")- expect(source).not.toContain("<DmHeaderSkeleton")+ expect(source).toContain("!sendAllowed ? <ComposerSkeleton")+ expect(source).toContain("<DmHeaderSkeleton")})it("uses the cache-first DM projection as the header and composer identity", () => {const source = readFileSync(new URL("../../../../components/community/channels/dm-view.tsx", import.meta.url), "utf8")- expect(source).toContain("dms.find((candidate) => candidate.id === dmId) ?? null")+ expect(source).toContain("const directoryDm = dms.find(candidate => candidate.id === dmId)")expect(source).not.toContain("profilesByUserId.get(raw.userId)")})diff --git a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.tsindex 26f51deb3..81adbbbeb 100644--- a/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts+++ b/src/web/src/components/community/channels/channel-route.text-scroll-target.dom.test.ts@@ -1213,7 +1213,7 @@ describe("ChannelRoute message surface ownership", () => {renderer.unmount()})- it("lets the qualified parent load while the forum opener still fences the child", () => {+ it("mounts qualified parent and child while the Forum title is still pending", () => {configureThreadRoute()mockRouteModel.isForumPostChild = truemockSplitMode.value = "split"@@ -1222,39 +1222,25 @@ describe("ChannelRoute message surface ownership", () => {const renderer = render(React.createElement(ChannelRoute, props))const split = screen.getByTestId("community-thread-split")expect(mockSplitParentSurface).toHaveBeenLastCalledWith(expect.objectContaining({ channel: expect.objectContaining({ id: "parent_1" }) }), undefined)- expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()- expect(mockCommitLastCommunityRoute).not.toHaveBeenCalled()- expect(screen.getByTestId("community-thread-split-panel").querySelector("[data-message-list-skeleton]")).not.toBeNull()+ expect(mockedUseChannelMessageFeed).toHaveBeenCalledWith(expect.objectContaining({ channelId: "channel_1" }))Object.assign(mockForumOpener, { data: { content: "Post title" }, isLoading: false })- mockedUseChannelMessageFeed.mockReturnValue(feed())renderer.rerender(React.createElement(ChannelRoute, props))expect(screen.getByTestId("community-thread-split")).toBe(split)- expect(mockedUseChannelMessageFeed).toHaveBeenCalledOnce()- expect(mockCommitLastCommunityRoute).toHaveBeenCalledOnce()+ expect(mockCommitLastCommunityRoute).toHaveBeenCalled()renderer.unmount()})- it("shows a required cold forum opener failure, keeps Retry feedback while pending, then opens body", async () => {+ it("keeps the qualified child mounted through a failed title hint and its recovery", () => {configureThreadRoute()mockRouteModel.isForumPostChild = trueObject.assign(mockForumOpener, { isError: true, error: new Error("deadline") })- let release!: () => void- mockForumOpener.refetch.mockImplementationOnce(() => new Promise<void>((resolve) => { release = resolve }))const props = { serverParam: "server_1", channelId: "channel_1" }const renderer = render(React.createElement(ChannelRoute, props))- expect(screen.getByRole("button", { name: "Retry" })).not.toBeDisabled()- expect(mockedUseChannelMessageFeed).not.toHaveBeenCalled()- fireEvent.click(screen.getByRole("button", { name: "Retry" }))- expect(mockForumOpener.refetch).toHaveBeenCalledOnce()- Object.assign(mockForumOpener, { isError: false, error: null, isFetching: true, isLoading: true })- renderer.rerender(React.createElement(ChannelRoute, props))- expect(screen.getByRole("button", { name: "Retrying…" })).toBeDisabled()- await act(async () => { release() })- Object.assign(mockForumOpener, { data: { content: "Recovered title" }, isFetching: false, isLoading: false })- mockedUseChannelMessageFeed.mockReturnValue(feed())+ expect(mockedUseChannelMessageFeed).toHaveBeenCalledWith(expect.objectContaining({ channelId: "channel_1" }))+ expect(screen.queryByRole("alert")).toBeNull()+ Object.assign(mockForumOpener, { data: { content: "Recovered title" }, isError: false, error: null, isFetching: false, isLoading: false })renderer.rerender(React.createElement(ChannelRoute, props))expect(screen.queryByRole("alert")).toBeNull()- expect(mockedUseChannelMessageFeed).toHaveBeenCalled()renderer.unmount()})diff --git a/src/web/src/components/community/channels/channel-route.tsx b/src/web/src/components/community/channels/channel-route.tsxindex 6f23fab1e..0602f3b83 100644--- a/src/web/src/components/community/channels/channel-route.tsx+++ b/src/web/src/components/community/channels/channel-route.tsx@@ -2,7 +2,7 @@import { useAtom, useCreateAtom } from "@tanstack/react-store";-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentProps } from "react"+import { useCallback, useEffect, useLayoutEffect, useMemo, useState, type ComponentProps } from "react"import { useSearchParams } from "next/navigation"import { useCommunityHistoryRouter as useRouter } from "@/lib/community/navigation"import { toastApiError } from "@/lib/api/client"@@ -35,11 +35,9 @@ import {useThreadOpenerRouteGate,} from "@/hooks/community/thread-opener-read-handoff"import { useThreadSplitMode } from "@/hooks/community/use-thread-split-mode"-import { useCommunityWsStore } from "@/stores/community/ws"import { resolveConversationSubtype } from "@/lib/community/conversation-subtype"-import { isConversationAccessError } from "@/lib/community/conversation-read"import { MobilePage } from "@/components/community/shell/mobile-page"-import { ConversationActivityContext, ConversationPresentationContext, useConversationActivity } from "@/contexts/community/conversation-activity"+import { ConversationActivityContext, ConversationPresentationContext, useConversationActivity, useConversationPresentation } from "@/contexts/community/conversation-activity"import { useRouteChannelProjection } from "@/lib/community-db/projections"import { useNativeSystemNotificationConversationDismissal } from "@/hooks/community/use-native-system-notifications"@@ -117,7 +115,7 @@ function ChannelRouteLayer({ serverParam, channelId, targetHref, routeCommittedconst next = intentAnchorMessageId !== undefined ? intentAnchorMessageId : routeAnchorMessageIdsetCaptured(current => current.scope === scope && current.anchorMessageId === next ? current : { scope, anchorMessageId: next })}, [resume, scope, captured.scope, entryIntent, intentAnchorMessageId, routeAnchorMessageId, routeCommitted, setCaptured])- const routeModel = useChannelRouteModel(serverId, serverParam, channelId, currentUser.id, anchorMessageId)+ const routeModel = useChannelRouteModel(serverId, serverParam, channelId, currentUser.id, anchorMessageId, searchParams.get("tag"))const content = <ChannelRouteFrame key={JSON.stringify([currentUser.id, serverId])}serverId={serverId} serverParam={serverParam} channelId={channelId}searchParams={searchParams} routeCommitted={routeCommitted} resume={resume}@@ -203,9 +201,9 @@ function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, rouonOpenChild: (id: string) => void}) {const active = useConversationActivity()+ const presented = useConversationPresentation()const { navigation } = useCommunityRouteFrame()const router = useRouter()- const accessEpoch = useCommunityWsStore((state) => state.accessEpoch)const currentAnchorMessageId = anchorMessageIdconst uiHandlers = useUiHandlers()const currentChannelId = useCurrentChannelId()@@ -221,26 +219,8 @@ function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, rouconst forumPostOpener = useForumOpenerHint(serverId,currentChannelMeta?.parentMessageId,- isForumPostChild && !resolvingParent && routeModel.routeHydrated,+ presented && isForumPostChild && !resolvingParent && routeModel.routeHydrated,)- const { isFetching: fetchingOpener, refetch: refetchOpener } = forumPostOpener- const openerScope = JSON.stringify([currentUser.id, serverId, channelId, currentChannelMeta?.parentMessageId, accessEpoch])- const [openerRetryAttempt, setOpenerRetryAttempt] = useAtom(useCreateAtom<{ scope: string } | null>(null))- const openerRetryRef = useRef<{ scope: string } | null>(null)- const retryingOpener = openerRetryAttempt?.scope === openerScope- const openerError = isForumPostChild && (isConversationAccessError(forumPostOpener.error)- || (!forumPostOpener.data && (forumPostOpener.isError || retryingOpener)))- const retryOpener = useCallback(async () => {- if (!openerError || fetchingOpener || openerRetryRef.current?.scope === openerScope) return- const attempt = { scope: openerScope }- openerRetryRef.current = attempt- setOpenerRetryAttempt(attempt)- try { await refetchOpener({ cancelRefetch: false }) }- finally {- if (openerRetryRef.current === attempt) openerRetryRef.current = null- setOpenerRetryAttempt((current) => current === attempt ? null : current)- }- }, [fetchingOpener, refetchOpener, openerError, openerScope, setOpenerRetryAttempt])const channelName = useMemo(() => resolveChannelDisplayName({forumPostTitle: isForumPostChild ? forumPostOpener.data?.content : null,topLevelName: channelInServer?.name,@@ -259,8 +239,8 @@ function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, rouisChildChannel,isNotifyUnit,currentUser,- accessAllowed: !resolvingParent && routeCommitted && routeModel.routeLifecycle === "ready",- roleDisplayAllowed: !resolvingParent && routeModel.routeLifecycle === "ready"+ accessAllowed: presented && !resolvingParent && routeCommitted && routeModel.routeLifecycle === "ready",+ roleDisplayAllowed: presented && !resolvingParent && routeModel.routeLifecycle === "ready"&& (routeCommitted || resume && isForum && routeModel.routeHydrated),})const {@@ -281,7 +261,7 @@ function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, rou.flatMap((category) => category.channels).map((channel) => toChannelRefCandidate(currentServer, channel))}, [currentServer])- const notifs = useNotificationSettings()+ const notifs = useNotificationSettings(false)const channelNotif = notifs.channelconst { mutate: setChannelNotif } = useSetChannelNotif()@@ -323,8 +303,7 @@ function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, rouconst channelReadReady =routeModel.routeLifecycle === "ready" &&routeModel.routeHydrated- const channelHydrated = !resolvingParent && channelReadReady &&- (!isForumPostChild || (Boolean(forumPostOpener.data) && !openerError))+ const channelHydrated = !resolvingParent && channelReadReadyconst clientReady = active && routeCommitted && channelHydrated && currentChannelId === channelIduseNativeSystemNotificationConversationDismissal(currentUser.id, {kind: "server",@@ -352,10 +331,6 @@ function ChannelTargetPane({ serverId, serverParam, channelId, searchParams, rouonRetry={() => { void routeModel.retryMetadata() }}/>}- if (openerError) {- return <ConversationResolutionErrorFrame retrying={retryingOpener}- onRetry={() => { void retryOpener() }} />- }if (subtype === "unknown") {return <ConversationResolutionPendingFrame />}diff --git a/src/web/src/components/community/channels/dm-header.identity.dom.test.tsx b/src/web/src/components/community/channels/dm-header.identity.dom.test.tsxnew file mode 100644index 000000000..d0a845c19--- /dev/null+++ b/src/web/src/components/community/channels/dm-header.identity.dom.test.tsx@@ -0,0 +1,19 @@+import { expect, it, vi } from "vitest"+import { fireEvent, render, screen } from "@/test/react-dom-harness"+import { DmHeaderSkeleton } from "./dm-header"++it("keeps Back usable while recipient identity has a local retry and disables only that retry in flight", () => {+ const back = vi.fn(), retry = vi.fn()+ const view = render(<DmHeaderSkeleton onBack={back} onRetryIdentity={retry} />)+ fireEvent.click(screen.getByRole("button", { name: "Retry recipient" }))+ expect(retry).toHaveBeenCalledOnce()+ const button = screen.getByRole("button", { name: "Retry recipient" })+ view.rerender(<DmHeaderSkeleton onBack={back} onRetryIdentity={retry} retryingIdentity />)+ expect(screen.getByRole("button", { name: "Retry recipient" })).toBe(button)+ expect(button).toBeDisabled()+ fireEvent.click(button)+ expect(retry).toHaveBeenCalledOnce()+ fireEvent.click(screen.getByRole("button", { name: "Back" }))+ expect(back).toHaveBeenCalledOnce()+ view.unmount()+})diff --git a/src/web/src/components/community/channels/dm-header.tsx b/src/web/src/components/community/channels/dm-header.tsxindex fe2264eb5..bd83df26b 100644--- a/src/web/src/components/community/channels/dm-header.tsx+++ b/src/web/src/components/community/channels/dm-header.tsx@@ -1,4 +1,4 @@-import { Bell, BellOff, Check } from "lucide-react"+import { Bell, BellOff, Check, RotateCcw } from "lucide-react"import { NOTIF_LEVELS, type NotifLevel } from "@alook/shared"import { Button } from "@/components/ui/button"import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu"@@ -8,12 +8,14 @@ import type { DM } from "@/lib/community/models/people"import { tid } from "@/lib/community/testids"import { MessageHeader, MessageHeaderMobileBack } from "./message-header"-export function DmHeader({ dm, onBack, titleAs: Title = "h1", notifLevel, onSetNotifLevel }: {+export function DmHeader({ dm, onBack, titleAs: Title = "h1", notifLevel, onSetNotifLevel, onRetryIdentity, retryingIdentity }: {dm: DMonBack?: () => voidtitleAs?: "h1" | "div"notifLevel?: NotifLevelonSetNotifLevel?: (level: NotifLevel) => void+ onRetryIdentity?: () => void+ retryingIdentity?: boolean}) {return (<MessageHeader@@ -33,11 +35,17 @@ export function DmHeader({ dm, onBack, titleAs: Title = "h1", notifLevel, onSetN</Title></>)}- actions={notifLevel && <DmNotifDropdown level={notifLevel} onSetLevel={onSetNotifLevel} />}+ actions={onRetryIdentity || notifLevel ? <>{onRetryIdentity && <RetryRecipient onRetry={onRetryIdentity} retrying={retryingIdentity} />}+ {notifLevel && <DmNotifDropdown level={notifLevel} onSetLevel={onSetNotifLevel} />}</> : undefined}/>)}+function RetryRecipient({ onRetry, retrying }: { onRetry: () => void; retrying?: boolean }) {+ return <Button variant="ghost" size="icon-sm" className="size-11 sm:size-7" aria-label="Retry recipient" disabled={retrying}+ onClick={onRetry}><RotateCcw className="size-4" /></Button>+}+function DmNotifDropdown({ level, onSetLevel }: { level: NotifLevel; onSetLevel?: (level: NotifLevel) => void }) {const muted = level === "Nothing"return (@@ -62,10 +70,10 @@ function DmNotifDropdown({ level, onSetLevel }: { level: NotifLevel; onSetLevel?// Loading placeholder for <DmHeader> — same h-12 footprint so the body below// stays anchored across the route change.-export function DmHeaderSkeleton({ onBack }: { onBack?: () => void }) {+export function DmHeaderSkeleton({ onBack, onRetryIdentity, retryingIdentity }: { onBack?: () => void; onRetryIdentity?: () => void; retryingIdentity?: boolean }) {return (<MessageHeader- leading={onBack ? (+ leading={onBack && onRetryIdentity ? <MessageHeaderMobileBack onNavigate={onBack} /> : onBack ? (<div data-slot="loading-mobile-leading" aria-hidden className="grid size-11 shrink-0 place-items-center sm:hidden"><Skeleton className="size-6 rounded-md" /></div>@@ -77,7 +85,7 @@ export function DmHeaderSkeleton({ onBack }: { onBack?: () => void }) {<Skeleton className="h-4 w-32 rounded" /></>)}- actions={<Skeleton className="size-7 rounded-md" />}+ actions={onRetryIdentity ? <RetryRecipient onRetry={onRetryIdentity} retrying={retryingIdentity} /> : <Skeleton className="size-7 rounded-md" />}/>)}diff --git a/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.ts b/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.tsindex 638789a63..e52264800 100644--- a/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.ts+++ b/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.ts@@ -5,13 +5,14 @@ import { act, render, screen, waitFor } from "@/test/react-dom-harness"import { createCommunityQueryOwner } from "@/test/community-query-owner"import { CommunityTestProvider } from "@/test/community-owner-fixture"import { DmView } from "./dm-view"+import { dmConversationEntryFixture, seedConversationEntry } from "@/test/conversation-entry-fixtures"-const mocks = vi.hoisted(() => ({ api: vi.fn(), advance: vi.fn(), list: vi.fn(), positionEntry: null as object | null, failed: true, breakpoint: "mobile" }))+const mocks = vi.hoisted(() => ({ api: vi.fn(), advance: vi.fn(), list: vi.fn(), positionEntry: null as object | null, failed: true, breakpoint: "mobile", identity: true, blocked: false }))vi.mock("@/lib/api/client", () => ({ apiFetch: mocks.api, toastApiError: vi.fn() }))vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => mocks.breakpoint }))vi.mock("@/contexts/community/current-user", () => ({ useCurrentUser: () => ({ id: "u_me", name: "Me", avatar: "M" }) }))-vi.mock("@/hooks/community/use-dms", () => ({ useDms: () => ({ dms: ["dm_1", "dm_2"].map(id => ({ id, userId: "peer", name: "Peer", avatar: "P" })), isLoading: false, isFetching: false }) }))-vi.mock("@/hooks/community/use-friends", () => ({ useFriends: () => ({ friends: [], blocked: [] }) }))+vi.mock("@/hooks/community/use-dms", () => ({ useDms: () => ({ dms: mocks.identity ? ["dm_1", "dm_2"].map(id => ({ id, userId: "peer", name: "Peer", avatar: "P" })) : [], isLoading: false, isFetching: false }) }))+vi.mock("@/hooks/community/use-friends", () => ({ useFriends: () => ({ friends: [], blocked: mocks.blocked ? [{ id: "peer", userId: "peer" }] : [] }) }))vi.mock("@/hooks/community/use-messages", () => ({ useDmMessages: () => ({ messages: mocks.failed ? [{ id: "failed", clientNonce: "retry_nonce", authorId: "u_me", type: "chat", content: "retry" }] : [], positionEntry: mocks.positionEntry, positionDataState: "ready", isLoading: false, isPending: false, isError: false, latestSeq: 0 }) }))vi.mock("@/hooks/community/use-channel-metadata", () => ({ useChannelMetadata: () => ({ canRead: true, status: "readable" }) }))vi.mock("@/hooks/community/use-dm-watermark", () => ({ useDmWatermark: vi.fn() }))@@ -23,21 +24,76 @@ vi.mock("@/hooks/community/use-notification-settings", () => ({ useNotificationSvi.mock("@/hooks/community/use-community-ws", () => ({ communityWsSubscribe: vi.fn(), communityWsUnsubscribe: vi.fn(), communityWsSendTyping: vi.fn(), communityWsEndTyping: vi.fn() }))vi.mock("@/lib/community-onboarding", () => ({ readCommunityOnboardingState: () => ({ status: "active", stage: "dm", dmId: "dm_1" }), advanceCommunityOnboarding: mocks.advance }))vi.mock("@/hooks/community/mutations", async importOriginal => ({ ...await importOriginal<typeof import("@/hooks/community/mutations")>(), useAddReactionApi: () => vi.fn(), useToggleReactionApi: () => vi.fn(), useToggleMark: () => vi.fn(), useSetChannelNotif: () => ({ mutate: vi.fn() }) }))-vi.mock("./dm-header", () => ({ DmHeader: ({ onBack }: { onBack?: () => void }) => React.createElement("header", null, onBack ? React.createElement("button", { onClick: onBack, "aria-label": "Back" }) : null) }))+vi.mock("./dm-header", () => ({ DmHeaderSkeleton: () => React.createElement("header", { "data-testid": "pending-peer" }), DmHeader: ({ onBack }: { onBack?: () => void }) => React.createElement("header", null, onBack ? React.createElement("button", { onClick: onBack, "aria-label": "Back" }) : null) }))vi.mock("@/components/community/avatar", () => ({ Avatar: () => null }))vi.mock("@/components/community/messages/message-context-sheet", () => ({ MessageContextSheet: () => null }))vi.mock("@/components/community/messages/conversation-footer-shell", () => ({ ConversationFooterSlotProvider: ({ children }: PropsWithChildren) => children, ConversationFooterShell: ({ children }: PropsWithChildren) => children }))vi.mock("@/components/community/messages/composer", () => ({ ComposerSkeleton: () => null, Composer: ({ onAcceptSend }: { onAcceptSend: (text: string) => boolean }) => React.createElement("button", { onClick: () => onAcceptSend("hello") }, "Send") }))-vi.mock("@/components/community/messages/message-list", () => ({ MessageList: (props: { onRetry: (id: string) => void }) => {+vi.mock("@/components/community/messages/message-list", () => ({ MessageList: (props: { onRetry?: (id: string) => void }) => {mocks.list(props)- return React.createElement("button", { onClick: () => props.onRetry("failed") }, "Retry")+ return React.createElement("button", { onClick: () => props.onRetry?.("failed") }, "Retry")} }))-beforeEach(() => { mocks.api.mockReset(); mocks.advance.mockReset(); mocks.list.mockReset(); mocks.positionEntry = null; mocks.failed = true; mocks.breakpoint = "mobile" })+beforeEach(() => { mocks.api.mockReset(); mocks.advance.mockReset(); mocks.list.mockReset(); mocks.positionEntry = null; mocks.failed = true; mocks.breakpoint = "mobile"; mocks.identity = true; mocks.blocked = false })++async function createDmOwner() {+ const owner = await createCommunityQueryOwner("u_me")+ for (const id of ["dm_1", "dm_2"]) {+ const value = dmConversationEntryFixture()+ value.viewerId = "u_me"+ value.channelId = id+ value.channel = { ...value.channel, id }+ value.access = { ...value.access, channelId: id }+ value.readState = { ...value.readState, channelId: id }+ value.surfaceReceipt = { channelId: id, surfaceKind: "dm" }+ value.messages = []+ value.selection = { reason: "tail", anchorMessageId: null }+ value.readState = { ...value.readState, lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 }+ value.page = { ...value.page, olderCursor: null, hasMoreOlder: false, latestSeq: 0 }+ await seedConversationEntry(owner.client, value)+ }+ return owner+}describe("real DmView accepted send UI lifecycle", () => {+ it("keeps qualified messages when peer identity is absent and restricts sends until the peer relationship is known", async () => {+ const owner = await createDmOwner()+ mocks.identity = false+ await act(async () => {+ owner.registry.collections.profiles.utils.writeDelete("peer")+ owner.registry.collections.channelMemberships.utils.writeDelete("dm_1:peer:access")+ })+ const wrapper = ({ children }: PropsWithChildren) => React.createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "u_me", retainOwner: true }, children)+ const view = render(React.createElement(DmView, { dmId: "dm_1" }), { wrapper })+ const retained = screen.getByRole("button", { name: "Retry" })+ expect(screen.getByTestId("pending-peer")).toBeInTheDocument()+ expect(mocks.list.mock.lastCall?.[0].messages).toHaveLength(1)+ expect(mocks.list.mock.lastCall?.[0].onRetry).toBeUndefined()+ expect(screen.queryByRole("button", { name: "Send" })).toBeNull()+ await act(async () => owner.registry.collections.channelMemberships.utils.writeUpsert({ id: "dm_1:peer:access", channelId: "dm_1", userId: "peer", relation: "access", source: "added", isCreator: false, role: null }))+ await waitFor(() => expect(screen.getByRole("button", { name: "Send" })).toBeInTheDocument())+ expect(mocks.list.mock.lastCall?.[0].channel).toBe("Direct message")+ expect(screen.getByRole("button", { name: "Retry" })).toBe(retained)+ expect(mocks.api).not.toHaveBeenCalled()+ view.unmount()+ })++ it("keeps a known blocked peer hidden even when its presentation profile is missing", async () => {+ const owner = await createDmOwner()+ mocks.identity = false+ mocks.blocked = true+ await act(async () => owner.registry.collections.profiles.utils.writeDelete("peer"))+ const wrapper = ({ children }: PropsWithChildren) => React.createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "u_me", retainOwner: true }, children)+ const view = render(React.createElement(DmView, { dmId: "dm_1" }), { wrapper })+ expect(mocks.list).not.toHaveBeenCalled()+ expect(screen.queryByRole("button", { name: "Send" })).toBeNull()+ expect(screen.getByText("You have blocked this user. Unblock to send messages.")).toBeInTheDocument()+ expect(mocks.api).not.toHaveBeenCalled()+ view.unmount()+ })+it("passes a fresh same-DM position attempt and route activity to the retained message list", async () => {- const owner = await createCommunityQueryOwner("u_me")+ const owner = await createDmOwner()const wrapper = ({ children }: PropsWithChildren) => React.createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "u_me", retainOwner: true }, children)mocks.positionEntry = {}const first = mocks.positionEntry@@ -55,7 +111,7 @@ describe("real DmView accepted send UI lifecycle", () => {view.unmount()})it.each(["send", "retry"] as const)("continues %s after target view retires without advancing old onboarding", async action => {- const owner = await createCommunityQueryOwner("u_me")+ const owner = await createDmOwner()owner.runtime.messageStream.actions.accept({ kind: "dm", id: "dm_1" }, { nonce: "retry_nonce", tempId: "temp_retry", message: { type: "chat", authorId: "u_me", content: "retry" }, localUploads: [] })owner.runtime.messageStream.actions.dispatch({ kind: "dm", id: "dm_1" }, { type: "postFail", nonce: "retry_nonce" })let finish!: (value: unknown) => void@@ -76,7 +132,7 @@ describe("real DmView accepted send UI lifecycle", () => {view.unmount()})it.each(["send", "retry"] as const)("allows a current %s callback after real confirmation", async action => {- const owner = await createCommunityQueryOwner("u_me")+ const owner = await createDmOwner()owner.runtime.messageStream.actions.accept({ kind: "dm", id: "dm_1" }, { nonce: "retry_nonce", tempId: "temp_retry", message: { type: "chat", authorId: "u_me", content: "retry" }, localUploads: [] })owner.runtime.messageStream.actions.dispatch({ kind: "dm", id: "dm_1" }, { type: "postFail", nonce: "retry_nonce" })mocks.api.mockResolvedValueOnce({ message: { id: "confirmed", seq: 9, type: "chat", content: "hello", authorId: "u_me", authorName: "Me", authorImage: null, authorAvatarVersion: 0, createdAt: "2026-10-09T00:00:00Z", embeds: [] } })@@ -91,14 +147,14 @@ describe("real DmView accepted send UI lifecycle", () => {describe("DM initial responsive Back admission", () => {it("includes the mobile Back control in server markup before breakpoint effects", async () => {mocks.breakpoint = "unknown"- const owner = await createCommunityQueryOwner("u_me")+ const owner = await createDmOwner()const markup = renderToString(React.createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "u_me", retainOwner: true },React.createElement(DmView, { dmId: "dm_1" })))expect(markup).toContain('aria-label="Back"')})it.each(["unknown", "mobile", "desktop"])("leaves Back display to its native responsive component while breakpoint is %s", async breakpoint => {mocks.breakpoint = breakpoint- const owner = await createCommunityQueryOwner("u_me")+ const owner = await createDmOwner()const wrapper = ({ children }: PropsWithChildren) => React.createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "u_me", retainOwner: true }, children)const view = render(React.createElement(DmView, { dmId: "dm_1" }), { wrapper })expect(screen.getByRole("button", { name: "Back" })).toBeInTheDocument()diff --git a/src/web/src/components/community/channels/dm-view.tsx b/src/web/src/components/community/channels/dm-view.tsxindex b4e0781fa..a27953f74 100644--- a/src/web/src/components/community/channels/dm-view.tsx+++ b/src/web/src/components/community/channels/dm-view.tsx@@ -6,10 +6,11 @@ import { useAtom, useCreateAtom } from "@tanstack/react-store"import { useCommunityRuntime } from "@/stores/community/runtime"import { toast } from "sonner"import { useBreakpoint } from "@/hooks/use-mobile"-import { DmHeader } from "@/components/community/channels/dm-header"+import { DmHeader, DmHeaderSkeleton } from "@/components/community/channels/dm-header"import { DmLoadingFrame } from "@/components/community/channels/dm-loading-frame"import { DmRouteErrorFrame } from "@/components/community/channels/dm-route-error-frame"import { Avatar } from "@/components/community/avatar"+import { Skeleton } from "@/components/ui/skeleton"import { MessageList } from "@/components/community/messages/message-list"import { MessageContextSheet } from "@/components/community/messages/message-context-sheet"import { Composer, ComposerSkeleton, type SendAttachment } from "@/components/community/messages/composer"@@ -58,6 +59,7 @@ import { useSetChannelNotif } from "@/hooks/community/mutations"import { toastApiError } from "@/lib/api/client"import {useCanonicalProfilesByUserId,+ useCanonicalCommunityProfile, useChannelRosterRows,} from "@/lib/community-db/projections"import { useNativeSystemNotificationConversationDismissal } from "@/hooks/community/use-native-system-notifications"import { commitCommunityChannelRoute } from "@/lib/community/last-community-route"@@ -88,16 +90,29 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeComconst currentUser = useCurrentUser()const metadata = useChannelMetadata(null, dmId)const uiHandlers = useUiHandlers()- const notifications = useNotificationSettings()+ const notifications = useNotificationSettings(false)const setNotification = useSetChannelNotif()- const dmsQuery = useDms()+ const dmsQuery = useDms(false, true)const dms = dmsQuery.dmsconst dmsLoading = dmsQuery.isLoading- const { friends: rawFriends, blocked } = useFriends()- const dm = useMemo(() => dms.find((candidate) => candidate.id === dmId) ?? null, [dms, dmId])- const dmBlocked = !!dm && blocked.some((b) => (b.userId ?? b.id) === dm.userId)+ const { friends: rawFriends, blocked } = useFriends({ enabled: false })+ const access = useChannelRosterRows(dmId, "access")+ const peers = [...new Set(access.filter(row => row.userId !== currentUser.id).map(row => row.userId))]+ const directoryDm = dms.find(candidate => candidate.id === dmId)+ const peerId = peers.length === 1 ? peers[0] : peers.length === 0 ? directoryDm?.userId ?? null : null+ const peerProfile = useCanonicalCommunityProfile(peerId)+ const dm = useMemo(() => {+ if (!peerId) return null+ const known = dms.find(candidate => candidate.id === dmId && candidate.userId === peerId)+ if (known) return known+ const profile = readCommunityProfile(peerProfile ? { ...peerProfile, name: peerProfile.name ?? "Direct message" } : { id: peerId, name: "Direct message" }, peerId)+ return { ...profile, id: dmId, userId: peerId, status: profile.presence, preview: "" }+ }, [dms, dmId, peerId, peerProfile])+ const displayName = dm?.name ?? "Direct message"+ const dmBlocked = !!peerId && blocked.some((b) => (b.userId ?? b.id) === peerId)const historyAllowed = !dmBlocked && metadata.canRead+ const sendAllowed = historyAllowed && !!peerIdconst profilesByUserId = useCanonicalProfilesByUserId()// Enrich with presence — the Composer @-picker uses `f.status` to render// the avatar presence dot; without this enrichment every avatar shows offline.@@ -143,7 +158,7 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeComnavigationBlocked,anchorReconciled,readSnapshot, readSnapshotFetching, initialPositionKnown,- initialLoadError, retryInitialLoad, retryingInitialLoad, observation, positionEntry, positionScope, positionDataState, messageWindow,+ initialLoadError, retryInitialLoad, retryingInitialLoad, observation, positionEntry, positionScope, positionDataState, targetPositionDataState, messageWindow,} = useDmMessages(dmId, {enabled: !dmBlocked && !metadata.revoked && !metadata.denied,viewerUserId: currentUser.id,@@ -329,6 +344,7 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom// A DM is a channel (type='dm'), so its id IS the mark route's channelId.onMark: (id: string) => toggleMark(dmId, id),onRetry: (id: string) => {+ if (!sendAllowed) returnconst m = messages.find((x) => x.id === id)if (!m?.clientNonce) returnconst assertActive = sendView.capture()@@ -351,11 +367,12 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeComonPreviewAttachment: (attachment: FileAttachment) => {uiHandlers.previewAttachment?.(attachment)},- }), [toggleReaction, dmId, currentUser.id, addReaction, messages, setReplyTo, toggleMark, retryDmMessage, sendView, advanceOnboardingAfterSend, communityRuntime.messageStream.actions, uiHandlers])+ }), [toggleReaction, dmId, currentUser.id, addReaction, messages, setReplyTo, toggleMark, retryDmMessage, sendView, advanceOnboardingAfterSend, communityRuntime.messageStream.actions, uiHandlers, sendAllowed])// DM endpoint ignores mentionType. Replies are supported — the backend// persists replyToId for DMs too.const acceptDmSend = (markdown: string, attachments?: SendAttachment[]): boolean => {+ if (!sendAllowed) return falseconst assertActive = sendView.capture()const receipt = acceptDmMessage({assertActive,@@ -381,18 +398,14 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeComreturn true}- const handleTyping = () => { communityWsSendTyping(communityRuntime, { channelId: dmId }) }+ const handleTyping = () => { if (sendAllowed) communityWsSendTyping(communityRuntime, { channelId: dmId }) }- // The DM row owns header/composer identity. Until it is known, keep the- // complete DM frame pending; once known, read-state and message fetching- // are allowed to affect only MessageList below.const loadingOwnership = resolveDmLoadingOwnership({hasDm: !!dm,dmsLoading,messagesLoading,})- const routeReady = historyAllowed && !navigationBlocked && !loadingOwnership.fullFramePending- && !loadingOwnership.missingPeer && !!dm+ const routeReady = historyAllowed && !navigationBlockeduseEffect(() => {if (!routeCommitted || !routeReady) returncommitCommunityChannelRoute(currentUser.id, null, dmId)@@ -406,25 +419,27 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeComreturn <DmLoadingFrame reserveBackSlot />}- if (loadingOwnership.fullFramePending) {+ if (!historyAllowed && loadingOwnership.fullFramePending) {return <DmLoadingFrame reserveBackSlot />}- if (loadingOwnership.missingPeer || !dm) {+ if (!historyAllowed && (loadingOwnership.missingPeer || !dm)) {return <DmRouteErrorFrame onRetry={() => { void dmsQuery.refetch({ cancelRefetch: false }) }}retrying={dmsQuery.isFetching} reserveBackSlot />}return (<>- <DmHeader+ {dm ? <DmHeaderdm={dm}onBack={goBack}+ onRetryIdentity={!peerProfile?.name ? () => { void dmsQuery.refetch({ cancelRefetch: false }) } : undefined}+ retryingIdentity={dmsQuery.isFetching}notifLevel={(notifications.channel[dmId] ?? notifLevelDisplay("all")) as NotifLevel}onSetNotifLevel={(level) => setNotification.mutate({ channelId: dmId, level }, {onError: (error) => toastApiError(error, "Failed to update notification level"),})}- />+ /> : <DmHeaderSkeleton onBack={goBack} onRetryIdentity={() => { void dmsQuery.refetch({ cancelRefetch: false }) }} retryingIdentity={dmsQuery.isFetching} />}<maindata-slot="community-conversation-surface"data-channel-id={dmId}@@ -434,7 +449,7 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom{dmBlocked ? null : metadata.denied ? <div role="alert" className="flex min-h-0 flex-1 items-center justify-center p-4 text-sm text-muted-foreground">You can no longer read this conversation.</div> : metadata.status === "retryable-error" ? <ConversationResolutionErrorFrame as="div" onRetry={metadata.retry} retrying={metadata.retrying} /> : !historyAllowed && initialLoadError ? <ConversationResolutionErrorFrame as="div" onRetry={retryInitialLoad} retrying={retryingInitialLoad} /> : <MessageListkey={dmId}variant="dm"- channel={dm.name}+ channel={displayName}messages={messages}loading={!historyAllowed || loadingOwnership.messageBodyLoading}initialLoadError={initialLoadError}@@ -448,7 +463,7 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeComonReply={dmBlocked ? undefined : messageActions.onReply}onCopy={messageActions.onCopy}onMark={dmBlocked ? undefined : messageActions.onMark}- onRetry={dmBlocked ? undefined : messageActions.onRetry}+ onRetry={sendAllowed ? messageActions.onRetry : undefined}onDismiss={dmBlocked ? undefined : messageActions.onDismiss}onPreviewImage={messageActions.onPreviewImage}onPreviewAttachment={messageActions.onPreviewAttachment}@@ -463,6 +478,7 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCompositionEntry={positionEntry}positionScope={positionScope}positionDataState={positionDataState}+ targetPositionDataState={targetPositionDataState}messageWindow={messageWindow}active={routeCommitted}positioningActive@@ -479,16 +495,20 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeComunreadCount={unreadCount}typingUsers={typingUsers.map((id) => typingNames[id] ?? resolveUserName(id))}hero={- <>+ dm ? <><div className="relative mb-3 w-fit"><Avatar label={dm.avatar} seed={dm.userId} size={64} /></div><h2 className="text-2xl font-semibold leading-tight">{dm.name}</h2><p className="mt-1 text-sm text-muted-foreground">This is the beginning of your direct message history with <span className="font-medium text-foreground">{dm.name}</span>.</p>+ </> : <>+ <Skeleton className="mb-3 size-16 rounded-full" />+ <Skeleton className="h-8 w-48 rounded" />+ <Skeleton className="mt-1 h-5 w-72 max-w-full rounded" /></>}/>}<ConversationFooterShelldata-onboarding-target="dm-composer"- data-onboarding-name={dm.name}+ data-onboarding-name={displayName}>{dmBlocked ? (<div@@ -497,10 +517,10 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom>You have blocked this user. Unblock to send messages.</div>- ) : metadata.denied ? null : !historyAllowed ? <ComposerSkeleton /> : (+ ) : metadata.denied ? null : !sendAllowed ? <ComposerSkeleton /> : (<ComposersendContract="accepted"- channel={dm.name}+ channel={displayName}channelType={metadata.data?.type}context="dm"// DM context short-circuits `rankMentionItems` to `[]` — no popup,diff --git a/src/web/src/components/community/channels/text-channel-surface.tsx b/src/web/src/components/community/channels/text-channel-surface.tsxindex 4327ef545..a92eb18ee 100644--- a/src/web/src/components/community/channels/text-channel-surface.tsx+++ b/src/web/src/components/community/channels/text-channel-surface.tsx@@ -86,6 +86,7 @@ export function TextChannelSurface({viewerUserId: viewer.id,isChildChannel: false,anchorMessageId,+ threadsEnabled: rightPanel === "threads",})useEffect(() => {setRightPanel(null)@@ -163,7 +164,7 @@ export function TextChannelSurface({initialPositionMessageId={feed.initialPositionMessageId}positionEntry={feed.positionEntry}positionScope={feed.positionScope}- positionDataState={feed.positionDataState}+ positionDataState={feed.positionDataState} targetPositionDataState={feed.targetPositionDataState}messageWindow={feed.messageWindow}isFetching={feed.isFetching}isFetchingOlder={feed.isFetchingOlder}diff --git a/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts b/src/web/src/components/community/channels/thread-channel-surface.dom.test.tsindex 4c4a2cbba..bdcb672be 100644--- a/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts+++ b/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts@@ -299,6 +299,7 @@ describe("ThreadChannelSurface ownership", () => {viewerUserId: "viewer_1",isChildChannel: true,anchorMessageId: "m_target",+ threadsEnabled: false,})const messageListProps = mockedMessageList.mock.calls.at(-1)![0]const opener = messageListProps.hero as React.ReactElement<React.ComponentProps<typeof ThreadOpener>>diff --git a/src/web/src/components/community/channels/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsxindex d01d9be4e..f2f28d865 100644--- a/src/web/src/components/community/channels/thread-channel-surface.tsx+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx@@ -125,6 +125,7 @@ export function ThreadChannelSurface({viewerUserId: viewer.id,isChildChannel: true,anchorMessageId,+ threadsEnabled: rightPanel === "threads",})const displayName = localName ?? channelNameconst Body = embedded ? "div" : "main"@@ -255,7 +256,7 @@ export function ThreadChannelSurface({initialPositionMessageId={controller.feed.initialPositionMessageId}positionEntry={controller.feed.positionEntry}positionScope={controller.feed.positionScope}- positionDataState={controller.feed.positionDataState}+ positionDataState={controller.feed.positionDataState} targetPositionDataState={controller.feed.targetPositionDataState}messageWindow={controller.feed.messageWindow}isFetching={controller.feed.isFetching}isFetchingOlder={controller.feed.isFetchingOlder}diff --git a/src/web/src/components/community/channels/thread-split-parent-surface.tsx b/src/web/src/components/community/channels/thread-split-parent-surface.tsxindex 4a1ec705b..d9a5984a9 100644--- a/src/web/src/components/community/channels/thread-split-parent-surface.tsx+++ b/src/web/src/components/community/channels/thread-split-parent-surface.tsx@@ -76,7 +76,7 @@ export function ThreadSplitParentSurface({accessAllowed: active && metadata.canRead,roleDisplayAllowed: metadata.canRead,})- const notifs = useNotificationSettings()+ const notifs = useNotificationSettings(false)const { mutate: setChannelNotif } = useSetChannelNotif()const notificationLevel = (notifs.channel[channel.id] as ChannelNotifLevel) ?? USE_SERVER_DEFAULTconst setNotificationLevel = (level: ChannelNotifLevel) => {diff --git a/src/web/src/components/community/messages/message-list-controller.ts b/src/web/src/components/community/messages/message-list-controller.tsindex e23e7750f..068b2b615 100644--- a/src/web/src/components/community/messages/message-list-controller.ts+++ b/src/web/src/components/community/messages/message-list-controller.ts@@ -19,6 +19,7 @@ export function useMessageListController({positionEntry,positionScope,positionDataState,+ targetPositionDataState,messageWindow,active,positioningActive,@@ -112,6 +113,7 @@ export function useMessageListController({positionEntry,positionScope,positionDataState: positionDataState ?? (initialLoadError ? "error" : loading ? "pending" : undefined),+ targetPositionDataState,messageWindow,active,positioningActive,diff --git a/src/web/src/components/community/messages/message-list-types.ts b/src/web/src/components/community/messages/message-list-types.tsindex 88fe1a288..4fcf5d91c 100644--- a/src/web/src/components/community/messages/message-list-types.ts+++ b/src/web/src/components/community/messages/message-list-types.ts@@ -36,6 +36,7 @@ export type MessageListProps = {positionEntry?: object | nullpositionScope?: VirtualListPositionScopepositionDataState?: MessagePositionState+ targetPositionDataState?: MessagePositionStatemessageWindow?: objectactive?: booleanpositioningActive?: booleandiff --git a/src/web/src/components/community/messages/message-list.tsx b/src/web/src/components/community/messages/message-list.tsxindex 5cbc3c170..59aa97aad 100644--- a/src/web/src/components/community/messages/message-list.tsx+++ b/src/web/src/components/community/messages/message-list.tsx@@ -26,7 +26,7 @@ function MessageListEntry({}: MessageListProps) {const [admitted, setAdmitted] = useState(false)const ready = initialScrollReady && (props.messages.length > 0 || !props.loading && !props.initialLoadError)- || !!props.scrollToMessageId && props.positionDataState === "ready" && props.messages.length > 0+ || !!props.scrollToMessageId && (props.targetPositionDataState ?? props.positionDataState) === "ready" && props.messages.length > 0if (ready && !admitted) setAdmitted(true)if (props.positionScope && !admitted && !ready && !props.initialLoadError) return <MessageListSkeleton variant={variant} />return <MessageListOwner {...props} variant={variant} initialScrollReady={initialScrollReady} />diff --git a/src/web/src/components/community/messages/thread-opener.dom.test.ts b/src/web/src/components/community/messages/thread-opener.dom.test.tsindex 3cdef786e..1fd84d4ed 100644--- a/src/web/src/components/community/messages/thread-opener.dom.test.ts+++ b/src/web/src/components/community/messages/thread-opener.dom.test.ts@@ -26,6 +26,18 @@ import { ThreadOpener } from "./thread-opener"import { attachmentImageFrameStyle } from "./attachment-layout"describe("ThreadOpener image attachment layout", () => {+ it("retries an unavailable opener locally and disables its control while that read is pending", () => {+ const refetch = vi.fn()+ useMessageMock.mockReturnValue({ message: undefined, isLoading: false, isError: true, isFetching: false, refetch })+ const tree = () => React.createElement(ThreadOpener, { parentMessageId: "opener", parentChannelId: "parent", serverId: "server", viewerUserId: "viewer" })+ const view = render(tree())+ fireEvent.click(view.getByRole("button", { name: "Retry original message" }))+ expect(refetch).toHaveBeenCalledExactlyOnceWith({ cancelRefetch: false })+ useMessageMock.mockReturnValue({ message: undefined, isLoading: false, isError: true, isFetching: true, refetch })+ view.rerender(tree())+ expect(view.getByRole("button", { name: "Retry original message" })).toBeDisabled()+ })+afterEach(() => {profileState.name = "Alice"vi.useRealTimers()diff --git a/src/web/src/components/community/messages/thread-opener.tsx b/src/web/src/components/community/messages/thread-opener.tsxindex 6de9fdb93..c715a23ba 100644--- a/src/web/src/components/community/messages/thread-opener.tsx+++ b/src/web/src/components/community/messages/thread-opener.tsx@@ -18,6 +18,7 @@ import { useCanonicalCommunityProfile } from "@/lib/community-db/projections"import { useHoverCapable } from "@/hooks/use-hover-capable"import { MessageReactions } from "./message-reactions"import { RemoteContentImage } from "@/components/remote-image/remote-image"+import { Button } from "@/components/ui/button"// Thread opener — the parent message the thread was created from, pinned at// the top of the thread's message list. Deliberately styled like a REGULAR@@ -58,7 +59,7 @@ export function ThreadOpener({onJump?: () => void}) {const hoverCapable = useHoverCapable()- const { message: msg, isLoading, isError } = useMessage(parentMessageId, {+ const { message: msg, isLoading, isError, refetch, isFetching } = useMessage(parentMessageId, {...(parentChannelId ? { channelId: parentChannelId } : {}),serverId,})@@ -91,6 +92,8 @@ export function ThreadOpener({<span>Thread started from a message</span></div><p className="text-sm italic text-muted-foreground">Original message is unavailable.</p>+ <Button variant="ghost" size="sm" className="h-11 self-start sm:h-8" disabled={isFetching}+ onClick={() => { void refetch({ cancelRefetch: false }) }}>Retry original message</Button></div>)}diff --git a/src/web/src/components/community/shell/cached-conversation-route.dom.test.tsx b/src/web/src/components/community/shell/cached-conversation-route.dom.test.tsxindex 861c0f8bb..f6c3b5aea 100644--- a/src/web/src/components/community/shell/cached-conversation-route.dom.test.tsx+++ b/src/web/src/components/community/shell/cached-conversation-route.dom.test.tsx@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"-import { useLayoutEffect } from "react"+import { StrictMode, useLayoutEffect } from "react"import { IsRestoringProvider, QueryClientProvider } from "@tanstack/react-query"import { CurrentUserProvider } from "@/contexts/community/current-user"import { CommunityDbProvider } from "@/lib/community-db/projections"@@ -7,14 +7,19 @@ import { CommunityRouteContext } from "./community-route-context"import { CommunityModuleRoute } from "./community-module-route"import { createCommunityQueryOwner } from "@/test/community-query-owner"import { conversationEntryFixture, seedConversationEntry } from "@/test/conversation-entry-fixtures"-import { act, render } from "@/test/react-dom-harness"-import { installMessageScrollFixture, restoreMessageScrollFixture, resize } from "@/test/message-scroll-fixture"+import { act, fireEvent, render } from "@/test/react-dom-harness"+import { installMessageScrollFixture, restoreMessageScrollFixture, resize, scrollFixture } from "@/test/message-scroll-fixture"+import { useCommunityNavigationController } from "./use-community-navigation-controller"+import { normalizeCommunityHref } from "@/lib/community/community-route"+import { resolveCommunityLandingHref } from "@/lib/community/last-channel"+import { virtualListPositionKey } from "@/lib/community/virtual-list-position"+import { captureChannelMetadataToken } from "@/lib/community/conversation-qualification"import { disposeReadCoordinator, getLocalReadingPosition } from "@/hooks/community/read-coordinator"import { disposeAccountReadStateReconciliation } from "@/hooks/community/community-ws/read-state-reconciliation"-const mocks = vi.hoisted(() => ({ load: vi.fn(), replace: vi.fn(), memory: vi.fn(), dismiss: vi.fn(), snapshots: [] as unknown[], observedRows: new Set<Element>(), href: "/c/channels/old/old" }))+const mocks = vi.hoisted(() => ({ load: vi.fn(), push: vi.fn(), replace: vi.fn(), memory: vi.fn(), dismiss: vi.fn(), snapshots: [] as unknown[], observedRows: new Set<Element>(), href: "/c/channels/old/old" }))vi.mock("next/navigation", () => ({- useRouter: () => ({ replace: mocks.replace, push: vi.fn() }),+ useRouter: () => ({ replace: mocks.replace, push: mocks.push }),usePathname: () => mocks.href.split("?")[0],useSearchParams: () => new URLSearchParams(mocks.href.split("?")[1]),}))@@ -59,6 +64,7 @@ beforeEach(async () => {mocks.memory.mockClear()mocks.dismiss.mockClear()mocks.replace.mockClear()+ mocks.push.mockClear()mocks.href = "/c/channels/old/old"mocks.load.mockImplementation((url: string) => {if (url === "/api/community/users/me/attention") return Promise.resolve({scopes: [], items: [], limit: 100, truncated: false})@@ -94,7 +100,80 @@ async function mount(restoring = false, target = href) {}describe("cached target through the real route, entry and message consumers", () => {- it("keeps a cold forum opener unknown through restore instead of mounting then removing the composer", async () => {+ it.each([false, true])("keeps the restored offset through an already-active row selection after a server return (StrictMode=%s)", async strict => {+ const entry = conversationEntryFixture()+ entry.channel = { ...entry.channel, type: "text", messageCount: 42 }+ entry.messages = Array.from({ length: 42 }, (_, index) => ({ ...entry.messages[0], id: `m${index + 1}`, seq: index + 1,+ createdAt: new Date(Date.UTC(2026, 9, 1, 0, 0, index + 1)).toISOString() }))+ entry.readState = { channelId: "c1", lastReadMessageId: "m42", lastReadSeq: 42, lastReadAt: entry.messages[41].createdAt }+ entry.selection = { reason: "tail", anchorMessageId: null }+ entry.page = { ...entry.page, hasMoreOlder: false, hasMoreNewer: false, olderCursor: null, newerCursor: null, latestSeq: 42 }+ await seedConversationEntry(owner.client, entry)+ scrollFixture.width = 905+ scrollFixture.height = 683+ entry.messages.forEach((message, index) => scrollFixture.bodyHeights.set(message.id, 90 + index % 5 * 31))+ mocks.href = href+ let revision = 1+ let navigation!: ReturnType<typeof useCommunityNavigationController>+ function Route() {+ const current = useCommunityNavigationController({ ...normalizeCommunityHref(mocks.href), revision })+ const target = current.pendingHref ?? mocks.href+ useLayoutEffect(() => { navigation = current }, [current])+ return <CommunityRouteContext value={{ breakpoint: "desktop", frame: { revision }, navigation: current } as never}>+ {target.startsWith("/c/channels/")+ ? <CommunityModuleRoute key="server:s1" href={target} routeCommitted={!current.navigationPending} />+ : <div data-testid="away">Away</div>}+ </CommunityRouteContext>+ }+ const tree = () => <QueryClientProvider client={owner.client}><CommunityDbProvider registry={owner.registry}>+ <CurrentUserProvider initialUser={{ id: "viewer", name: "Viewer", avatar: "V", email: "[email protected]" }}>+ {strict ? <StrictMode><Route /></StrictMode> : <Route />}+ </CurrentUserProvider>+ </CommunityDbProvider></QueryClientProvider>+ view = render(tree())+ resize()+ const root = () => view!.getByTestId("community-message-scroller")+ const previous = root()+ fireEvent.wheel(previous, { deltaY: -600 })+ act(() => previous.scrollTo({ top: previous.scrollHeight - previous.clientHeight - 600 }))+ resize()+ const body = Array.from(previous.querySelectorAll<HTMLElement>("[data-msg-id]"))+ .find(row => row.getBoundingClientRect().bottom > 0)!+ const id = body.dataset.msgId!+ const top = body.getBoundingClientRect().top+ const offset = previous.scrollTop+ const scope = { proof: captureChannelMetadataToken(owner.client, "c1"), kind: "messages" as const, tag: null }+ expect(owner.client.getQueryData(virtualListPositionKey(scope))).toMatchObject({ offset })+ const go = async (target: string) => {+ await act(async () => navigation.push(target))+ mocks.href = target+ revision += 1+ await act(async () => view!.rerender(tree()))+ resize()+ }+ await go("/c/me/friends")+ await go("/c/me/dm-test")+ expect(previous.isConnected).toBe(false)+ await act(async () => vi.advanceTimersByTimeAsync(6000))+ const previousLoad = mocks.load.getMockImplementation()!+ mocks.load.mockImplementation((url: string) => url === "/api/community/channels/c1/messages?entry=1"+ ? new Promise(() => {}) : previousLoad(url))+ const serverTarget = resolveCommunityLandingHref({ serverId: "s1", channelIds: ["c1"], last: "c1", breakpoint: "desktop" })+ await go(serverTarget)+ expect(serverTarget).toBe(href)+ expect(mocks.load.mock.calls.some(([url]) => url === "/api/community/channels/c1/messages?entry=1")).toBe(true)+ expect(root().scrollTop).toBeCloseTo(offset, 0)+ expect(root().querySelector<HTMLElement>(`[data-msg-id="${id}"]`)!.getBoundingClientRect().top).toBeCloseTo(top, 0)+ const admitted = navigation.entryIntent+ await act(async () => { navigation.cancelPendingNavigation(); navigation.push(href) })+ resize()+ expect(root().scrollTop).toBeCloseTo(offset, 0)+ expect(root().querySelector<HTMLElement>(`[data-msg-id="${id}"]`)!.getBoundingClientRect().top).toBeCloseTo(top, 0)+ expect(navigation.entryIntent).toBe(admitted)+ expect(mocks.load.mock.calls.filter(([url, options]) => String(url).endsWith("/read") && options?.method === "PUT")).toEqual([])+ })++ it("mounts cached forum child messages and keeps its composer while the opener remains pending", async () => {const entry = conversationEntryFixture()entry.channel = { ...entry.channel, type: "thread", parentChannelId: "parent", parentMessageId: "opener" }entry.surfaceReceipt = { channelId: entry.channelId, surfaceKind: "thread" }@@ -109,10 +188,13 @@ describe("cached target through the real route, entry and message consumers", ()})const target = `${href}?threadView=full`const mounted = await mount(true, target)- expect(mounted.queryByTestId("qualified-composer")).toBeNull()+ const composer = mounted.getByTestId("qualified-composer")+ const scroller = mounted.getByTestId("community-message-scroller")+ expect(composer).toBeVisible()mounted.rerender(node(false, false, target))await act(async () => {})- expect(mounted.queryByTestId("qualified-composer")).toBeNull()+ expect(mounted.getByTestId("qualified-composer")).toBe(composer)+ expect(mounted.getByTestId("community-message-scroller")).toBe(scroller)})it("keeps a canonical cached forum opener and composer through restore and route commit", async () => {diff --git a/src/web/src/components/community/shell/community-list-errors.dom.test.tsx b/src/web/src/components/community/shell/community-list-errors.dom.test.tsxindex 7f83edaf9..db81c062e 100644--- a/src/web/src/components/community/shell/community-list-errors.dom.test.tsx+++ b/src/web/src/components/community/shell/community-list-errors.dom.test.tsx@@ -7,7 +7,7 @@ import { CommunityRouteContext } from "@/contexts/community/route-frame"import { CommunityModuleRouteContext } from "@/contexts/community/module-route"import { normalizeCommunityHref } from "@/lib/community/community-route"import { communityKeys } from "@/lib/query-keys"-import { friendsQueryFn } from "@/hooks/community/use-friends"+import { friendsQueryFn, useFriends } from "@/hooks/community/use-friends"import { dmsProjectedQueryFn } from "@/hooks/community/use-dms"import FriendsRoute from "../social/friends-route"import { DmSidebarSlot } from "./dm-sidebar-slot"@@ -33,9 +33,11 @@ function response(path: string, populated = false) {if (path.endsWith("/dms")) return { conversations: populated ? [dm] : [] }throw new Error(`Unexpected list request: ${path}`)}+function SharedAccountReader() { useFriends(); return null }function node(owner: Awaited<ReturnType<typeof createCommunityQueryOwner>>, kind: Kind) {const href = kind === "friends" ? "/c/me/friends" : "/c/me"return <CommunityTestProvider client={owner.client} registry={owner.registry}>+ {kind === "friends" && <SharedAccountReader />}<CurrentUserProvider initialUser={{ id: "viewer", name: "Viewer", avatar: "V", email: "[email protected]" }}><CommunityRouteContext value={{ frame: { ...normalizeCommunityHref(href), revision: 1 } } as never}><CommunityModuleRouteContext value={{ href, routeCommitted: false }}>diff --git a/src/web/src/components/community/shell/dm-sidebar-slot.tsx b/src/web/src/components/community/shell/dm-sidebar-slot.tsxindex 9a5b64de4..fb8cb0183 100644--- a/src/web/src/components/community/shell/dm-sidebar-slot.tsx+++ b/src/web/src/components/community/shell/dm-sidebar-slot.tsx@@ -34,7 +34,7 @@ function MeSidebar({ pathname, routeCommitted }: { pathname: string; routeCommitisFetching,refetch,} = useDms()- const { blocked } = useFriends()+ const { blocked } = useFriends({ enabled: false })const initialError = isError && data === undefineduseObservedRegion("sidebar", !dmsLoading && !initialError, dms.length)const friendRequestCount = useInboxUnreads().friendRequests.lengthdiff --git a/src/web/src/components/community/shell/server-sidebar-slot.tsx b/src/web/src/components/community/shell/server-sidebar-slot.tsxindex 092d9252f..f04ed2b1e 100644--- a/src/web/src/components/community/shell/server-sidebar-slot.tsx+++ b/src/web/src/components/community/shell/server-sidebar-slot.tsx@@ -149,7 +149,7 @@ function ServerSidebar({ serverId, href, routeCommitted }: { serverId: string; hconst role = useViewerServerRole(serverId, currentUser.id)const isAdmin = routeCommitted && canManageServer(role)usePresence(routeCommitted && currentServer ? serverId : null)- const notifs = useNotificationSettings()+ const notifs = useNotificationSettings(false)const notifLevel = resolveServerNotificationDisplayLevel(notifs.server[serverId])const channelNotif = notifs.channelconst currentChannelId = routeChannelIddiff --git a/src/web/src/components/community/shell/use-community-navigation-controller.dom.test.ts b/src/web/src/components/community/shell/use-community-navigation-controller.dom.test.tsindex 6adc381a1..afb12382b 100644--- a/src/web/src/components/community/shell/use-community-navigation-controller.dom.test.ts+++ b/src/web/src/components/community/shell/use-community-navigation-controller.dom.test.ts@@ -289,6 +289,61 @@ describe("useCommunityNavigationController", () => {expect(hook.current.pendingHref).toBeNull()})+ it.each(["push", "pushImmediate", "replace"] as const)("keeps the admitted entry when idle cancellation precedes same-href %s", async method => {+ const hook = await renderController(), href = "/c/channels/s1/c1"+ await act(async () => hook.current.push(href))+ mocks.pathname.current = href+ mocks.frame.current = { ...normalizeCommunityHref(href), revision: 1 }+ await hook.rerender()+ const admitted = hook.current.entryIntent+ expect(admitted).toEqual({ href })+ mocks.push.mockClear()+ await act(async () => { hook.current.cancelPendingNavigation(); hook.current[method](href) })+ expect(hook.current.entryIntent).toBe(admitted)+ expect(hook.current.navigationPending).toBe(false)+ expect(mocks.push).not.toHaveBeenCalled()+ expect(mocks.replace).not.toHaveBeenCalled()+ })++ it.each(["push", "pushImmediate", "replace"] as const)("keeps intentional repeated msg and seq targets with %s", async method => {+ const hook = await renderController()+ for (const search of ["msg=m1", "seq=12"]) {+ const href = `/c/channels/s1/c1?${search}`+ await act(async () => hook.current.push(href))+ mocks.pathname.current = "/c/channels/s1/c1"+ mocks.search.current = new URLSearchParams(search)+ mocks.frame.current = { ...normalizeCommunityHref(href), revision: 1 }+ await hook.rerender()+ const previous = hook.current.entryIntent+ mocks.push.mockClear()+ await act(async () => hook.current[method](href))+ expect(hook.current.entryIntent).not.toBe(previous)+ expect(hook.current.entryIntent).toEqual({ href })+ expect(hook.current.navigationPending).toBe(false)+ expect(mocks.push).not.toHaveBeenCalled()+ expect(mocks.replace).not.toHaveBeenCalled()+ }+ })++ it("clears a submitted entry on synchronous router failure", async () => {+ const hook = await renderController()+ mocks.push.mockImplementationOnce(() => { throw new Error("router failed") })+ await expect(act(async () => hook.current.push("/c/channels/s1/c1"))).rejects.toThrow("router failed")+ expect(hook.current.entryIntent).toBeNull()+ expect(hook.current.navigationPending).toBe(false)+ })++ it("clears an admitted entry on native history even with no pending navigation", async () => {+ const hook = await renderController(), href = "/c/channels/s1/c1"+ await act(async () => hook.current.push(href))+ mocks.pathname.current = href+ mocks.frame.current = { ...normalizeCommunityHref(href), revision: 1 }+ await hook.rerender()+ expect(hook.current.entryIntent).not.toBeNull()+ await act(async () => window.dispatchEvent(new Event("popstate")))+ expect(hook.current.entryIntent).toBeNull()+ })+it.each(["push", "replace"] as const)("lets %s to the published route supersede a pending resolver", async (method) => {const hook = await renderController()let resolve!: (href: string) => voiddiff --git a/src/web/src/components/community/shell/use-community-navigation-controller.ts b/src/web/src/components/community/shell/use-community-navigation-controller.tsindex b8279a9d0..82a56de1d 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@@ -77,16 +77,26 @@ export function useCommunityNavigationController(}, [])const pendingBaselineRevisionRef = useRef(committedFrame.revision)const pendingBaselineLeafRef = useRef(committedFrame.leafKey)- const [navigationPending, setNavigationPending] = useAtom(useCreateAtom(false))+ const pendingState = useCreateAtom(false)+ const [navigationPending, setNavigationPending] = useAtom(pendingState)const [pendingHref, setPendingHref] = useAtom(useCreateAtom<string | null>(null))const [entryIntent, setEntryIntent] = useAtom(useCreateAtom<{ href: string; resume?: boolean } | null>(null))const cancelPendingNavigation = useCallback(() => {supersedeNavigationIntent(gateRef.current)- setEntryIntent(null)+ if (pendingState.get()) setEntryIntent(null)setNavigationPending(false)setPendingHref(null)- }, [setEntryIntent, setNavigationPending, setPendingHref])+ }, [pendingState, setEntryIntent, setNavigationPending, setPendingHref])++ const captureEntryIntent = useCallback((href: string, resume = false) => {+ const noop = href === publishedHref && !navigationPending+ const search = new URLSearchParams(normalizeCommunityHref(href).search)+ if (!noop || resume || search.has("msg") || search.has("seq")) {+ setEntryIntent({ href, ...(resume ? { resume: true } : {}) })+ }+ return noop+ }, [navigationPending, publishedHref, setEntryIntent])useEffect(() => {if (pendingHref === null) return@@ -111,12 +121,12 @@ export function useCommunityNavigationController(useEffect(() => {if (typeof window === "undefined") return- const onPopState = () => cancelPendingNavigation()+ const onPopState = () => { setEntryIntent(null); cancelPendingNavigation() }window.addEventListener("popstate", onPopState)return () => {window.removeEventListener("popstate", onPopState)}- }, [cancelPendingNavigation])+ }, [cancelPendingNavigation, setEntryIntent])const submitNavigation = useCallback((submit: () => void, isCurrent?: () => boolean) => {if (isCurrent && !isCurrent()) return@@ -131,8 +141,7 @@ export function useCommunityNavigationController(const push = useCallback((...args: Parameters<typeof router.push>) => {const [href] = args- setEntryIntent({ href })- if (href === publishedHref && !navigationPending) { settledIntentRef.current = null; navigationNoop(href); return }+ if (captureEntryIntent(href)) { settledIntentRef.current = null; navigationNoop(href); return }beginNavigation(href)void prepareNavigationMetadata(queryClient, href, "foreground")supersedeNavigationIntent(gateRef.current)@@ -147,11 +156,10 @@ export function useCommunityNavigationController(setPendingHref(href)})submitNavigation(() => router.push(...args), isCurrent)- }, [captureIntent, committedFrame.leafKey, committedFrame.revision, navigationPending, publishedHref, queryClient, router, setEntryIntent, setNavigationPending, setPendingHref, submitNavigation])+ }, [captureEntryIntent, captureIntent, committedFrame.leafKey, committedFrame.revision, queryClient, router, setNavigationPending, setPendingHref, submitNavigation])const pushImmediate = useCallback((href: string, prepare?: (action?: Action) => void) => {- setEntryIntent({ href })- if (href === publishedHref && !navigationPending) { settledIntentRef.current = null; navigationNoop(href); prepare?.(); return }+ if (captureEntryIntent(href)) { settledIntentRef.current = null; navigationNoop(href); prepare?.(); return }const action = beginNavigation(href)prepare?.(action)void prepareNavigationMetadata(queryClient, href, "foreground")@@ -166,11 +174,10 @@ export function useCommunityNavigationController(setPendingHref(href)})submitNavigation(() => router.push(href), isCurrent)- }, [captureIntent, committedFrame.leafKey, committedFrame.revision, navigationPending, publishedHref, queryClient, router, setEntryIntent, setNavigationPending, setPendingHref, submitNavigation])+ }, [captureEntryIntent, captureIntent, committedFrame.leafKey, committedFrame.revision, queryClient, router, setNavigationPending, setPendingHref, submitNavigation])const replace = useCallback((href: string, options?: { resume?: boolean }) => {- setEntryIntent({ href, ...(options?.resume ? { resume: true } : {}) })- if (href === publishedHref && !navigationPending) { settledIntentRef.current = null; navigationNoop(href); return }+ if (captureEntryIntent(href, options?.resume)) { settledIntentRef.current = null; navigationNoop(href); return }beginNavigation(href)void prepareNavigationMetadata(queryClient, href, "foreground")supersedeNavigationIntent(gateRef.current)@@ -179,7 +186,7 @@ export function useCommunityNavigationController(setNavigationPending(true)setPendingHref(href)submitNavigation(() => router.replace(href))- }, [committedFrame.leafKey, committedFrame.revision, navigationPending, publishedHref, queryClient, router, setEntryIntent, setNavigationPending, setPendingHref, submitNavigation])+ }, [captureEntryIntent, committedFrame.leafKey, committedFrame.revision, queryClient, router, setNavigationPending, setPendingHref, submitNavigation])const resolveAndPush = useCallback(async (resolve: () => Promise<string>) => {pendingBaselineRevisionRef.current = committedFrame.revisiondiff --git a/src/web/src/components/community/social/friends-route.tsx b/src/web/src/components/community/social/friends-route.tsxindex b97ded4e6..e143320b5 100644--- a/src/web/src/components/community/social/friends-route.tsx+++ b/src/web/src/components/community/social/friends-route.tsx@@ -24,7 +24,7 @@ import { toastApiError } from "@/lib/api/client"export default function MeFriendsPage() {const { router, searchParams } = useCommunityModuleLocation()const activeTab = searchParams.get("tab") === "new" ? "new" : "all"- const { friends: rawFriends, pending, blocked, isPending: isLoading, data, isError, isFetching, refetch } = useFriends()+ const { friends: rawFriends, pending, blocked, isPending: isLoading, data, isError, isFetching, refetch } = useFriends({ enabled: false })const uiHandlers = useUiHandlers()const profilesByUserId = useCanonicalProfilesByUserId()const friends = useMemo(diff --git a/src/web/src/contexts/community/conversation-activity.ts b/src/web/src/contexts/community/conversation-activity.tsindex e5629bb5c..3a240f063 100644--- a/src/web/src/contexts/community/conversation-activity.ts+++ b/src/web/src/contexts/community/conversation-activity.ts@@ -8,3 +8,9 @@ export const ConversationPresentationContext = createContext<boolean | null>(nulexport function useConversationActivity() {return useContext(ConversationActivityContext)}++export function useConversationPresentation() {+ const presented = useContext(ConversationPresentationContext)+ const active = useConversationActivity()+ return presented ?? active+}diff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.tsindex d9894697d..b70a5aea1 100644--- a/src/web/src/hooks/community/community-ws/reconnect-messages.ts+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.ts@@ -8,6 +8,10 @@ import { ApiError, isAbortError } from "@/lib/errors"import { communityKeys } from "@/lib/query-keys"import { getCommunityRuntime } from "@/stores/community/runtime"import { messageScopeKey } from "@/stores/community/message-stream-store"+import type { ApiRequestOptions } from "@/lib/api/client"+import { actionAttributes, currentPageObservation } from "@/lib/observability/context"+import { emitTelemetry, isTelemetryEligible, telemetryGeneration } from "@/lib/observability/telemetry"+import { channelHref } from "@/lib/community/community-route"import { messageWindowPage, type MessageInput, type MessagesPage, type MessagesPageParam, type MessagesWindowPage } from "@/lib/community/models/message"import { buildMessagesUrl, messageWindowIdentity } from "@/lib/community/message-window"@@ -77,7 +81,7 @@ function cachedCoverage(queryClient: QueryClient, scopeId: string, cache: Messag} satisfies MessagesPage }}-type MessageRepairOwner = { query: Query; signal: AbortSignal }+type MessageRepairOwner = { query: Query; signal: AbortSignal; lifetime?: "query"; observation?: ApiRequestOptions["observation"] }type MessageRepairReceipt = {token: ReturnType<typeof captureCommunityLiveSnapshotToken>window: Query | undefined@@ -98,7 +102,7 @@ function assertRepairCurrent(queryClient: QueryClient, receipt: MessageRepairRecif (receipt.window.isActive()) returnconst owner = receipt.ownerif (!owner || owner.signal.aborted || queryClient.getQueryCache().get(owner.query.queryHash) !== owner.query- || !owner.query.isActive() && owner.query.state.fetchStatus === "idle") {+ || owner.lifetime !== "query" && !owner.query.isActive() && owner.query.state.fetchStatus === "idle") {throw new DOMException("Retired message repair owner", "AbortError")}}@@ -149,66 +153,78 @@ export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepanetworkMode: "online",meta: { communityMessageRepair: receipt },queryFn: async ({ signal }) => {+ const path = scope.kind === "dm" ? `/c/me/${encodeURIComponent(scopeId)}` : serverId ? channelHref(serverId, scopeId) : undefined+ const observation = owner?.observation ?? (typeof window !== "undefined" && window.location.pathname === path+ ? { page: currentPageObservation(), reason: "background" as const } : { page: undefined, reason: "unknown" as const })+ const generation = telemetryGeneration()+ const observed = isTelemetryEligible()+ const record = (reconcile_stage: "start" | "settled" | "error" | "cancelled" | "retired") => {+ if (observed && generation === telemetryGeneration()) emitTelemetry("conversation.reconcile", {+ ...actionAttributes(observation?.action ?? observation?.page), reconcile_stage, request_role: "reconcile",+ })+ }+ record("start")const assert = () => assertRepairCurrent(queryClient, receipt, signal)- await registry?.ready- assert()- const data = originalQuery?.state.data- if (!isMessageCache(data) || !data.pageParams[0]) return { latestSeq: 0 }- await queryClient.cancelQueries({ queryKey: key, exact: true }, { revert: true, silent: true })- assert()- const tag = messageWindowIdentity(key)?.tag ?? null- const load = async (param: MessagesPageParam) => {+ try {+ await registry?.readyassert()- const page = await withConversationReadDeadline(signal, (readSignal) => apiFetchCommunity<MessagesPage>(- url(scopeId, param, tag), { signal: readSignal, assertActive: assert }, token,- ))+ const data = originalQuery?.state.data+ if (!isMessageCache(data) || !data.pageParams[0]) { record("retired"); return { latestSeq: 0 } }+ await queryClient.cancelQueries({ queryKey: key, exact: true }, { revert: true, silent: true })assert()- return page- }- const target = () => queryClient.getQueryData<number>(targetKey(key)) ?? 0- let cached: MessagesPage | undefined- let cachedCovered = 0- const published = new Set<MessagesPage>()- const prefetch = async (current: MessageCache, refreshed: MessagesPage) => {- if (prefetched) return- const required = Math.max(refreshed.latestSeq ?? 0, target())- const coverage = cachedCoverage(queryClient, scopeId, current, refreshed, required, tag)- cached = coverage?.page- cachedCovered = coverage?.covered ?? 0- if (coverage ? coverage.covered >= required : required <= latest(current, false)) return- if (cached?.messages.length) publish(refreshed)- const nextCursor = coverage?.cursor ?? cursor(current)- if (!nextCursor && (refreshed.latestSeq ?? 0) >= target()) return- const param: MessagesPageParam = nextCursor ? { mode: "since", since: nextCursor } : current.pageParams[0]- prefetched = { param, page: await load(param) }- const after = originalQuery?.state.data- if (isMessageCache(after)) {- const remaining = cachedCoverage(queryClient, scopeId, after, {- ...prefetched.page, messages: [...refreshed.messages, ...prefetched.page.messages],- }, Math.max(required, target(), prefetched.page.latestSeq ?? 0), tag)- if (remaining) { cached = remaining.page; cachedCovered = remaining.covered }+ const tag = messageWindowIdentity(key)?.tag ?? null+ const load = async (param: MessagesPageParam) => {+ assert()+ const page = await withConversationReadDeadline(signal, (readSignal) => apiFetchCommunity<MessagesPage>(+ url(scopeId, param, tag), { signal: readSignal, assertActive: assert,+ observation: { ...observation, reason: "background", role: "reconcile", windowMode: param.mode } }, token,+ ))+ assert()+ return page}- }- const publish = (refreshed: MessagesPage) => {- assert()- const fetchedEnd = Math.max(0, ...(prefetched?.page.messages.map(message => message.seq ?? 0) ?? []))- const catchUp = cached && prefetched && cachedCovered >= fetchedEnd- ? [prefetched.page, cached] : [...(cached ? [cached] : []), ...(prefetched ? [prefetched.page] : [])]- const pending = [refreshed, ...(prefetched ? [prefetched.page] : [])].filter(page => !published.has(page))- if (pending.length) {- publishCommunityMessages(queryClient, { channelId: scopeId, messages: pending.flatMap(page => page.messages), proof: { token, signal } })- for (const page of pending) published.add(page)+ const target = () => queryClient.getQueryData<number>(targetKey(key)) ?? 0+ let cached: MessagesPage | undefined+ let cachedCovered = 0+ const published = new Set<MessagesPage>()+ const prefetch = async (current: MessageCache, refreshed: MessagesPage) => {+ if (prefetched) return+ const required = Math.max(refreshed.latestSeq ?? 0, target())+ const coverage = cachedCoverage(queryClient, scopeId, current, refreshed, required, tag)+ cached = coverage?.page+ cachedCovered = coverage?.covered ?? 0+ if (coverage ? coverage.covered >= required : required <= latest(current, false)) return+ if (cached?.messages.length) publish(refreshed)+ const nextCursor = coverage?.cursor ?? cursor(current)+ if (!nextCursor && (refreshed.latestSeq ?? 0) >= target()) return+ const param: MessagesPageParam = nextCursor ? { mode: "since", since: nextCursor } : current.pageParams[0]+ prefetched = { param, page: await load(param) }+ const after = originalQuery?.state.data+ if (isMessageCache(after)) {+ const remaining = cachedCoverage(queryClient, scopeId, after, {+ ...prefetched.page, messages: [...refreshed.messages, ...prefetched.page.messages],+ }, Math.max(required, target(), prefetched.page.latestSeq ?? 0), tag)+ if (remaining) { cached = remaining.page; cachedCovered = remaining.covered }+ }+ }+ const publish = (refreshed: MessagesPage) => {+ assert()+ const fetchedEnd = Math.max(0, ...(prefetched?.page.messages.map(message => message.seq ?? 0) ?? []))+ const catchUp = cached && prefetched && cachedCovered >= fetchedEnd+ ? [prefetched.page, cached] : [...(cached ? [cached] : []), ...(prefetched ? [prefetched.page] : [])]+ const pending = [refreshed, ...(prefetched ? [prefetched.page] : [])].filter(page => !published.has(page))+ if (pending.length) {+ publishCommunityMessages(queryClient, { channelId: scopeId, messages: pending.flatMap(page => page.messages), proof: { token, signal } })+ for (const page of pending) published.add(page)+ }+ queryClient.setQueryData<MessageCache>(key, (cache) => isMessageCache(cache) ? mergeWindow(cache, refreshed, catchUp) : cache)}- queryClient.setQueryData<MessageCache>(key, (cache) => isMessageCache(cache) ? mergeWindow(cache, refreshed, catchUp) : cache)- }- try {const current = originalQuery?.state.data- if (!isMessageCache(current) || !current.pageParams[0]) return { latestSeq: 0 }+ if (!isMessageCache(current) || !current.pageParams[0]) { record("retired"); return { latestSeq: 0 } }if (!landingPage || hashKey([landingPage.param]) !== hashKey([current.pageParams[0]])) {landingPage = { param: current.pageParams[0], page: await load(current.pageParams[0]) }}const refreshed = landingPage.page- if (!isMessageCache(originalQuery?.state.data)) return { latestSeq: 0 }+ if (!isMessageCache(originalQuery?.state.data)) { record("retired"); return { latestSeq: 0 } }await prefetch(current, refreshed)publish(refreshed)if (pendingDirection && !paginationReplayed) {@@ -226,8 +242,10 @@ export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepaif (latestSeq < target() && !(prefetched?.page.hasMoreNewer && prefetched.page.newerCursor)) {throw new Error("Messages have not caught up yet")}+ record("settled")return { latestSeq }} catch (error) {+ record(signal.aborted ? "cancelled" : isAbortError(error) ? "retired" : "error")assert()if (!(error instanceof ApiError) || (error.status !== 403 && error.status !== 404) || isConversationAnchorMissingError(error)) throw errorif (registry) retireCommunityChannelReading(registry, scopeId, {@@ -266,10 +284,14 @@ export function reconcileWindow(queryClient: QueryClient, scope: GapRepairScope,}}owner?.signal.addEventListener("abort", cancelRetiredOwner, { once: true })+ const unsubscribe = owner?.lifetime === "query" ? queryClient.getQueryCache().subscribe(event => {+ if (event.type === "removed" && event.query === owner.query) cancelRetiredOwner()+ }) : undefinedreturn queryClient.query({ ...options, select: undefined }).then(() => undefined).catch((error: unknown) => {if (!isAbortError(error) && !(error instanceof CancelledError)) throw error}).finally(() => {owner?.signal.removeEventListener("abort", cancelRetiredOwner)+ unsubscribe?.()const current = queryClient.getQueryCache().find({ queryKey: repairKey, exact: true })if (current?.meta?.communityMessageRepair === options.meta?.communityMessageRepair && current?.state.status !== "error") {queryClient.removeQueries({ queryKey: targetKey(key), exact: true })diff --git a/src/web/src/hooks/community/conversation-entry.request-scope.dom.test.tsx b/src/web/src/hooks/community/conversation-entry.request-scope.dom.test.tsxnew file mode 100644index 000000000..446351882--- /dev/null+++ b/src/web/src/hooks/community/conversation-entry.request-scope.dom.test.tsx@@ -0,0 +1,111 @@+import { afterEach, expect, it, vi } from "vitest"+import { QueryClientProvider } from "@tanstack/react-query"+import { act, renderHook, waitFor } from "@/test/react-dom-harness"+import { createCommunityQueryOwner } from "@/test/community-query-owner"+import { conversationEntryFixture, forumConversationEntryFixture, seedConversationEntry } from "@/test/conversation-entry-fixtures"+import { CommunityDbProvider } from "@/lib/community-db/projections"+import { communityKeys } from "@/lib/query-keys"+import { ConversationActivityContext, ConversationPresentationContext } from "@/contexts/community/conversation-activity"+import { useMessages } from "./use-messages"+import { usePins, useThreads } from "./use-channel-panels"+import { useFriends } from "./use-friends"+import { useNotificationSettings } from "./use-notification-settings"+import { useDms } from "./use-dms"+import { useForumFeed } from "./use-forum-feed"++const load = vi.hoisted(() => vi.fn())+vi.mock("@/lib/api/client", async original => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: (...args: unknown[]) => load(...args) }))+afterEach(() => { load.mockReset(); localStorage.clear() })++it("retains hidden message and panel caches without starting requests, then loads the presented pending route before commit", async () => {+ const owner = await createCommunityQueryOwner()+ const value = conversationEntryFixture()+ const seeded = await seedConversationEntry(owner.client, value)+ owner.client.removeQueries({ queryKey: communityKeys.conversationEntries("c1") })+ owner.client.setQueryData(communityKeys.pins("c1"), { pins: [] }, { updatedAt: 1 })+ owner.client.setQueryData(communityKeys.threads("c1"), { parentChannelId: "c1", parentType: "text", serverId: "s1", threads: [] }, { updatedAt: 1 })+ let presented = false+ const held = new Promise(() => {})+ load.mockImplementation((url: string) => url.includes("entry=1") ? held : url.endsWith("/pins") ? { pins: [] }+ : { parentChannelId: "c1", parentType: "text", serverId: "s1", threads: [], included: { parentMessages: [], firstMessages: [], tags: [], participants: [] } })+ const hook = renderHook(() => ({ feed: useMessages("c1", { serverId: "s1" }), pins: usePins("c1"), threads: useThreads("c1") }), {+ wrapper: ({ children }) => <QueryClientProvider client={owner.client}><CommunityDbProvider registry={owner.registry}>+ <ConversationActivityContext value={false}><ConversationPresentationContext value={presented}>{children}</ConversationPresentationContext></ConversationActivityContext>+ </CommunityDbProvider></QueryClientProvider>,+ })+ expect(hook.result.current.feed.messages.map(message => message.id)).toEqual(["m1"])+ expect(owner.client.getQueryData(seeded.resource.windowKey)).toBeDefined()+ expect(hook.result.current.feed.jumpToPresent().accepted).toBe(false)+ await act(async () => { await Promise.resolve() })+ expect(load).not.toHaveBeenCalled()+ presented = true+ hook.rerender()+ await waitFor(() => expect(load.mock.calls.map(([url]) => String(url))).toHaveLength(3))+ expect(load.mock.calls.map(([url]) => String(url))).toEqual(expect.arrayContaining([+ "/api/community/channels/c1/messages?entry=1", "/api/community/channels/c1/pins",+ "/api/community/channels/c1/threads?include=parentMessage,firstMessage,tags,participants&archived=false",+ ]))+ expect(hook.result.current.feed.messages.map(message => message.id)).toEqual(["m1"])+ hook.unmount()+})++it("reuses the entry-provided Forum first page instead of starting a parallel threads request", async () => {+ localStorage.clear()+ const owner = await createCommunityQueryOwner()+ const value = forumConversationEntryFixture()+ await seedConversationEntry(owner.client, value)+ owner.client.removeQueries({ queryKey: communityKeys.conversationEntries("c1") })+ owner.client.removeQueries({ queryKey: communityKeys.forumFeed("c1", null), exact: true })+ let release!: () => void+ load.mockImplementation((url: string) => url.includes("entry=1") ? new Promise(resolve => { release = () => resolve(value) }) : { tags: [] })+ const hook = renderHook(() => useForumFeed("s1", "c1"), {+ wrapper: ({ children }) => <QueryClientProvider client={owner.client}><CommunityDbProvider registry={owner.registry}>{children}</CommunityDbProvider></QueryClientProvider>,+ })+ await waitFor(() => expect(release).toBeTypeOf("function"))+ expect(load.mock.calls.some(([url]) => String(url).includes("/threads"))).toBe(false)+ await act(async () => release())+ await waitFor(() => expect(hook.result.current.posts.map(post => post.id)).toEqual(["t1"]))+ expect(load.mock.calls.some(([url]) => String(url).includes("/threads"))).toBe(false)+ hook.unmount()+})++it("shares account collections with subscribed consumers without refreshing them on consumer mount", async () => {+ const owner = await createCommunityQueryOwner()+ load.mockImplementation((url: string) => url.endsWith("/accepted") ? { friends: [] }+ : url.endsWith("/blocked") ? { blocked: [] } : url.endsWith("/pending") ? { pending: [] }+ : url.endsWith("/dms") ? { conversations: [] } : [])+ const wrapper = ({ children }: { children: React.ReactNode }) => <QueryClientProvider client={owner.client}><CommunityDbProvider registry={owner.registry}>{children}</CommunityDbProvider></QueryClientProvider>+ const consumer = renderHook(() => ({ friends: useFriends({ enabled: false }), settings: useNotificationSettings(false), dms: useDms(false, true) }), { wrapper })+ await act(async () => { await Promise.resolve() })+ expect(load).not.toHaveBeenCalled()+ const shared = renderHook(() => ({ friends: useFriends(), settings: useNotificationSettings(), dms: useDms() }), { wrapper })+ await waitFor(() => expect(shared.result.current.friends.isSuccess && shared.result.current.settings.isSuccess && shared.result.current.dms.isSuccess).toBe(true))+ expect(load).toHaveBeenCalledTimes(5)+ expect(consumer.result.current.friends.isSuccess && consumer.result.current.settings.isSuccess && consumer.result.current.dms.isSuccess).toBe(true)+ owner.client.setQueryDefaults(communityKeys.friends(), { staleTime: 0 })+ owner.client.setQueryDefaults(communityKeys.dms(), { staleTime: 0 })+ const another = renderHook(() => ({ friends: useFriends({ enabled: false }), settings: useNotificationSettings(false), dms: useDms(false, true) }), { wrapper })+ await act(async () => { await Promise.resolve() })+ expect(load).toHaveBeenCalledTimes(5)+ await act(async () => { await owner.client.invalidateQueries({ queryKey: communityKeys.friends(), exact: true }) })+ expect(load).toHaveBeenCalledTimes(8)+ expect(another.result.current.friends.isSuccess).toBe(true)+ another.unmount(); consumer.unmount(); shared.unmount()+})++it("reads the complete active threads only on panel demand and keeps pin status available while closed", async () => {+ const owner = await createCommunityQueryOwner()+ let requested = false+ load.mockImplementation((url: string) => url.endsWith("/pins") ? { pins: [] } : { serverId: "s1", parentType: "text", threads: [], included: { parentMessages: [], firstMessages: [], tags: [], participants: [] } })+ const hook = renderHook(() => ({ threads: useThreads("c1", requested), pins: usePins("c1") }), {+ wrapper: ({ children }) => <QueryClientProvider client={owner.client}><CommunityDbProvider registry={owner.registry}>{children}</CommunityDbProvider></QueryClientProvider>,+ })+ await waitFor(() => expect(hook.result.current.pins.isSuccess).toBe(true))+ expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/pins"])+ requested = true; hook.rerender()+ await waitFor(() => expect(hook.result.current.threads.isSuccess).toBe(true))+ expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/pins", "/api/community/channels/c1/threads?include=parentMessage,firstMessage,tags,participants&archived=false"])+ requested = false; hook.rerender()+ expect(hook.result.current.threads.data?.threads).toEqual([])+ hook.unmount()+})diff --git a/src/web/src/hooks/community/use-channel-message-feed.ts b/src/web/src/hooks/community/use-channel-message-feed.tsindex aee97a1c9..d7cd88ecb 100644--- a/src/web/src/hooks/community/use-channel-message-feed.ts+++ b/src/web/src/hooks/community/use-channel-message-feed.ts@@ -16,12 +16,14 @@ export function useChannelMessageFeed({viewerUserId,isChildChannel: _isChildChannel,anchorMessageId,+ threadsEnabled = false,}: {channelId: string | nullserverId: stringviewerUserId: stringisChildChannel: booleananchorMessageId: string | null+ threadsEnabled?: boolean}) {const active = useConversationActivity()const messagesQuery = useMessages(channelId, {@@ -66,7 +68,7 @@ export function useChannelMessageFeed({historyStartKnown: messagesQuery.historyStartKnown, hasMoreNewer: messagesQuery.hasMoreNewer,ready: !!readSnapshot && !messagesQuery.readSnapshotFetching && !messagesQuery.isPending && !messagesQuery.isError,})- const threadsQuery = useThreads(channelId)+ const threadsQuery = useThreads(channelId, threadsEnabled)const pinsQuery = usePins(channelId)return {...messagesQuery,diff --git a/src/web/src/hooks/community/use-channel-metadata.ts b/src/web/src/hooks/community/use-channel-metadata.tsindex 424d26e56..54ff375a4 100644--- a/src/web/src/hooks/community/use-channel-metadata.ts+++ b/src/web/src/hooks/community/use-channel-metadata.ts@@ -1,27 +1,37 @@"use client"import { useMemo } from "react"+import { useQueryClient } from "@tanstack/react-query"+import { getCommunityDbRegistry } from "@/lib/community-db/collections"+import { forumTagFromUrl } from "@/lib/community/forum-tag-selection"+import { useStoredForumTag } from "./use-stored-forum-tag"import { useConversationResource } from "./use-conversation-entry"type ChannelReadingStatus = "no-target" | "pending" | "readable" | "denied" | "unresolved" | "retryable-error"export function useChannelMetadata(serverId: string | null, channelId: string | undefined, intent?: { anchorMessageId?: string | null; tag?: string | null }) {- const entry = useConversationResource(channelId ? { channelId, serverId, ...intent } : null)- const { query, canonical, resource, canRead, revoked, denied } = entry- const identityKnown = !!resource && !!canonical && canonical.id === channelId && canonical.serverId === serverId && !canonical.pending && canonical.resourceComplete === true+ const client = useQueryClient()+ const canonicalType = channelId ? getCommunityDbRegistry(client)?.collections.channels.get(channelId)?.type : undefined+ const forumSelection = serverId !== null && (!canonicalType || canonicalType === "forum")+ const storedTag = useStoredForumTag(forumSelection ? channelId ?? null : null)+ const selectedTag = forumSelection ? forumTagFromUrl(intent?.tag) ?? storedTag : intent?.tag ?? "All"+ const tag = selectedTag === "All" ? null : selectedTag+ const entry = useConversationResource(channelId ? { channelId, serverId, ...intent, tag } : null, null, false, "metadata", selectedTag !== null)+ const { query, canonical, scope, canRead, revoked, denied } = entry+ const identityKnown = canRead && !!scope && !!canonical && canonical.id === channelId && canonical.serverId === serverId && !canonical.pending && canonical.resourceComplete === trueconst error = entry.verificationErrorconst status: ChannelReadingStatus = !channelId ? "no-target" : denied ? "denied" : canRead ? "readable": error || entry.verificationFailed ? "retryable-error" : query.isFetching || entry.verificationPending ? "pending" : "unresolved"const data = useMemo(() => {- if (!identityKnown || !canonical || canonical.resourceComplete !== true || !resource) return undefined+ if (!identityKnown || !canonical || canonical.resourceComplete !== true || !scope) return undefinedreturn { ...canonical, serverId,createdAt: canonical.createdAt ?? "", name: canonical.name ?? "",- verifiedEpoch: resource.proof.accessEpoch, identityProof: resource.proof, readProof: resource.proof,+ verifiedEpoch: scope.proof.accessEpoch, identityProof: scope.proof, readProof: scope.proof,parentChannelId: canonical.parentChannelId ?? null, parentMessageId: canonical.parentMessageId ?? null,creatorId: canonical.creatorId ?? null, lastMessageAt: canonical.lastMessageAt ?? null,- } }, [canonical, identityKnown, resource, serverId])+ } }, [canonical, identityKnown, scope, serverId])return { ...query, error, data, status, identityKnown, canRead, isVerified: canRead,- isArchived: !!canonical?.archived && !!resource, denied, revoked, canonical,+ isArchived: canonical?.resourceComplete === true && !!canonical.archived, denied, revoked, canonical,retry: entry.retryVerification, retrying: entry.verificationFetching,}}diff --git a/src/web/src/hooks/community/use-channel-panels.test.ts b/src/web/src/hooks/community/use-channel-panels.test.tsindex 482075849..5b7b44640 100644--- a/src/web/src/hooks/community/use-channel-panels.test.ts+++ b/src/web/src/hooks/community/use-channel-panels.test.ts@@ -47,7 +47,7 @@ describe("useThreads / threadsQueryFn", () => {.mockResolvedValueOnce({ participants: [] })const { threadsQueryFn } = await import("./use-channel-panels")const data = await threadsQueryFn("ch_1", qc)()- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/ch_1/threads?include=parentMessage,firstMessage,tags,participants", expect.objectContaining({ authenticationAccount: "viewer", signal: undefined }))+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/ch_1/threads?include=parentMessage,firstMessage,tags,participants&archived=false", expect.objectContaining({ authenticationAccount: "viewer", signal: undefined }))expect(apiFetchMock).not.toHaveBeenCalledWith("/api/community/channels/ch_1/posts")expect(data.threads).toHaveLength(1)expect(project(data)[0]?.parent.text).toBe("identityless preview")diff --git a/src/web/src/hooks/community/use-channel-panels.ts b/src/web/src/hooks/community/use-channel-panels.tsindex 864d5013a..777336313 100644--- a/src/web/src/hooks/community/use-channel-panels.ts+++ b/src/web/src/hooks/community/use-channel-panels.ts@@ -1,4 +1,5 @@"use client"+import { useConversationPresentation } from "@/contexts/community/conversation-activity"import { useMemo } from "react"import { getCommunityDbRegistry } from "@/lib/community-db/collections"@@ -43,7 +44,7 @@ export type ThreadsResponse = {async function loadThreadResources(queryClient: QueryClient, channelId: string, proof: CommunityFreshQueryProof) {const options = qualifiedCommunityRequestOptions(queryClient, proof.token, proof.signal)- const response = await apiFetch<ForumFeedTransportPage | CommunityThreadsRead | CommunityLegacyThreadsRead>(`/api/community/channels/${channelId}/threads?include=parentMessage,firstMessage,tags,participants`, options)+ const response = await apiFetch<ForumFeedTransportPage | CommunityThreadsRead | CommunityLegacyThreadsRead>(`/api/community/channels/${channelId}/threads?include=parentMessage,firstMessage,tags,participants&archived=false`, options)assertCommunityLiveSnapshotTokenCurrent(queryClient, proof.token, proof.signal)if ("contractVersion" in response || response.included) return normalizeThreadResources(channelId, response)const openerIds = response.threads.flatMap((thread) => thread.parentMessageId ? [thread.parentMessageId] : [])@@ -77,18 +78,19 @@ export function materializeThreadsResponse(data: ThreadsResponse | undefined, me})}-export function useThreads(channelId: string | null): UseQueryResult<ThreadsResponse> & {+export function useThreads(channelId: string | null, requested = true): UseQueryResult<ThreadsResponse> & {threads: Thread[]} {const queryClient = useQueryClient()const channels = useCanonicalChannelsById()+ const presented = useConversationPresentation()const enabled = !!channelIdconst query = useQuery({queryKey: enabled ? communityKeys.threads(channelId!) : communityKeys.threads("__none__"),queryFn: enabled? threadsQueryFn(channelId!, queryClient): (() => Promise.reject(new Error("disabled"))),- enabled,+ enabled: enabled && presented && requested,})const messageIds = useMemo(() => query.data?.threads.flatMap((thread) => thread.openerMessageId ? [thread.openerMessageId] : []) ?? [], [query.data?.threads])const canonicalMessages = useCanonicalMessagesById(messageIds)@@ -100,10 +102,11 @@ export function useThreads(channelId: string | null): UseQueryResult<ThreadsResp}export function useForumTags(channelId: string | null, enabled: boolean) {+ const presented = useConversationPresentation()return useQuery({queryKey: communityKeys.forumTags(channelId ?? "__none__"),queryFn: ({ client, signal }) => apiFetch<{ tags: string[] }>(`/api/community/channels/${channelId}/messages/tags`, communityRequestOptions(client, signal)),- enabled: !!channelId && enabled,+ enabled: !!channelId && enabled && presented,})}@@ -135,13 +138,14 @@ export function usePins(channelId: string | null): UseQueryResult<PinsWindowRespcanonicalPending: boolean} {const queryClient = useQueryClient()+ const presented = useConversationPresentation()const enabled = !!channelIdconst query = useQuery({queryKey: enabled ? communityKeys.pins(channelId!) : communityKeys.pins("__none__"),queryFn: enabled? pinsQueryFn(channelId!, queryClient): (() => Promise.reject(new Error("disabled"))),- enabled,+ enabled: enabled && presented,})const pending = useMutationState({ filters: { mutationKey: ["community", "pin-command"], status: "pending" }, select: (mutation) => ({ channelId: (mutation.state.variables as { channelId: string }).channelId, messageId: (mutation.state.variables as { messageId: string }).messageId, pinned: mutation.options.mutationKey?.[2] === "pin" }) })const ids = useMemo(() => {diff --git a/src/web/src/hooks/community/use-channel-route-model.ts b/src/web/src/hooks/community/use-channel-route-model.tsindex b16222908..f2720fc80 100644--- a/src/web/src/hooks/community/use-channel-route-model.ts+++ b/src/web/src/hooks/community/use-channel-route-model.ts@@ -64,6 +64,7 @@ export function useChannelRouteModel(channelId: string,accountId: string,anchorMessageId?: string | null,+ tag?: string | null,) {const active = useConversationActivity()const ownedChannel = useRef(channelId)@@ -73,7 +74,7 @@ export function useChannelRouteModel(const queryClient = useQueryClient()const runtime = useCommunityRuntime()const { server } = useServer(serverId)- const metaQuery = useChannelMetadata(serverId, channelId, { anchorMessageId })+ const metaQuery = useChannelMetadata(serverId, channelId, { anchorMessageId, tag })const identity = metaQuery.canRead && metaQuery.data?.id === channelId && metaQuery.data.serverId === serverId ? metaQuery.data : undefinedconst isChild = identity?.type === "thread"const renderableChannelMeta: ChannelMeta = useMemo(() => isChild && identity?.parentChannelId && identity.parentMessageIddiff --git a/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx b/src/web/src/hooks/community/use-conversation-entry.dom.test.tsxindex 8ed9a2ff1..17a11aef6 100644--- a/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx+++ b/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx@@ -3,7 +3,7 @@ import { createElement, type PropsWithChildren } from "react"import { QueryClientProvider } from "@tanstack/react-query"import { act, render, renderHook, waitFor } from "@/test/react-dom-harness"import { createCommunityQueryOwner } from "@/test/community-query-owner"-import { conversationEntryFixture as fixture, dmConversationEntryFixture, conversationEntryTarget as target } from "@/test/conversation-entry-fixtures"+import { conversationEntryFixture as fixture, dmConversationEntryFixture, forumConversationEntryFixture, conversationEntryTarget as target } from "@/test/conversation-entry-fixtures"import { CommunityDbProvider } from "@/lib/community-db/projections"import { registerCommunityDbRegistry } from "@/lib/community-db/collections"import { captureCommunityLiveSnapshotToken, ingestMessages, ingestReadStateSnapshot, publishAccountAttentionSnapshot } from "@/lib/community-db/sync"@@ -15,6 +15,7 @@ import { ConversationActivityContext } from "@/contexts/community/conversation-aimport { useConversationEntry } from "./use-conversation-entry"import { useChannelMetadata } from "./use-channel-metadata"import { useDmMessages, useMessages } from "./use-messages"+import { useForumFeed } from "./use-forum-feed"import { resolveMessageReadProjection } from "@/lib/community/message-read-projection"import { useMessageListController } from "@/components/community/messages/message-list-controller"import { VirtualRows } from "@/components/community/messages/virtual-cursor-list"@@ -48,6 +49,79 @@ async function setup() {}describe("conversation entry selection", () => {+ it.each([+ { kind: "text", useSurface: function useText() { return useMessages("c1", { serverId: "s1" }) } },+ { kind: "dm", useSurface: function useDm() { return useDmMessages("c1") } },+ { kind: "forum", useSurface: function useForum() { return useForumFeed("s1", "c1") } },+ { kind: "thread", useSurface: function useThread() { return useMessages("c1", { serverId: "s1" }) } },+ ] as const)("presents the qualified $kind cache while the missing entry is actually pending", async ({ kind, useSurface }) => {+ const { client, wrapper } = await setup()+ const value = kind === "dm" ? dmConversationEntryFixture() : kind === "forum" ? forumConversationEntryFixture() : fixture()+ if (kind === "thread") {+ value.channel = { ...value.channel, type: "thread", parentChannelId: "parent", parentMessageId: "opener" }+ value.parent = { ...fixture().channel, id: "parent", type: "text" }+ value.surfaceReceipt = { channelId: "c1", surfaceKind: "thread" }+ }+ const destination = { channelId: "c1", serverId: value.channel.serverId }+ const resource = publishConversationEntry(client, destination, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })+ client.setQueryData(conversationEntryOptions(client, destination).queryKey, resource)+ client.removeQueries({ queryKey: communityKeys.conversationEntries("c1") })+ const held = deferred<typeof value>()+ load.mockReturnValue(held.promise)+ const hook = renderHook(() => {+ const metadata = useChannelMetadata(destination.serverId, "c1")+ const surface = useSurface()+ return { metadata, surface }+ }, { wrapper })+ await waitFor(() => expect(load.mock.calls.some(([url]) => url === "/api/community/channels/c1/messages?entry=1")).toBe(true))+ expect(hook.result.current.metadata.canRead).toBe(true)+ expect(hook.result.current.metadata.data?.id).toBe("c1")+ expect(hook.result.current.metadata.isFetching).toBe(true)+ if ("messages" in hook.result.current.surface) {+ await waitFor(() => expect(hook.result.current.surface).toMatchObject({ isLoading: false, messages: [expect.objectContaining({ id: "m1", content: "Body" })] }))+ } else await waitFor(() => {+ const surface = hook.result.current.surface+ expect("posts" in surface ? surface.posts.map(post => post.id) : []).toEqual(["t1"])+ })+ hook.unmount()+ })++ it("does not block a valid cached empty window on missing entry data", async () => {+ const { client, wrapper, publish } = await setup()+ const value = fixture()+ value.messages = []+ value.readState = { ...value.readState, lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 }+ value.selection = { reason: "tail", anchorMessageId: null }+ value.page = { ...value.page, olderCursor: null, hasMoreOlder: false, latestSeq: 0 }+ publish(value)+ client.removeQueries({ queryKey: communityKeys.conversationEntries("c1") })+ load.mockReturnValue(new Promise(() => {}))+ const hook = renderHook(() => useMessages("c1", { serverId: "s1" }), { wrapper })+ await waitFor(() => expect(hook.result.current.isLoading).toBe(false))+ expect(hook.result.current.messages).toEqual([])+ expect(hook.result.current.initialPositionKnown).toBe(true)+ expect(hook.result.current.positionDataState).toBe("empty")+ expect(hook.result.current.isFetching).toBe(true)+ hook.unmount()+ })++ it("keeps the current qualified cache while another server retires old entry proofs", async () => {+ const { wrapper, publish, registry } = await setup()+ publish()+ const held = deferred<ReturnType<typeof fixture>>()+ load.mockReturnValue(held.promise)+ const hook = renderHook(() => useMessages("c1", { serverId: "s1" }), { wrapper })+ await waitFor(() => expect(hook.result.current.messages.map(message => message.id)).toEqual(["m1"]))+ await act(async () => registry.runtime.ws.actions.revokeServerAccess("unrelated"))+ await waitFor(() => expect(load).toHaveBeenCalledOnce())+ expect(hook.result.current.entryCanRead).toBe(true)+ expect(hook.result.current.isLoading).toBe(false)+ expect(hook.result.current.messages[0]?.content).toBe("Body")+ expect(hook.result.current.initialPositionKnown).toBe(true)+ expect(hook.result.current.readSnapshot?.lastReadMessageId).toBe("m1")+ hook.unmount()+ })+it("retains a parent's window and NEW through background and semantic resume, while a fresh entry reselects", async () => {const { wrapper: Owner, publish, registry } = await setup()const value = fixture()@@ -181,7 +255,8 @@ describe("conversation entry selection", () => {load.mockReturnValue(transport.promise)const hook = renderHook(() => useConversationEntry(target), { wrapper })await waitFor(() => expect(load).toHaveBeenCalledOnce())- expect(hook.result.current.window).toBeNull()+ expect(hook.result.current.window).not.toBeNull()+ expect(hook.result.current.targetCovered).toBe(false)const next = fixture()next.readState = { channelId: "c1", lastReadMessageId: "m2", lastReadAt: "second", lastReadSeq: 2 }next.readStateRevision = 5@@ -245,7 +320,7 @@ describe("conversation entry selection", () => {hook.unmount()})- it("withdraws a completed proof and exactly refetches after its real registry registration retires", async () => {+ it("retires the old entry proof and refetches while qualifying the current canonical scope after registry registration changes", async () => {const { wrapper, publish, registry, client } = await setup()const original = publish()const hook = renderHook(() => useConversationEntry({ ...target }), { wrapper })@@ -262,7 +337,8 @@ describe("conversation entry selection", () => {})await waitFor(() => expect(load).toHaveBeenCalledOnce())expect(invalidate).toHaveBeenCalledWith({ queryKey: conversationEntryOptions(client, target).queryKey, exact: true })- expect(hook.result.current.canRead).toBe(false)+ expect(hook.result.current.canRead).toBe(true)+ expect(hook.result.current.scope?.proof.ownerGeneration).toBeGreaterThan(original.proof.ownerGeneration)expect(hook.result.current.resource).toBeUndefined()await act(async () => request.resolve(fixture()))await waitFor(() => expect(hook.result.current.canRead).toBe(true))@@ -545,7 +621,7 @@ describe("conversation entry return during accepted reading", () => {return { alternate, alternateResource, alternateKey, retainedWindow, ordinaryKey }}- it.each([true, false])("uses alternate entry coverage after ordinary entry eviction only with qualification: %s", async qualified => {+ it.each([true, false])("uses qualified canonical coverage after ordinary entry eviction with alternate entry retained=%s", async qualified => {const owner = await readingOwner()const { alternate, alternateResource, alternateKey, retainedWindow, ordinaryKey } = evictOrdinaryEntryWithAlternateCoverage(owner)if (!qualified) owner.client.removeQueries({ queryKey: alternateKey, exact: true })@@ -562,7 +638,7 @@ describe("conversation entry return during accepted reading", () => {}const entryRead = deferred<ReturnType<typeof fixture>>()const originalLoad = load.getMockImplementation()!- const expectedRequest = `/api/community/channels/c1/messages?entry=1${qualified ? "" : "&anchor=m42"}`+ const expectedRequest = "/api/community/channels/c1/messages?entry=1"load.mockImplementation((url: string, options: unknown) => {if (!url.includes("/messages?entry=1")) return originalLoad(url, options)if (url !== expectedRequest) throw new Error(`Unexpected entry coverage request ${url}`)@@ -572,7 +648,7 @@ describe("conversation entry return during accepted reading", () => {try {expect(submitReadIntentGeneration(owner.lease, { kind: "timeline", channelId: "c1", messageId: "m42", seq: 42 })).not.toBeNull()view = mountReadingEntry(owner)- expect(view.latest.feed.initialPositionKnown).toBe(qualified)+ expect(view.latest.feed.initialPositionKnown).toBe(true)if (qualified) {expect(view.latest.feed.initialPositionMessageId).toBe("m42")expect(view.latest.feed.readSnapshot?.lastReadSeq).toBe(30)@@ -640,7 +716,7 @@ describe("conversation entry return during accepted reading", () => {expect(view.visible("m42")).toBe(true)expect(view.latest.controller.readPositionReady).toBe(true)} else {- expect(view.latest.feed.readSnapshot).toBeNull()+ expect(view.latest.feed.readSnapshot?.lastReadSeq).toBe(100)expect(view.latest.controller.readPositionReady).toBe(false)}expect(load.mock.calls.filter(([url]) => url.includes("/messages?entry=1")).map(([url]) => url)).toEqual([expectedRequest])@@ -791,7 +867,7 @@ describe("conversation entry return during accepted reading", () => {} finally { view.unmount(); releaseReadSurface(owner.lease); await owner.finish() }})- it("does not claim the beginning from a live row before the selected history window is known", async () => {+ it("retains the actual cached history boundary while an uncovered newer target keeps first admission masked", async () => {const owner = await readingOwner()const entryRead = deferred<ReturnType<typeof fixture>>()const previousKey = communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "m30" })@@ -822,16 +898,17 @@ describe("conversation entry return during accepted reading", () => {})const view = mountReadingEntry(owner)try {- expect(view.latest.feed.messages.map(message => message.id)).toEqual(["m80"])+ expect(view.latest.feed.messages.map(message => message.id)).toEqual([...Array.from({ length: 42 }, (_, index) => `m${index + 1}`), "m80"])expect(view.latest.feed.initialPositionKnown).toBe(false)expect(owner.client.getQueryData(previousKey)).toBe(previousWindow)- expect(view.latest.feed.readSnapshot).toBeNull()- expect(view.latest.feed.isLoading).toBe(true)+ expect(view.latest.feed.readSnapshot?.lastReadSeq).toBe(60)+ expect(view.latest.feed.isLoading).toBe(false)expect(view.latest.controller.initialPosition.contentVisible).toBe(false)expect(view.latest.controller.initialPosition.showSkeleton).toBe(true)expect(view.latest.controller.readPositionReady).toBe(false)expect(view.latest.feed.hasMoreOlder).toBe(false)- expect.soft(view.root.textContent).not.toContain("Beginning of the channel")+ expect(view.latest.feed.historyStartKnown).toBe(true)+ expect(view.root.textContent).toContain("Beginning of the channel")await act(async () => entryRead.resolve(fresh))resize()expect(view.latest.feed.initialPositionKnown).toBe(true)@@ -914,7 +991,7 @@ describe("native entry freshness with authoritative newer attention", () => {await waitFor(() => expect(signal).toBeDefined())expect(window.isActive()).toBe(false)await act(async () => {- if (reason === "cancel") await client.cancelQueries({ queryKey: options.queryKey, exact: true })+ if (reason === "cancel") await client.cancelQueries({ queryKey: [...original.windowKey, "reconcile"], exact: true })else if (reason === "replacement") client.removeQueries({ queryKey: options.queryKey, exact: true })else if (reason === "account") registry.runtime.ws.actions.activateProfileAccount("other")else registry.runtime.ws.actions.revokeChannelAccess("s1", "c1")diff --git a/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx b/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsxindex 29e8580ed..1ef24558b 100644--- a/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx+++ b/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx@@ -338,6 +338,31 @@ describe("conversation entry positioning through real reading owners", () => {}})+ it("preserves600px of real cached message-owner layout on a stale-entry remount", async () => {+ const view = await setup("channel", true)+ await view.tail()+ const oldRoot = view.root()+ fireEvent.wheel(oldRoot, { deltaY: -600 })+ act(() => oldRoot.scrollTo({ top: oldRoot.scrollHeight - oldRoot.clientHeight - 600 }))+ resize()+ const bodies = Array.from(oldRoot.querySelectorAll<HTMLElement>("[data-msg-id]"))+ const original = bodies.find(body => body.getBoundingClientRect().bottom > 0)!+ const id = original.dataset.msgId!+ const before = original.getBoundingClientRect().top+ const offset = oldRoot.scrollTop+ expect(oldRoot.scrollHeight - oldRoot.clientHeight - offset).toBe(600)+ await view.navigate("/c/channels/s1/c2")+ expect(oldRoot.isConnected).toBe(false)+ await act(async () => vi.advanceTimersByTimeAsync(6000))+ const previousLoad = load.getMockImplementation()!+ load.mockImplementation((url: string, options: unknown) => url === "/api/community/channels/c1/messages?entry=1" ? new Promise(() => {}) : previousLoad(url, options))+ await view.navigate("/c/channels/s1/c1")+ expect(load.mock.calls.some(([url]) => url === "/api/community/channels/c1/messages?entry=1")).toBe(true)+ expect(view.root().scrollTop).toBeCloseTo(offset, 0)+ expect(view.root().querySelector<HTMLElement>(`[data-msg-id="${id}"]`)!.getBoundingClientRect().top).toBeCloseTo(before, 0)+ expect(load.mock.calls.some(([, options]) => options?.method === "PUT")).toBe(false)+ })+it.each([{ kind: "channel", strict: false }, { kind: "post", strict: false },{ kind: "thread", strict: false }, { kind: "channel", strict: true },diff --git a/src/web/src/hooks/community/use-conversation-entry.ts b/src/web/src/hooks/community/use-conversation-entry.tsindex 8b350fe37..a5179575b 100644--- a/src/web/src/hooks/community/use-conversation-entry.ts+++ b/src/web/src/hooks/community/use-conversation-entry.ts@@ -3,30 +3,40 @@import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useState } from "react"import { createStore, useSelector } from "@tanstack/react-store"import { hashKey, useQuery, useQueryClient } from "@tanstack/react-query"-import { useConversationActivity } from "@/contexts/community/conversation-activity"+import { useConversationActivity, useConversationPresentation } from "@/contexts/community/conversation-activity"import { CommunityRouteContext } from "@/contexts/community/route-frame"import { channelHref, normalizeCommunityHref } from "@/lib/community/community-route"import type { CommunityReadStateResource } from "@alook/shared"-import { useRouteChannelProjection } from "@/lib/community-db/projections"+import { useChannelReadStateProjection, useChannelRosterRows, useRouteChannelProjection } from "@/lib/community-db/projections"import { getCommunityDbRegistry } from "@/lib/community-db/collections"import { useCommunityRuntime } from "@/stores/community/runtime"import { isChannelMetadataTokenCurrent } from "@/lib/community/conversation-qualification"+import { actionAttributes, currentPageObservation, navigationForHref } from "@/lib/observability/context"+import { emitTelemetry, telemetryGeneration } from "@/lib/observability/telemetry"import {- conversationEntryOptions, currentConversationReadState, findConversationEntryWindow, getQualifiedConversationEntry,+ assessConversationScope, conversationEntryOptions, currentConversationReadState, findConversationDisplayWindow, findConversationEntryWindow, getQualifiedConversationEntry, getQualifiedConversationScope,type ConversationEntryResource, type ConversationEntryTarget,} from "@/lib/community/conversation-entry"-import type { MessageWindowData } from "@/lib/community/message-window"+import { messageWindowIdentity, type MessageWindowData } from "@/lib/community/message-window"+import { communityKeys } from "@/lib/query-keys"import { reconcileWindow } from "./community-ws/reconnect-messages"import { isConversationAccessError, isConversationAnchorMissingError } from "@/lib/community/conversation-read"import { getLocalReadingPosition } from "./read-coordinator"type EntryWindow = NonNullable<ReturnType<typeof findConversationEntryWindow>>-export function useConversationResource(target: ConversationEntryTarget | null, intent?: { href: string; resume?: boolean } | null, useLocalPosition = false) {+export function useConversationResource(target: ConversationEntryTarget | null, intent?: { href: string; resume?: boolean } | null, useLocalPosition = false, consumer: "metadata" | "messages" | "forum" = "metadata", networkEnabled = true) {const client = useQueryClient()+ const active = useConversationActivity()+ const presented = useConversationPresentation()const runtime = useCommunityRuntime()const canonical = useRouteChannelProjection(target?.channelId ?? null)?? (target ? getCommunityDbRegistry(client)?.collections.channels.get(target.channelId) : undefined)+ useRouteChannelProjection(canonical?.parentChannelId ?? null)+ useChannelRosterRows(target?.channelId ?? "", "access")+ useChannelRosterRows(canonical?.parentChannelId ?? "", "access")+ const read = useChannelReadStateProjection(target?.channelId ?? null)+ const lifetime = useSelector(runtime.lifecycle, state => state.active ? state.generation : -1)const [accountEpoch, accessEpoch, generation, parentGeneration, revoked, serverRevoked] = useSelector(runtime.ws, (state) => [state.profileAccountEpoch, state.accessEpoch,target ? state.channelAccessScopes.get(target.channelId)?.generation ?? 0 : 0,canonical?.parentChannelId ? state.channelAccessScopes.get(canonical.parentChannelId)?.generation ?? 0 : 0,@@ -38,13 +48,18 @@ export function useConversationResource(target: ConversationEntryTarget | null,const anchorMessageId = target?.anchorMessageId ?? nullconst tag = target?.tag ?? nullconst preferTail = target?.preferTail === true- const enabled = target !== null+ const enabled = target !== null && networkEnabledconst baseInput = useMemo(() => ({ channelId, serverId, anchorMessageId, tag, preferTail }), [channelId, serverId, anchorMessageId, tag, preferTail])- const qualification = useMemo(() => ({ accountEpoch, accessEpoch, generation, parentGeneration }), [accountEpoch, accessEpoch, generation, parentGeneration])+ const qualification = useMemo(() => ({ accountEpoch, accessEpoch, generation, parentGeneration, lifetime, parentId: canonical?.parentChannelId }),+ [accountEpoch, accessEpoch, generation, parentGeneration, lifetime, canonical?.parentChannelId])+ const assessment = assessConversationScope(client, baseInput)+ const scopeAvailable = !!target && !!assessment.scope+ const scope = useMemo(() => ({ qualification, value: scopeAvailable ? getQualifiedConversationScope(client, baseInput) : undefined }),+ [scopeAvailable, client, baseInput, qualification]).valueconst cachedSelection = useMemo(() => {const cached = client.getQueryData<ConversationEntryResource>(conversationEntryOptions(client, baseInput).queryKey)- return { qualification, intent, resource: cached && isChannelMetadataTokenCurrent(cached.proof) ? cached : getQualifiedConversationEntry(client, channelId) }- }, [client, baseInput, channelId, qualification, intent])+ return { qualification, intent, scope, resource: cached && isChannelMetadataTokenCurrent(cached.proof) ? cached : getQualifiedConversationEntry(client, channelId) }+ }, [client, baseInput, channelId, qualification, intent, scope])const cachedResource = cachedSelection.resourceconst landing = useMemo(() => {const search = new URLSearchParams(intent?.href.split("?")[1] ?? "")@@ -53,7 +68,8 @@ export function useConversationResource(target: ConversationEntryTarget | null,const pointer = currentConversationReadState(client, channelId)if (!position || !pointer || pointer.lastReadSeq >= position.seq) return { qualification: cachedSelection.qualification, input: baseInput, requestInput: baseInput, position: null }const input = { ...baseInput, anchorMessageId: position.messageId }- const covered = cachedSelection.resource && findConversationEntryWindow(client, input, cachedSelection.resource, pointer)+ const cachedScope = cachedSelection.resource ?? cachedSelection.scope+ const covered = cachedScope && findConversationEntryWindow(client, input, cachedScope, pointer)return { qualification: cachedSelection.qualification, input, requestInput: covered ? baseInput : input, position }}, [client, baseInput, cachedSelection, intent, useLocalPosition, enabled, anchorMessageId, channelId, tag, preferTail])const input = landing.input@@ -65,32 +81,58 @@ export function useConversationResource(target: ConversationEntryTarget | null,setVerification({ runtime, channelId, serverId,needed: !serverRevoked && runtime.ws.actions.isChannelAccessRevoked(channelId, serverId, parentId), generation })}- const query = useQuery({ ...options, enabled: !!target && !revoked, refetchOnReconnect: false, refetchOnWindowFocus: false })+ const query = useQuery({ ...options, enabled: presented && enabled && !revoked, refetchOnReconnect: false, refetchOnWindowFocus: false })const anchorMissing = isConversationAnchorMissingError(query.error)const fallbackInput = useMemo(() => ({ ...baseInput, anchorMessageId: null }), [baseInput])const fallbackRequest = useMemo(() => ({ qualification, options: conversationEntryOptions(client, fallbackInput) }), [client, fallbackInput, qualification])const fallbackOptions = fallbackRequest.options- const fallback = useQuery({ ...fallbackOptions, enabled: !!target && anchorMissing && !revoked, subscribed: !!target && anchorMissing,+ const fallback = useQuery({ ...fallbackOptions, enabled: presented && enabled && anchorMissing && !revoked, subscribed: !!target && anchorMissing,refetchOnReconnect: false, refetchOnWindowFocus: false })const resource = query.data && isChannelMetadataTokenCurrent(query.data.proof) ? query.data: fallback.data && isChannelMetadataTokenCurrent(fallback.data.proof) ? fallback.data: cachedResource && isChannelMetadataTokenCurrent(cachedResource.proof) ? cachedResource : undefined- const qualified = !!target && !!canonical && !!resource && !revoked+ const readableScope = useMemo(() => scope ?? resource, [scope, resource])+ const qualified = !!target && !!canonical && !!readableScope && !revoked&& canonical.id === channelId && canonical.serverId === serverId && !canonical.archivedconst refetch = query.refetch- useEffect(() => { if (enabled && verification.needed) void refetch({ cancelRefetch: false }) }, [refetch, verification, enabled])+ useEffect(() => { if (presented && enabled && verification.needed) void refetch({ cancelRefetch: false }) }, [refetch, verification, enabled, presented])useEffect(() => {- if (!target || revoked || !query.data || isChannelMetadataTokenCurrent(query.data.proof) || query.isFetching || query.isError) return+ if (!presented || !target || revoked || !query.data || isChannelMetadataTokenCurrent(query.data.proof) || query.isFetching || query.isError) returnvoid client.invalidateQueries({ queryKey: options.queryKey, exact: true })- }, [client, parentGeneration, options.queryKey, query.data, query.isFetching, query.isError, revoked, target])+ }, [client, parentGeneration, options.queryKey, query.data, query.isFetching, query.isError, revoked, target, presented])const fallbackRefetch = fallback.refetchconst retryVerification = useCallback(() => (anchorMissing ? fallbackRefetch : refetch)({ cancelRefetch: false }), [anchorMissing, fallbackRefetch, refetch])useEffect(() => {- if (!target || !intent || revoked || !query.data || query.isFetching || query.isError) return+ if (!presented || !target || !intent || revoked || !query.data || query.isFetching || query.isError) return+ if (client.getQueryData(options.queryKey) !== query.data) returnconst pointer = currentConversationReadState(client, channelId)+ const received = client.getQueryData<MessageWindowData>(query.data.windowKey)+ const anchor = input.anchorMessageId ?? pointer?.lastReadMessageId+ if (received?.pages?.some(page => Array.isArray(page.messages) && (anchor ? page.messages.some(message => message.id === anchor) : page.hasMoreNewer === false))) returnif (pointer && !findConversationEntryWindow(client, input, query.data, pointer)) void client.query({ ...options, select: undefined }).catch(() => undefined)- }, [client, channelId, intent, input, options, query.data, query.isFetching, query.isError, revoked, target])- return { client, cachedResource, input: anchorMissing && landing.position ? baseInput : input, options, query, canonical, resource: qualified ? resource : undefined, canRead: qualified, revoked,+ }, [client, channelId, intent, input, options, query.data, query.isFetching, query.isError, revoked, target, presented])+ const currentPointer = read.readState ?? (read.hasSnapshot ? currentConversationReadState(client, channelId) : undefined)+ const cachedWindow = scope ? findConversationDisplayWindow(client, baseInput, scope) : undefined+ const cachedData = cachedWindow ? client.getQueryData<{ pages: Array<{ messages?: unknown[]; threads?: unknown[] }> }>(cachedWindow.key) : undefined+ const rawWindowExists = canonical?.type === "forum" && !anchorMessageId ? client.getQueryData(communityKeys.forumFeed(channelId, tag)) !== undefined+ : client.getQueryCache().findAll({ queryKey: communityKeys.channelMessages(channelId) }).some(query => {+ const identity = messageWindowIdentity(query.queryKey)+ return !!identity && identity.tag === tag && identity.initial.mode !== "since" && query.state.data !== undefined+ })+ const cacheWindow = !cachedWindow ? rawWindowExists ? "incomplete" : "missing" : cachedData?.pages.some(page => (page.messages ?? page.threads ?? []).length > 0) ? "ready" : "empty"+ const targetCoverage = scope && findConversationEntryWindow(client, baseInput, resource ?? scope, currentPointer) ? "covered" : "uncovered"+ const entryStatus = resource ? "current" : client.getQueryCache().findAll({ queryKey: communityKeys.conversationEntries(channelId) }).some(candidate => candidate.state.data !== undefined) ? "stale" : "missing"+ const telemetryOwner = telemetryGeneration()+ useEffect(() => {+ if (!enabled || !active || telemetryOwner !== telemetryGeneration() || typeof window === "undefined") return+ const href = intent?.href ?? window.location.pathname + window.location.search+ const expected = serverId === null ? `/c/me/${encodeURIComponent(channelId)}` : channelHref(serverId, channelId)+ if (normalizeCommunityHref(href).pathname !== expected) return+ const action = navigationForHref(href) ?? (window.location.pathname === expected ? currentPageObservation() : undefined)+ emitTelemetry("conversation.cache", { ...actionAttributes(action), cache_consumer: consumer, cache_reason: assessment.reason,+ cache_window: cacheWindow, entry_status: entryStatus, target_coverage: targetCoverage, eligibility: scopeAvailable ? "eligible" : "rejected" })+ }, [active, assessment.reason, cacheWindow, channelId, consumer, enabled, entryStatus, intent, scopeAvailable, serverId, targetCoverage, telemetryOwner])+ return { client, cachedResource, scope: readableScope, currentPointer, input: anchorMissing && landing.position ? baseInput : input, options, query, canonical, resource: qualified ? resource : undefined, canRead: qualified, revoked,localPosition: anchorMissing ? null : landing.position,denied: serverRevoked || revoked && (!verification.needed || generation !== verification.generation) || isConversationAccessError(query.error) && Number((query.error as { status?: unknown } | null)?.status) !== 401, anchorMissing,verificationError: (!qualified && anchorMissing ? fallback.error : query.error)?.name === "AbortError" ? null : !qualified && anchorMissing ? fallback.error : query.error,@@ -105,6 +147,7 @@ export function useConversationEntry(target: ConversationEntryTarget | null) {const currentIntent = context?.navigation.entryIntentconst expectedPath = target ? target.serverId === null ? `/c/me/${encodeURIComponent(target.channelId)}` : channelHref(target.serverId, target.channelId) : nullconst active = useConversationActivity()+ const presented = useConversationPresentation()const incomingIntent = currentIntent && normalizeCommunityHref(currentIntent.href).pathname === expectedPath ? currentIntent : nullconst [retainedIntent, setRetainedIntent] = useState({ path: expectedPath, intent: incomingIntent })const resuming = incomingIntent?.resume === true@@ -113,37 +156,47 @@ export function useConversationEntry(target: ConversationEntryTarget | null) {? current : { path: expectedPath, intent: incomingIntent })}, [active, expectedPath, incomingIntent, resuming])const intent = (active && !resuming) || retainedIntent.path !== expectedPath ? incomingIntent : retainedIntent.intent- const { client, cachedResource, input, options: entryOptions, query, canonical, resource, canRead, revoked, denied, anchorMissing, localPosition } = useConversationResource(target, intent, true)+ const { client, cachedResource, scope, currentPointer, input, options: entryOptions, query, canonical, resource, canRead, revoked, denied, anchorMissing, localPosition } = useConversationResource(target, intent, true, "messages")const canonicalInput = useMemo(() => localPosition ? { ...input, anchorMessageId: null } : input, [input, localPosition])const entry = useMemo(() => {- const pointer = cachedResource && isChannelMetadataTokenCurrent(cachedResource.proof) ? currentConversationReadState(client, input.channelId) : undefined- const window = cachedResource && pointer ? findConversationEntryWindow(client,- localPosition && pointer.lastReadSeq >= localPosition.seq ? canonicalInput : input, cachedResource, pointer) : undefined- return { intent, knownRevision: pointer?.observedRevision ?? -1, state: createStore<{ snapshot: CommunityReadStateResource | null; window: EntryWindow | null }>({- snapshot: window ? pointer! : null,- window: window ?? null,+ const pointer = scope ? currentConversationReadState(client, input.channelId) : undefined+ const cachedScope = cachedResource ?? scope+ const covered = cachedScope ? findConversationEntryWindow(client,+ localPosition && pointer && pointer.lastReadSeq >= localPosition.seq ? canonicalInput : input, cachedScope, pointer) : undefined+ const window = covered ?? (cachedScope ? findConversationDisplayWindow(client, input, cachedScope) : undefined)+ return { intent, knownRevision: pointer?.observedRevision ?? -1, state: createStore<{ snapshot: CommunityReadStateResource | null; window: EntryWindow | null; covered: boolean }>({+ snapshot: pointer ?? null,+ window: window ?? null, covered: !!covered,}) }- }, [client, cachedResource, input, canonicalInput, localPosition, intent])+ }, [client, cachedResource, scope, input, canonicalInput, localPosition, intent])const selected = useSelector(entry.state, (state) => state)- const currentRevision = currentConversationReadState(client, input.channelId)?.observedRevision ?? -1- const needsCanonicalWindow = !!localPosition && !selected.window && !!resource && (resource.readStateRevision < currentRevision+ const currentRevision = currentPointer?.observedRevision ?? -1+ const needsCanonicalWindow = !!localPosition && !!resource && (resource.readStateRevision < currentRevision && !findConversationEntryWindow(client, canonicalInput, resource, currentPointer)|| resource.readStateAtEntry.lastReadSeq >= localPosition.seq && !findConversationEntryWindow(client, canonicalInput, resource, resource.readStateAtEntry))- const canonicalQuery = useQuery({ ...conversationEntryOptions(client, canonicalInput), enabled: canRead && needsCanonicalWindow,+ const canonicalQuery = useQuery({ ...conversationEntryOptions(client, canonicalInput), enabled: presented && canRead && needsCanonicalWindow,subscribed: needsCanonicalWindow, staleTime: 0, refetchOnReconnect: false, refetchOnWindowFocus: false })const candidateResource = needsCanonicalWindow && canonicalQuery.data && isChannelMetadataTokenCurrent(canonicalQuery.data.proof)&& canonicalQuery.data.readStateRevision >= Math.max(entry.knownRevision, currentRevision) ? canonicalQuery.data : resource- const candidateTarget = localPosition && candidateResource && candidateResource.readStateAtEntry.lastReadSeq >= localPosition.seq+ const candidatePointer = candidateResource && candidateResource.readStateRevision >= Math.max(entry.knownRevision, currentRevision)+ ? candidateResource.readStateAtEntry : scope ? currentConversationReadState(client, input.channelId) : undefined+ const candidateTarget = localPosition && candidatePointer && candidatePointer.lastReadSeq >= localPosition.seq? canonicalInput : input- const candidate = !selected.window && candidateResource && candidateResource.readStateRevision >= Math.max(entry.knownRevision, currentRevision)- ? findConversationEntryWindow(client, candidateTarget, candidateResource, candidateResource.readStateAtEntry) : undefined- const window = canRead ? selected.window ?? candidate ?? null : null- const snapshot = window ? selected.snapshot ?? candidateResource!.readStateAtEntry : null+ const candidateScope = candidateResource ?? scope+ const candidate = (!selected.covered || needsCanonicalWindow) && candidateScope+ ? findConversationEntryWindow(client, candidateTarget, candidateScope, candidatePointer) : undefined+ const display = !selected.window && candidateScope ? findConversationDisplayWindow(client, input, candidateScope) : undefined+ const window = canRead ? candidate ?? selected.window ?? display ?? null : null+ const snapshot = window ? (needsCanonicalWindow || !selected.covered ? candidatePointer ?? selected.snapshot : selected.snapshot) ?? null : null+ const targetCovered = canRead && (needsCanonicalWindow ? !!candidate : selected.covered || !!candidate)useLayoutEffect(() => {- if (!candidate || !candidateResource) return- entry.state.setState((state) => state.window ? state : { window: candidate, snapshot: candidateResource.readStateAtEntry })- }, [candidate, entry, candidateResource])+ if (!window || !snapshot || selected.window === window && selected.snapshot === snapshot && selected.covered === targetCovered) return+ entry.state.setState(() => ({ window, snapshot, covered: targetCovered }))+ }, [window, snapshot, targetCovered, entry, selected])useEffect(() => {- if (!canRead || !window || !resource || hashKey(window.key) === hashKey(resource.windowKey)) return+ if (!presented || query.isFetching || !canRead || !selected.covered || !window || !resource || hashKey(window.key) === hashKey(resource.windowKey)) return+ if (client.getQueryData(entryOptions.queryKey) !== resource) return+ const retained = entry.state.get()+ if (!retained.covered || retained.window !== window) returnconst landing = client.getQueryData<MessageWindowData>(resource.windowKey)const target = Math.max(0, ...(landing?.pages.map(page => page.latestSeq ?? 0) ?? []))const owner = client.getQueryCache().find({ queryKey: entryOptions.queryKey, exact: true })@@ -152,12 +205,13 @@ export function useConversationEntry(target: ConversationEntryTarget | null) {kind: input.serverId === null ? "dm" : "channel", scopeId: input.channelId, serverId: input.serverId ?? undefined,}, window.key, target, undefined, owner ? { query: owner, signal: controller.signal } : undefined).catch(() => undefined)return () => controller.abort()- }, [canRead, client, entryOptions.queryKey, input.channelId, input.serverId, resource, window])+ }, [canRead, client, entryOptions.queryKey, input.channelId, input.serverId, resource, window, presented, selected.covered, entry.state, query.isFetching])const activeQuery = needsCanonicalWindow ? canonicalQuery : queryconst refetch = activeQuery.refetchconst retry = useCallback(() => refetch({ cancelRefetch: false }), [refetch])- return { ...activeQuery, intent, resource, canonical, canRead, window, snapshot, revoked, denied, anchorMissing,- initialPositionMessageId: window && localPosition && snapshot && snapshot.lastReadSeq < localPosition.seq ? localPosition.messageId : null,+ return { ...activeQuery, intent, resource, scope, canonical, canRead, window, snapshot, targetCovered, revoked, denied, anchorMissing,+ initialPositionPending: !targetCovered,+ initialPositionMessageId: targetCovered && localPosition && snapshot && snapshot.lastReadSeq < localPosition.seq ? localPosition.messageId : null,isPending: !!target && !window && !denied && !anchorMissing && !activeQuery.isError && activeQuery.errorUpdatedAt === 0,failed: !window && activeQuery.errorUpdatedAt > 0,retry, retrying: activeQuery.isFetching,diff --git a/src/web/src/hooks/community/use-dms.ts b/src/web/src/hooks/community/use-dms.tsindex 2f2f4b184..9c17eb85e 100644--- a/src/web/src/hooks/community/use-dms.ts+++ b/src/web/src/hooks/community/use-dms.ts@@ -67,7 +67,7 @@ export const dmsProjectedQueryFn = (}}-export function useDms(enabled = true): UseQueryResult<{ ids: string[] }> & { dms: DM[] } {+export function useDms(enabled = true, subscribed = enabled): UseQueryResult<{ ids: string[] }> & { dms: DM[] } {const dbDms = useDmProjection()const queryClient = useQueryClient()const queryFn = useMemo(@@ -78,7 +78,7 @@ export function useDms(enabled = true): UseQueryResult<{ ids: string[] }> & { dmqueryKey: communityKeys.dms(),queryFn,enabled,- subscribed: enabled,+ subscribed,// Inbox navigation projects the destination into this canonical cache// before routing. Reusing that projection across /c/me layout mounts keeps// the transition request-neutral; WS and reconnect invalidations stilldiff --git a/src/web/src/hooks/community/use-forum-entry-selection.dom.test.tsx b/src/web/src/hooks/community/use-forum-entry-selection.dom.test.tsxnew file mode 100644index 000000000..85782e93a--- /dev/null+++ b/src/web/src/hooks/community/use-forum-entry-selection.dom.test.tsx@@ -0,0 +1,69 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest"+import { QueryClientProvider } from "@tanstack/react-query"+import { act, renderHook, waitFor } from "@/test/react-dom-harness"+import { createCommunityQueryOwner } from "@/test/community-query-owner"+import { forumConversationEntryFixture } from "@/test/conversation-entry-fixtures"+import { CommunityDbProvider } from "@/lib/community-db/projections"+import { writeForumTagSelection } from "@/lib/community/forum-tag-selection"+import { useChannelRouteModel } from "./use-channel-route-model"+import { useChannelMetadata } from "./use-channel-metadata"+import { useForumFeed } from "./use-forum-feed"++const load = vi.hoisted(() => vi.fn())+vi.mock("@/lib/api/client", async original => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: (...args: unknown[]) => load(...args) }))+vi.mock("next/navigation", () => ({ usePathname: () => window.location.pathname, useRouter: () => ({ push: vi.fn(), replace: vi.fn() }) }))+vi.mock("./use-servers", () => ({ useServer: () => ({ server: null, isError: false, isFetching: false }) }))+vi.mock("./use-community-ws", () => ({ communityWsSubscribe: vi.fn(), communityWsUnsubscribe: vi.fn() }))+vi.mock("./use-channel-panels", () => ({ useForumTags: () => ({ data: { tags: ["beta", "gamma"] }, isSuccess: true }) }))+beforeEach(() => { load.mockReset(); localStorage.clear(); window.history.replaceState(null, "", "/c/channels/s1/c1") })+afterEach(() => { vi.restoreAllMocks(); localStorage.clear(); window.history.replaceState(null, "", "/") })++it.each(["URL", "saved"] as const)("shares one cold %s-tag entry between route metadata and Forum body", async source => {+ const owner = await createCommunityQueryOwner()+ const value = forumConversationEntryFixture()+ value.forumFeed!.included.tags = [{ messageId: "m1", tag: "beta" }]+ if (source === "saved") writeForumTagSelection(localStorage, "c1", "beta")+ else window.history.replaceState(null, "", "/c/channels/s1/c1?tag=beta")+ let release!: () => void+ load.mockImplementation(() => new Promise(resolve => { release = () => resolve(value) }))+ const hook = renderHook(() => ({+ route: useChannelRouteModel("s1", "s1", "c1", "viewer", null, source === "URL" ? "beta" : null),+ feed: useForumFeed("s1", "c1", source === "URL" ? { routeTag: "beta" } : undefined),+ }), { wrapper: ({ children }) => <QueryClientProvider client={owner.client}><CommunityDbProvider registry={owner.registry}>{children}</CommunityDbProvider></QueryClientProvider> })+ await waitFor(() => expect(release).toBeTypeOf("function"))+ expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages?entry=1&tag=beta"])+ await act(async () => release())+ await waitFor(() => expect(hook.result.current.feed.posts.map(post => post.id)).toEqual(["t1"]))+ expect(hook.result.current.route.routeLifecycle).toBe("ready")+ expect(load).toHaveBeenCalledOnce()+ hook.unmount()+})++it("updates metadata and body from the same-window saved selection without an extra All read", async () => {+ const owner = await createCommunityQueryOwner()+ writeForumTagSelection(localStorage, "c1", "beta")+ load.mockImplementation((url: string) => {+ const value = forumConversationEntryFixture()+ value.forumFeed!.included.tags = [{ messageId: "m1", tag: url.includes("gamma") ? "gamma" : "beta" }]+ return value+ })+ const hook = renderHook(() => ({ metadata: useChannelMetadata("s1", "c1"), feed: useForumFeed("s1", "c1") }), {+ wrapper: ({ children }) => <QueryClientProvider client={owner.client}><CommunityDbProvider registry={owner.registry}>{children}</CommunityDbProvider></QueryClientProvider>,+ })+ await waitFor(() => expect(hook.result.current.feed.data).toBeDefined())+ await act(async () => hook.result.current.feed.selectTag("gamma"))+ await waitFor(() => expect(hook.result.current.feed.tag).toBe("gamma"))+ expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages?entry=1&tag=beta", "/api/community/channels/c1/messages?entry=1&tag=gamma"])+ hook.unmount()+})++it("keeps tag selection usable when storage writes fail", async () => {+ const owner = await createCommunityQueryOwner()+ load.mockImplementation(() => forumConversationEntryFixture())+ const hook = renderHook(() => useForumFeed("s1", "c1"), { wrapper: ({ children }) => <QueryClientProvider client={owner.client}><CommunityDbProvider registry={owner.registry}>{children}</CommunityDbProvider></QueryClientProvider> })+ await waitFor(() => expect(hook.result.current.data).toBeDefined())+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { throw new Error("storage unavailable") })+ await act(async () => hook.result.current.selectTag("beta"))+ expect(hook.result.current.tag).toBe("beta")+ hook.unmount()+})diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.tsindex 219e204e1..6812c7982 100644--- a/src/web/src/hooks/community/use-forum-feed.ts+++ b/src/web/src/hooks/community/use-forum-feed.ts@@ -1,5 +1,7 @@"use client"-import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react"++import { useConversationPresentation } from "@/contexts/community/conversation-activity"+import { useCallback, useEffect, useMemo } from "react"import { createStore, useAtom, useCreateAtom } from "@tanstack/react-store"import { useInfiniteQuery, useIsMutating, useQueryClient, type Query } from "@tanstack/react-query"import { compareAsciiSqliteBinary, DEFAULT_MESSAGE_PAGE_SIZE, type CommunityLegacyThreadsRead, type CommunityThreadsRead } from "@alook/shared"@@ -11,11 +13,14 @@ import { avatarInitial } from "@/lib/community/avatar"import { getCommunityDbRegistry } from "@/lib/community-db/collections"import { useCanonicalChannelsById, useCanonicalMessagesById, useCanonicalProfilesByUserId } from "@/lib/community-db/projections"import { assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken, publishCommunityForumFeed } from "@/lib/community-db/sync"-import { forumTagFromUrl, readForumTagSelection, validateForumTagSelection, writeForumTagSelection } from "@/lib/community/forum-tag-selection"+import { forumTagFromUrl, validateForumTagSelection, writeForumTagSelection } from "@/lib/community/forum-tag-selection"import type { ForumThread, Msg } from "@/lib/community/models/message"import type { ChannelRow } from "@/lib/community-db/schema"import { readCommunityProfile } from "@/lib/community/profile-read"+import { channelHref } from "@/lib/community/community-route"+import { currentPageObservation, navigationForHref } from "@/lib/observability/context"import { useForumTags } from "./use-channel-panels"+import { useStoredForumTag } from "./use-stored-forum-tag"import { useConversationResource } from "./use-conversation-entry"import { forumFeedMatchesTags, forumFeedWindow, normalizeThreadResources, projectThread, type ForumFeedPage, type ForumFeedTransportPage } from "./forum-feed-window"@@ -52,7 +57,16 @@ export function forumFeedPageQueryFn(channelId: string, tag: string | null, querconst params = new URLSearchParams({ order: "createdAt", limit: String(DEFAULT_MESSAGE_PAGE_SIZE), include: "parentMessage,firstMessage,tags,participants" })if (tag) params.set("tag", tag)if (pageParam) params.set("cursor", pageParam)- const transport = await apiFetch<ForumFeedTransportPage | CommunityThreadsRead | CommunityLegacyThreadsRead>(`/api/community/channels/${channelId}/threads?${params}`, communityRequestOptions(queryClient, token, readSignal))+ const request = communityRequestOptions(queryClient, token, readSignal)+ const channel = registry!.collections.channels.get(channelId)+ const path = channel?.serverId ? channelHref(channel.serverId, channelId) : undefined+ const action = typeof window !== "undefined" && window.location.pathname === path ? navigationForHref(window.location.pathname + window.location.search) : undefined+ const observation = request.observation ?? (action && !action.done ? { action, reason: "foreground" as const }+ : typeof window !== "undefined" && window.location.pathname === path ? { page: currentPageObservation(), reason: "background" as const }+ : { page: undefined, reason: "unknown" as const })+ const transport = await apiFetch<ForumFeedTransportPage | CommunityThreadsRead | CommunityLegacyThreadsRead>(`/api/community/channels/${channelId}/threads?${params}`, {+ ...request, observation: { ...observation, ...(pageParam ? { reason: "pagination" as const } : {}), role: pageParam ? "pagination" : "window", windowMode: pageParam ? "older" : "newest" },+ })assertCommunityLiveSnapshotTokenCurrent(queryClient, token, readSignal)const page = normalizeThreadResources(channelId, transport)const freshThreads = page.threads.filter((thread) => !protocol.get().publishedIds.has(thread.id))@@ -88,37 +102,38 @@ export function mapForumFeedPages(pages: ForumFeedPage[], messages: ReadonlyMap<}export function useForumFeed(serverId: string, channelId: string, options?: { routeTag?: string | null; onSelectTag?: (tag: string) => void }) {+ const presented = useConversationPresentation()const queryClient = useQueryClient(), channels = useCanonicalChannelsById(), profiles = useCanonicalProfilesByUserId()- const readTag = () => { try { return readForumTagSelection(window.localStorage, channelId) } catch { return "All" } }- const subscribeTag = useCallback((notify: () => void) => { window.addEventListener("storage", notify); return () => window.removeEventListener("storage", notify) }, [])- const persistedTag = useSyncExternalStore(subscribeTag, readTag, (): string | null => null)+ const persistedTag = useStoredForumTag(channelId)const routeTag = forumTagFromUrl(options?.routeTag)- const [selection, setSelection] = useAtom(useCreateAtom({ channelId: null as string | null, tag: "All" }))- const resolvedTag = routeTag ?? (selection.channelId === channelId ? selection.tag : persistedTag)+ const [fallbackSelection, setFallbackSelection] = useAtom(useCreateAtom<{ channelId: string | null; tag: string }>({ channelId: null, tag: "All" }))+ const resolvedTag = routeTag ?? (fallbackSelection.channelId === channelId ? fallbackSelection.tag : persistedTag)const selectionReady = resolvedTag !== nullconst tag = resolvedTag ?? "All"const onSelectTag = options?.onSelectTagconst selectTag = useCallback((next: string) => {- setSelection({ channelId, tag: next })- try { writeForumTagSelection(window.localStorage, channelId, next) } catch {}+ try {+ writeForumTagSelection(window.localStorage, channelId, next)+ setFallbackSelection({ channelId: null, tag: "All" })+ } catch { setFallbackSelection({ channelId, tag: next }) }onSelectTag?.(next)- }, [channelId, setSelection, onSelectTag])- const tagsQuery = useForumTags(channelId, true)+ }, [channelId, onSelectTag, setFallbackSelection])+ const tagsQuery = useForumTags(channelId, presented)const pendingTagCommands = useIsMutating({ mutationKey: ["community", "forum-tag-command"], exact: true, predicate: (mutation) => {const args = mutation.state.variables as { serverId?: string; forumChannelId?: string } | undefinedreturn args?.serverId === serverId && args.forumChannelId === channelId} })useEffect(() => { if (selectionReady && !pendingTagCommands && tagsQuery.isSuccess && tag !== "All" && validateForumTagSelection(tag, tagsQuery.data.tags) === "All") selectTag("All") }, [selectionReady, pendingTagCommands, tag, tagsQuery.isSuccess, tagsQuery.data, selectTag])const selectedTag = tag === "All" ? null : tag- const entry = useConversationResource(selectionReady ? { channelId, serverId, tag: selectedTag } : null)+ const entry = useConversationResource(selectionReady ? { channelId, serverId, tag: selectedTag } : null, null, false, "forum")const queryKey = communityKeys.forumFeed(entry.canRead ? channelId : "__none__", selectedTag)const query = useInfiniteQuery({ queryKey, queryFn: forumFeedPageQueryFn(channelId, selectedTag, queryClient), initialPageParam: null as string | null, getNextPageParam: (lastPage) => lastPage.hasMore ? lastPage.nextCursor : undefined,- enabled: selectionReady && entry.canRead, subscribed: selectionReady && entry.canRead, staleTime: 5_000,+ enabled: presented && selectionReady && entry.canRead && !entry.verificationFetching, subscribed: selectionReady && entry.canRead, staleTime: 5_000,retry: conversationReadRetryPolicy(queryClient.defaultQueryOptions({ queryKey }).retry), networkMode: "always" })const messageIds = useMemo(() => [...new Set(query.data?.pages.flatMap((page) => page.threads.flatMap((thread) => thread.openerMessageId ? [thread.openerMessageId] : [])) ?? [])], [query.data?.pages])const messages = useCanonicalMessagesById(messageIds)const posts = useMemo(() => selectionReady ? mapForumFeedPages(query.data?.pages ?? [], messages ?? new Map(), channels, profiles, selectedTag) : [], [selectionReady, query.data?.pages, messages, channels, profiles, selectedTag])const fetchNextPage = query.fetchNextPage- const fetchOlder = useCallback(() => { void fetchNextPage({ cancelRefetch: false }) }, [fetchNextPage])+ const fetchOlder = useCallback(() => { if (presented) void fetchNextPage({ cancelRefetch: false }) }, [fetchNextPage, presented])return { ...query, observation: { snapshot_source: entry.resource?.source ?? "unknown" as const, target_coverage: query.data ? "covered" as const : "uncovered" as const, wait_reason: !entry.canRead ? "entry" as const : query.data ? "none" as const : "window" as const }, posts, tag, selectionReady, selectTag, tagsKnown: tagsQuery.data !== undefined, tagsError: tagsQuery.isError, retryTags: tagsQuery.refetch, availableTags: tagsQuery.data?.tags ?? [], hasMoreOlder: query.hasNextPage, isFetchingOlder: query.isFetchingNextPage, fetchOlder }}diff --git a/src/web/src/hooks/community/use-friends.ts b/src/web/src/hooks/community/use-friends.tsindex 2cb047700..1410fde2b 100644--- a/src/web/src/hooks/community/use-friends.ts+++ b/src/web/src/hooks/community/use-friends.ts@@ -102,7 +102,7 @@ export const friendsQueryFn = async (context: QueryFunctionContext) => {return { ids: [...acceptedData.friends.map((friend) => friend.id), ...pendingData.pending.map((pending) => pending.id), ...blockedData.blocked.map((blocked) => `blocked:${blocked.userId ?? blocked.id}`)] }}-export function useFriends(): UseQueryResult<{ ids: string[] }> & {+export function useFriends(options?: { enabled?: boolean }): UseQueryResult<{ ids: string[] }> & {friends: Friend[]pending: PendingRequest[]blocked: BlockedUser[]@@ -110,6 +110,7 @@ export function useFriends(): UseQueryResult<{ ids: string[] }> & {const query = useQuery({queryKey: communityKeys.friends(),queryFn: friendsQueryFn,+ enabled: options?.enabled,placeholderData: keepPreviousData,})const profilesByUserId = useCanonicalProfilesByUserId()diff --git a/src/web/src/hooks/community/use-messages.anchor-retry.dom.test.ts b/src/web/src/hooks/community/use-messages.anchor-retry.dom.test.tsindex 033faac5d..f06d60b87 100644--- a/src/web/src/hooks/community/use-messages.anchor-retry.dom.test.ts+++ b/src/web/src/hooks/community/use-messages.anchor-retry.dom.test.ts@@ -96,7 +96,8 @@ describe("entry failure and explicit recovery", () => {await waitFor(() => expect(hook.result.current.entryCanRead).toBe(true))expect(hook.result.current.entryDenied).toBe(false)expect(hook.result.current.entryAnchorMissing).toBe(true)- expect(hook.result.current.messages).toEqual([])+ expect(hook.result.current.messages.map(message => message.id)).toEqual(["m1"])+ expect(hook.result.current.readSnapshotFetching).toBe(true)expect(registry.collections.channels.has("c1")).toBe(true)expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages?entry=1&anchor=gone", "/api/community/channels/c1/messages?entry=1"])hook.unmount()diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.tsindex af3e626e7..b3fdab0c9 100644--- a/src/web/src/hooks/community/use-messages.ts+++ b/src/web/src/hooks/community/use-messages.ts@@ -1,5 +1,7 @@"use client"+import { useConversationPresentation } from "@/contexts/community/conversation-activity"+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"import { createStore, useSelector } from "@tanstack/react-store"import { hashKey, useInfiniteQuery, useQuery, useQueryClient, type QueryKey } from "@tanstack/react-query"@@ -84,10 +86,11 @@ export function useDmMessages(dmId: string | null, opts?: MessagesOpts) {function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefined, serverId: string | null) {const client = useQueryClient()+ const presented = useConversationPresentation()const tag = opts?.tag ?? nullconst anchorMessageId = opts?.anchorMessageId ?? nullconst entry = useConversationEntry(channelId && opts?.enabled !== false ? { channelId, serverId, anchorMessageId, tag } : null)- const proof = entry.resource?.proof+ const proof = entry.scope?.proofconst positionScope = useMemo<VirtualListPositionScope | undefined>(() => entry.canRead && proof? { proof, kind: "messages", tag } : undefined, [entry.canRead, proof, tag])const viewKey = hashKey([channelId, serverId, anchorMessageId, tag, proof?.accountEpoch ?? -1, proof?.accessEpoch ?? -1,@@ -114,15 +117,15 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefi}, [channelId, serverId])const options = messageWindowOptions(client, enabled ? channelId : "__none__", initial, tag, { observation })const queryKey = selectedWindow?.key ?? options.queryKey- const query = useInfiniteQuery({ ...options, queryKey, enabled, subscribed: enabled })+ const query = useInfiniteQuery({ ...options, queryKey, enabled: enabled && presented, subscribed: enabled })const repairKey: QueryKey = [...queryKey, "reconcile"]const repairOptions = client.getQueryCache().find<{ latestSeq: number }>({ queryKey: repairKey, exact: true })?.options- const reconciliation = useQuery({ ...(repairOptions?.queryFn ? repairOptions : messageReconcileOptions(client, {+ useQuery({ ...(repairOptions?.queryFn ? repairOptions : messageReconcileOptions(client, {kind: serverId === null ? "dm" : "channel", scopeId: channelId ?? "__none__", serverId: serverId ?? undefined,}, queryKey)),- queryKey: repairKey, enabled: false, subscribed: enabled })+ queryKey: repairKey, enabled: false, subscribed: enabled, notifyOnChangeProps: "all" })const originalQuery = client.getQueryCache().find({ queryKey, exact: true })- const owner = useMemo(() => ({ present, retries, query: originalQuery, enabled }), [present, retries, originalQuery, enabled])+ const owner = useMemo(() => ({ present, retries, query: originalQuery, enabled: enabled && presented }), [present, retries, originalQuery, enabled, presented])const committed = useRef<typeof owner | null>(null)useLayoutEffect(() => {committed.current = owner@@ -160,8 +163,11 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undeficonst latestSeq = Math.max(0, ...(query.data?.pages.map((page) => page.latestSeq ?? 0) ?? []))const landingWindow = entry.resource ? client.getQueryData<MessageWindowData>(entry.resource.windowKey) : undefinedconst landingLatestSeq = Math.max(0, ...(landingWindow?.pages.map(page => page.latestSeq ?? 0) ?? []))- const readSnapshotFetching = entry.isPending || ids.some(id => !canonicalById.has(id))- || !anchorMessageId && !tag && (landingLatestSeq > latestSeq && (!reconciliation.isError || reconciliation.isFetching)+ const repairTarget = client.getQueryData<number>([...queryKey, "reconcile-target"]) ?? 0+ const coveredLatestSeq = Math.max(0, ...canonicalBase.map(message => message.seq))+ const readSnapshotFetching = !entry.snapshot || !entry.targetCovered && !selection.window || entry.isPending || ids.some(id => !canonicalById.has(id))+ || repairTarget > coveredLatestSeq+ || !anchorMessageId && !tag && (landingLatestSeq > latestSeq|| entry.isFetching && !!channelId && knownConversationLatestSeq(client, channelId) > latestSeq)const pages = query.data?.pages ?? []const oldest = pages.at(-1)@@ -231,12 +237,15 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefiretries.setState(() => ({ attempt, pending: false, error: result.error }))})}, [channelId, client, entryWindow, retryEntry, refetchWindow, retries])- const positionDataState: MessagePositionState = retrySelection.pending ? "pending"+ const targetPositionDataState: MessagePositionState = retrySelection.pending ? "pending": initialLoadError || retrySelection.error || entry.denied || !windowAvailable && entry.anchorMissing && !entry.isFetching ? "error"- : !windowAvailable || !entry.snapshot || loading || readSnapshotFetching ? "pending"+ : !windowAvailable || loading || missingCanonical || !!anchorMessageId && !entry.targetCovered && !selection.window && !entry.anchorMissing ? "pending": messages.length ? "ready" : "empty"+ const positionDataState: MessagePositionState = targetPositionDataState === "error" ? "error"+ : !windowAvailable || !entry.snapshot || loading || readSnapshotFetching || retrySelection.pending ? "pending"+ : messages.length ? "ready" : "empty"return {- ...query, observation: { snapshot_source: entry.resource?.source ?? "unknown" as const, target_coverage: windowAvailable ? "covered" as const : "uncovered" as const,+ ...query, observation: { snapshot_source: entry.resource?.source ?? "unknown" as const, target_coverage: entry.targetCovered || selection.window ? "covered" as const : "uncovered" as const,wait_reason: !entry.canRead ? "entry" as const : !windowAvailable ? "window" as const : loading ? "projection" as const : "none" as const },messages, canonicalMessages: canonicalBase, canonicalById,latestSeq, hasMoreOlder, hasMoreNewer, historyStartKnown, hasMore: hasMoreOlder,@@ -245,11 +254,11 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefiisFetchingOlder: query.isFetchingNextPage,isFetchingNewer: query.isFetchingPreviousPage || selection.pending,fetchOlder, fetchNewer, jumpToPresent, presentVersion: selection.version, presentRequest: selection.request,- anchorReconciled: !!selectedWindow,+ anchorReconciled: entry.targetCovered || !!selection.window,navigationBlocked: !entry.canRead,readSnapshot: entry.snapshot, readSnapshotFetching,- initialPositionKnown: windowAvailable && entry.snapshot !== null && !loading && !missingCanonical && !initialLoadError && !retrySelection.pending,- initialPositionMessageId: entry.initialPositionMessageId, positionEntry, positionScope, positionDataState, messageWindow: query.data,+ initialPositionKnown: windowAvailable && entry.snapshot !== null && !loading && !missingCanonical && !initialLoadError && !retrySelection.pending && !entry.initialPositionPending,+ initialPositionMessageId: entry.initialPositionMessageId, positionEntry, positionScope, positionDataState, targetPositionDataState, messageWindow: query.data,retryInitialLoad, retryingInitialLoad: entry.isFetching || query.isFetching,entryCanRead: entry.canRead, entryDenied: entry.denied, entryAnchorMissing: entry.anchorMissing,}diff --git a/src/web/src/hooks/community/use-notification-settings.ts b/src/web/src/hooks/community/use-notification-settings.tsindex 7b84a7d6e..44e05fadf 100644--- a/src/web/src/hooks/community/use-notification-settings.ts+++ b/src/web/src/hooks/community/use-notification-settings.ts@@ -114,7 +114,7 @@ export async function reconcileNotificationSettings(queryClient: QueryClient) {return settings}-export function useNotificationSettings(): UseQueryResult<NotificationSettings> & {+export function useNotificationSettings(enabled = true): UseQueryResult<NotificationSettings> & {server: Record<string, string>channel: Record<string, string>} {@@ -122,6 +122,7 @@ export function useNotificationSettings(): UseQueryResult<NotificationSettings>const query = useQuery({queryKey: communityKeys.notificationSettings(),queryFn: notificationSettingsQueryFn,+ enabled,})return {...query,diff --git a/src/web/src/hooks/community/use-scroll-anchor.restoration.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.restoration.dom.test.tsindex 56bc8b63c..d10644885 100644--- a/src/web/src/hooks/community/use-scroll-anchor.restoration.dom.test.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.restoration.dom.test.ts@@ -54,6 +54,47 @@ describe("native snapshot restoration and one-shot late unread ownership", () =>expect(scrollFixture.latest.readPositionReady).toBe(true)})+ it.each([false, true])("restores 600px from tail when cached rows arrive after the initial mount (StrictMode=%s)", async strict => {+ const { client } = await createCommunityQueryOwner()+ const positionScope: VirtualListPositionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages", tag: null }+ const items = Array.from({ length: 40 }, (_, index) => message(`m${index}`))+ const first = mount({ positionScope, items }, strict)+ first.move(first.root.scrollHeight - first.root.clientHeight - 600)+ resize()+ const snapshot = client.getQueryData<VirtualListPositionSnapshot>(virtualListPositionKey(positionScope))!+ const id = String(snapshot.anchorKey).slice(4)+ const before = bodyTop(first.root, id)+ const offset = first.root.scrollTop+ expect(first.root.scrollHeight - first.root.clientHeight - offset).toBe(600)+ first.view.unmount()+ const returned = mount({ positionScope, items: [], initialScrollReady: false, positionDataState: "pending" }, strict)+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ expect(client.getQueryData(virtualListPositionKey(positionScope))).toBe(snapshot)+ returned.update({ items, initialScrollReady: true, positionDataState: "ready" })+ expect(returned.root.scrollTop).toBeCloseTo(offset, 0)+ expect(bodyTop(returned.root, id)).toBeCloseTo(before, 0)+ expect(scrollFixture.latest.readPositionReady).toBe(true)+ })++ it("does not restore a late snapshot after real manual takeover", async () => {+ const { client } = await createCommunityQueryOwner()+ const positionScope: VirtualListPositionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages", tag: null }+ const items = Array.from({ length: 40 }, (_, index) => message(`m${index}`))+ const first = mount({ positionScope, items })+ first.move(800)+ first.view.unmount()+ const returned = mount({ positionScope, items: [], initialScrollReady: false, positionDataState: "pending" })+ const jump = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToIndex")+ fireEvent.wheel(returned.root, { deltaY: -10 })+ returned.update({ items, initialScrollReady: true, positionDataState: "pending" })+ expect(jump).not.toHaveBeenCalled()+ expect(scrollFixture.latest.positionOutcome).toBe("user-cancelled")+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ returned.update({ positionDataState: "ready" })+ expect(jump).not.toHaveBeenCalled()+ expect(scrollFixture.latest.readPositionReady).toBe(true)+ })+it.each(["other-channel", "other-account", "changed-rows", "changed-width", "explicit-target"] as const)("does not restore stale pixels for %s", async mode => {const { client } = await createCommunityQueryOwner()const positionScope: VirtualListPositionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages", tag: null }diff --git a/src/web/src/hooks/community/use-scroll-anchor.telemetry.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.telemetry.dom.test.tsnew file mode 100644index 000000000..aed38f067--- /dev/null+++ b/src/web/src/hooks/community/use-scroll-anchor.telemetry.dom.test.ts@@ -0,0 +1,159 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest"+import { act, fireEvent } from "@/test/react-dom-harness"+import { configureTelemetry, installTelemetrySink, retireTelemetry } from "@/lib/observability/telemetry"+import { installMessageScrollFixture, restoreMessageScrollFixture, mount, message, runFrames, scrollFixture } from "@/test/message-scroll-fixture"+import { createCommunityQueryOwner } from "@/test/community-query-owner"+import { captureChannelMetadataToken } from "@/lib/community/conversation-qualification"+import { virtualListPositionKey, type VirtualListPositionSnapshot } from "@/lib/community/virtual-list-position"++let events: Array<{ name: string; attributes: Record<string, string> }>+beforeEach(() => {+ installMessageScrollFixture()+ events = []+ configureTelemetry({ session_id: "position-session" }, true)+ installTelemetrySink(event => events.push(event))+})+afterEach(() => { retireTelemetry(); restoreMessageScrollFixture() })+const terminals = () => events.filter(event => event.name === "position.finish").map(event => event.attributes)++it("finishes a covered local target while newer continuity remains pending without granting reads or paging", () => {+ const positioned = vi.fn()+ const h = mount({ scrollToMessageId: "m4", positionDataState: "pending", targetPositionDataState: "ready", onScrollTargetPositioned: positioned })+ expect(positioned).toHaveBeenCalledExactlyOnceWith("m4")+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ expect(scrollFixture.latest.paginationEnabled).toBe(false)+ expect(terminals()).toContainEqual(expect.objectContaining({ position_owner: "target", position_reason: "settled", target_coverage: "covered", position_source: "explicit_target", position_snapshot: "not_requested" }))+ const count = terminals().length+ h.update({ positionDataState: "ready" })+ runFrames()+ expect(terminals()).toHaveLength(count)+ expect(scrollFixture.latest.readPositionReady).toBe(true)+})++it("records real geometry success once and records a new target independently of initial presentation", () => {+ const h = mount({ positionDataState: "ready" })+ expect(terminals()).toEqual([expect.objectContaining({ position_owner: "initial", position_reason: "settled" })])+ h.update({ scrollToMessageId: "m4" })+ expect(terminals()).toHaveLength(2)+ expect(terminals()[1]).toMatchObject({ position_owner: "target", position_reason: "settled" })+ h.view.unmount()+ expect(terminals()).toHaveLength(2)+})++it("records an explicit imperative jump even when no target-consumed callback is requested", () => {+ mount()+ act(() => scrollFixture.latest.jumpTo("m4", "auto"))+ runFrames()+ expect(terminals().at(-1)).toMatchObject({ position_owner: "target", position_source: "explicit_target", position_snapshot: "not_requested", position_reason: "settled" })+})++it("retires an absent ready target without geometry or a false successful finish", () => {+ scrollFixture.height = 0+ const cancelled = vi.fn()+ const h = mount({ scrollToMessageId: "absent", positionDataState: "pending", targetPositionDataState: "pending", onScrollTargetCancelled: cancelled })+ expect(terminals().some(event => event.position_owner === "target")).toBe(false)+ h.update({ targetPositionDataState: "ready" })+ expect(cancelled).toHaveBeenCalledExactlyOnceWith("absent")+ expect(terminals().filter(event => event.position_owner === "target")).toEqual([expect.objectContaining({ position_reason: "target_missing", target_coverage: "uncovered" })])+ expect(scrollFixture.latest.readPositionReady).toBe(false)+})++it.each(["manual", "hidden", "entry", "unmount"] as const)("records %s retirement once at the existing owner", reason => {+ scrollFixture.height = 0+ const h = mount({ positionDataState: "pending", initialScrollReady: false, positionEntry: {} })+ if (reason === "manual") fireEvent.wheel(h.root, { deltaY: 20 })+ else if (reason === "hidden") h.update({ positioningActive: false })+ else if (reason === "entry") h.update({ positionEntry: {} })+ else h.view.unmount()+ const expected = { manual: "manual_takeover", hidden: "hidden", entry: "entry_changed", unmount: "retired" }[reason]+ expect(terminals().filter(event => event.position_reason === expected)).toHaveLength(1)+ expect(terminals().some(event => event.position_reason === "settled")).toBe(false)+})++it.each(["valid", "missing", "fingerprint", "viewport", "padding", "anchor", "expired", "version"] as const)("records actual snapshot admission for %s without exporting its values", async state => {+ const { client } = await createCommunityQueryOwner()+ const positionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages" as const, tag: null }+ const items = Array.from({ length: 40 }, (_, index) => message(`m${index}`))+ const first = mount({ items, positionScope })+ first.move(800)+ const key = virtualListPositionKey(positionScope)+ const snapshot = client.getQueryData<VirtualListPositionSnapshot>(key)!+ expect(snapshot.offset).toBe(800)+ first.view.unmount()+ events.length = 0+ if (state === "missing") client.removeQueries({ queryKey: key, exact: true })+ else if (state === "viewport") scrollFixture.width += 1+ else if (state !== "valid") client.setQueryData(key, { ...snapshot,+ ...(state === "fingerprint" ? { fingerprint: "PRIVATE-position-fingerprint" } : {}),+ ...(state === "padding" ? { paddingEnd: snapshot.paddingEnd + 1 } : {}),+ ...(state === "anchor" ? { anchorKey: "PRIVATE-position-anchor" } : {}),+ ...(state === "expired" ? { at: Date.now() - 300001 } : {}),+ ...(state === "version" ? { version: 2 } : {}),+ })+ const restored = mount({ items, positionScope })+ const expected = { valid: "accepted", missing: "missing", fingerprint: "fingerprint_mismatch", viewport: "viewport_mismatch",+ padding: "padding_mismatch", anchor: "anchor_missing", expired: "expired", version: "invalid_version" }[state]+ expect(terminals()).toEqual([expect.objectContaining({ position_owner: "initial", position_reason: "settled",+ position_source: state === "valid" ? "snapshot" : "tail", position_snapshot: expected })])+ if (state === "valid") expect(restored.root.scrollTop).toBeCloseTo(800, 0)+ expect(JSON.stringify(events)).not.toContain("PRIVATE-position")+})++it.each(["read_anchor", "new_divider", "tail"] as const)("records the actual %s selection instead of inferring it from initial/settled", source => {+ mount({ ...(source === "read_anchor" ? { initialPositionMessageId: "m4" } : {}),+ ...(source === "new_divider" ? { newDividerBefore: "m4" } : {}) })+ expect(terminals()).toEqual([expect.objectContaining({ position_source: source, position_snapshot: "no_scope", position_reason: "settled" })])+})++it("keeps a new entry decision separate from a prior successful snapshot restore", async () => {+ const { client } = await createCommunityQueryOwner()+ const positionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages" as const, tag: null }+ const first = mount({ positionScope })+ first.move(600)+ first.view.unmount()+ events.length = 0+ const returned = mount({ positionScope, positionEntry: {} })+ expect(terminals()).toEqual([expect.objectContaining({ position_source: "snapshot", position_snapshot: "accepted" })])+ returned.update({ positionEntry: {} })+ expect(terminals()).toHaveLength(2)+ expect(terminals()[1]).toMatchObject({ position_source: "tail", position_snapshot: "entry_changed" })+ returned.update({ positionEntry: {}, positionDataState: "pending", initialScrollReady: false })+ fireEvent.wheel(returned.root, { deltaY: -20 })+ expect(terminals().at(-1)).toMatchObject({ position_source: "unknown", position_snapshot: "entry_changed", position_reason: "manual_takeover" })+})++it("records a fingerprint changed after lookup as a rejected restore at actual admission", async () => {+ const { client } = await createCommunityQueryOwner()+ const positionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages" as const, tag: null }+ const items = Array.from({ length: 40 }, (_, index) => message(`m${index}`))+ const first = mount({ items, positionScope })+ first.move(800)+ first.view.unmount()+ events.length = 0+ const returned = mount({ items, positionScope, initialScrollReady: false, positionDataState: "pending" })+ const changed = items.map((item, index) => index === 0 ? { ...item, m: { ...item.m, content: "Changed shape" } } : item)+ returned.update({ items: changed, initialScrollReady: true, positionDataState: "ready" })+ expect(terminals()).toEqual([expect.objectContaining({ position_source: "tail", position_snapshot: "fingerprint_mismatch", position_reason: "settled" })])+})++it("does not call an available snapshot accepted when a user cancels before admission", async () => {+ const { client } = await createCommunityQueryOwner()+ const positionScope = { proof: captureChannelMetadataToken(client, "A"), kind: "messages" as const, tag: null }+ const first = mount({ positionScope })+ first.move(600)+ first.view.unmount()+ events.length = 0+ const returned = mount({ positionScope, initialScrollReady: false, positionDataState: "pending" })+ fireEvent.wheel(returned.root, { deltaY: -20 })+ expect(terminals()).toEqual([expect.objectContaining({ position_source: "unknown", position_snapshot: "available", position_reason: "manual_takeover" })])+})++it.each(["late-consent", "retired-session"] as const)("does not export an old attempt after %s", boundary => {+ if (boundary === "late-consent") configureTelemetry({}, false)+ const h = mount({ positionDataState: "pending", initialScrollReady: false })+ if (boundary === "retired-session") retireTelemetry()+ configureTelemetry({ session_id: "replacement-session" }, true)+ installTelemetrySink(event => events.push(event))+ act(() => h.update({ positionDataState: "ready", initialScrollReady: true }))+ expect(terminals()).toEqual([])+})diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.tsindex 98f864e29..6f2c8a12c 100644--- a/src/web/src/hooks/community/use-scroll-anchor.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.ts@@ -1,3 +1,4 @@+import { beginPositionObservation, type PositionDecision, type PositionReason, type PositionSnapshotReason } from "@/lib/observability/position"import { useAtom, useCreateAtom } from "@tanstack/react-store";import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react"import { measureElement, useVirtualizer, type ReactVirtualizer } from "@tanstack/react-virtual"@@ -5,7 +6,7 @@ import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS, type VirtualRowsLayoutSnapshot } fimport { estimateRowHeight, computeBelowCount, type FlatItem } from "@/lib/community/message-list-items"import { MESSAGE_RAIL_TAIL_PADDING_END_PX } from "@/lib/community/conversation-layout"import type { MessagePositionState, MessageRequest, MessageRequestResult } from "@/lib/community/message-position"-import { readVirtualListPosition, saveVirtualListPosition, virtualListLayoutFingerprint, type VirtualListPositionScope } from "@/lib/community/virtual-list-position"+import { assessVirtualListPosition, saveVirtualListPosition, virtualListLayoutFingerprint, type VirtualListPositionScope } from "@/lib/community/virtual-list-position"export const MESSAGE_LIST_DISPLAY_END_THRESHOLD_PX = 100const VIEWPORT_RESIZE_TAIL_DISTANCE_PX = 100@@ -78,6 +79,7 @@ export function useScrollAnchor({newDividerBefore,initialScrollReady,positionDataState,+ targetPositionDataState,messageWindow,active = true,positioningActive = active,@@ -101,6 +103,7 @@ export function useScrollAnchor({newDividerBefore?: stringinitialScrollReady: booleanpositionDataState?: MessagePositionState+ targetPositionDataState?: MessagePositionStatemessageWindow?: objectactive?: booleanpositioningActive?: boolean@@ -149,16 +152,22 @@ export function useScrollAnchor({}const scrollRef = useRef<HTMLDivElement>(null)const fingerprint = useMemo(() => virtualListLayoutFingerprint(items), [items])- const [initialSnapshot] = useState(() => scrollToMessageId ? null : readVirtualListPosition(positionScope, fingerprint))+ const [initialPosition] = useState(() => scrollToMessageId+ ? { snapshot: null, reason: "not_requested" as const } : assessVirtualListPosition(positionScope, fingerprint))+ const initialSnapshot = initialPosition.snapshotconst restorationRef = useRef(initialSnapshot)+ const snapshotReasonRef = useRef<PositionSnapshotReason>(initialPosition.reason)+ const snapshotReadRef = useRef(initialSnapshot !== null || !!scrollToMessageId)const snapshotContextRef = useRef({ scope: positionScope, fingerprint })const virtualizerRef = useRef<ReactVirtualizer<HTMLDivElement, Element> | null>(null)const positionOwnerRef = useRef({ epoch: 0, active: true })+ const positionObservationRef = useRef<{ epoch: number; finish: ReturnType<typeof beginPositionObservation>; decision: PositionDecision } | null>(null)const [documentVisible, setDocumentVisible] = useState(() => typeof document === "undefined" || document.visibilityState !== "hidden")const visible = positioningActive && documentVisibleconst entryActivationRef = useRef({ entry: positionEntry, seen: visible })const dataState = positionDataState ?? (initialScrollReady ? items.some(item => item.kind === "message") ? "ready" : "empty" : "pending")- const contextRef = useRef({ dataState, initialScrollReady, messageWindow, isFetchingOlder, isFetchingNewer, visible, newDividerBefore })+ const targetDataState = targetPositionDataState ?? dataState+ const contextRef = useRef({ dataState, targetDataState, initialScrollReady, messageWindow, isFetchingOlder, isFetchingNewer, visible, newDividerBefore })const [requestRevision, setRequestRevision] = useState(0)const [committedEntry, setCommittedEntry] = useState(positionEntry)const entryChanged = committedEntry !== positionEntry@@ -212,9 +221,9 @@ export function useScrollAnchor({onTargetPositionedRef.current = onScrollTargetPositionedonTargetCancelledRef.current = onScrollTargetCancelledsettleCallbackRef.current = onInitialPositionSettled- contextRef.current = { dataState, initialScrollReady, messageWindow, isFetchingOlder, isFetchingNewer, visible, newDividerBefore }+ contextRef.current = { dataState, targetDataState, initialScrollReady, messageWindow, isFetchingOlder, isFetchingNewer, visible, newDividerBefore }snapshotContextRef.current = { scope: positionScope, fingerprint }- }, [items, positionEntry, positionScope, fingerprint, initialScrollReady, newDividerBefore, onScrollTargetPositioned, onScrollTargetCancelled, onInitialPositionSettled, dataState, messageWindow, isFetchingOlder, isFetchingNewer, visible])+ }, [items, positionEntry, positionScope, fingerprint, initialScrollReady, newDividerBefore, onScrollTargetPositioned, onScrollTargetCancelled, onInitialPositionSettled, dataState, targetDataState, messageWindow, isFetchingOlder, isFetchingNewer, visible])const followSuspension = useCreateAtom(false)const [followSuspended, setFollowSuspended] = useAtom(followSuspension)const acceptedGeometryRef = useRef<Geometry | null>(null)@@ -266,6 +275,21 @@ export function useScrollAnchor({? currentItemsRef.current.findIndex(row => row.key === anchor.key) : -1return item.index < index}, [positionKind])+ const beginPosition = useCallback((kind: Kind) => {+ const epoch = positionOwnerRef.current.epoch+ if (kind === "idle" || !contextRef.current.visible || positionObservationRef.current?.epoch === epoch) return+ positionObservationRef.current = { epoch, finish: beginPositionObservation(kind, snapshotContextRef.current.scope, positionEntryRef.current),+ decision: { position_source: "unknown", position_snapshot: kind === "initial" ? snapshotReasonRef.current : "not_requested" } }+ }, [])+ const finishPosition = useCallback((reason: PositionReason) => {+ const observation = positionObservationRef.current+ observation?.finish(reason, observation.decision)+ }, [])+ const recordSnapshotDecision = useCallback((reason: PositionSnapshotReason) => {+ snapshotReasonRef.current = reason+ const observation = positionObservationRef.current+ if (observation?.epoch === positionOwnerRef.current.epoch && positionKind.get() === "initial") observation.decision.position_snapshot = reason+ }, [positionKind])const claimPosition = useCallback((kind: Kind) => {if (kind === "target" || kind === "present") lateNewRef.current.allowed = falseconst owner = positionOwnerRef.current@@ -275,7 +299,9 @@ export function useScrollAnchor({paginationRef.current = nullobservePageBody()setPaginationDirection(null)+ finishPosition("superseded")owner.epoch += 1+ beginPosition(kind)setOwnerKind(kind)cancelFrame()semanticIntentRef.current = null@@ -284,12 +310,12 @@ export function useScrollAnchor({presentIntentRef.current = nullsetReadPositionReady(false)return owner.epoch- }, [cancelFrame, clearMeasurementAnchor, holdNativeOrigin, observePageBody, setOwnerKind, setPaginationDirection, setReadPositionReady])+ }, [beginPosition, cancelFrame, clearMeasurementAnchor, finishPosition, holdNativeOrigin, observePageBody, setOwnerKind, setPaginationDirection, setReadPositionReady])const retireInitialPosition = useCallback(() => {initialRetiredRef.current = trueentryResolvedRef.current = true}, [])- const releasePosition = useCallback((userHandover = false, outcome: PositionOutcome = userHandover ? "user-cancelled" : "cancelled") => {+ const releasePosition = useCallback((userHandover = false, outcome: PositionOutcome = userHandover ? "user-cancelled" : "cancelled", reason: PositionReason = userHandover ? "manual_takeover" : outcome === "empty" ? "empty" : outcome === "error" ? "data_error" : "cancelled") => {lateNewRef.current.allowed = falseconst intent = semanticIntentRef.currentconst cancelledTarget = positionKind.get() === "target"@@ -297,6 +323,7 @@ export function useScrollAnchor({: !intent && positionedTargetRef.current !== targetIntentRef.current ? targetIntentRef.current : null: nullconst wasReadable = positionKind.get() === "idle" && readReady.get()+ finishPosition(reason)claimPosition("idle")if (userHandover && wasReadable) setReadPositionReady(true)retireInitialPosition()@@ -305,7 +332,7 @@ export function useScrollAnchor({if (userHandover) userInputRef.current.handover = truesettlePresentation(outcome)scheduleGeometryRef.current()- }, [claimPosition, positionKind, readReady, retireInitialPosition, setReadPositionReady, settlePresentation])+ }, [claimPosition, finishPosition, positionKind, readReady, retireInitialPosition, setReadPositionReady, settlePresentation])const readPageMessageGeometry = useCallback((key: string): { viewportOffset: number; bodyInset: number } | null => {const root = scrollRef.currentconst native = virtualizerRef.current@@ -491,13 +518,13 @@ export function useScrollAnchor({: intent.id ? intent.type === "unread" ? findMountScrollTargetIndex(currentItemsRef.current, intent.id): findMessageIndex(currentItemsRef.current, intent.id) : nullif (index === null || index < 0) {- if (intent.type !== "end" && contextRef.current.dataState === "ready") releasePosition()+ if (intent.type !== "end" && (positionKind.get() === "target" ? contextRef.current.targetDataState : contextRef.current.dataState) === "ready") releasePosition(false, "cancelled", "target_missing")return}if ((positionKind.get() === "initial" || positionKind.get() === "late-new") && !contextRef.current.initialScrollReady) returnif (!intent.issued) {if (intent.origin && (intent.origin.root !== root || Math.abs(root.scrollTop - intent.origin.offset) > 1)) {- releasePosition(true)+ releasePosition(true, "user-cancelled", "origin_changed")return}if (!hasCommittedRows()) return@@ -558,7 +585,8 @@ export function useScrollAnchor({if (!geometry) returnif (intent.type !== "end" && root.scrollTop <= 1) holdNativeOrigin(currentItemsRef.current[0]?.key ?? null)settlePresentation()- if (!initial && contextRef.current.dataState === "pending") return+ if (!initial && (positionKind.get() === "target" ? contextRef.current.targetDataState : contextRef.current.dataState) === "pending") return+ finishPosition("settled")acceptedGeometryRef.current = geometryif (intent.type === "restore") {native.cancelScroll()@@ -580,7 +608,7 @@ export function useScrollAnchor({}}initialSettleFrameRef.current = window.requestAnimationFrame(settle)- }, [clearMeasurementAnchor, hasCommittedRows, holdNativeOrigin, positionKind, readGeometry, readPageMessageGeometry, releasePosition, retireInitialPosition, setFollowSuspended, setOwnerKind, setReadPositionReady, settlePresentation])+ }, [clearMeasurementAnchor, finishPosition, hasCommittedRows, holdNativeOrigin, positionKind, readGeometry, readPageMessageGeometry, releasePosition, retireInitialPosition, setFollowSuspended, setOwnerKind, setReadPositionReady, settlePresentation])const onRowsLayoutCommit = useCallback((layout: VirtualRowsLayoutSnapshot | null) => {committedRowsRef.current = layout ? { layout, native: virtualizer, entry: positionEntry, items } : null@@ -592,13 +620,19 @@ export function useScrollAnchor({const startIntent = useCallback((type: Intent["type"], id: string | null, behavior: ScrollBehavior = "auto", notifyTarget = false, loadedTailPresent = false) => {const owner = positionOwnerRef.currentif (!owner.active || !contextRef.current.visible) return+ beginPosition(positionKind.get())+ const observation = positionObservationRef.current+ if (observation?.epoch === owner.epoch) observation.decision = {+ position_source: type === "restore" ? "snapshot" : type === "end" ? "tail" : type === "unread" ? "new_divider" : positionKind.get() === "initial" ? "read_anchor" : "explicit_target",+ position_snapshot: positionKind.get() === "initial" ? snapshotReasonRef.current : "not_requested",+ }const index = type === "restore" ? currentItemsRef.current.findIndex(item => item.key === id): type === "end" ? currentItemsRef.current.length - 1: id ? type === "unread" ? findMountScrollTargetIndex(currentItemsRef.current, id): findMessageIndex(currentItemsRef.current, id) : nullsemanticIntentRef.current = {epoch: owner.epoch, type, id, index, behavior, notifyTarget, loadedTailPresent,- awaitingData: positionKind.get() === "initial" || positionKind.get() === "late-new" ? !contextRef.current.initialScrollReady : contextRef.current.dataState === "pending",+ awaitingData: positionKind.get() === "initial" || positionKind.get() === "late-new" ? !contextRef.current.initialScrollReady : (positionKind.get() === "target" ? contextRef.current.targetDataState : contextRef.current.dataState) === "pending",viewport: { width: scrollRef.current?.clientWidth ?? 0, height: scrollRef.current?.clientHeight ?? 0 },issued: false,origin: positionKind.get() === "initial" && type !== "restore" && !initialSnapshot ? { root: scrollRef.current, offset: scrollRef.current?.scrollTop ?? 0 } : null,@@ -618,11 +652,12 @@ export function useScrollAnchor({}}scheduleInitialPositionSettled()- }, [adjustAnchoredMeasurement, initialSnapshot, positionKind, scheduleInitialPositionSettled])+ }, [adjustAnchoredMeasurement, beginPosition, initialSnapshot, positionKind, scheduleInitialPositionSettled])useLayoutEffect(() => {const owner = positionOwnerRef.currentowner.active = true+ beginPosition(positionKind.get())const intent = semanticIntentRef.currentif (intent && intent.epoch !== owner.epoch) {intent.epoch = owner.epoch@@ -632,6 +667,7 @@ export function useScrollAnchor({}if (acceptedGeometryRef.current) acceptedGeometryRef.current.epoch = owner.epochreturn () => {+ finishPosition("retired")owner.active = falseowner.epoch += 1virtualizerRef.current?.cancelScroll()@@ -642,7 +678,7 @@ export function useScrollAnchor({if (geometryFrameRef.current !== null) window.cancelAnimationFrame(geometryFrameRef.current)geometryFrameRef.current = null}- }, [cancelFrame, clearMeasurementAnchor, observePageBody, positionKind, scheduleInitialPositionSettled, startIntent])+ }, [beginPosition, cancelFrame, clearMeasurementAnchor, finishPosition, observePageBody, positionKind, scheduleInitialPositionSettled, startIntent])useLayoutEffect(() => {const update = () => setDocumentVisible(document.visibilityState !== "hidden")@@ -655,7 +691,7 @@ export function useScrollAnchor({if (!visible) {if (entryActivationRef.current.seen) lateNewRef.current.allowed = falsesetResumeValidated(false)- if (entryActivationRef.current.seen && positionKind.get() !== "idle") releasePosition()+ if (entryActivationRef.current.seen && positionKind.get() !== "idle") releasePosition(false, "cancelled", "hidden")positionOwnerRef.current.active = falsevirtualizerRef.current?.cancelScroll()cancelFrame()@@ -666,16 +702,20 @@ export function useScrollAnchor({geometryFrameRef.current = null} else {positionOwnerRef.current.active = true+ beginPosition(positionKind.get())if (!readReady.get() || readGeometry()) setResumeValidated(true)scheduleGeometryRef.current()}- }, [cancelFrame, observePageBody, positionKind, readGeometry, readReady, releasePosition, setPaginationDirection, visible])+ }, [beginPosition, cancelFrame, observePageBody, positionKind, readGeometry, readReady, releasePosition, setPaginationDirection, visible])useLayoutEffect(() => {if (committedEntry === positionEntry) returnsetCommittedEntry(() => positionEntry)+ finishPosition("entry_changed")claimPosition("initial")entryResolvedRef.current = false+ snapshotReadRef.current = initialRetiredRef.current+ recordSnapshotDecision(snapshotReadRef.current ? "entry_changed" : "not_requested")initialRetiredRef.current = falsesetPositionOutcome("pending")restorationRef.current = null@@ -686,7 +726,7 @@ export function useScrollAnchor({consumedLocalSubmitVersionRef.current = localSubmitVersion ?? 0userInputRef.current.handover = falsesetFollowSuspended(false)- }, [claimPosition, committedEntry, localSubmitVersion, positionEntry, presentVersion, setFollowSuspended, setPositionOutcome])+ }, [claimPosition, committedEntry, finishPosition, localSubmitVersion, positionEntry, presentVersion, recordSnapshotDecision, setFollowSuspended, setPositionOutcome])useLayoutEffect(() => {const target = scrollToMessageId ?? null@@ -701,23 +741,23 @@ export function useScrollAnchor({claimPosition("target")retireInitialPosition()positionedTargetRef.current = null- if (dataState === "ready" && visible) startIntent("target", target, "auto", true)- }, [claimPosition, dataState, items.length, positionEntry, positionKind, releasePosition, retireInitialPosition, scrollToMessageId, startIntent, visible])+ if (targetDataState === "ready" && visible) startIntent("target", target, "auto", true)+ }, [claimPosition, targetDataState, items.length, positionEntry, positionKind, releasePosition, retireInitialPosition, scrollToMessageId, startIntent, visible])useLayoutEffect(() => {const intent = semanticIntentRef.current- if (visible && intent?.awaitingData && (positionKind.get() === "initial" || positionKind.get() === "late-new" ? initialScrollReady : dataState === "ready")) {+ if (visible && intent?.awaitingData && (positionKind.get() === "initial" || positionKind.get() === "late-new" ? initialScrollReady : (positionKind.get() === "target" ? targetDataState : dataState) === "ready")) {startIntent(intent.type, intent.id, intent.behavior, intent.notifyTarget, intent.loadedTailPresent)}- }, [dataState, initialScrollReady, positionKind, startIntent, visible])+ }, [dataState, targetDataState, initialScrollReady, positionKind, startIntent, visible])useLayoutEffect(() => {- if (!visible || dataState !== "ready") return+ if (!visible || targetDataState !== "ready") returnif (positionKind.get() === "target") {if (!semanticIntentRef.current && targetIntentRef.current) startIntent("target", targetIntentRef.current, "auto", true)else scheduleInitialPositionSettled()}- }, [dataState, items, positionKind, scheduleInitialPositionSettled, startIntent, visible])+ }, [targetDataState, items, positionKind, scheduleInitialPositionSettled, startIntent, visible])const observeGeometry = useCallback((next: Geometry, scrollEvent = false) => {const previous = acceptedGeometryRef.current@@ -1145,12 +1185,12 @@ export function useScrollAnchor({if (intent.receipt) {const result = intent.receipt.resultif (!result) return- if (result.status !== "success" || dataState === "error") { releasePosition(); return }+ if (result.status !== "success" || dataState === "error") { releasePosition(false, "error"); return }if (messageWindow !== result.window && messageWindow !== intent.receipt.before) { releasePosition(); return }if (messageWindow !== result.window || dataState === "pending") returnpresentIntentRef.current = nullif (dataState === "empty") {- releasePosition()+ releasePosition(false, "empty")setReadPositionReady(true)} else {setFollowSuspended(false)@@ -1188,17 +1228,24 @@ export function useScrollAnchor({}, [claimPosition, hasMessages, initialScrollReady, items, newDividerBefore, positionEntry, positionKind, startIntent, visible])useLayoutEffect(() => {if (!visible) return- if (dataState === "error" || dataState === "empty") {+ const state = positionKind.get() === "target" ? targetDataState : dataState+ if (state === "error" || state === "empty") {lateNewRef.current.allowed = falseif (positionKind.get() === "idle") return- releasePosition(false, dataState)- if (dataState === "empty") setReadPositionReady(true)+ releasePosition(false, state)+ if (state === "empty") setReadPositionReady(true)return}if (positionKind.get() === "idle") returnif (dataState === "pending" && !initialScrollReady) returnif (positionKind.get() !== "initial" || initialRetiredRef.current || !hasMessages) returnif (!entryResolvedRef.current) {+ if (!snapshotReadRef.current) {+ snapshotReadRef.current = true+ const read = scrollToMessageId ? { snapshot: null, reason: "not_requested" as const } : assessVirtualListPosition(positionScope, fingerprint)+ restorationRef.current = read.snapshot+ recordSnapshotDecision(read.reason)+ }const snapshot = restorationRef.currentconst root = scrollRef.currentif (snapshot && (!root || root.clientWidth <= 0 || root.clientHeight <= 0)) return@@ -1206,9 +1253,15 @@ export function useScrollAnchor({if (newDividerBefore) lateNewRef.current.consumed = trueif (snapshot && snapshot.fingerprint === fingerprint && snapshot.width === root?.clientWidth&& snapshot.height === root.clientHeight && snapshot.paddingEnd === tailPaddingEnd- && items.some(item => item.key === snapshot.anchorKey)) startIntent("restore", String(snapshot.anchorKey))+ && items.some(item => item.key === snapshot.anchorKey)) {+ recordSnapshotDecision("accepted")+ startIntent("restore", String(snapshot.anchorKey))+ }else {if (snapshot) {+ recordSnapshotDecision(snapshot.fingerprint !== fingerprint ? "fingerprint_mismatch"+ : snapshot.width !== root?.clientWidth || snapshot.height !== root?.clientHeight ? "viewport_mismatch"+ : snapshot.paddingEnd !== tailPaddingEnd ? "padding_mismatch" : "anchor_missing")restorationRef.current = nullvirtualizer.setOptions({ ...virtualizer.options, initialMeasurementsCache: [] })virtualizer.measure()@@ -1217,7 +1270,7 @@ export function useScrollAnchor({startIntent(initialPositionMessageId ? "target" : newDividerBefore ? "unread" : "end", initialPositionMessageId ?? newDividerBefore ?? null)}} else scheduleInitialPositionSettled()- }, [dataState, fingerprint, hasMessages, initialPositionMessageId, initialScrollReady, items, newDividerBefore, positionEntry, positionKind, releasePosition, scheduleInitialPositionSettled, setReadPositionReady, startIntent, tailPaddingEnd, virtualItems, virtualizer, visible])+ }, [dataState, targetDataState, fingerprint, hasMessages, initialPositionMessageId, initialScrollReady, items, newDividerBefore, positionEntry, positionScope, positionKind, recordSnapshotDecision, scrollToMessageId, releasePosition, scheduleInitialPositionSettled, setReadPositionReady, startIntent, tailPaddingEnd, virtualItems, virtualizer, visible])const scrollToBottom = useCallback(() => {if (!positionOwnerRef.current.active || !contextRef.current.visible) returndiff --git a/src/web/src/hooks/community/use-stored-forum-tag.ts b/src/web/src/hooks/community/use-stored-forum-tag.tsnew file mode 100644index 000000000..e9ce43916--- /dev/null+++ b/src/web/src/hooks/community/use-stored-forum-tag.ts@@ -0,0 +1,18 @@+"use client"++import { useCallback, useSyncExternalStore } from "react"+import { forumTagSelectionKey, readForumTagSelection } from "@/lib/community/forum-tag-selection"++export function useStoredForumTag(channelId: string | null) {+ const read = useCallback(() => {+ if (!channelId) return "All"+ try { return readForumTagSelection(window.localStorage, channelId) } catch { return "All" }+ }, [channelId])+ const subscribe = useCallback((notify: () => void) => {+ if (!channelId) return () => {}+ const changed = (event: StorageEvent) => { if (event.key === null || event.key === forumTagSelectionKey(channelId)) notify() }+ window.addEventListener("storage", changed)+ return () => window.removeEventListener("storage", changed)+ }, [channelId])+ return useSyncExternalStore(subscribe, read, () => channelId ? null : "All")+}diff --git a/src/web/src/lib/community/conversation-entry.test.ts b/src/web/src/lib/community/conversation-entry.test.tsindex 9711555e7..8001163a0 100644--- a/src/web/src/lib/community/conversation-entry.test.ts+++ b/src/web/src/lib/community/conversation-entry.test.ts@@ -1,3 +1,4 @@+import { writeCommunityCollectionRows } from "@/lib/community-db/write"import { beforeEach, describe, expect, it, vi } from "vitest"import { COMMUNITY_CONTRACT_HEADER, COMMUNITY_CONVERSATION_ANCHOR_MISSING, type CommunityConversationEntryRead } from "@alook/shared"import { ApiError } from "@/lib/errors"@@ -5,8 +6,10 @@ import { createCommunityQueryOwner } from "@/test/community-query-owner"import { communityKeys } from "@/lib/query-keys"import { captureCommunityLiveSnapshotToken, projectCommunityWsEventToDb, publishCommunityLiveSnapshot } from "@/lib/community-db/sync"import { retireCommunityAccount } from "./account-cache-lifecycle"-import { conversationEntryOptions, currentConversationReadState, findConversationEntryWindow, publishConversationEntry } from "./conversation-entry"+import { assessConversationScope, conversationEntryOptions, currentConversationReadState, findConversationDisplayWindow, findConversationEntryWindow, getQualifiedConversationScope, publishConversationEntry } from "./conversation-entry"+import type { ChannelRow } from "@/lib/community-db/schema"import type { MessageWindowData } from "./message-window"+import { configureTelemetry, installTelemetrySink, retireTelemetry } from "@/lib/observability/telemetry"const load = vi.hoisted(() => vi.fn())vi.mock("@/lib/api/client", async (original) => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: (...args: unknown[]) => load(...args) }))@@ -15,6 +18,152 @@ beforeEach(() => { load.mockReset() })import { conversationEntryFixture as entry, conversationEntryTarget as target, dmConversationEntryFixture, forumConversationEntryFixture } from "@/test/conversation-entry-fixtures"describe("conversation entry canonical publication", () => {+ it("does not backfill entry phases when observation becomes eligible after that request began", async () => {+ const { client } = await createCommunityQueryOwner()+ const events: Array<{ name: string }> = []+ let resolve!: (value: CommunityConversationEntryRead) => void+ configureTelemetry({}, false)+ load.mockReturnValue(new Promise<CommunityConversationEntryRead>(done => { resolve = done }))+ try {+ const pending = client.query(conversationEntryOptions(client, target))+ configureTelemetry({ session_id: "current" }, true)+ installTelemetrySink(event => events.push(event))+ resolve(entry())+ await pending+ expect(events.filter(event => event.name === "conversation.entry")).toEqual([])+ } finally { retireTelemetry() }+ })++ it("preserves a qualified window after actual native Query garbage collection removes its entry", async () => {+ vi.useFakeTimers()+ try {+ const { client } = await createCommunityQueryOwner()+ load.mockResolvedValue(entry())+ const options = { ...conversationEntryOptions(client, target), gcTime: 1 }+ const resource = await client.query(options)+ const window = client.getQueryData(resource.windowKey)+ await vi.advanceTimersByTimeAsync(2)+ expect(client.getQueryData(options.queryKey)).toBeUndefined()+ expect(client.getQueryData(resource.windowKey)).toBe(window)+ const scope = getQualifiedConversationScope(client, target)!+ expect(findConversationEntryWindow(client, target, scope, currentConversationReadState(client, "c1"))?.key).toEqual(resource.windowKey)+ } finally { vi.useRealTimers() }+ })++ it.each(["missing", "incomplete", "pending", "archived", "foreign", "parent-missing", "parent-foreign", "retired"] as const)("rejects a %s cache closure without deleting its retained message window", async condition => {+ const { client, registry } = await createCommunityQueryOwner()+ const value = entry()+ if (condition.startsWith("parent")) {+ value.channel = { ...value.channel, type: "thread", parentChannelId: "parent", parentMessageId: "opener" }+ value.parent = { ...entry().channel, id: "parent" }+ value.surfaceReceipt = { channelId: "c1", surfaceKind: "thread" }+ }+ const resource = publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })+ const before = client.getQueryData(resource.windowKey)+ const channels = communityKeys.communityDbCollection("viewer", "channels")+ if (condition === "retired") registry.runtime.lifecycle.setState(state => ({ active: false, generation: state.generation + 1 }))+ else await writeCommunityCollectionRows(registry, "channels", (client.getQueryData<ChannelRow[]>(channels) ?? []).flatMap(row => {+ if (condition === "missing" && row.id === "c1" || condition === "parent-missing" && row.id === "parent") return []+ if (row.id === "c1") return [{ ...row, ...(condition === "incomplete" ? { resourceComplete: false as const } : {}),+ ...(condition === "pending" ? { pending: true } : {}), ...(condition === "archived" ? { archived: true } : {}),+ ...(condition === "foreign" ? { serverId: "foreign" } : {}) }]+ return [{ ...row, ...(condition === "parent-foreign" ? { serverId: "foreign" } : {}) }]+ }), row => row.id)+ expect(getQualifiedConversationScope(client, target)).toBeUndefined()+ expect(assessConversationScope(client, target).reason).not.toBe("qualified")+ expect(client.getQueryData(resource.windowKey)).toBe(before)+ })++ it("cancels an entry before response delivery and refuses an ignored-abort late body", async () => {+ const { client, registry } = await createCommunityQueryOwner()+ let resolve!: (value: CommunityConversationEntryRead) => void+ load.mockReturnValue(new Promise<CommunityConversationEntryRead>(done => { resolve = done }))+ const options = conversationEntryOptions(client, target)+ const pending = client.query(options).catch(error => error)+ await client.cancelQueries({ queryKey: options.queryKey, exact: true })+ resolve(entry())+ await pending+ await Promise.resolve()+ expect(registry.collections.messages.has("m1")).toBe(false)+ expect(getQualifiedConversationScope(client, target)).toBeUndefined()+ })++ it.each(["text", "dm", "forum", "thread"] as const)("qualifies the canonical %s closure after every short-lived entry is removed", async kind => {+ const { client, registry } = await createCommunityQueryOwner()+ const value = kind === "dm" ? dmConversationEntryFixture() : kind === "forum" ? forumConversationEntryFixture() : entry()+ if (kind === "thread") {+ value.channel = { ...value.channel, type: "thread", parentChannelId: "parent", parentMessageId: "opener" }+ value.parent = { ...entry().channel, id: "parent" }+ value.surfaceReceipt = { channelId: "c1", surfaceKind: "thread" }+ }+ const destination = { channelId: "c1", serverId: value.channel.serverId }+ const options = conversationEntryOptions(client, destination)+ const resource = publishConversationEntry(client, destination, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })+ client.setQueryData(options.queryKey, resource)+ client.removeQueries({ queryKey: communityKeys.conversationEntries("c1") })+ const scope = getQualifiedConversationScope(client, destination)+ expect(scope).toBeDefined()+ expect(scope).not.toHaveProperty("access")+ expect(findConversationDisplayWindow(client, destination, scope!)?.key).toEqual(resource.windowKey)+ expect(findConversationEntryWindow(client, destination, scope!, value.readState)?.key).toEqual(resource.windowKey)+ registry.runtime.ws.actions.revokeChannelAccess(destination.serverId, "c1")+ expect(getQualifiedConversationScope(client, destination)).toBeUndefined()+ })++ it("rejects residual entities without viewer access and retires the same cache on an account change", async () => {+ const { client, registry } = await createCommunityQueryOwner()+ publishConversationEntry(client, target, entry(), { token: captureCommunityLiveSnapshotToken(client, "c1") })+ expect(getQualifiedConversationScope(client, target)).toBeDefined()+ const key = communityKeys.communityDbCollection("viewer", "channelMemberships")+ const rows = client.getQueryData(key)+ await writeCommunityCollectionRows(registry, "channelMemberships", [], (row: { id: string }) => row.id)+ expect(getQualifiedConversationScope(client, target)).toBeUndefined()+ expect(registry.collections.messages.has("m1")).toBe(true)+ client.setQueryData(key, rows)+ registry.runtime.ws.actions.activateProfileAccount("other")+ expect(getQualifiedConversationScope(client, target)).toBeUndefined()+ })++ it("keeps a real cached display window distinct from an uncovered target and an isolated canonical entity", async () => {+ const { client, registry } = await createCommunityQueryOwner()+ const value = entry()+ const resource = publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })+ const scope = getQualifiedConversationScope(client, target)!+ const selected = { ...target, anchorMessageId: "elsewhere" }+ expect(findConversationDisplayWindow(client, selected, scope)?.key).toEqual(resource.windowKey)+ expect(findConversationEntryWindow(client, selected, scope, value.readState)).toBeUndefined()+ client.removeQueries({ queryKey: communityKeys.channelMessages("c1") })+ expect(registry.collections.messages.has("m1")).toBe(true)+ expect(findConversationDisplayWindow(client, target, scope)).toBeUndefined()+ })++ it.each([false, true])("delivers entry while reconciliation is held and preserves its own result after repair failure=%s", async fail => {+ const { client, registry } = await createCommunityQueryOwner()+ const options = conversationEntryOptions(client, target)+ load.mockResolvedValueOnce(entry())+ const previous = await client.query(options)+ const before = client.getQueryData(previous.windowKey)+ const next = entry()+ next.page = { ...next.page, latestSeq: 2, hasMoreNewer: true, newerCursor: "next" }+ let resolve!: (value: unknown) => void+ let reject!: (error: unknown) => void+ const held = new Promise((yes, no) => { resolve = yes; reject = no })+ load.mockImplementation((url: string) => url.includes("entry=1") ? Promise.resolve(next) : held)+ const delivered = await client.query({ ...options, staleTime: 0 })+ const repairKey = [...previous.windowKey, "reconcile"]+ expect(delivered).toMatchObject({ channelId: "c1", readStateRevision: 4 })+ expect(client.getQueryState(options.queryKey)?.status).toBe("success")+ expect(client.getQueryState(repairKey)?.fetchStatus).toBe("fetching")+ expect(client.getQueryData(previous.windowKey)).toBe(before)+ const repair = client.getQueryCache().find({ queryKey: repairKey, exact: true })!.promise!.catch(error => error)+ if (fail) reject(new Error("held repair failed"))+ else resolve({ messages: [{ ...next.messages[0], id: "m2", seq: 2 }], latestSeq: 2, hasMoreNewer: false })+ await repair+ expect(client.getQueryState(options.queryKey)?.status).toBe("success")+ expect(client.getQueryState(repairKey)?.status).toBe(fail ? "error" : "success")+ expect(registry.collections.messages.has("m2")).toBe(!fail)+ })+it("keeps one failed DM verification attempt local until an explicit retry", async () => {const { client } = await createCommunityQueryOwner()const temporary = new ApiError("temporary", 503)@@ -41,6 +190,33 @@ describe("conversation entry canonical publication", () => {await client.query({ ...conversationEntryOptions(client, target), select: undefined })expect(load).toHaveBeenCalledOnce()})++ it.each(["child-missing", "child-incomplete", "child-type", "child-server", "child-parent", "opener-missing", "opener-incomplete", "opener-channel"] as const)("rejects a cached Forum display window with %s without refreshing its qualification", async invalid => {+ const { client, registry } = await createCommunityQueryOwner()+ const value = forumConversationEntryFixture()+ const resource = publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })+ const scope = getQualifiedConversationScope(client, target)!+ expect(findConversationDisplayWindow(client, target, scope)?.key).toEqual(resource.windowKey)+ if (invalid === "child-missing") await registry.collections.channels.utils.writeDelete("t1")+ else if (invalid.startsWith("child-")) {+ const child = registry.collections.channels.get("t1")!+ await registry.collections.channels.utils.writeUpsert({ ...child,+ ...(invalid === "child-incomplete" ? { resourceComplete: false } : {}),+ ...(invalid === "child-type" ? { type: "text" as const } : {}),+ ...(invalid === "child-server" ? { serverId: "other" } : {}),+ ...(invalid === "child-parent" ? { parentChannelId: "other" } : {}),+ })+ } else if (invalid === "opener-missing") await registry.collections.messages.utils.writeDelete("m1")+ else {+ const opener = registry.collections.messages.get("m1")!+ await registry.collections.messages.utils.writeUpsert({ ...opener,+ ...(invalid === "opener-incomplete" ? { resourceComplete: false } : { channelId: "other" }),+ })+ }+ expect(getQualifiedConversationScope(client, target)).toBeDefined()+ expect(findConversationDisplayWindow(client, target, scope)).toBeUndefined()+ expect(load).not.toHaveBeenCalled()+ })it.each(["empty-query", "failed-query", "empty-pages", "mismatched-params"] as const)("installs the real first window over %s for text and forum", async state => {for (const forum of [false, true]) {const { client } = await createCommunityQueryOwner()diff --git a/src/web/src/lib/community/conversation-entry.ts b/src/web/src/lib/community/conversation-entry.tsindex 61738920c..44d1ec6e4 100644--- a/src/web/src/lib/community/conversation-entry.ts+++ b/src/web/src/lib/community/conversation-entry.ts@@ -1,6 +1,7 @@import { reconcileConversationLanding } from "@/hooks/community/community-ws/reconnect-messages"import { channelHref } from "./community-route"-import { currentPageObservation, navigationForHref } from "@/lib/observability/context"+import { actionAttributes, currentPageObservation, navigationForHref } from "@/lib/observability/context"+import { emitTelemetry, isTelemetryEligible, telemetryGeneration } from "@/lib/observability/telemetry"import { hashKey, notifyManager, queryOptions, type QueryClient, type QueryKey } from "@tanstack/react-query"import { COMMUNITY_CONTRACT_HEADER, CommunityConversationEntryReadSchema, type CommunityConversationEntryRead, type CommunityReadStateResource } from "@alook/shared"import { apiFetch, type ApiRequestOptions } from "@/lib/api/client"@@ -8,7 +9,7 @@ import { communityKeys } from "@/lib/query-keys"import { communityRequestOptions } from "./account-cache-lifecycle"import { isChannelMetadataTokenCurrent } from "./conversation-qualification"import { getCommunityDbRegistry } from "@/lib/community-db/collections"-import type { ChannelRow, MessageRow, ReadStateRow } from "@/lib/community-db/schema"+import { channelMembershipKey, type ReadStateRow } from "@/lib/community-db/schema"import { ApiError } from "@/lib/errors"import {assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken,@@ -41,6 +42,37 @@ export type ConversationEntryResource = {proof: ReturnType<typeof captureCommunityLiveSnapshotToken>}+export type ConversationWindowScope = Pick<ConversationEntryResource, "channelId" | "proof">+ & Partial<Pick<ConversationEntryResource, "windowKey" | "readStateAtEntry" | "selection">>++export function assessConversationScope(client: QueryClient, target: ConversationEntryTarget) {+ const registry = getCommunityDbRegistry(client)+ if (!registry?.accountId || registry.sessionViewer() !== registry.accountId || registry.runtime.ws.get().profileViewerId !== registry.accountId) return { reason: "account_unknown" as const }+ if (!registry.runtime.lifecycle.get().active) return { reason: "owner_retired" as const }+ const channel = registry.collections.channels.get(target.channelId)+ if (registry.runtime.ws.actions.isChannelAccessRevoked(target.channelId, target.serverId, channel?.parentChannelId ?? undefined)) return { reason: "revoked" as const }+ if (!channel) return { reason: "metadata_missing" as const }+ if (!channel.resourceComplete || channel.pending) return { reason: "metadata_incomplete" as const }+ if (channel.archived) return { reason: "archived" as const }+ if (channel.serverId !== target.serverId || (target.serverId === null ? channel.type !== "dm" : channel.type === "dm")) return { reason: "scope_mismatch" as const }+ const parent = channel.parentChannelId+ ? registry.collections.channels.get(channel.parentChannelId) : undefined+ if (channel.type !== "thread" && channel.parentChannelId) return { reason: "scope_mismatch" as const }+ if (channel.type === "thread") {+ if (!parent?.resourceComplete || parent.pending) return { reason: "parent_missing" as const }+ if (parent.archived || parent.serverId !== target.serverId || parent.type !== "text" && parent.type !== "forum" || !channel.parentMessageId) return { reason: "parent_mismatch" as const }+ }+ const access = (id: string) => !!registry.collections.channelMemberships.get(channelMembershipKey(id, registry.accountId!, "access"))+ if (!access(channel.id) || parent && !access(parent.id)) return { reason: "access_missing" as const }+ const proof = { ...captureCommunityLiveSnapshotToken(client, channel.id), channelLineage: { parentChannelId: channel.parentChannelId ?? undefined } }+ if (!isChannelMetadataTokenCurrent(proof)) return { reason: "owner_retired" as const }+ return { reason: "qualified" as const, scope: { channelId: channel.id, proof } satisfies ConversationWindowScope }+}++export function getQualifiedConversationScope(client: QueryClient, target: ConversationEntryTarget): ConversationWindowScope | undefined {+ return assessConversationScope(client, target).scope+}+export function publishConversationEntry(client: QueryClient,target: ConversationEntryTarget,@@ -110,39 +142,53 @@ export function currentConversationReadState(client: QueryClient, channelId: strreturn clock ? { channelId, lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0, observedRevision: clock.revision } : undefined}-export function findConversationEntryWindow(client: QueryClient, target: ConversationEntryTarget, resource: ConversationEntryResource, pointer: CommunityReadStateResource) {+function conversationDisplayWindows(client: QueryClient, target: ConversationEntryTarget, resource: ConversationWindowScope) {if (!isChannelMetadataTokenCurrent(resource.proof) || resource.channelId !== target.channelId) returnconst registry = resource.proof.registry!- const channel = client.getQueryData<ChannelRow[]>(communityKeys.communityDbCollection(registry.scopeId, "channels"))?.find((row) => row.id === target.channelId)- ?? registry.collections.channels.get(target.channelId)+ const channel = registry.collections.channels.get(target.channelId)if (!channel || channel.serverId !== target.serverId || channel.archived) return- const rows = client.getQueryData<MessageRow[]>(communityKeys.communityDbCollection(registry.scopeId, "messages"))- const messages = rows ? new Map(rows.map((row) => [row.id, row])) : registry.collections.messages+ const messages = registry.collections.messagesif (channel.type === "forum" && !target.anchorMessageId) {const key = communityKeys.forumFeed(channel.id, target.tag ?? null)const feed = client.getQueryData<{ pages: ForumFeedPage[]; pageParams: Array<string | null> }>(key)if (!feed?.pages.length || !Array.isArray(feed.pageParams) || feed.pages.length !== feed.pageParams.length) return- const channels = client.getQueryData<ChannelRow[]>(communityKeys.communityDbCollection(registry.scopeId, "channels"))- const byId = channels ? new Map(channels.map(row => [row.id, row])) : registry.collections.channels- if (feed.pages.some(page => !Array.isArray(page.threads) || page.threads.some(thread => byId.get(thread.id)?.parentChannelId !== channel.id || !!thread.openerMessageId && messages.get(thread.openerMessageId)?.resourceComplete !== true))) return- return { key, initial: { mode: "newest" as const }, tag: target.tag ?? null }+ const byId = registry.collections.channels+ if (feed.pages.some(page => !Array.isArray(page.threads) || page.threads.some(thread => {+ const child = byId.get(thread.id)+ const opener = thread.openerMessageId ? messages.get(thread.openerMessageId) : undefined+ return !child?.resourceComplete || child.type !== "thread" || child.serverId !== channel.serverId || child.parentChannelId !== channel.id+ || !!thread.openerMessageId && (!opener?.resourceComplete || opener.channelId !== channel.id)+ }))) return+ return [{ key, initial: { mode: "newest" as const }, tag: target.tag ?? null }]}- const anchor = target.anchorMessageId ?? (target.preferTail ? null : pointer.lastReadMessageId)const windows = client.getQueryCache().findAll({ queryKey: communityKeys.channelMessages(target.channelId) })- .sort((left, right) => Number(hashKey(right.queryKey) === hashKey(resource.windowKey)) - Number(hashKey(left.queryKey) === hashKey(resource.windowKey)) || right.state.dataUpdatedAt - left.state.dataUpdatedAt)- for (const window of windows) {+ .sort((left, right) => Number(hashKey(right.queryKey) === hashKey(resource.windowKey ?? [])) - Number(hashKey(left.queryKey) === hashKey(resource.windowKey ?? [])) || right.state.dataUpdatedAt - left.state.dataUpdatedAt)+ return windows.flatMap(window => {const identity = messageWindowIdentity(window.queryKey)- if (!identity || identity.tag !== (target.tag ?? null) || identity.initial.mode === "since") continue+ if (!identity || identity.tag !== (target.tag ?? null) || identity.initial.mode === "since") return []const data = window.state.data as MessageWindowData | undefined- if (!Array.isArray(data?.pages) || !Array.isArray(data.pageParams) || !data.pages.length || data.pageParams.length !== data.pages.length || data.pages.some((page) => !Array.isArray(page.messages))) continue+ if (!Array.isArray(data?.pages) || !Array.isArray(data.pageParams) || !data.pages.length || data.pageParams.length !== data.pages.length || data.pages.some((page) => !Array.isArray(page.messages))) return []const ids = data.pages.flatMap((page) => page.messages.map((message) => message.id))- if (ids.length && !ids.some((id) => messages.get(id)?.resourceComplete === true)) continue- const anchored = !!anchor && ids.includes(anchor) && messages.get(anchor)?.resourceComplete === true- const missingPointer = !target.anchorMessageId && pointer.lastReadMessageId === resource.readStateAtEntry.lastReadMessageId && resource.selection.reason === "read_pointer_missing"- && hashKey(window.queryKey) === hashKey(resource.windowKey) && identity.initial.mode === "newest" && data.pages[0].hasMoreNewer === false- if (anchor ? !anchored && !missingPointer : data.pages[0].hasMoreNewer !== false) continue- return { key: window.queryKey, initial: identity.initial, tag: identity.tag }- }+ if (ids.some(id => messages.get(id)?.resourceComplete !== true || messages.get(id)?.channelId !== target.channelId)) return []+ return [{ key: window.queryKey, initial: identity.initial, tag: identity.tag }]+ })+}++export function findConversationDisplayWindow(client: QueryClient, target: ConversationEntryTarget, scope: ConversationWindowScope) {+ return conversationDisplayWindows(client, target, scope)?.[0]+}++export function findConversationEntryWindow(client: QueryClient, target: ConversationEntryTarget, resource: ConversationWindowScope, pointer: CommunityReadStateResource | undefined) {+ if (!pointer && !target.anchorMessageId) return+ const anchor = target.anchorMessageId ?? (target.preferTail ? null : pointer?.lastReadMessageId)+ return conversationDisplayWindows(client, target, resource)?.find(window => {+ if (!messageWindowIdentity(window.key)) return true+ const data = client.getQueryData<MessageWindowData>(window.key)!+ const anchored = !!anchor && data.pages.some(page => page.messages.some(message => message.id === anchor))+ const missingPointer = !target.anchorMessageId && pointer?.lastReadMessageId === resource.readStateAtEntry?.lastReadMessageId && resource.selection?.reason === "read_pointer_missing"+ && hashKey(window.key) === hashKey(resource.windowKey ?? []) && window.initial.mode === "newest" && data.pages[0].hasMoreNewer === false+ return anchor ? anchored || missingPointer : data.pages[0].hasMoreNewer === false+ })}export function knownConversationLatestSeq(client: QueryClient, channelId: string) {@@ -176,32 +222,46 @@ export function conversationEntryOptions(client: QueryClient, target: Conversaticonst action = typeof window !== "undefined" && window.location.pathname === expectedPath ? navigationForHref(window.location.pathname + window.location.search) : undefinedconst captured = observation ?? (typeof window === "undefined" || window.location.pathname !== expectedPath ? { page: undefined, reason: "unknown" as const }: action && !action.done ? { action, reason: "foreground" as const } : { page: currentPageObservation(), reason: "background" as const })- let entry: CommunityConversationEntryRead+ const generation = telemetryGeneration()+ const observed = isTelemetryEligible()+ const record = (entry_stage: "start" | "validated" | "published" | "delivered" | "error" | "cancelled") => {+ if (observed && generation === telemetryGeneration()) emitTelemetry("conversation.entry", {+ ...actionAttributes(captured?.action ?? captured?.page), entry_stage, request_role: "entry",+ window_mode: target.anchorMessageId ? "anchor" : "newest",+ })+ }+ record("start")try {- entry = await withConversationReadDeadline(signal, (readSignal) => apiFetch<CommunityConversationEntryRead>(+ const entry = await withConversationReadDeadline(signal, (readSignal) => apiFetch<CommunityConversationEntryRead>(`/api/community/channels/${encodeURIComponent(target.channelId)}/messages?${search}`,- { ...communityRequestOptions(client, token, readSignal, assert), headers: { [COMMUNITY_CONTRACT_HEADER]: "3" }, observation: captured },+ { ...communityRequestOptions(client, token, readSignal, assert), headers: { [COMMUNITY_CONTRACT_HEADER]: "3" },+ observation: { ...captured, role: "entry", windowMode: target.anchorMessageId ? "anchor" : "newest" } },))assert()+ const initial: InitialMessageWindow = entry.selection.anchorMessageId+ ? { mode: "anchor", anchor: entry.selection.anchorMessageId } : { mode: "newest" }+ const windowKey = communityKeys.channelMessagesWindow(target.channelId, initial, target.tag)+ const hadWindow = !!client.getQueryData<MessageWindowData>(windowKey)?.pages.length+ const resource = publishConversationEntry(client, target, entry, { token, signal })+ record("validated")+ record("published")+ if (hadWindow && !entry.forumFeed) {+ void reconcileConversationLanding(client, {+ kind: target.serverId === null ? "dm" : "channel", scopeId: target.channelId,+ serverId: target.serverId ?? undefined,+ }, resource.windowKey, { ...entry.page, olderCursor: entry.page.olderCursor ?? undefined, newerCursor: entry.page.newerCursor ?? undefined, messages: entry.messages }, initial,+ { query: original!, signal, lifetime: "query", observation: captured }).catch(() => undefined)+ }+ record("delivered")+ return resource} catch (error) {+ const current = !signal.aborted && isChannelMetadataTokenCurrent(token)+ && !!original && client.getQueryCache().get(original.queryHash) === original+ record(!current || error instanceof Error && error.name === "AbortError" ? "cancelled" : "error")assert()if (error instanceof ApiError && (error.status === 403 || error.status === 404) && !isConversationAnchorMissingError(error)) retireCommunityChannelReading(token.registry!, target.channelId, { reason: "read-denied", serverId: target.serverId, preserveQuery: original })throw error}- assert()- const initial: InitialMessageWindow = entry.selection.anchorMessageId- ? { mode: "anchor", anchor: entry.selection.anchorMessageId } : { mode: "newest" }- const windowKey = communityKeys.channelMessagesWindow(target.channelId, initial, target.tag)- const hadWindow = !!client.getQueryData<MessageWindowData>(windowKey)?.pages.length- const resource = publishConversationEntry(client, target, entry, { token, signal })- if (hadWindow && !entry.forumFeed) {- await reconcileConversationLanding(client, {- kind: target.serverId === null ? "dm" : "channel", scopeId: target.channelId,- serverId: target.serverId ?? undefined,- }, resource.windowKey, { ...entry.page, olderCursor: entry.page.olderCursor ?? undefined, newerCursor: entry.page.newerCursor ?? undefined, messages: entry.messages }, initial, { query: original!, signal })- assert()- }- return resource},staleTime: (query) => {const resource = query.state.datadiff --git a/src/web/src/lib/community/enrich-messages.test.ts b/src/web/src/lib/community/enrich-messages.test.tsindex c423dc233..dd8c02019 100644--- a/src/web/src/lib/community/enrich-messages.test.ts+++ b/src/web/src/lib/community/enrich-messages.test.ts@@ -85,6 +85,16 @@ describe("enrichMessages attachment projection", () => {expect(mocks.getLatestSeq).toHaveBeenCalledWith(db, { channelId: "dm1" })})+ it("loads ordinary child indicators for this page only and preserves archived/legacy child projection", async () => {+ mocks.listAttachments.mockResolvedValue([])+ mocks.listForumChildren.mockResolvedValue([{ id: "child", parentMessageId: "m1", type: "text", archived: true, name: "Legacy", messageCount: 2, lastMessageAt: "then" }])+ const row = { id: "m1", channelId: "channel", seq: 1, authorId: "author", authorName: "Author", authorImage: null, content: "body", type: "default", mentionType: null, replyToId: null, embeds: null, createdAt: "now" }+ const result = await enrichMessages({} as never, "viewer", { channelId: "channel" }, [row])+ expect(mocks.listChildren).not.toHaveBeenCalled()+ expect(mocks.listForumChildren).toHaveBeenCalledExactlyOnceWith({}, "channel", ["m1"], null)+ expect(result.messages[0]).toMatchObject({ thread: { id: "child", name: "Legacy", messageCount: 2 } })+ })+it("hydrates only creation IDs in a mixed DM and does no creation lookup for ordinary/friend messages", async () => {mocks.listAttachments.mockResolvedValue([])const base = { seq: 1, authorId: "u1", authorName: "Alice", authorImage: null, content: "hello", mentionType: null, replyToId: null, embeds: null, createdAt: "2026-08-13T00:00:00.000Z", channelId: "dm1" }diff --git a/src/web/src/lib/community/enrich-messages.ts b/src/web/src/lib/community/enrich-messages.tsindex e8894e9c5..14e3a91d3 100644--- a/src/web/src/lib/community/enrich-messages.ts+++ b/src/web/src/lib/community/enrich-messages.ts@@ -40,7 +40,7 @@ export async function enrichMessages(!isDm? scope.isForum? queries.communityChannel.listChildChannelsByParentMessageIds(db, scope.channelId, messageIds)- : queries.communityChannel.listChildChannels(db, scope.channelId)+ : queries.communityChannel.listChildChannelsByParentMessageIds(db, scope.channelId, messageIds, null): Promise.resolve([]),queries.communityMessage.getLatestMessageSeq(db, { channelId: scope.channelId }),// Friend-approval cards only ever live in DMs — skip the hydration querydiff --git a/src/web/src/lib/community/forum-tag-selection.ts b/src/web/src/lib/community/forum-tag-selection.tsindex 5e2a19b48..059cccff6 100644--- a/src/web/src/lib/community/forum-tag-selection.ts+++ b/src/web/src/lib/community/forum-tag-selection.ts@@ -1,16 +1,19 @@-const keyFor = (channelId: string) => `alook:forum-tag:${channelId}`+export const forumTagSelectionKey = (channelId: string) => `alook:forum-tag:${channelId}`export function forumTagFromUrl(value: string | null | undefined): string | null {return value == null ? null : value.trim().toLowerCase() || "All"}export function readForumTagSelection(storage: Pick<Storage, "getItem">, channelId: string): string {- return storage.getItem(keyFor(channelId)) || "All"+ return storage.getItem(forumTagSelectionKey(channelId)) || "All"}export function writeForumTagSelection(storage: Pick<Storage, "setItem" | "removeItem">, channelId: string, tag: string): void {- if (tag === "All") storage.removeItem(keyFor(channelId))- else storage.setItem(keyFor(channelId), tag)+ if (tag === "All") storage.removeItem(forumTagSelectionKey(channelId))+ else storage.setItem(forumTagSelectionKey(channelId), tag)+ if (typeof window !== "undefined") {+ try { if (storage === window.localStorage) window.dispatchEvent(new StorageEvent("storage", { key: forumTagSelectionKey(channelId) })) } catch {}+ }}export function validateForumTagSelection(tag: string, availableTags: string[]): string {diff --git a/src/web/src/lib/community/message-window.ts b/src/web/src/lib/community/message-window.tsindex c3faa3e99..0e1a1cacd 100644--- a/src/web/src/lib/community/message-window.ts+++ b/src/web/src/lib/community/message-window.ts@@ -81,7 +81,9 @@ export const channelMessagesQueryFn =pageParam,tag,)- const page = await fetchMessagesTransport(originalClient, url, signal, { ...options, observation }, publicationToken)+ const page = await fetchMessagesTransport(originalClient, url, signal, { ...options, observation: { ...observation,+ role: pageParam.mode === "older" || pageParam.mode === "newer" ? "pagination" : "window", windowMode: pageParam.mode,+ } }, publicationToken){const result = publishCommunityMessages(originalClient, {channelId,diff --git a/src/web/src/lib/community/navigation-metadata.dom.test.tsx b/src/web/src/lib/community/navigation-metadata.dom.test.tsxindex d5c5772ca..d11e04a1a 100644--- a/src/web/src/lib/community/navigation-metadata.dom.test.tsx+++ b/src/web/src/lib/community/navigation-metadata.dom.test.tsx@@ -1,3 +1,4 @@+import { writeForumTagSelection } from "./forum-tag-selection"import React, { useEffect } from "react"import { beforeEach, describe, expect, it, vi } from "vitest"import { QueryClientProvider } from "@tanstack/react-query"@@ -129,4 +130,19 @@ describe("native navigation warming and DM consumer mounting", () => {expect(load).toHaveBeenCalledOnce()})+ it.each(["route", "stored"] as const)("warms the actual %s Forum tag and shares that target key", async source => {+ const owner = await createCommunityQueryOwner()+ const value = forumConversationEntryFixture()+ await seedConversationEntry(owner.client, value)+ owner.client.removeQueries({ queryKey: communityKeys.conversationEntries("c1") })+ writeForumTagSelection(localStorage, "c1", source === "stored" ? "saved" : "different")+ load.mockResolvedValue(value)+ try {+ const href = source === "route" ? "/c/channels/s1/c1?tag=explicit" : "/c/channels/s1/c1"+ await prepareNavigationMetadata(owner.client, href, "prefetch")+ await prepareNavigationMetadata(owner.client, href, "foreground")+ expect(load.mock.calls.map(([url]) => url)).toEqual([`/api/community/channels/c1/messages?entry=1&tag=${source === "route" ? "explicit" : "saved"}`])+ } finally { localStorage.clear() }+ })+})diff --git a/src/web/src/lib/community/navigation-metadata.ts b/src/web/src/lib/community/navigation-metadata.tsindex b874cc736..ce329b125 100644--- a/src/web/src/lib/community/navigation-metadata.ts+++ b/src/web/src/lib/community/navigation-metadata.ts@@ -1,3 +1,4 @@+import { forumTagFromUrl, readForumTagSelection } from "./forum-tag-selection"import { noop, QueryObserver, type QueryClient } from "@tanstack/react-query"import { conversationEntryOptions } from "./conversation-entry"import { getCommunityDbRegistry } from "@/lib/community-db/collections"@@ -39,8 +40,17 @@ export function prepareNavigationMetadata(queryClient: QueryClient, href: stringif (!target) returnconst { channelId, serverId } = targetconst action = intent === "prefetch" ? prefetchForHref(href) : navigationForHref(href)- const anchorMessageId = new URL(href, "https://alook.test").searchParams.get("msg")- const options = conversationEntryOptions(queryClient, { serverId, channelId, anchorMessageId }, { action, reason: intent })+ const search = new URL(href, "https://alook.test").searchParams+ const anchorMessageId = search.get("msg")+ const channel = getCommunityDbRegistry(queryClient)?.collections.channels.get(channelId)+ let tag: string | null = null+ if (channel?.type === "forum") {+ let stored = "All"+ try { if (typeof window !== "undefined") stored = readForumTagSelection(window.localStorage, channelId) } catch {}+ const selected = forumTagFromUrl(search.get("tag")) ?? stored+ tag = selected === "All" ? null : selected+ }+ const options = conversationEntryOptions(queryClient, { serverId, channelId, anchorMessageId, tag }, { action, reason: intent })const observer = new QueryObserver(queryClient, { ...options, enabled: false })const unsubscribe = observer.subscribe(noop)return queryClient.query({ ...options, select: undefined }).catch(noop).finally(unsubscribe)diff --git a/src/web/src/lib/community/virtual-list-position.test.ts b/src/web/src/lib/community/virtual-list-position.test.tsindex 4cdde203d..759514237 100644--- a/src/web/src/lib/community/virtual-list-position.test.ts+++ b/src/web/src/lib/community/virtual-list-position.test.ts@@ -4,7 +4,7 @@ import { captureChannelMetadataToken } from "./conversation-qualification"import { retireCommunityAccount } from "./account-cache-lifecycle"import { retireCommunityChannelReading } from "@/lib/community-db/sync"import { shouldDehydrateCommunityQuery } from "@/lib/query-persister"-import { readVirtualListPosition, saveVirtualListPosition, virtualListLayoutFingerprint, virtualListPositionKey, type VirtualListPositionScope, type VirtualListPositionSnapshot } from "./virtual-list-position"+import { assessVirtualListPosition, readVirtualListPosition, saveVirtualListPosition, virtualListLayoutFingerprint, virtualListPositionKey, type VirtualListPositionScope, type VirtualListPositionSnapshot } from "./virtual-list-position"const snapshot = (fingerprint = "rows"): VirtualListPositionSnapshot => ({version: 1, fingerprint, offset: 300, width: 320, height: 500, paddingStart: 0, paddingEnd: 48,@@ -18,7 +18,10 @@ describe("account-owned virtual layout lifetime", () => {const base: VirtualListPositionScope = { proof: captureChannelMetadataToken(alice.client, "A"), kind: "messages", tag: null }const rows = [{ key: "m1", content: "Private message text", grouped: false }]const fingerprint = virtualListLayoutFingerprint(rows)+ expect(assessVirtualListPosition(undefined, fingerprint)).toEqual({ snapshot: null, reason: "no_scope" })+ expect(assessVirtualListPosition(base, fingerprint)).toEqual({ snapshot: null, reason: "missing" })saveVirtualListPosition(base, snapshot(fingerprint))+ expect(assessVirtualListPosition(base, fingerprint)).toMatchObject({ reason: "available", snapshot: { offset: 300 } })expect(readVirtualListPosition(base, fingerprint)?.offset).toBe(300)for (const scope of [{ ...base, proof: captureChannelMetadataToken(bob.client, "A") },@@ -26,6 +29,7 @@ describe("account-owned virtual layout lifetime", () => {{ ...base, kind: "forum" as const }, { ...base, tag: "bug" },]) expect(readVirtualListPosition(scope, fingerprint)).toBeNull()expect(readVirtualListPosition(base, virtualListLayoutFingerprint([{ ...rows[0], grouped: true }]))).toBeNull()+ expect(assessVirtualListPosition(base, virtualListLayoutFingerprint([{ ...rows[0], grouped: true }]))).toEqual({ snapshot: null, reason: "fingerprint_mismatch" })expect(JSON.stringify(alice.client.getQueryData(virtualListPositionKey(base)))).not.toContain("Private message text")const query = alice.client.getQueryCache().find({ queryKey: virtualListPositionKey(base), exact: true })!expect(shouldDehydrateCommunityQuery(query)).toBe(false)@@ -43,6 +47,7 @@ describe("account-owned virtual layout lifetime", () => {expect(readVirtualListPosition(scopes[0], "rows")).toBeNull()saveVirtualListPosition(scopes[0], { ...snapshot(), at: Date.now() - 300001 })expect(readVirtualListPosition(scopes[0], "rows")).toBeNull()+ expect(assessVirtualListPosition(scopes[0], "rows")).toEqual({ snapshot: null, reason: "expired" })})it("uses the existing account and channel retirement fences for stale capture callbacks", async () => {@@ -53,6 +58,7 @@ describe("account-owned virtual layout lifetime", () => {expect(client.getQueryData(virtualListPositionKey(scope))).toBeUndefined()saveVirtualListPosition(scope, snapshot())expect(readVirtualListPosition(scope, "rows")).toBeNull()+ expect(assessVirtualListPosition(scope, "rows")).toEqual({ snapshot: null, reason: "invalid_scope" })retireCommunityAccount(registry)saveVirtualListPosition(scope, snapshot())expect(client.getQueryData(virtualListPositionKey(scope))).toBeUndefined()diff --git a/src/web/src/lib/community/virtual-list-position.ts b/src/web/src/lib/community/virtual-list-position.tsindex 60fccc297..cca1e2e73 100644--- a/src/web/src/lib/community/virtual-list-position.ts+++ b/src/web/src/lib/community/virtual-list-position.ts@@ -26,6 +26,8 @@ const POSITION_GC_MS = 5 * 60 * 1000const MAX_POSITION_LISTS = 32const MAX_POSITION_MEASUREMENTS = 2048+export type VirtualListPositionReadReason = "no_scope" | "invalid_scope" | "missing" | "invalid_version" | "fingerprint_mismatch" | "expired" | "available"+export function virtualListPositionKey({ proof, kind, tag }: VirtualListPositionScope) {const channelId = proof.channelId!const parentId = proof.channelLineage?.parentChannelId@@ -51,10 +53,19 @@ function current(scope: VirtualListPositionScope) {return !!scope.proof.viewerId && !!scope.proof.channelId && isChannelMetadataTokenCurrent(scope.proof)}-export function readVirtualListPosition(scope: VirtualListPositionScope | undefined, fingerprint: string) {- if (!scope || !current(scope)) return null+export function assessVirtualListPosition(scope: VirtualListPositionScope | undefined, fingerprint: string): { snapshot: VirtualListPositionSnapshot | null; reason: VirtualListPositionReadReason } {+ if (!scope) return { snapshot: null, reason: "no_scope" }+ if (!current(scope)) return { snapshot: null, reason: "invalid_scope" }const value = scope.proof.queryClient.getQueryData<VirtualListPositionSnapshot>(virtualListPositionKey(scope))- return value?.version === 1 && value.fingerprint === fingerprint && Date.now() - value.at < POSITION_GC_MS ? value : null+ if (!value) return { snapshot: null, reason: "missing" }+ if (value.version !== 1) return { snapshot: null, reason: "invalid_version" }+ if (value.fingerprint !== fingerprint) return { snapshot: null, reason: "fingerprint_mismatch" }+ if (!(Date.now() - value.at < POSITION_GC_MS)) return { snapshot: null, reason: "expired" }+ return { snapshot: value, reason: "available" }+}++export function readVirtualListPosition(scope: VirtualListPositionScope | undefined, fingerprint: string) {+ return assessVirtualListPosition(scope, fingerprint).snapshot}export function saveVirtualListPosition(scope: VirtualListPositionScope | undefined, value: VirtualListPositionSnapshot) {diff --git a/src/web/src/lib/observability/context.ts b/src/web/src/lib/observability/context.tsindex 677a7f932..eea1799fc 100644--- a/src/web/src/lib/observability/context.ts+++ b/src/web/src/lib/observability/context.ts@@ -110,7 +110,17 @@ export function finishAction(action: Action | undefined, outcome: Attributes["ou}export function startRegionObservation(action: Action | undefined, region: Attributes["region"], evidence?: Attributes) {if (!action || action.done) return- return startPageOperation("region.wait", { region, phase: "commit", source: "unknown", ...evidence }, action)+ return startPageOperation("region.wait", { region, phase: "commit", source: "unknown", ...evidence, initial_wait_reason: evidence?.wait_reason }, action)+}+export function updateRegionObservation(operation: PageOperation | undefined, evidence: Attributes) {+ if (!operation || operation.done || operation.generation !== telemetryGeneration() || !isTelemetryEligible()) return+ const next = cleanAttributes(evidence)+ if (Object.entries(next).every(([key, value]) => operation.fields[key] === value)) return+ const previous = operation.fields.wait_reason+ if (previous && previous !== "none") next.last_wait_reason = String(previous)+ operation.fields = { ...operation.fields, ...next }+ try { operation.span?.setAttributes(cleanAttributes(operation.fields)) } catch {}+ emitTelemetry("region.wait_change", { ...pageOperationAttributes(operation), ...next })}export function finishRegionObservation(operation: PageOperation | undefined, action: Action | undefined, outcome: Attributes["outcome"]) {if (!action || operation?.page !== action) return@@ -222,7 +232,7 @@ export function finishPageOperation(operation: PageOperation | undefined, outcom}function endPageOperationSpan(operation: PageOperation) {if (!isTelemetryEligible() || operation.generation !== telemetryGeneration()) retireObservationSpan(operation.span)- try { operation.span?.setAttribute("outcome", String(operation.outcome)) } catch {}+ try { operation.span?.setAttributes(cleanAttributes({ ...operation.fields, outcome: operation.outcome })) } catch {}try { operation.span?.end(observationTime(operation.end!, operation.page.origin)) } catch {}}const commandActions = new WeakMap<object, Action>()diff --git a/src/web/src/lib/observability/conversation-export.dom.test.tsx b/src/web/src/lib/observability/conversation-export.dom.test.tsxnew file mode 100644index 000000000..cde90761f--- /dev/null+++ b/src/web/src/lib/observability/conversation-export.dom.test.tsx@@ -0,0 +1,173 @@+import { afterEach, expect, it, vi } from "vitest"+import type { Faro } from "@grafana/faro-web-sdk"+import { QueryClientProvider } from "@tanstack/react-query"+import { useLayoutEffect } from "react"+import { act, render } from "@/test/react-dom-harness"+import { createCommunityQueryOwner } from "@/test/community-query-owner"+import { conversationEntryFixture, seedConversationEntry } from "@/test/conversation-entry-fixtures"+import { CommunityDbProvider } from "@/lib/community-db/projections"+import { communityKeys } from "@/lib/query-keys"+import { useMessages } from "@/hooks/community/use-messages"+import { announceAnalyticsConsent } from "@/lib/analytics-consent"+import { COMMUNITY_CONTRACT_HEADER } from "@alook/shared"+import { traceResponse } from "./trace-response"+import { useObservedRegion } from "./regions"+import { installMessageScrollFixture, restoreMessageScrollFixture, mount } from "@/test/message-scroll-fixture"+import { captureChannelMetadataToken } from "@/lib/community/conversation-qualification"+import { virtualListPositionKey, type VirtualListPositionSnapshot } from "@/lib/community/virtual-list-position"++const native = vi.hoisted(() => {+ vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public")+ return { faro: undefined as Faro | undefined }+})+vi.mock("@grafana/faro-web-sdk", async original => {+ const real = await original<typeof import("@grafana/faro-web-sdk")>()+ return { ...real, initializeFaro: (...args: Parameters<typeof real.initializeFaro>) => {+ native.faro = real.initializeFaro(...args)+ return native.faro+ } }+})++afterEach(async () => {+ await act(async () => {+ document.cookie = "alook_analytics_consent=v1.denied; path=/"+ announceAnalyticsConsent("denied")+ if (vi.isFakeTimers()) await vi.advanceTimersByTimeAsync(0)+ })+ restoreMessageScrollFixture()+ vi.restoreAllMocks()+ vi.unstubAllEnvs()+ vi.unstubAllGlobals()+ window.history.replaceState(null, "", "/")+})++it("exports real cache, entry, repair and request roles through installed Faro and beforeSend with finite private-safe fields", async () => {+ installMessageScrollFixture()+ sessionStorage.clear()+ vi.stubEnv("NEXT_PUBLIC_FARO_COLLECTOR_URL", "https://collector.example/collect/public")+ vi.spyOn(performance, "getEntriesByType").mockReturnValue([])+ window.history.replaceState(null, "", "/c/channels/s1/c1")+ const owner = await createCommunityQueryOwner()+ const value = conversationEntryFixture()+ value.messages[0].content = "PRIVATE257-message-body"+ await seedConversationEntry(owner.client, value)+ owner.client.removeQueries({ queryKey: communityKeys.conversationEntries("c1") })+ const sent: unknown[] = []+ let releaseEntry!: () => void+ let releaseRepair!: () => void+ const next = { ...value, page: { ...value.page, latestSeq: 2, hasMoreNewer: true, newerCursor: "next" } }+ const second = { ...value.messages[0], id: "m2", seq: 2, createdAt: "2026-10-01T00:00:02.000Z" }+ vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL, options?: RequestInit) => {+ const path = input instanceof Request ? input.url : String(input)+ if (path === "https://collector.example/collect/public") {+ if (options?.body) sent.push(JSON.parse(String(options.body)))+ return new Response(null, { status: 204 })+ }+ const url = new URL(path, window.location.origin)+ const request = new Request(url, options)+ const respond = (body: unknown, version: number) => traceResponse(new Response(JSON.stringify(body), {+ headers: { "content-type": "application/json", [COMMUNITY_CONTRACT_HEADER]: String(version) },+ }), request, { isTraced: true, spanContext: () => ({ traceId: "a".repeat(32), spanId: "b".repeat(16), traceFlags: 1 }) })+ if (url.searchParams.has("entry")) return new Promise<Response>(resolve => { releaseEntry = () => resolve(respond(next, 3)) })+ const page = { contractVersion: 2, channelId: "c1", surfaceReceipt: value.surfaceReceipt,+ messages: [second], page: { ...value.page, latestSeq: 2, hasMoreNewer: false } }+ if (url.searchParams.has("since")) return new Promise<Response>(resolve => { releaseRepair = () => resolve(respond(page, 2)) })+ if (url.searchParams.has("cursor")) return respond({ ...page, messages: [{ ...value.messages[0], id: "m0", seq: 0 }], page: { ...page.page, hasMoreOlder: false, olderCursor: null } }, 2)+ return respond({ ...page, messages: [...value.messages, second] }, 2)+ }))+ document.cookie = "alook_analytics_consent=v1.granted; path=/"+ announceAnalyticsConsent("granted")+ const { bootstrapObservability, setTelemetryUser } = await import("./client")+ await act(async () => { bootstrapObservability("web"); setTelemetryUser("viewer") })+ await vi.waitFor(() => expect(native.faro).toBeDefined())+ const { beginNavigation } = await import("./context")+ const navigation = beginNavigation("/c/channels/s1/c1")!+ let latest!: ReturnType<typeof useMessages>+ function Probe({ ready, reason }: { ready: boolean; reason: "entry" | "position" | "none" }) {+ const feed = useMessages("c1", { serverId: "s1" })+ useLayoutEffect(() => { latest = feed }, [feed])+ useObservedRegion("messages", ready, 1, { wait_reason: reason, target_coverage: reason === "entry" ? "uncovered" : "covered" })+ return <p>{feed.messages.map(message => message.content).join(" ")}</p>+ }+ const node = (ready: boolean, reason: "entry" | "position" | "none") => <QueryClientProvider client={owner.client}>+ <CommunityDbProvider registry={owner.registry}><Probe ready={ready} reason={reason} /></CommunityDbProvider>+ </QueryClientProvider>+ const view = render(node(false, "entry"))+ try {+ await vi.waitFor(() => expect(releaseEntry).toBeTypeOf("function"))+ expect(latest.messages[0]?.content).toBe("PRIVATE257-message-body")+ expect(latest.isLoading).toBe(false)+ await act(async () => { view.rerender(node(false, "position")); releaseEntry() })+ await vi.waitFor(() => expect(releaseRepair).toBeTypeOf("function"))+ expect(latest.messages.map(message => message.id)).toEqual(["m1"])+ expect(latest.readSnapshotFetching).toBe(true)+ expect(latest.positionDataState).toBe("pending")+ expect(latest.targetPositionDataState).toBe("ready")+ expect(owner.client.getQueryCache().findAll({ queryKey: communityKeys.conversationEntries("c1") })[0]?.state.status).toBe("success")+ await act(async () => { releaseRepair(); await vi.advanceTimersByTimeAsync(1) })+ await vi.waitFor(() => expect(latest.messages.map(message => message.id)).toContain("m2"))+ let present!: ReturnType<typeof latest.jumpToPresent>+ await act(async () => { present = latest.jumpToPresent() })+ expect(present.accepted).toBe(true)+ const presentRequest = present+ if (presentRequest.accepted) await act(async () => { await presentRequest.completed })+ let older!: ReturnType<typeof latest.fetchOlder>+ await act(async () => { older = latest.fetchOlder() })+ expect(older.accepted).toBe(true)+ const olderRequest = older+ if (olderRequest.accepted) await act(async () => { await olderRequest.completed })+ await act(async () => view.rerender(node(true, "none")))+ native.faro!.api.pushEvent("conversation.cache", { cache_reason: "PRIVATE257-invalid", content: "PRIVATE257-content", cache_window: "ready" })+ const position = mount({ scrollToMessageId: "m4", positionDataState: "ready" })+ position.view.unmount()+ const positionScope = { proof: captureChannelMetadataToken(owner.client, "c1"), kind: "messages" as const, tag: null }+ const saved = mount({ positionScope })+ saved.move(600)+ saved.view.unmount()+ const restored = mount({ positionScope })+ expect(restored.root.scrollTop).toBeCloseTo(600, 0)+ restored.view.unmount()+ owner.client.setQueryData<VirtualListPositionSnapshot>(virtualListPositionKey(positionScope), previous => ({+ ...previous!, fingerprint: "PRIVATE257-position-fingerprint", anchorKey: "PRIVATE257-position-anchor",+ }))+ const rejected = mount({ positionScope })+ rejected.view.unmount()+ native.faro!.api.pushEvent("position.finish", { position_source: "PRIVATE257-invalid", position_snapshot: "PRIVATE257-invalid", snapshot: "PRIVATE257-body" })+ await act(async () => owner.registry.collections.channelMemberships.utils.writeDelete("c1:viewer:access"))+ await vi.advanceTimersByTimeAsync(5000)+ const events: Array<{ name: string; attributes: Record<string, string> }> = []+ const spans: Array<{ name: string; spanId: string; parentSpanId?: string; attributes: Array<{ key: string; value: { stringValue: string } }> }> = []+ const visit = (value: unknown) => {+ if (!value || typeof value !== "object") return+ const row = value as Record<string, unknown>+ if (typeof row.name === "string" && row.attributes && !Array.isArray(row.attributes)) events.push(row as typeof events[number])+ if (typeof row.spanId === "string") spans.push(row as typeof spans[number])+ for (const child of Object.values(row)) visit(child)+ }+ visit(sent)+ expect(events).toContainEqual(expect.objectContaining({ name: "conversation.cache", attributes: expect.objectContaining({ cache_reason: "qualified", entry_status: "missing", cache_window: "ready" }) }))+ expect(events).toContainEqual(expect.objectContaining({ name: "conversation.cache", attributes: expect.objectContaining({ cache_reason: "access_missing", eligibility: "rejected" }) }))+ expect(events.filter(event => event.name === "conversation.entry").map(event => event.attributes.entry_stage)).toEqual(["start", "validated", "published", "delivered"])+ expect(events.filter(event => event.name === "conversation.reconcile").map(event => event.attributes.reconcile_stage)).toEqual(["start", "settled"])+ const roles = new Set(events.filter(event => event.name === "request.start").map(event => event.attributes.request_role))+ expect(roles).toEqual(new Set(["entry", "reconcile", "window", "pagination"]))+ expect(events).toContainEqual(expect.objectContaining({ name: "region.wait_change", attributes: expect.objectContaining({ wait_reason: "position", last_wait_reason: "entry" }) }))+ expect(events).toContainEqual(expect.objectContaining({ name: "position.finish", attributes: expect.objectContaining({ position_owner: "target", position_reason: "settled", position_source: "explicit_target", position_snapshot: "not_requested" }) }))+ expect(events).toContainEqual(expect.objectContaining({ name: "position.finish", attributes: expect.objectContaining({ position_source: "snapshot", position_snapshot: "accepted" }) }))+ expect(events).toContainEqual(expect.objectContaining({ name: "position.finish", attributes: expect.objectContaining({ position_source: "tail", position_snapshot: "fingerprint_mismatch" }) }))+ const wait = spans.find(span => span.name === "region.wait")!+ expect(wait.parentSpanId).toBe(navigation.span!.spanContext().spanId)+ expect(Object.fromEntries(wait.attributes.map(attribute => [attribute.key, attribute.value.stringValue]))).toMatchObject({ initial_wait_reason: "entry", last_wait_reason: "position", wait_reason: "none", outcome: "success" })+ expect(spans.some(span => span.attributes.some(attribute => attribute.key === "request_role" && attribute.value.stringValue === "reconcile"))).toBe(true)+ const headers = events.filter(event => event.name === "request.headers")+ expect(headers.length).toBeGreaterThanOrEqual(4)+ expect(headers.every(event => event.attributes.server_sampling === "unavailable")).toBe(true)+ expect(headers.some(event => event.attributes.server_identity === "available")).toBe(true)+ expect(JSON.stringify(sent)).not.toContain("PRIVATE257")+ expect(JSON.stringify(sent)).not.toContain("/c/channels/s1/c1")+ } finally {+ view.unmount()+ await owner.registry.cleanup()+ owner.client.clear()+ }+})diff --git a/src/web/src/lib/observability/position.ts b/src/web/src/lib/observability/position.tsnew file mode 100644index 000000000..c203b9431--- /dev/null+++ b/src/web/src/lib/observability/position.ts@@ -0,0 +1,35 @@+import type { VirtualListPositionReadReason, VirtualListPositionScope } from "@/lib/community/virtual-list-position"+import { channelHref, normalizeCommunityHref } from "@/lib/community/community-route"+import { actionAttributes, currentPageObservation, navigationForHref } from "./context"+import { emitTelemetry, isTelemetryEligible, telemetryGeneration } from "./telemetry"++export type PositionReason = "settled" | "empty" | "target_missing" | "manual_takeover" | "hidden" | "entry_changed" | "retired" | "data_error" | "cancelled" | "superseded" | "origin_changed"+type PositionOwner = "initial" | "late-new" | "target" | "present" | "idle"+export type PositionSnapshotReason = VirtualListPositionReadReason | "not_requested" | "entry_changed" | "viewport_mismatch" | "padding_mismatch" | "anchor_missing" | "accepted"+export type PositionDecision = {+ position_source: "snapshot" | "read_anchor" | "explicit_target" | "new_divider" | "tail" | "unknown"+ position_snapshot: PositionSnapshotReason+}++export function beginPositionObservation(kind: PositionOwner, scope?: VirtualListPositionScope, entry?: object | null) {+ const start = performance.now()+ const generation = telemetryGeneration()+ const eligible = isTelemetryEligible()+ const channel = scope?.proof.channelId ? scope.proof.registry?.collections.channels.get(scope.proof.channelId) : undefined+ const expected = channel ? channel.serverId === null ? `/c/me/${encodeURIComponent(channel.id)}` : channelHref(channel.serverId!, channel.id) : undefined+ const intent = entry && "intent" in entry && typeof entry.intent === "object" && entry.intent !== null ? entry.intent : entry+ const href = intent && "href" in intent && typeof intent.href === "string" ? intent.href+ : typeof window === "undefined" ? undefined : window.location.pathname + window.location.search+ const action = href && (!expected || normalizeCommunityHref(href).pathname === expected)+ ? navigationForHref(href) ?? (typeof window !== "undefined" && window.location.pathname === expected ? currentPageObservation() : undefined) : undefined+ let done = false+ return (reason: PositionReason, decision?: PositionDecision) => {+ if (done) return+ done = true+ if (!eligible || generation !== telemetryGeneration()) return+ emitTelemetry("position.finish", { ...actionAttributes(action), position_owner: kind, position_reason: reason,+ position_source: decision?.position_source ?? "unknown", position_snapshot: decision?.position_snapshot ?? "not_requested",+ start_ms: start, duration_ms: Math.max(0, performance.now() - start),+ target_coverage: reason === "settled" ? "covered" : reason === "target_missing" ? "uncovered" : "unknown" })+ }+}diff --git a/src/web/src/lib/observability/region-span.dom.test.tsx b/src/web/src/lib/observability/region-span.dom.test.tsxindex 57195c363..d4d671bcb 100644--- a/src/web/src/lib/observability/region-span.dom.test.tsx+++ b/src/web/src/lib/observability/region-span.dom.test.tsx@@ -26,7 +26,7 @@ it("records only the visible component commit-to-ready wait as a native child wiawait act(async () => view.rerender(<Component ready />))const child = exporter.getFinishedSpans().find(span => span.name === "region.wait")!expect(child.parentSpanContext).toEqual(action.span!.spanContext())- expect(child.attributes).toMatchObject({ region: "bots", span_role: "region_readiness", phase: "commit", source: "unknown", snapshot_source: "rsc", target_coverage: "uncovered", wait_reason: "identity", outcome: "success" })+ expect(child.attributes).toMatchObject({ region: "bots", span_role: "region_readiness", phase: "commit", source: "unknown", snapshot_source: "rsc", target_coverage: "covered", initial_wait_reason: "identity", last_wait_reason: "identity", wait_reason: "none", outcome: "success" })expect(child.startTime).toEqual(observationTime(100, action.origin))expect(child.endTime).toEqual(observationTime(180, action.origin))expect(action.done).toBe(true)diff --git a/src/web/src/lib/observability/regions.tsx b/src/web/src/lib/observability/regions.tsxindex a22ee443a..26762c47d 100644--- a/src/web/src/lib/observability/regions.tsx+++ b/src/web/src/lib/observability/regions.tsx@@ -2,7 +2,7 @@import { createContext, useContext, type ReactNode, Suspense, useEffect, useEffectEvent, useRef, useSyncExternalStore } from "react"import { usePathname, useSearchParams } from "next/navigation"-import { commitNavigation, committedNavigationPathname, currentRoute, navigationForHref, finishAction, actionAttributes, startRegionObservation, finishRegionObservation, type Action, type PageOperation } from "./context"+import { commitNavigation, committedNavigationPathname, currentRoute, navigationForHref, finishAction, actionAttributes, startRegionObservation, updateRegionObservation, finishRegionObservation, type Action, type PageOperation } from "./context"import { emitTelemetry, isTelemetryEligible, telemetryGeneration, subscribeObservation, observationSnapshot } from "./telemetry"import type { Attributes } from "./schema"@@ -17,7 +17,7 @@ export type ResourceObservation = { snapshot_source?: "rsc" | "network" | "restoexport function useObservedRegion(region: Attributes["region"], ready: boolean, count?: number, evidence?: ResourceObservation) {const visible = useContext(visibility)const captureEvidence = useEffectEvent(() => evidence)- const snapshotSource = evidence?.snapshot_source, targetCoverage = evidence?.target_coverage+ const snapshotSource = evidence?.snapshot_source, targetCoverage = evidence?.target_coverage, waitReason = evidence?.wait_reasonuseSyncExternalStore(subscribeObservation, observationSnapshot, () => 0)const href = typeof window === "undefined" ? "/" : window.location.pathname + window.location.searchconst pathname = committedNavigationPathname(), route = currentRoute(), navigation = navigationForHref(href), generation = telemetryGeneration(), eligible = isTelemetryEligible()@@ -32,6 +32,11 @@ export function useObservedRegion(region: Attributes["region"], ready: boolean,}}}, [visible, eligible, generation, navigation, region])+ useEffect(() => {+ const current = waiting.current+ if (!visible || !eligible || !current || current.action !== navigation || current.region !== region || generation !== telemetryGeneration()) return+ updateRegionObservation(current.span, { snapshot_source: snapshotSource, target_coverage: targetCoverage, wait_reason: ready ? "none" : waitReason })+ }, [visible, eligible, generation, navigation, region, snapshotSource, targetCoverage, waitReason, ready])useEffect(() => {if (!ready || !visible || !eligible || generation !== telemetryGeneration() || href !== window.location.pathname + window.location.search) returnif (pathname !== undefined && pathname !== window.location.pathname) returndiff --git a/src/web/src/lib/observability/requests.ts b/src/web/src/lib/observability/requests.tsindex f1fd51fb8..5c497e9b0 100644--- a/src/web/src/lib/observability/requests.ts+++ b/src/web/src/lib/observability/requests.ts@@ -11,14 +11,14 @@ export type RequestObservation = { id: string; start: number; origin: number; geconst responses = new WeakMap<Response, RequestObservation>()const requestContext = createContextKey("alook.request")const transportRequests = new WeakMap<Span, RequestObservation>()-export function startRequest(path: string, options?: { method?: string; kind?: Attributes["request_kind"]; observation?: { action?: Action; page?: Action; reason?: Attributes["request_reason"] } }): RequestObservation | undefined {+export function startRequest(path: string, options?: { method?: string; kind?: Attributes["request_kind"]; observation?: { action?: Action; page?: Action; reason?: Attributes["request_reason"]; role?: "entry" | "window" | "reconcile" | "pagination"; windowMode?: "newest" | "anchor" | "since" | "older" | "newer" } }): RequestObservation | undefined {if (!isTelemetryEligible()) returnconst origin = typeof window === "undefined" ? "https://alook.ai" : window.location.originconst explicit = options?.observationconst candidate = explicit?.action ?? explicit?.page ?? (explicit === undefined ? currentPageObservation() : undefined)const action = candidate?.generation === telemetryGeneration() && (!candidate.done || candidate.name === "navigation") ? candidate : undefinedconst clock = action?.origin ?? observationOrigin()- const fields = { ...actionAttributes(action), route_template: routeTemplate(path, origin), method: options?.method ?? "GET", request_reason: options?.observation?.reason ?? "unknown", request_kind: options?.kind ?? "api", eligibility: "unknown", observation_origin_ms: clock, clock_source: "operation_monotonic", clock_domain: "browser", clock_alignment: "unverified" }+ const fields = { ...actionAttributes(action), route_template: routeTemplate(path, origin), method: options?.method ?? "GET", request_reason: options?.observation?.reason ?? "unknown", request_role: explicit?.role, window_mode: explicit?.windowMode, request_kind: options?.kind ?? "api", eligibility: "unknown", observation_origin_ms: clock, clock_source: "operation_monotonic", clock_domain: "browser", clock_alignment: "unverified" }const request = { id: telemetryId(), start: performance.now(), origin: clock, generation: telemetryGeneration(), fields, done: false, action }emitTelemetry("request.start", { ...fields, request_id: request.id, start_ms: request.start })return requestdiff --git a/src/web/src/lib/observability/resource.test.ts b/src/web/src/lib/observability/resource.test.tsindex 0d12b4707..c55946a43 100644--- a/src/web/src/lib/observability/resource.test.ts+++ b/src/web/src/lib/observability/resource.test.ts@@ -7,7 +7,7 @@ import { observeResourceResponse } from "./resource"import { traceResponse } from "./trace-response"afterEach(() => { vi.restoreAllMocks() })-it.each([true, false])("links the exact response server identity without replacing the browser parent when sampled=%s", async sampled => {+it.each([true, false])("links the exact response server identity without replacing the browser parent when native flags=%s", async sampled => {const exporter = new InMemorySpanExporter()const provider = new WebTracerProvider({ spanProcessors: [new SimpleSpanProcessor(exporter)] })const tracer = provider.getTracer("alook.frontend")@@ -19,7 +19,7 @@ it.each([true, false])("links the exact response server identity without replaciobserveResourceResponse(span, response.headers.get("server-timing")!)span.end()const recorded = exporter.getFinishedSpans()[0]!- expect(recorded.attributes).toMatchObject({ server_identity: "available", server_sampling: sampled ? "selected" : "not_selected", server_trace_id: server.traceId, server_span_id: server.spanId })+ expect(recorded.attributes).toMatchObject({ server_identity: "available", server_sampling: "unavailable", server_trace_id: server.traceId, server_span_id: server.spanId })expect(recorded.links).toEqual([{ context: server, attributes: { relationship: "server_response" } }])expect(recorded.parentSpanContext).toEqual(root.spanContext())root.end()diff --git a/src/web/src/lib/observability/schema.ts b/src/web/src/lib/observability/schema.tsindex e62320bf6..36259fb26 100644--- a/src/web/src/lib/observability/schema.ts+++ b/src/web/src/lib/observability/schema.ts@@ -7,6 +7,7 @@ export const eventNames = ["request.body_parsed", "request.finish", "data.publish", "data.response_rejected","ws.connect", "ws.ready", "ws.close", "ws.reconnect", "ws.event_applied","main_thread.longtask", "telemetry.coverage", "telemetry.drop", "business.result", "message.milestone",+ "conversation.cache", "conversation.entry", "conversation.reconcile", "position.finish", "region.wait_change",] as constexport type TelemetryEvent = typeof eventNames[number]export type Attributes = Record<string, string | number | boolean | undefined>@@ -42,6 +43,20 @@ const enumValues: Record<string, ReadonlySet<string>> = Object.fromEntries(Objecsource: ["restored_idb", "network", "ws", "local_mutation", "mixed", "unknown"],snapshot_source: ["rsc", "network", "restored_idb", "unknown"],target_coverage: ["covered", "uncovered", "unknown"],+ cache_reason: ["account_unknown", "owner_retired", "metadata_missing", "metadata_incomplete", "scope_mismatch", "parent_missing", "parent_mismatch", "access_missing", "revoked", "archived", "qualified"],+ cache_consumer: ["metadata", "messages", "forum"],+ cache_window: ["missing", "incomplete", "ready", "empty"],+ entry_status: ["missing", "current", "stale", "pending", "error"],+ entry_stage: ["start", "validated", "published", "delivered", "error", "cancelled"],+ reconcile_stage: ["start", "settled", "error", "cancelled", "retired"],+ request_role: ["entry", "window", "reconcile", "pagination"],+ window_mode: ["newest", "anchor", "since", "older", "newer"],+ position_owner: ["idle", "initial", "target", "late-new", "present", "pagination", "restore"],+ position_reason: ["settled", "empty", "target_missing", "manual_takeover", "hidden", "entry_changed", "retired", "data_error", "cancelled", "superseded", "origin_changed"],+ position_source: ["snapshot", "read_anchor", "explicit_target", "new_divider", "tail", "unknown"],+ position_snapshot: ["no_scope", "invalid_scope", "missing", "invalid_version", "fingerprint_mismatch", "expired", "available", "not_requested", "entry_changed", "viewport_mismatch", "padding_mismatch", "anchor_missing", "accepted"],+ initial_wait_reason: ["none", "entry", "window", "projection", "identity", "restore", "position", "unknown"],+ last_wait_reason: ["none", "entry", "window", "projection", "identity", "restore", "position", "unknown"],wait_reason: ["none", "entry", "window", "projection", "identity", "restore", "position", "unknown"],eligibility: ["eligible", "rejected", "unknown", "denied"],request_reason: ["foreground", "prefetch", "background", "restore_invalidate", "pagination", "command", "router", "unknown"],diff --git a/src/web/src/lib/observability/trace-response.test.ts b/src/web/src/lib/observability/trace-response.test.tsindex 8adef5054..96e0d5dcc 100644--- a/src/web/src/lib/observability/trace-response.test.ts+++ b/src/web/src/lib/observability/trace-response.test.ts@@ -16,14 +16,14 @@ it("preserves the original stream, status and cache headers and uses only actualexpect(header).toContain('db;dur=2;desc="a,b"')expect(header).not.toContain("private-token")expect(header).not.toContain("/api/community/bots")- expect(readTraceResponse(header, client)).toEqual({ matched: true, server, sampling: "selected" })+ expect(readTraceResponse(header, client)).toEqual({ matched: true, server, sampling: "unavailable" })expect(await response.text()).toBe("body")})-it("separates sampler selection from getter availability and never substitutes upstream identity", () => {+it("does not infer head sampling from isTraced or native flags and never substitutes upstream identity", () => {for (const isTraced of [true, false]) {const response = traceResponse(new Response(), request(), { isTraced })- expect(readTraceResponse(response.headers.get("server-timing")!, client)).toEqual({ matched: true, server: undefined, sampling: isTraced ? "selected" : "not_selected" })+ expect(readTraceResponse(response.headers.get("server-timing")!, client)).toEqual({ matched: true, server: undefined, sampling: "unavailable" })expect(response.headers.get("server-timing")).not.toContain("traceparent;")}for (const getter of [() => ({ ...server, traceId: "0".repeat(32) }), () => { throw new Error("missing runtime capability") }]) {diff --git a/src/web/src/lib/observability/trace-response.ts b/src/web/src/lib/observability/trace-response.tsindex 0111cebcc..dbc44abad 100644--- a/src/web/src/lib/observability/trace-response.ts+++ b/src/web/src/lib/observability/trace-response.ts@@ -47,7 +47,7 @@ export function traceResponse(response: Response, request: Request, span?: Nativif (response.status === 101 || response.status === 0) return responseconst upstream = responseTraceContext(request.headers.get("traceparent"))const server = nativeContext(span)- const sampling: Sampling = typeof span?.isTraced === "boolean" ? span.isTraced ? "selected" : "not_selected" : "unavailable"+ const sampling: Sampling = "unavailable"const headers = new Headers(response.headers)const existing = metrics(headers.get("server-timing") ?? "").filter(metric => !owned.has(metric.split(";", 1)[0]?.trim() ?? ""))if (upstream) existing.push('alook_upstream;desc="' + upstream.traceId + "-" + upstream.spanId + '"')diff --git a/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts b/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.tsindex 9e85a8422..e3120f9e7 100644--- a/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts+++ b/src/web/src/test/e2e-ui/17-forum-sidebar-stage-b.spec.ts@@ -149,22 +149,37 @@ test.describe("forum sidebar Stage B request shape", () => {const { serverId, threadId, forumTitle } = await prepareCase1(actors)const { page } = await asUser("alice")+ const readRequests: string[] = []const requests: string[] = []const successfulResponses: string[] = []- page.on("request", request => { if (request.method() === "GET") requests.push(request.url()) })+ page.on("request", request => {+ if (request.method() === "GET") requests.push(request.url())+ if (request.method() === "PUT" && new URL(request.url()).pathname === `/api/community/channels/${threadId}/read`) readRequests.push(request.url())+ })page.on("response", response => { if (response.request().method() === "GET" && response.ok()) successfulResponses.push(response.url()) })for (const refresh of [false, true]) {const entryGate = await holdRoute(page, url => isConversationEntryRequest(url.href, threadId), caseResources)+ const sidebarGate = !refresh ? await holdRoute(page, url => isSidebarRequest(url.href, serverId), caseResources) : null+ readRequests.length = 0requests.length = 0successfulResponses.length = 0const combined = page.waitForResponse(response => response.ok() && isSidebarRequest(response.url(), serverId))if (refresh) await page.reload({ waitUntil: "commit" })else await page.goto(`/c/channels/${serverId}/${threadId}`)+ await expect.poll(entryGate.held).toBe(1)+ if (sidebarGate) {+ await expect.poll(sidebarGate.held).toBe(1)+ await expect(page.getByTestId(tid.composerInput)).toHaveCount(0)+ await expect(page.getByText("post body", { exact: true })).toHaveCount(0)+ await expect(page.locator('[data-slot="skeleton"]').first()).toBeVisible()+ await sidebarGate.release()+ }await combinedawait expect.poll(() => new URL(page.url()).pathname).toBe(`/c/channels/${serverId}/${threadId}`)await expect.poll(entryGate.held).toBe(1)await expect(childPanel(page).getByText("post body", { exact: true })).toHaveCount(0)- await expect(childPanel(page).getByTestId(tid.composerInput)).toHaveCount(0)+ await expect(childPanel(page).getByTestId(tid.composerInput)).toBeVisible()+ expect(readRequests).toEqual([])await entryGate.release()await expect(childPanel(page).getByRole("heading", { name: forumTitle })).toBeVisible({ timeout: 20_000 })await expect(childPanel(page).getByText("post body", { exact: true })).toBeVisible({ timeout: 20_000 })diff --git a/src/web/src/test/e2e-ui/45-desktop-thread-split-view.spec.ts b/src/web/src/test/e2e-ui/45-desktop-thread-split-view.spec.tsindex ed0a6deed..242eb4c8d 100644--- a/src/web/src/test/e2e-ui/45-desktop-thread-split-view.spec.ts+++ b/src/web/src/test/e2e-ui/45-desktop-thread-split-view.spec.ts@@ -243,7 +243,7 @@ test.describe("desktop thread split view", () => {test("keeps a cold parent placeholder until its own entry is readable", async ({ caseActors, caseResources }) => {const actors = await caseActors(["alice"])const { asUser } = actors- const { serverId, forumId, forumPostId } = await prepareCase1(actors)+ const { serverId, forumId, forumPostId, forumTitle } = await prepareCase1(actors)const { page } = await asUser("alice")await page.setViewportSize({ width: 1280, height: 900 })@@ -262,10 +262,12 @@ test.describe("desktop thread split view", () => {await requestedconst parent = page.getByTestId(tid.threadSplitParent)await expect(page.getByTestId(tid.threadSplit)).toHaveAttribute("data-layout", "split")- await expect(parent.getByTestId(tid.forumPostList)).toHaveCount(0)- await expect(parent.getByRole("main").locator('[data-slot="skeleton"]').first()).toBeVisible()+ const list = parent.getByTestId(tid.forumPostList)+ await expect(list).toBeVisible()+ await expect(list.getByText(forumTitle, { exact: true })).toHaveCount(0)+ await expect(list.locator('[data-slot="skeleton"]').first()).toBeVisible()releaseEntry()- await expect(parent.getByTestId(tid.forumPostList)).toBeVisible()+ await expect(list.getByText(forumTitle, { exact: true })).toBeVisible()await expect(page.getByTestId(tid.threadSplitPanel).getByText("Forum reply", { exact: false })).toBeVisible()} finally {