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): separate cached conversation reveal from target loading (#1102)
Generb43bd758122e
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex bd8456695..578586ec1 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -116,7 +116,7 @@ Forums are channels with a different presentation. Share account/access qualific| Initial viewport and active user input | [use-scroll-anchor](src/web/src/hooks/community/use-scroll-anchor.ts). A fresh ordinary entry can consume a newer qualified local target once. Explicit message/sequence navigation wins; active entries and retained parent resume keep their original position ownership. || Navigation completion and role display | [navigation controller](src/web/src/components/community/shell/use-community-navigation-controller.ts), [shell frame](src/web/src/components/community/shell/shell-frame.tsx), [channel route](src/web/src/components/community/channels/channel-route.tsx) and [member VM](src/web/src/components/community/members/channel-member-view-model.tsx). The existing navigation owner completes URL publication plus structural frame; the existing server-role authority supplies display facts. |-Use a qualified cached window only when its IDs and complete canonical entities cover the requested target. Display and position from that coverage immediately while an ordinary entry refresh runs in the background. A missing ordinary-entry key does not retire another valid entry's qualification. Otherwise obtain coverage through the existing entry/window request. Preserve valid older windows and the actual selected Query's pages/page parameters. Landing reconciliation carries its sequence high waterline through the existing [reconnect owner](src/web/src/hooks/community/community-ws/reconnect-messages.ts), including a newer requirement that arrives during an older read.+Use a qualified cached display window only when its IDs and complete canonical entities are locally readable for the current account and access generation. Reveal it after the existing list owner completes its first local placement, while entry refresh, target coverage and repair continue separately. Target positioning, reading and pagination retain their original coverage, snapshot and geometry requirements; revealing cached content does not grant those qualifications. A missing ordinary-entry key does not retire another valid entry's qualification. Otherwise obtain coverage through the existing entry/window request. Preserve valid older windows and the actual selected Query's pages/page parameters. Landing reconciliation carries its sequence high waterline through the existing [reconnect owner](src/web/src/hooks/community/community-ws/reconnect-messages.ts), including a newer requirement that arrives during an older read.Freshness and retention are different. Entry and message-window options own stale/GC policy; [query-persister](src/web/src/lib/query-persister.ts) owns the bounded persisted closure and restore eligibility. A prior visit, restored entity or fresh metadata does not establish an available, qualified landing window. Account retirement and channel/parent access generation changes retire original authority before reuse; never recapture new permission for old work or carry an old generation's maximum into the new one.diff --git a/src/web/src/components/community/channels/dm-view.tsx b/src/web/src/components/community/channels/dm-view.tsxindex 15f883a44..ac9708ccf 100644--- a/src/web/src/components/community/channels/dm-view.tsx+++ b/src/web/src/components/community/channels/dm-view.tsx@@ -157,8 +157,8 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeComrefetch: refetchMessages,navigationBlocked,anchorReconciled,- readSnapshot, readSnapshotFetching, initialPositionKnown,- initialLoadError, retryInitialLoad, retryingInitialLoad, observation, positionEntry, positionScope, positionDataState, targetPositionDataState, messageWindow,+ readSnapshot, readSnapshotFetching, initialDisplayReady, preserveInitialPresentation, onUserTakeover,+ initialLoadError, targetLoadError, retryInitialLoad, retryingInitialLoad, observation, positionEntry, positionScope, positionDataState, targetPositionDataState, messageWindow,} = useDmMessages(dmId, {enabled: !dmBlocked && !metadata.revoked && !metadata.denied,viewerUserId: currentUser.id,@@ -456,6 +456,7 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCommessages={messages}loading={!historyAllowed || loadingOwnership.messageBodyLoading}initialLoadError={initialLoadError}+ targetLoadError={targetLoadError}observation={observation}retryingInitialLoad={retryingInitialLoad || messagesFetching}onRetryInitialLoad={retryInitialLoad}@@ -474,7 +475,9 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeComresolveUserName={resolveUserName}onScrollRoot={setScrollRootEl}viewerUserId={currentUser.id}- initialScrollReady={initialPositionKnown}+ initialScrollReady={initialDisplayReady}+ preserveInitialPresentation={preserveInitialPresentation}+ onUserTakeover={onUserTakeover}hasMore={hasMoreMessages}historyStartKnown={historyStartKnown}initialPositionMessageId={initialPositionMessageId}diff --git a/src/web/src/components/community/channels/forum-cache-reveal.dom.test.tsx b/src/web/src/components/community/channels/forum-cache-reveal.dom.test.tsxnew file mode 100644index 000000000..58c67a587--- /dev/null+++ b/src/web/src/components/community/channels/forum-cache-reveal.dom.test.tsx@@ -0,0 +1,161 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest"+import { act, fireEvent, render, renderHook } from "@/test/react-dom-harness"+import { CommunityTestProvider } from "@/test/community-owner-fixture"+import { createCommunityQueryOwner } from "@/test/community-query-owner"+import { forumConversationEntryFixture, seedConversationEntry } from "@/test/conversation-entry-fixtures"+import { communityKeys } from "@/lib/query-keys"+import { installMessageScrollFixture, restoreMessageScrollFixture, resize } from "@/test/message-scroll-fixture"+import { ForumSurface } from "./forum-surface"+import { ForumPostList } from "./forum-post-list"+import { useForumFeed } from "@/hooks/community/use-forum-feed"++const load = vi.hoisted(() => vi.fn())+vi.mock("@/lib/api/client", async original => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: load }))+vi.mock("@/hooks/community/use-channel-panels", () => ({ useForumTags: () => ({ data: { tags: [] }, isSuccess: true }) }))+vi.mock("@/hooks/community/use-read-observer", () => ({ useTimelineReadObserver: () => {} }))+vi.mock("./forum-view", () => ({ ForumView: (props: Parameters<typeof ForumPostList>[0]) => <ForumPostList {...props}+ loadingContent={<span>Loading actual cards</span>} renderPost={post => <div data-msg-id={post.openerMessageId}>{post.name}</div>} /> }))+beforeEach(() => { installMessageScrollFixture(); load.mockReset(); localStorage.clear() })+afterEach(restoreMessageScrollFixture)++it.each([false, true].flatMap(empty => (["success", "offline", "timeout"] as const).map(result => ({ empty, result }))))("keeps a qualified Forum instance through pending entry and $result, empty=$empty", async ({ empty, result }) => {+ const owner = await createCommunityQueryOwner()+ const packet = forumConversationEntryFixture("c1", "s1", empty)+ await seedConversationEntry(owner.client, packet)+ owner.client.removeQueries({ queryKey: communityKeys.conversationEntries("c1") })+ let resolve!: (value: typeof packet) => void, reject!: (error: Error) => void+ load.mockReturnValue(new Promise((yes, no) => { resolve = yes; reject = no }))+ const view = render(<CommunityTestProvider {...owner}><ForumSurface serverId="s1" forumChannelId="c1" routeTag="" members={[]} onOpenPost={() => {}} /></CommunityTestProvider>)+ try {+ resize()+ const root = view.getByTestId("community-forum-post-list")+ expect(root).not.toHaveAttribute("aria-busy")+ expect(view.queryByText("Loading actual cards")).toBeNull()+ expect(root.textContent).toContain(empty ? "No posts with this tag" : "Body")+ await act(async () => {+ if (result === "success") resolve(packet)+ else if (result === "offline") reject(new Error("offline"))+ await vi.advanceTimersByTimeAsync(result === "timeout" ? 15000 : result === "offline" ? 2000 : 0)+ })+ resize()+ expect(view.getByTestId("community-forum-post-list")).toBe(root)+ expect(root).not.toHaveAttribute("aria-busy")+ expect(view.queryByText("Loading actual cards")).toBeNull()+ } finally { view.unmount(); owner.client.clear() }+})++it.each(["child", "opener", "author", "participant"] as const)("does not turn missing Forum %s into an empty list, and has a finite failure exit", async missing => {+ const owner = await createCommunityQueryOwner()+ const packet = forumConversationEntryFixture()+ await seedConversationEntry(owner.client, packet)+ const key = communityKeys.forumFeed("c1", null)+ if (missing === "child") owner.registry.collections.channels.utils.writeDelete("t1")+ if (missing === "opener") owner.registry.collections.messages.utils.writeDelete("m1")+ if (missing === "author") owner.registry.collections.profiles.utils.writeDelete("peer")+ if (missing === "participant") owner.client.setQueryData(key, (data: { pages: Array<{ threads: Array<{ participantIds: string[] }> }> }) => ({+ ...data, pages: data.pages.map(page => ({ ...page, threads: page.threads.map(thread => ({ ...thread, participantIds: ["absent-profile"] })) })),+ }))+ owner.client.removeQueries({ queryKey: communityKeys.conversationEntries("c1") })+ load.mockReturnValue(new Promise(() => {}))+ const view = render(<CommunityTestProvider {...owner}><ForumSurface serverId="s1" forumChannelId="c1" routeTag="" members={[]} onOpenPost={() => {}} /></CommunityTestProvider>)+ try {+ resize()+ expect(view.getByLabelText("Loading forum")).toHaveAttribute("aria-busy", "true")+ expect(view.queryByText(/No posts with this tag/)).toBeNull()+ expect(view.queryByText("Body")).toBeNull()+ await act(async () => { await vi.advanceTimersByTimeAsync(15000) })+ resize()+ expect(view.getByRole("alert")).toBeVisible()+ expect(view.getByRole("button", { name: "Retry" })).toBeEnabled()+ expect(view.queryByText(/No posts with this tag/)).toBeNull()+ } finally { view.unmount(); owner.client.clear() }+})+++it.each(["child", "opener"] as const)("keeps the Forum root while complete data loses its %s and recovers", async missing => {+ const owner = await createCommunityQueryOwner()+ const packet = forumConversationEntryFixture()+ await seedConversationEntry(owner.client, packet)+ load.mockReturnValue(new Promise(() => {}))+ const view = render(<CommunityTestProvider {...owner}><ForumSurface serverId="s1" forumChannelId="c1" routeTag="" members={[]} onOpenPost={() => {}} /></CommunityTestProvider>)+ try {+ resize()+ const root = view.getByTestId("community-forum-post-list")+ expect(root.textContent).toContain("Body")+ await act(async () => {+ if (missing === "child") owner.registry.collections.channels.utils.writeDelete("t1")+ else owner.registry.collections.messages.utils.writeDelete("m1")+ await vi.advanceTimersByTimeAsync(0)+ })+ resize()+ expect(view.getByTestId("community-forum-post-list")).toBe(root)+ expect(root).toHaveAttribute("aria-busy", "true")+ expect(root.querySelector("[data-read-position-ready]")).toHaveAttribute("data-read-position-ready", "false")+ expect(view.queryByText(/No posts with this tag/)).toBeNull()+ await act(async () => { await seedConversationEntry(owner.client, packet); await vi.advanceTimersByTimeAsync(0) })+ resize()+ expect(view.getByTestId("community-forum-post-list")).toBe(root)+ expect(root).not.toHaveAttribute("aria-busy")+ expect(root.textContent).toContain("Body")+ } finally { view.unmount(); owner.client.clear() }+})++it("starts a new finite feed projection attempt on Retry and refetches through the original query", async () => {+ const owner = await createCommunityQueryOwner()+ const packet = forumConversationEntryFixture()+ await seedConversationEntry(owner.client, packet)+ owner.registry.collections.messages.utils.writeDelete("m1")+ load.mockReturnValue(new Promise(() => {}))+ const view = renderHook(() => useForumFeed("s1", "c1", { routeTag: "" }), {+ wrapper: ({ children }) => <CommunityTestProvider {...owner}>{children}</CommunityTestProvider>,+ })+ try {+ await act(async () => { await vi.advanceTimersByTimeAsync(15000) })+ expect(view.result.current.initialLoadError).toMatchObject({ name: "ConversationReadTimeoutError" })+ expect(view.result.current.posts).toEqual([])+ const requestsBefore = load.mock.calls.length+ let complete!: (value: NonNullable<typeof packet.forumFeed>) => void+ load.mockReturnValue(new Promise(resolve => { complete = resolve }))+ let retry!: ReturnType<typeof view.result.current.refetch>+ await act(async () => {+ retry = view.result.current.refetch({ cancelRefetch: false })+ await vi.advanceTimersByTimeAsync(0)+ })+ expect(load.mock.calls.slice(requestsBefore).map(([url]) => url)).toEqual([+ "/api/community/channels/c1/threads?order=createdAt&limit=50&include=parentMessage%2CfirstMessage%2Ctags%2Cparticipants",+ ])+ expect(view.result.current.isFetching).toBe(true)+ expect(view.result.current.initialLoadError).toBeNull()+ expect(view.result.current.displayReady).toBe(false)+ expect(view.result.current.posts).toEqual([])+ await act(async () => { await vi.advanceTimersByTimeAsync(1000) })+ expect(view.result.current.initialLoadError).toBeNull()+ await act(async () => { complete(packet.forumFeed!); await retry })+ expect(view.result.current.posts.map(post => post.name)).toEqual(["Body"])+ expect(view.result.current.displayReady).toBe(true)+ expect(view.result.current.initialLoadError).toBeNull()+ expect(view.result.current.isLoading).toBe(false)+ } finally { view.unmount(); owner.client.clear() }+})++it("recovers missing Forum dependencies through the visible Retry button", async () => {+ const owner = await createCommunityQueryOwner()+ const packet = forumConversationEntryFixture()+ await seedConversationEntry(owner.client, packet)+ owner.registry.collections.messages.utils.writeDelete("m1")+ load.mockReturnValue(new Promise(() => {}))+ const view = render(<CommunityTestProvider {...owner}><ForumSurface serverId="s1" forumChannelId="c1" routeTag="" members={[]} onOpenPost={() => {}} /></CommunityTestProvider>)+ try {+ await act(async () => { await vi.advanceTimersByTimeAsync(15000) })+ const retry = view.getByRole("button", { name: "Retry" })+ expect(retry).toBeEnabled()+ const requestsBefore = load.mock.calls.length+ load.mockImplementation(async url => String(url).includes("/threads?") ? packet.forumFeed : packet)+ await act(async () => { fireEvent.click(retry); await vi.advanceTimersByTimeAsync(0) })+ resize()+ expect(load.mock.calls.slice(requestsBefore).some(([url]) => String(url).includes("/threads?"))).toBe(true)+ expect(view.getByTestId("community-forum-post-list").textContent).toContain("Body")+ expect(view.queryByRole("alert")).toBeNull()+ expect(view.queryByText(/No posts with this tag/)).toBeNull()+ } finally { view.unmount(); owner.client.clear() }+})diff --git a/src/web/src/components/community/channels/forum-post-list.restoration.dom.test.tsx b/src/web/src/components/community/channels/forum-post-list.restoration.dom.test.tsxindex 6d3b07515..af916cb55 100644--- a/src/web/src/components/community/channels/forum-post-list.restoration.dom.test.tsx+++ b/src/web/src/components/community/channels/forum-post-list.restoration.dom.test.tsx@@ -39,6 +39,8 @@ describe("Forum native list identity and ordinary reconstruction", () => {resize()if (mode === "hidden") {expect(second.getByTestId("community-forum-post-list").querySelector("[data-read-position-ready]")).toHaveAttribute("data-read-position-ready", "false")+ expect(second.getByTestId("community-forum-post-list")).toHaveAttribute("aria-busy", "true")+ expect(second.getByTestId("community-forum-post-list").querySelector("[data-message-list-content]")).toHaveAttribute("aria-hidden", "true")scrollFixture.width = 320scrollFixture.height = 500resize()@@ -83,7 +85,7 @@ it("exposes only an unadmitted forum's initial loading and keeps an admitted empconst admitted = view.getByTestId("community-forum-post-list")expect(admitted).not.toHaveAttribute("aria-busy")expect(view.queryByLabelText("Loading forum")).toBeNull()- view.rerender(<ForumPostList {...props} loading isFetching />)+ view.rerender(<ForumPostList {...props} isFetching />)expect(view.getByTestId("community-forum-post-list")).toBe(admitted)expect(view.queryByText("Loading actual forum")).toBeNull()expect(view.queryByLabelText("Loading forum")).toBeNull()diff --git a/src/web/src/components/community/channels/forum-post-list.tsx b/src/web/src/components/community/channels/forum-post-list.tsxindex c25d1bb78..cdc7dc3ec 100644--- a/src/web/src/components/community/channels/forum-post-list.tsx+++ b/src/web/src/components/community/channels/forum-post-list.tsx@@ -13,6 +13,7 @@ import type { ForumThread } from "@/lib/community/models/message"import { tid } from "@/lib/community/testids"import { EmptyState } from "../empty-state"import { VirtualRows } from "../messages/virtual-cursor-list"+import { useInitialPositionTransition } from "../messages/initial-position-transition"const OVERSCAN = 5const forumRangeExtractor = (range: Range) => defaultRangeExtractor({ ...range, overscan: range.overscan + range.endIndex - range.startIndex + 1 })@@ -42,10 +43,13 @@ function ForumPostListEntry(props: Props) {return <ForumPostListOwner {...props} />}-function ForumPostListOwner({ posts, loading, observation, hasMore, loadingMore, isFetching, isError, onLoadMore, onScrollRoot, renderPost }: Props) {+function ForumPostListOwner({ posts, loading, observation, hasMore, loadingMore, isFetching, isError, onLoadMore, onScrollRoot, renderPost, loadingContent }: Props) {const scrollRef = useRef<HTMLDivElement>(null)const initialized = useRef(false)const [positionReady, setPositionReady] = useState(false)+ useLayoutEffect(() => { if (posts.length === 0) setPositionReady(!loading) }, [loading, posts.length])+ const presentation = useInitialPositionTransition({ firstWindowReady: !loading || posts.length > 0,+ authoritativeEmpty: !loading && posts.length === 0, positionSettled: positionReady })const postsRef = useRef(posts)useLayoutEffect(() => { postsRef.current = posts }, [posts])const bindScrollRoot = useCallback((node: HTMLDivElement | null) => { scrollRef.current = node; onScrollRoot?.(node) }, [onScrollRoot])@@ -56,12 +60,14 @@ function ForumPostListOwner({ posts, loading, observation, hasMore, loadingMore,|| native.isScrolling || Math.abs((native.scrollOffset ?? 0) - root.scrollTop) > 1|| native.options.count !== current.length|| current.some((post, index) => native.options.getItemKey(index) !== post.id)) return+ const viewport = root.getBoundingClientRect()+ if (viewport.width <= 0 || viewport.height <= 0) returnconst fold = native.getVirtualItemForOffset(root.scrollTop + 1)const wrapper = fold && root.querySelector<HTMLElement>(`[data-index="${fold.index}"]`)const rect = wrapper?.getBoundingClientRect()const padding = Number.parseFloat(window.getComputedStyle(root).paddingTop) || 0if (!fold || !rect || rect.height <= 0 || Math.abs(rect.height - fold.size) > 1- || Math.abs(rect.top - root.getBoundingClientRect().top + root.scrollTop - padding - fold.start) > 1) return+ || Math.abs(rect.top - viewport.top + root.scrollTop - padding - fold.start) > 1) returnsetPositionReady(true)}, [])const getItemKey = useCallback((index: number) => posts[index]?.id ?? index, [posts])@@ -104,14 +110,22 @@ function ForumPostListOwner({ posts, loading, observation, hasMore, loadingMore,return virtualItems.filter(item => indexes.has(item.index))}, [posts.length, range, virtualItems])const observedPosts = visibleVirtualItems(virtualizer).flatMap(item => posts[item.index] ? [posts[item.index]] : [])- useObservedRegion("forum", (!loading || posts.length > 0) && (!posts.length || observedPosts.length > 0), observedPosts.length, observation)+ useObservedRegion("forum", presentation.contentVisible && (!posts.length || observedPosts.length > 0), observedPosts.length, observation)useVirtualCursorPagination({virtualizer: { getVirtualItems: () => paginationItems }, count: posts.length, enabled: !loading,hasMore, isFetching: isFetching || loadingMore, isError, onLoad: onLoadMore, edge: "end",})- return <div ref={bindScrollRoot} role="main" data-testid={tid.forumPostList} className="flex-1 overflow-y-auto thin-scrollbar [overflow-anchor:none] px-0 py-2 sm:px-4">- {!posts.length ? <div data-message-list-content aria-hidden="false" data-read-position-ready="true"><EmptyState icon={ListChevronsUpDown} label="No posts with this tag yet. Start one with New Post." /></div>+ return <div className="relative flex min-h-0 flex-1 flex-col">+ <div ref={bindScrollRoot} role="main" data-testid={tid.forumPostList} data-community-conversation-subtype="forum"+ aria-busy={presentation.showSkeleton || undefined} aria-label={presentation.showSkeleton ? "Loading forum" : undefined}+ className="flex-1 overflow-y-auto thin-scrollbar [overflow-anchor:none] px-0 py-2 sm:px-4">+ {!posts.length && loading ? <div data-message-list-content aria-hidden="true" inert data-read-position-ready="false" />+ : !posts.length ? <div data-message-list-content aria-hidden="false" data-read-position-ready="true"><EmptyState icon={ListChevronsUpDown} label="No posts with this tag yet. Start one with New Post." /></div>: <VirtualRows directDomUpdatesMode="position" items={posts} virtualizer={virtualizer} renderItem={renderPost}- containerAttributes={{ "data-message-list-content": "", "aria-hidden": false, "data-read-position-ready": positionReady ? "true" : "false" }} />}+ containerAttributes={{ "data-message-list-content": "", "aria-hidden": !presentation.contentVisible, inert: !presentation.contentInteractive,+ "data-read-position-ready": positionReady ? "true" : "false" }} />}+ </div>+ {presentation.showSkeleton && <div data-forum-positioning-skeleton aria-hidden="true"+ className="pointer-events-none absolute inset-0 overflow-hidden bg-background px-0 py-2 sm:px-4">{loadingContent}</div>}</div>}diff --git a/src/web/src/components/community/channels/forum-surface.dom.test.ts b/src/web/src/components/community/channels/forum-surface.dom.test.tsindex 34be45a2c..57ee8b67a 100644--- a/src/web/src/components/community/channels/forum-surface.dom.test.ts+++ b/src/web/src/components/community/channels/forum-surface.dom.test.ts@@ -63,7 +63,7 @@ const mocks = vi.hoisted(() => ({vi.mock("@tanstack/react-query", async (load) => ({ ...await load<typeof import("@tanstack/react-query")>(), useQueryClient: () => ({ refetchQueries: mocks.read.retry }) }))vi.mock("@/hooks/community/use-forum-feed", () => ({- useForumFeed: () => ({ ...mocks.feed, data: mocks.feed.posts.length ? { pages: [] } : undefined }),+ useForumFeed: () => ({ ...mocks.feed, displayReady: mocks.feed.posts.length > 0, data: mocks.feed.posts.length ? { pages: [] } : undefined }),}))vi.mock("@/hooks/community/use-conversation-entry", () => ({useConversationEntry: () => ({ ...mocks.read, refetch: mocks.read.retry }),diff --git a/src/web/src/components/community/channels/forum-surface.pagination.dom.test.ts b/src/web/src/components/community/channels/forum-surface.pagination.dom.test.tsindex 7d0538024..3be98a663 100644--- a/src/web/src/components/community/channels/forum-surface.pagination.dom.test.ts+++ b/src/web/src/components/community/channels/forum-surface.pagination.dom.test.ts@@ -26,7 +26,7 @@ vi.mock("@/hooks/community/use-forum-feed", async () => {staleTime: Infinity, retry: 1, retryDelay: 0,})return {- ...query, posts: query.data.pages.flatMap(value => value.posts), tag: "All", selectionReady: true,+ ...query, displayReady: true, posts: query.data.pages.flatMap(value => value.posts), tag: "All", selectionReady: true,availableTags: [], selectTag: vi.fn(), hasMoreOlder: query.hasNextPage,isFetchingOlder: query.isFetchingNextPage, fetchOlder: () => { void query.fetchNextPage() },}diff --git a/src/web/src/components/community/channels/forum-surface.tsx b/src/web/src/components/community/channels/forum-surface.tsxindex a9c134327..182a9244f 100644--- a/src/web/src/components/community/channels/forum-surface.tsx+++ b/src/web/src/components/community/channels/forum-surface.tsx@@ -33,7 +33,7 @@ export function ForumSurface({ serverId, forumChannelId, routeTag, onSelectTag,}) {const feed = useForumFeed(serverId, forumChannelId, { routeTag, onSelectTag })const readState = useConversationEntry(feed.selectionReady ? { channelId: forumChannelId, serverId, tag: feed.tag === "All" ? null : feed.tag } : null)- const proof = readState.resource?.proof+ const proof = readState.scope?.proofconst positionScope = useMemo<ConversationListScope | undefined>(() => readState.canRead && proof? { proof, tag: feed.tag === "All" ? null : feed.tag } : undefined, [readState.canRead, proof, feed.tag])const [scrollRootEl, setScrollRootEl] = useAtom(useCreateAtom<HTMLDivElement | null>(null))@@ -42,8 +42,8 @@ export function ForumSurface({ serverId, forumChannelId, routeTag, onSelectTag,const retryRef = useRef<{ scope: string } | null>(null)const retrying = retryAttempt?.scope === retryScopeconst accessError = isConversationAccessError(feed.error) || isConversationAccessError(readState.error)- const initialLoadError = accessError || (feed.data === undefined && (- feed.isError || !!readState.error || retrying+ const initialLoadError = accessError || (!feed.displayReady && (+ feed.isError || !!feed.initialLoadError || !!readState.error || retrying))useTimelineReadObserver({channelId: forumChannelId,diff --git a/src/web/src/components/community/channels/forum-view.swipe.dom.test.tsx b/src/web/src/components/community/channels/forum-view.swipe.dom.test.tsxindex 8e262aaea..7a4c83fe4 100644--- a/src/web/src/components/community/channels/forum-view.swipe.dom.test.tsx+++ b/src/web/src/components/community/channels/forum-view.swipe.dom.test.tsx@@ -1,4 +1,4 @@-import { afterEach, describe, expect, it, vi } from "vitest"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { fireEvent, mockElementGeometry, render, waitFor } from "@/test/react-dom-harness"import { SwipeRoot, SwipePortal, SwipeViewport, SwipePopup, SwipeTitle } from "@/components/ui/swipe-container"import { canStartSwipe } from "@/components/ui/swipe-gesture-policy"@@ -10,6 +10,12 @@ vi.mock("@/hooks/use-mobile", () => ({ useIsMobile: () => true, useBreakpoint: (vi.mock("@/lib/community-db/projections", () => ({ useCanonicalProfilesByUserId: () => new Map() }))const hitTest = Object.getOwnPropertyDescriptor(document, "elementFromPoint")+const originalRect = HTMLElement.prototype.getBoundingClientRect+beforeEach(() => {+ vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {+ return this.hasAttribute("data-index") ? new DOMRect(0, Number.parseFloat(this.style.top) || 0, 390, 128) : originalRect.call(this)+ })+})afterEach(() => {vi.restoreAllMocks()if (hitTest) Object.defineProperty(document, "elementFromPoint", hitTest)@@ -30,7 +36,7 @@ function fixture({ empty = false, kind = "page" as "page" | "overlay" } = {}) {<ForumView forumChannelId="forum" members={[]} posts={empty ? [] : [post]}tag="All" tagsKnown availableTags={[]} onTagChange={() => {}} onOpenPost={opened}onEditPostTags={archive} canEditPostTags={() => true}- onScrollRoot={node => { if (node) mockElementGeometry(node, { clientHeight: 600, clientWidth: 390 }) }} />+ onScrollRoot={node => { if (node) mockElementGeometry(node, { clientHeight: 600, clientWidth: 390, width: 390, height: 600 }) }} /></SwipePopup></SwipeViewport></SwipePortal></SwipeRoot>)const root = view.getByTestId("page-viewport"), popup = view.getByTestId("page-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 37c4187d7..740ea2d84 100644--- a/src/web/src/components/community/channels/text-channel-surface.tsx+++ b/src/web/src/components/community/channels/text-channel-surface.tsx@@ -130,9 +130,9 @@ export function TextChannelSurface({<Bodydata-slot="community-conversation-surface"data-channel-id={channelId}- data-testid={!embedded && feed.positionDataState === "pending" ? tid.conversationResolutionPending : undefined}- aria-busy={!embedded && feed.positionDataState === "pending" ? true : undefined}- aria-label={!embedded && feed.positionDataState === "pending" ? "Loading conversation" : undefined}+ data-testid={!embedded && feed.isLoading ? tid.conversationResolutionPending : undefined}+ aria-busy={!embedded && feed.isLoading ? true : undefined}+ aria-label={!embedded && feed.isLoading ? "Loading conversation" : undefined}data-community-conversation-subtype="text"className="flex min-h-0 min-w-0 flex-1 flex-col">@@ -143,6 +143,7 @@ export function TextChannelSurface({messages={feed.messages}loading={feed.isLoading}initialLoadError={feed.initialLoadError}+ targetLoadError={feed.targetLoadError}observation={feed.observation}retryingInitialLoad={feed.retryingInitialLoad}onRetryInitialLoad={feed.retryInitialLoad}@@ -158,7 +159,9 @@ export function TextChannelSurface({scrollToMessageId={controller.scrollTargetId}onScrollRoot={feed.setScrollRootEl}viewerUserId={viewer.id}- initialScrollReady={feed.initialPositionKnown}+ initialScrollReady={feed.initialDisplayReady}+ preserveInitialPresentation={feed.preserveInitialPresentation}+ onUserTakeover={feed.onUserTakeover}onScrollTargetConsumed={controller.consumeScrollTarget}hasMore={feed.hasMoreOlder}historyStartKnown={feed.historyStartKnown}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 c71504bb6..b689c38f3 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@@ -158,6 +158,7 @@ function feed(overrides: Record<string, unknown> = {}) {readSnapshotFetching: false,anchorInCache: true,initialPositionKnown: true,+ initialDisplayReady: true,newDividerBefore: undefined,unreadCount: 0,setScrollRootEl: vi.fn(),diff --git a/src/web/src/components/community/channels/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsxindex 2aed9cddf..034de5929 100644--- a/src/web/src/components/community/channels/thread-channel-surface.tsx+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx@@ -221,9 +221,9 @@ export function ThreadChannelSurface({<Bodydata-slot="community-conversation-surface"data-channel-id={channelId}- data-testid={!embedded && controller.feed.positionDataState === "pending" ? tid.conversationResolutionPending : undefined}- aria-busy={!embedded && controller.feed.positionDataState === "pending" ? true : undefined}- aria-label={!embedded && controller.feed.positionDataState === "pending" ? "Loading thread" : undefined}+ data-testid={!embedded && controller.feed.isLoading ? tid.conversationResolutionPending : undefined}+ aria-busy={!embedded && controller.feed.isLoading ? true : undefined}+ aria-label={!embedded && controller.feed.isLoading ? "Loading thread" : undefined}data-community-conversation-subtype="thread"className="flex min-h-0 min-w-0 flex-1 flex-col">@@ -234,6 +234,7 @@ export function ThreadChannelSurface({messages={controller.feed.messages}loading={controller.feed.isLoading}initialLoadError={controller.feed.initialLoadError}+ targetLoadError={controller.feed.targetLoadError}observation={controller.feed.observation}retryingInitialLoad={controller.feed.retryingInitialLoad}onRetryInitialLoad={controller.feed.retryInitialLoad}@@ -250,7 +251,9 @@ export function ThreadChannelSurface({hero={opener}onScrollRoot={controller.feed.setScrollRootEl}viewerUserId={viewer.id}- initialScrollReady={controller.feed.initialPositionKnown}+ initialScrollReady={controller.feed.initialDisplayReady}+ preserveInitialPresentation={controller.feed.preserveInitialPresentation}+ onUserTakeover={controller.feed.onUserTakeover}onScrollTargetConsumed={controller.consumeScrollTarget}hasMore={controller.feed.hasMoreOlder}historyStartKnown={controller.feed.historyStartKnown}diff --git a/src/web/src/components/community/messages/message-list-controller.dom.test.ts b/src/web/src/components/community/messages/message-list-controller.dom.test.tsindex 21925c516..739ce8a7d 100644--- a/src/web/src/components/community/messages/message-list-controller.dom.test.ts+++ b/src/web/src/components/community/messages/message-list-controller.dom.test.ts@@ -204,6 +204,17 @@ describe("useMessageListController", () => {expect(mocks.scrollInputs.at(-1)).toMatchObject({ localSubmitVersion: 8, presentVersion: 3 })})+ it("forwards the current takeover action to the existing position owner", () => {+ const first = vi.fn(), current = vi.fn()+ const view = rtlRender(React.createElement(Probe, { value: props({ onUserTakeover: first }) }))+ expect(mocks.scrollInputs.at(-1)).toMatchObject({ onUserTakeover: first })+ view.rerender(React.createElement(Probe, { value: props({ onUserTakeover: current }) }))+ const action = (mocks.scrollInputs.at(-1) as { onUserTakeover: () => void }).onUserTakeover+ act(action)+ expect(current).toHaveBeenCalledOnce()+ expect(first).not.toHaveBeenCalled()+ })+it("uses whole Query activity to pause both pagination directions", () => {const onLoadOlder = vi.fn(), onLoadNewer = vi.fn()rtlRender(React.createElement(Probe, { value: props({ isFetching: true, hasMore: true, hasMoreNewer: true, onLoadOlder, onLoadNewer }) }))diff --git a/src/web/src/components/community/messages/message-list-controller.ts b/src/web/src/components/community/messages/message-list-controller.tsindex 068b2b615..e03b70ac0 100644--- a/src/web/src/components/community/messages/message-list-controller.ts+++ b/src/web/src/components/community/messages/message-list-controller.ts@@ -24,6 +24,7 @@ export function useMessageListController({active,positioningActive,initialScrollReady,+ preserveInitialPresentation,hasMore,hasMoreNewer,isFetching,@@ -38,6 +39,7 @@ export function useMessageListController({unreadCount,onScrollRoot,onScrollTargetConsumed,+ onUserTakeover,}: ResolvedMessageListProps) {const [jumpRevision, setJumpRevision] = useAtom(useCreateAtom(0))const [jumped, setJumped] = useAtom(useCreateAtom<string | null>(null))@@ -108,6 +110,8 @@ export function useMessageListController({items,newDividerBefore,initialScrollReady,+ ...(preserveInitialPresentation ? { preserveInitialPresentation } : {}),+ ...(onUserTakeover ? { onUserTakeover } : {}),scrollToMessageId,initialPositionMessageId,positionEntry,diff --git a/src/web/src/components/community/messages/message-list-types.ts b/src/web/src/components/community/messages/message-list-types.tsindex 168603f9c..d053a7813 100644--- a/src/web/src/components/community/messages/message-list-types.ts+++ b/src/web/src/components/community/messages/message-list-types.ts@@ -10,6 +10,7 @@ export type MessageListProps = {messages: Msg[]loading?: booleaninitialLoadError?: Error | null+ targetLoadError?: Error | nullretryingInitialLoad?: booleanonRetryInitialLoad?: () => voidpinnedIds?: Set<string>@@ -45,7 +46,9 @@ export type MessageListProps = {onScrollRoot?: (el: HTMLDivElement | null) => voidviewerUserId?: stringinitialScrollReady?: boolean+ preserveInitialPresentation?: booleanonScrollTargetConsumed?: (id: string) => void+ onUserTakeover?: () => voidhasMore?: booleanhistoryStartKnown?: booleanisFetching?: booleandiff --git a/src/web/src/components/community/messages/message-list-view.tsx b/src/web/src/components/community/messages/message-list-view.tsxindex 50d7dca77..b5c722920 100644--- a/src/web/src/components/community/messages/message-list-view.tsx+++ b/src/web/src/components/community/messages/message-list-view.tsx@@ -1,6 +1,7 @@import type { ReactNode } from "react"import { createPortal } from "react-dom"import { ConversationResolutionErrorFrame } from "../channels/conversation-resolution-error-frame"+import { Button } from "@/components/ui/button"import { Skeleton } from "@/components/ui/skeleton"import { tid } from "@/lib/community/testids"import { CONVERSATION_TAIL_SPACE_PX } from "@/lib/community/conversation-layout"@@ -48,6 +49,12 @@ export function renderMessageListView(onClose={controller.closeShare}/>)}+ {props.targetLoadError && controller.initialPosition.contentVisible && <div role="alert" className="flex items-center justify-between gap-2 px-4 py-2 text-sm">+ <span>Couldn’t load the requested messages</span>+ <Button variant="ghost" className="h-11 sm:h-9" disabled={props.retryingInitialLoad} onClick={props.onRetryInitialLoad}>+ {props.retryingInitialLoad ? "Retrying…" : "Retry"}+ </Button>+ </div>}<div data-message-scroller-boundary className="relative isolate min-h-0 flex-1"><divref={controller.scrollRef}diff --git a/src/web/src/hooks/community/conversation-cache-reveal.dom.test.tsx b/src/web/src/hooks/community/conversation-cache-reveal.dom.test.tsxnew file mode 100644index 000000000..910c08299--- /dev/null+++ b/src/web/src/hooks/community/conversation-cache-reveal.dom.test.tsx@@ -0,0 +1,249 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest"+import { act, fireEvent, render } from "@/test/react-dom-harness"+import { CommunityTestProvider } from "@/test/community-owner-fixture"+import { createCommunityQueryOwner } from "@/test/community-query-owner"+import { conversationEntryFixture, dmConversationEntryFixture, seedConversationEntry } from "@/test/conversation-entry-fixtures"+import { ingestReadStateSnapshot } from "@/lib/community-db/sync"+import { communityKeys } from "@/lib/query-keys"+import { MessageList } from "@/components/community/messages/message-list"+import { resolveMessageReadProjection } from "@/lib/community/message-read-projection"+import { useDmMessages, useMessages } from "./use-messages"+import { installMessageScrollFixture, restoreMessageScrollFixture, resize, scrollFixture } from "@/test/message-scroll-fixture"++const load = vi.hoisted(() => vi.fn())+vi.mock("@/lib/api/client", async original => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: load }))+beforeEach(() => { installMessageScrollFixture(); load.mockReset() })+afterEach(restoreMessageScrollFixture)+const kinds = ["text", "text-thread", "forum-post", "dm"] as const++it.each(kinds.flatMap(kind => [+ { takeover: true, repairFailure: false }, { takeover: false, repairFailure: false }, { takeover: true, repairFailure: true },+].map(mode => ({ kind, ...mode }))))(+ "preserves the actual $kind reader through Retry recovery with takeover=$takeover, repairFailure=$repairFailure",+ async ({ kind, takeover, repairFailure }) => {+ scrollFixture.width = 1280+ const owner = await createCommunityQueryOwner("viewer", { defaultOptions: { queries: { retry: false, staleTime: Infinity } } })+ const packet = kind === "dm" ? dmConversationEntryFixture() : conversationEntryFixture()+ if (kind === "text-thread" || kind === "forum-post") {+ packet.channel = { ...packet.channel, type: "thread", parentChannelId: "parent", parentMessageId: "opener" }+ packet.parent = { ...packet.channel, id: "parent", type: kind === "forum-post" ? "forum" : "text", parentChannelId: null, parentMessageId: null }+ packet.surfaceReceipt = { channelId: "c1", surfaceKind: "thread" }+ }+ const rows = Array.from({ length: 80 }, (_, index) => ({ ...packet.messages[0], id: `m${index + 1}`, seq: index + 1,+ createdAt: new Date(Date.UTC(2026, 9, 1, 0, 0, index + 1)).toISOString() }))+ packet.messages = rows.slice(0, 35)+ packet.readState = { ...packet.readState, lastReadMessageId: "m10", lastReadSeq: 10 }+ packet.selection = { reason: "read_pointer", anchorMessageId: "m10" }+ packet.page = { olderCursor: null, newerCursor: `${rows[34].createdAt}|m35`, hasMoreOlder: false, hasMoreNewer: true, latestSeq: 80 }+ await seedConversationEntry(owner.client, packet)+ const read = { ...packet.readState, lastReadMessageId: "m60", lastReadSeq: 60, lastReadAt: rows[59].createdAt }+ ingestReadStateSnapshot(owner.registry, { revision: 5, readStates: [read] })+ owner.client.removeQueries({ queryKey: communityKeys.conversationEntries("c1") })+ let reject!: (reason: Error) => void+ load.mockReturnValue(new Promise((_, no) => { reject = no }))+ let feed!: ReturnType<typeof useMessages>+ function Probe() {+ const channel = useMessages(kind === "dm" ? null : "c1", { serverId: "s1" })+ const dm = useDmMessages(kind === "dm" ? "c1" : null)+ feed = kind === "dm" ? dm : channel+ const projection = resolveMessageReadProjection({ messages: feed.messages, lastReadMessageId: feed.readSnapshot?.lastReadMessageId ?? null,+ viewerUserId: "viewer", anchorReconciled: feed.anchorReconciled })+ return <MessageList channel="Channel" variant={kind === "dm" ? "dm" : "channel"} messages={feed.messages}+ loading={feed.isLoading} initialLoadError={feed.initialLoadError} targetLoadError={feed.targetLoadError}+ initialScrollReady={feed.initialDisplayReady} preserveInitialPresentation={feed.preserveInitialPresentation} positionScope={feed.positionScope} positionEntry={feed.positionEntry}+ positionDataState={feed.positionDataState} targetPositionDataState={feed.targetPositionDataState} messageWindow={feed.messageWindow}+ newDividerBefore={projection.newDividerBefore} hasMore={feed.hasMoreOlder} hasMoreNewer={feed.hasMoreNewer}+ onUserTakeover={feed.onUserTakeover} onRetryInitialLoad={feed.retryInitialLoad} retryingInitialLoad={feed.retryingInitialLoad} onOpenThread={() => {}} />+ }+ const view = render(<CommunityTestProvider {...owner}><Probe /></CommunityTestProvider>)+ try {+ resize()+ const root = view.getByTestId("community-message-scroller")+ expect(root).toHaveAttribute("aria-busy", "false")+ expect(root.querySelector("[data-read-position-ready]")).toHaveAttribute("data-read-position-ready", "false")+ expect(root).toHaveAttribute("data-pagination-enabled", "false")+ await act(async () => { reject(new Error("held entry failed")); await vi.advanceTimersByTimeAsync(2000) })+ resize()+ let release!: (value: typeof packet) => void+ const retry = new Promise<typeof packet>(resolve => { release = resolve })+ const repairPage = { ...packet.page, profiles: packet.profiles, messages: packet.messages }+ let failRepair = repairFailure+ load.mockImplementation((url: string) => url.includes("entry=1") ? retry+ : failRepair ? Promise.reject(new Error("owned window repair failed")) : Promise.resolve(repairPage))+ fireEvent.click(view.getByRole("button", { name: "Retry" }))+ await act(async () => { await vi.advanceTimersByTimeAsync(0) })+ resize()+ expect(root).toHaveAttribute("aria-busy", "false")+ expect(root).toHaveAttribute("data-pagination-enabled", "false")+ if (takeover) {+ fireEvent.wheel(root, { deltaY: -300 })+ act(() => root.scrollTo({ top: root.scrollTop - 300 }))+ resize()+ }+ const viewport = root.getBoundingClientRect()+ const reader = Array.from(root.querySelectorAll<HTMLElement>("[data-msg-id]")).find(row => row.getBoundingClientRect().bottom > viewport.top + 1)!+ const readerId = reader.dataset.msgId!+ const offset = reader.getBoundingClientRect().top - viewport.top+ expect(Number(readerId.slice(1))).toBeLessThan(35)+ const fresh = { ...packet, messages: rows.slice(34), readState: read, readStateRevision: 5,+ selection: { reason: "read_pointer" as const, anchorMessageId: "m60" },+ page: { olderCursor: `${rows[34].createdAt}|m35`, newerCursor: null, hasMoreOlder: true, hasMoreNewer: false, latestSeq: 80 } }+ await act(async () => { release(fresh); await vi.advanceTimersByTimeAsync(0) })+ resize()+ expect(view.getByTestId("community-message-scroller")).toBe(root)+ expect(root).toHaveAttribute("aria-busy", "false")+ if (repairFailure) expect(view.getByRole("alert")).toHaveTextContent("Couldn’t load the requested messages")+ else expect(view.queryByRole("alert")).toBeNull()+ if (takeover) {+ expect(feed.messages.map(row => row.id)).toContain(readerId)+ expect(root.querySelector(`[data-msg-id="${readerId}"]`)).toBe(reader)+ expect(Math.abs(reader.getBoundingClientRect().top - root.getBoundingClientRect().top - offset)).toBeLessThanOrEqual(1)+ } else {+ expect(feed.messages.map(row => row.id)).toEqual(rows.slice(34).map(row => row.id))+ const divider = root.querySelector<HTMLElement>("[data-new-divider]")!.getBoundingClientRect()+ expect(divider.bottom).toBeGreaterThan(viewport.top)+ expect(divider.top).toBeLessThan(viewport.bottom)+ }+ if (repairFailure) {+ expect(root).toHaveAttribute("data-pagination-enabled", "false")+ expect(root.querySelector("[data-read-position-ready]")).toHaveAttribute("data-read-position-ready", "false")+ fireEvent.click(view.getByRole("button", { name: "Retry" }))+ await act(async () => { await vi.advanceTimersByTimeAsync(0) })+ resize()+ expect(view.getByRole("alert")).toHaveTextContent("Couldn’t load the requested messages")+ expect(root).toHaveAttribute("aria-busy", "false")+ expect(feed.messages.map(row => row.id)).toContain(readerId)+ failRepair = false+ fireEvent.click(view.getByRole("button", { name: "Retry" }))+ await act(async () => { await vi.advanceTimersByTimeAsync(0) })+ resize()+ expect(view.queryByRole("alert")).toBeNull()+ expect(view.getByTestId("community-message-scroller")).toBe(root)+ expect(root).toHaveAttribute("aria-busy", "false")+ expect(feed.messages.map(row => row.id)).toEqual(rows.map(row => row.id))+ }+ expect(feed.readSnapshotFetching).toBe(false)+ expect(feed.readSnapshot?.lastReadSeq).toBe(60)+ expect(root.querySelector("[data-read-position-ready]")).toHaveAttribute("data-read-position-ready", "true")+ expect(root).toHaveAttribute("data-pagination-enabled", "true")+ } finally { view.unmount(); owner.client.clear() }+ },+)++it.each(kinds.flatMap(kind => (["success", "offline", "timeout"] as const).map(result => ({ kind, result }))))(+ "reveals complete $kind cache through the real list during missing target work and $result",+ async ({ kind, result }) => {+ const owner = await createCommunityQueryOwner("viewer", { defaultOptions: { queries: { retry: false, staleTime: Infinity } } })+ const packet = kind === "dm" ? dmConversationEntryFixture() : conversationEntryFixture()+ if (kind === "text-thread" || kind === "forum-post") {+ packet.channel = { ...packet.channel, type: "thread", parentChannelId: "parent", parentMessageId: "opener" }+ packet.parent = { ...packet.channel, id: "parent", type: kind === "forum-post" ? "forum" : "text", parentChannelId: null, parentMessageId: null }+ packet.surfaceReceipt = { channelId: "c1", surfaceKind: "thread" }+ }+ packet.messages = Array.from({ length: 42 }, (_, index) => ({ ...packet.messages[0], id: `m${index + 1}`, seq: index + 1 }))+ packet.readState = { ...packet.readState, lastReadMessageId: "m30", lastReadSeq: 30 }+ packet.selection = { reason: "read_pointer", anchorMessageId: "m30" }+ packet.page = { olderCursor: null, newerCursor: "newer", hasMoreOlder: false, hasMoreNewer: true, latestSeq: 80 }+ await seedConversationEntry(owner.client, packet)+ if (kind === "dm") ingestReadStateSnapshot(owner.registry, { revision: 5, readStates: [{ ...packet.readState, lastReadMessageId: "m60", lastReadSeq: 60, lastReadAt: packet.messages[0].createdAt }] })+ owner.client.removeQueries({ queryKey: communityKeys.conversationEntries("c1") })+ let resolve!: (value: typeof packet) => void, reject!: (error: Error) => void+ load.mockReturnValue(new Promise<typeof packet>((yes, no) => { resolve = yes; reject = no }))+ let feed!: ReturnType<typeof useMessages>+ function Probe() {+ const channel = useMessages(kind === "dm" ? null : "c1", { serverId: "s1", anchorMessageId: "m60" })+ const dm = useDmMessages(kind === "dm" ? "c1" : null)+ feed = kind === "dm" ? dm : channel+ const projection = resolveMessageReadProjection({ messages: feed.messages, lastReadMessageId: feed.readSnapshot?.lastReadMessageId ?? null, viewerUserId: "viewer", anchorReconciled: feed.anchorReconciled })+ return <MessageList channel="Channel" variant={kind === "dm" ? "dm" : "channel"} messages={feed.messages}+ loading={feed.isLoading} initialLoadError={feed.initialLoadError} targetLoadError={feed.targetLoadError}+ initialScrollReady={feed.initialDisplayReady} preserveInitialPresentation={feed.preserveInitialPresentation} positionScope={feed.positionScope} positionEntry={feed.positionEntry}+ positionDataState={feed.positionDataState} targetPositionDataState={feed.targetPositionDataState} messageWindow={feed.messageWindow}+ newDividerBefore={projection.newDividerBefore} scrollToMessageId={kind === "dm" ? undefined : "m60"} hasMoreNewer={feed.hasMoreNewer}+ onRetryInitialLoad={feed.retryInitialLoad} retryingInitialLoad={feed.retryingInitialLoad} onOpenThread={() => {}} />+ }+ const view = render(<CommunityTestProvider {...owner}><Probe /></CommunityTestProvider>)+ try {+ resize()+ const root = view.getByTestId("community-message-scroller")+ expect(feed.initialDisplayReady).toBe(true)+ expect(feed.initialPositionKnown).toBe(false)+ expect(feed.readSnapshotFetching).toBe(true)+ expect(feed.targetPositionDataState).toBe(kind === "dm" ? "ready" : "pending")+ expect(feed.positionDataState).toBe("pending")+ expect(root).toHaveAttribute("aria-busy", "false")+ expect(root.querySelector("[data-message-list-content]")).toHaveAttribute("aria-hidden", "false")+ expect(root.querySelector("[data-read-position-ready]")).toHaveAttribute("data-read-position-ready", "false")+ expect(root).toHaveAttribute("data-pagination-enabled", "false")+ expect(root.querySelectorAll("[data-msg-id]").length).toBeGreaterThan(0)+ expect(load.mock.calls.some(([path]) => path.endsWith(kind === "dm" ? "entry=1" : "entry=1&anchor=m60"))).toBe(true)+ expect(load.mock.calls.some(([path]) => path.endsWith("/read"))).toBe(false)+ const fresh = { ...packet, selection: { reason: kind === "dm" ? "read_pointer" as const : "explicit_anchor" as const, anchorMessageId: "m60" },+ ...(kind === "dm" ? { readState: { ...packet.readState, lastReadMessageId: "m60", lastReadSeq: 60 }, readStateRevision: 5 } : {}),+ messages: Array.from({ length: 22 }, (_, index) => ({ ...packet.messages[0], id: `m${index + 59}`, seq: index + 59 })),+ page: { ...packet.page, hasMoreOlder: true, hasMoreNewer: false, newerCursor: null } }+ await act(async () => {+ if (result === "success") resolve(fresh)+ else if (result === "offline") reject(new Error("offline"))+ await vi.advanceTimersByTimeAsync(result === "timeout" ? 15000 : result === "offline" ? 2000 : 0)+ })+ resize()+ expect(view.getByTestId("community-message-scroller")).toBe(root)+ expect(root).toHaveAttribute("aria-busy", "false")+ expect(root.querySelector("[data-message-list-content]")).toHaveAttribute("aria-hidden", "false")+ if (result === "success") {+ expect(feed.initialPositionKnown).toBe(true)+ expect(feed.messages.some(message => message.id === "m60")).toBe(true)+ } else {+ expect(feed.messages).toHaveLength(42)+ expect(feed.targetPositionDataState).toBe("error")+ expect(view.getByRole("alert")).toHaveTextContent("Couldn’t load the requested messages")+ let resume!: (value: typeof fresh) => void+ load.mockReturnValue(new Promise(yes => { resume = yes }))+ fireEvent.click(view.getByRole("button", { name: "Retry" }))+ await act(async () => { await vi.advanceTimersByTimeAsync(0) })+ resize()+ expect(view.getByTestId("community-message-scroller")).toBe(root)+ expect(root).toHaveAttribute("aria-busy", "false")+ expect(root.querySelector("[data-message-list-content]")).toHaveAttribute("aria-hidden", "false")+ await act(async () => { resume(fresh); await vi.advanceTimersByTimeAsync(0) })+ resize()+ expect(feed.initialPositionKnown).toBe(true)+ expect(view.queryByRole("alert")).toBeNull()+ }+ } finally { view.unmount(); owner.client.clear() }+ },+)++it.each(kinds)("keeps $0 display qualification separate from an unavailable canonical read snapshot", async kind => {+ const owner = await createCommunityQueryOwner()+ const packet = kind === "dm" ? dmConversationEntryFixture() : conversationEntryFixture()+ if (kind === "text-thread" || kind === "forum-post") {+ packet.channel = { ...packet.channel, type: "thread", parentChannelId: "parent", parentMessageId: "opener" }+ packet.parent = { ...packet.channel, id: "parent", type: kind === "forum-post" ? "forum" : "text", parentChannelId: null, parentMessageId: null }+ packet.surfaceReceipt = { channelId: "c1", surfaceKind: "thread" }+ }+ await seedConversationEntry(owner.client, packet)+ owner.client.removeQueries({ queryKey: communityKeys.conversationEntries("c1") })+ owner.registry.collections.readStates.utils.writeDelete("c1")+ if (owner.registry.collections.readStateClock.has("account")) owner.registry.collections.readStateClock.utils.writeDelete("account")+ load.mockReturnValue(new Promise(() => {}))+ const { useChannelMetadata } = await import("./use-channel-metadata")+ const { renderHook } = await import("@/test/react-dom-harness")+ const view = renderHook(() => {+ const metadata = useChannelMetadata(packet.channel.serverId, "c1")+ const channel = useMessages(kind === "dm" ? null : "c1", { serverId: "s1" })+ const dm = useDmMessages(kind === "dm" ? "c1" : null)+ return { metadata, feed: kind === "dm" ? dm : channel }+ }, { wrapper: ({ children }) => <CommunityTestProvider {...owner}>{children}</CommunityTestProvider> })+ try {+ resize()+ expect(view.result.current.metadata.status).toBe("readable")+ expect(view.result.current.metadata.windowReady).toBe(false)+ expect(view.result.current.feed.initialDisplayReady).toBe(true)+ expect(view.result.current.feed.initialPositionKnown).toBe(false)+ expect(view.result.current.feed.readSnapshotFetching).toBe(true)+ expect(view.result.current.feed.positionDataState).toBe("pending")+ expect(view.result.current.feed.navigationBlocked).toBe(true)+ } finally { view.unmount(); owner.client.clear() }+})diff --git a/src/web/src/hooks/community/use-channel-metadata.ts b/src/web/src/hooks/community/use-channel-metadata.tsindex 7b392a48d..3ff1096b6 100644--- a/src/web/src/hooks/community/use-channel-metadata.ts+++ b/src/web/src/hooks/community/use-channel-metadata.ts@@ -27,7 +27,7 @@ export function useChannelMetadata(serverId: string | null, channelId: string |})const identityKnown = canRead && !!scope && !!canonical && canonical.id === channelId && canonical.serverId === serverId && !canonical.pendingconst error = entry.verificationError- const status: ChannelReadingStatus = !channelId ? "no-target" : denied ? "denied" : windowReady ? "readable"+ const status: ChannelReadingStatus = !channelId ? "no-target" : denied ? "denied" : canRead && entry.displayWindow !== undefined ? "readable": error || entry.verificationFailed ? "retryable-error" : query.isFetching || entry.verificationPending ? "pending" : "unresolved"const data = useMemo(() => {if (!identityKnown || !canonical || !scope) return undefineddiff --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 f1e74bc24..a3956a94e 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@@ -51,6 +51,44 @@ async function setup() {}describe("conversation entry selection", () => {+ it("keeps takeover on its original entry and retires that selection on a fresh navigation", async () => {+ const { client, wrapper: Owner, publish, registry } = await setup()+ const old = fixture()+ const original = publish(old)+ const fresh = fixture()+ fresh.messages = [{ ...fresh.messages[0], id: "m2", seq: 2, createdAt: "2026-10-01T00:00:02.000Z" }]+ fresh.readState = { ...fresh.readState, lastReadMessageId: "m2", lastReadSeq: 2, lastReadAt: fresh.messages[0].createdAt }+ fresh.readStateRevision = 5+ fresh.selection = { reason: "read_pointer", anchorMessageId: "m2" }+ ingestReadStateSnapshot(registry, { revision: 5, readStates: [{ ...fresh.readState, lastReadAt: fresh.messages[0].createdAt }] })+ client.removeQueries({ queryKey: communityKeys.conversationEntries("c1") })+ const held = deferred<typeof fresh>()+ load.mockImplementation((url: string) => url.includes("entry=1") ? held.promise+ : Promise.resolve({ ...old.page, messages: old.messages, profiles: old.profiles }))+ const navigation = { entryIntent: { href: "/c/channels/s1/c1" } }+ function Wrapper({ children }: PropsWithChildren) {+ return createElement(Owner, null, createElement(CommunityRouteContext, { value: { navigation } as never }, children))+ }+ const hook = renderHook(() => useConversationEntry(target), { wrapper: Wrapper })+ const retained = hook.result.current.window+ const oldTakeover = hook.result.current.retainWindow+ act(() => { oldTakeover(); oldTakeover() })+ await act(async () => held.resolve(fresh))+ await waitFor(() => expect(hook.result.current.targetCovered).toBe(true))+ expect(hook.result.current.window).toBe(retained)+ expect(hook.result.current.window?.key).toEqual(original.windowKey)+ navigation.entryIntent = { href: "/c/channels/s1/c1" }+ hook.rerender()+ expect(hook.result.current.window?.initial).toEqual({ mode: "anchor", anchor: "m2" })+ act(oldTakeover)+ expect(hook.result.current.window?.initial).toEqual({ mode: "anchor", anchor: "m2" })+ await act(async () => registry.runtime.ws.actions.revokeChannelAccess("s1", "c1"))+ act(() => hook.result.current.retainWindow())+ expect(hook.result.current.window).toBeNull()+ expect(hook.result.current.canRead).toBe(false)+ hook.unmount()+ })+it("ignores actual reconnect helper cache keys when the original entry hook consumes a complete warm window", async () => {const { client, wrapper, publish } = await setup()const value = fixture()@@ -554,7 +592,7 @@ describe("conversation entry return during accepted reading", () => {const props = { channel: "Channel", messages: feed.messages,loading: feed.isLoading, initialLoadError: feed.initialLoadError,newDividerBefore: projection.newDividerBefore, scrollToMessageId,- initialScrollReady: feed.initialPositionKnown,+ initialScrollReady: feed.initialDisplayReady,positionDataState: feed.positionDataState, positionEntry: feed.positionEntry, messageWindow: feed.messageWindow,hasMore: feed.hasMoreOlder, hasMoreNewer: feed.hasMoreNewer,historyStartKnown: feed.historyStartKnown,@@ -1014,7 +1052,7 @@ describe("conversation entry return during accepted reading", () => {} finally { view.unmount(); releaseReadSurface(owner.lease); await owner.finish() }})- it("retains the actual cached history boundary while an uncovered newer target keeps first admission masked", async () => {+ it("reveals the actual cached history boundary while an uncovered newer target is pending", async () => {const owner = await readingOwner()const entryRead = deferred<ReturnType<typeof fixture>>()const previousKey = communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "m30" })@@ -1050,12 +1088,13 @@ describe("conversation entry return during accepted reading", () => {expect(owner.client.getQueryData(previousKey)).toBe(previousWindow)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.feed.initialDisplayReady).toBe(true)+ expect(view.latest.controller.initialPosition.contentVisible).toBe(true)+ expect(view.latest.controller.initialPosition.showSkeleton).toBe(false)expect(view.latest.controller.readPositionReady).toBe(false)expect(view.latest.feed.hasMoreOlder).toBe(false)expect(view.latest.feed.historyStartKnown).toBe(true)- expect(view.root.textContent).toContain("Beginning of the channel")+ expect(view.latest.controller.items.some(item => item.kind === "leading")).toBe(true)await act(async () => entryRead.resolve(fresh))resize()expect(view.latest.feed.initialPositionKnown).toBe(true)diff --git a/src/web/src/hooks/community/use-conversation-entry.ts b/src/web/src/hooks/community/use-conversation-entry.tsindex c812468b2..57fbf10d4 100644--- a/src/web/src/hooks/community/use-conversation-entry.ts+++ b/src/web/src/hooks/community/use-conversation-entry.ts@@ -210,9 +210,9 @@ export function useConversationEntry(target: ConversationEntryTarget | null) {const covered = cachedScope ? findConversationEntryWindow(client,localPosition && pointer && pointer.lastReadSeq >= localPosition.seq ? canonicalInput : input, cachedScope, pointer) : undefinedconst window = covered ?? (cachedScope ? findConversationDisplayWindow(client, input, cachedScope) : undefined)- return { intent, knownRevision: pointer?.observedRevision ?? -1, state: createStore<{ snapshot: CommunityReadStateResource | null; window: EntryWindow | null; covered: boolean }>({+ return { intent, knownRevision: pointer?.observedRevision ?? -1, state: createStore<{ snapshot: CommunityReadStateResource | null; window: EntryWindow | null; covered: boolean; retained: boolean }>({snapshot: pointer ?? null,- window: window ?? null, covered: !!covered,+ window: window ?? null, covered: !!covered, retained: false,}) }}, [client, cachedResource, scope, input, canonicalInput, localPosition, intent])const selected = useSelector(entry.state, (state) => state)@@ -231,13 +231,17 @@ export function useConversationEntry(target: ConversationEntryTarget | null) {const candidate = (!selected.covered || needsCanonicalWindow) && candidateScope? findConversationEntryWindow(client, candidateTarget, candidateScope, candidatePointer) : undefinedconst display = !selected.window && candidateScope ? findConversationDisplayWindow(client, input, candidateScope) : undefined- const window = canRead ? candidate ?? selected.window ?? display ?? null : null+ const window = canRead ? (selected.retained ? selected.window : candidate) ?? selected.window ?? candidate ?? display ?? null : nullconst snapshot = window ? (needsCanonicalWindow || !selected.covered ? candidatePointer ?? selected.snapshot : selected.snapshot) ?? null : nullconst targetCovered = canRead && (needsCanonicalWindow ? !!candidate : selected.covered || !!candidate)useLayoutEffect(() => {if (!window || !snapshot || selected.window === window && selected.snapshot === snapshot && selected.covered === targetCovered) return- entry.state.setState(() => ({ window, snapshot, covered: targetCovered }))+ entry.state.setState(current => ({ ...current, window, snapshot, covered: targetCovered }))}, [window, snapshot, targetCovered, entry, selected])+ const retainWindow = useCallback(() => {+ if (!canRead || !window) return+ entry.state.setState(current => current.retained ? current : { ...current, window, retained: true })+ }, [canRead, entry, window])useEffect(() => {if (!presented || query.isFetching || !canRead || !selected.covered || !window || !resource || hashKey(window.key) === hashKey(resource.windowKey)) returnif (client.getQueryData(entryOptions.queryKey) !== resource) return@@ -260,6 +264,6 @@ export function useConversationEntry(target: ConversationEntryTarget | null) {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,+ retry, retrying: activeQuery.isFetching, retainWindow,}}diff --git a/src/web/src/hooks/community/use-forum-feed.convergence.dom.test.ts b/src/web/src/hooks/community/use-forum-feed.convergence.dom.test.tsindex cf5c0a7f0..d168f16e1 100644--- a/src/web/src/hooks/community/use-forum-feed.convergence.dom.test.ts+++ b/src/web/src/hooks/community/use-forum-feed.convergence.dom.test.ts@@ -21,10 +21,17 @@ const useForumTagsMock = vi.fn(() => ({vi.mock("@/lib/api/client", () => ({apiFetch: (...args: unknown[]) => apiFetchMock(...args),}))-vi.mock("./use-conversation-entry", async (original) => ({- ...await original<typeof import("./use-conversation-entry")>(),- useConversationResource: () => ({ canRead: true }),-}))+vi.mock("./use-conversation-entry", async original => {+ const actual = await original<typeof import("./use-conversation-entry")>()+ const { useQueryClient } = await import("@tanstack/react-query")+ const { findConversationDisplayWindow, getQualifiedConversationScope, currentConversationReadState } = await import("@/lib/community/conversation-entry")+ return { ...actual, useConversationResource: (target: Parameters<typeof getQualifiedConversationScope>[1]) => {+ const client = useQueryClient()+ const scope = getQualifiedConversationScope(client, target)+ const displayWindow = scope && findConversationDisplayWindow(client, target, scope)+ return { canRead: !!scope, displayWindow, windowReady: !!displayWindow && currentConversationReadState(client, target.channelId) !== undefined }+ } }+})vi.mock("./use-channel-panels", () => ({useForumTags: (...args: unknown[]) => useForumTagsMock(...args),}))diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.tsindex fec957d90..c2d86656c 100644--- a/src/web/src/hooks/community/use-forum-feed.ts+++ b/src/web/src/hooks/community/use-forum-feed.ts@@ -1,13 +1,14 @@"use client"import { useConversationPresentation } from "@/contexts/community/conversation-activity"-import { useCallback, useEffect, useMemo } from "react"+import { useCallback, useEffect, useMemo, useState } 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 CommunityThreadsRead } from "@alook/shared"import { apiFetch } from "@/lib/api/client"import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"-import { conversationReadRetryPolicy, withConversationReadDeadline } from "@/lib/community/conversation-read"+import { ConversationReadTimeoutError, conversationReadRetryPolicy, withConversationReadDeadline } from "@/lib/community/conversation-read"+import { conversationListScopeKey } from "@/lib/community/conversation-qualification"import { communityKeys } from "@/lib/query-keys"import { avatarInitial } from "@/lib/community/avatar"import { getCommunityDbRegistry } from "@/lib/community-db/collections"@@ -129,12 +130,36 @@ export function useForumFeed(serverId: string, channelId: string, options?: { roconst 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: presented && selectionReady && entry.canRead && !entry.verificationFetching, subscribed: selectionReady && entry.canRead, staleTime: 5_000,+ enabled: presented && selectionReady && entry.canRead && !entry.verificationFetching && (!entry.verificationFailed || entry.displayWindow !== undefined), 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 displayCandidate = selectionReady && entry.canRead && entry.displayWindow !== undefined+ const messageIds = useMemo(() => [...new Set(displayCandidate ? query.data?.pages.flatMap((page) => page.threads.flatMap((thread) => thread.openerMessageId ? [thread.openerMessageId] : [])) ?? [] : [])], [displayCandidate, 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 displayReady = displayCandidate && query.data !== undefined && messageIds.every(id => messages?.has(id))+ && query.data.pages.every(page => page.threads.every(thread => channels.has(thread.id) && thread.participantIds.every(id => profiles.has(id))))+ const posts = useMemo(() => displayReady ? mapForumFeedPages(query.data?.pages ?? [], messages ?? new Map(), channels, profiles, selectedTag) : [], [displayReady, query.data?.pages, messages, channels, profiles, selectedTag])+ const projectionScope = JSON.stringify([queryKey, entry.scope ? conversationListScopeKey({ proof: entry.scope.proof, tag: selectedTag }) : null])+ const hasWindowData = query.data !== undefined+ const [retryAttempt, setRetryAttempt] = useState(0)+ const [projectionFailure, setProjectionFailure] = useState<{ scope: string; attempt: number; error: Error } | null>(null)+ useEffect(() => {+ if (!presented || !entry.canRead || !hasWindowData || displayReady) return+ const controller = new AbortController()+ void withConversationReadDeadline(controller.signal, () => new Promise<never>(() => {})).catch(error => {+ if (!controller.signal.aborted && error instanceof ConversationReadTimeoutError) setProjectionFailure({ scope: projectionScope, attempt: retryAttempt, error })+ })+ return () => controller.abort()+ }, [presented, entry.canRead, hasWindowData, projectionScope, retryAttempt, displayReady])+ const initialLoadError = !displayReady && projectionFailure?.scope === projectionScope && projectionFailure?.attempt === retryAttempt+ ? projectionFailure.error : null+ const pending = !displayReady && !initialLoadError && !query.isError && !entry.verificationFailed && !entry.denied+ const refetchQuery = query.refetch+ const refetch = useCallback((...args: Parameters<typeof refetchQuery>) => {+ setRetryAttempt(attempt => attempt + 1)+ return refetchQuery(...args)+ }, [refetchQuery])const fetchNextPage = query.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 }+ const fetchOlder = useCallback(() => { if (presented && displayReady && entry.windowReady) void fetchNextPage({ cancelRefetch: false }) }, [fetchNextPage, presented, displayReady, entry.windowReady])+ return { ...query, refetch, isPending: pending, isLoading: pending, displayReady, initialLoadError,+ observation: { snapshot_source: entry.resource?.source ?? "unknown" as const, target_coverage: displayReady ? "covered" as const : "uncovered" as const, wait_reason: !entry.canRead ? "entry" as const : displayReady ? "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: displayReady && entry.windowReady && query.hasNextPage, isFetchingOlder: query.isFetchingNextPage, fetchOlder }}diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.tsindex a502f8b16..b9e34b3f0 100644--- a/src/web/src/hooks/community/use-messages.ts+++ b/src/web/src/hooks/community/use-messages.ts@@ -19,7 +19,7 @@ import { knownConversationLatestSeq, type findConversationEntryWindow } from "@/import type { Msg } from "@/lib/community/models/message"import type { MessagePositionState, MessageRequest, MessageRequestResult } from "@/lib/community/message-position"import { ConversationReadTimeoutError, withConversationReadDeadline } from "@/lib/community/conversation-read"-import { messageReconcileOptions } from "./community-ws/reconnect-messages"+import { isFailedMessageRepair, messageReconcileOptions, reconcileWindow } from "./community-ws/reconnect-messages"import type { ConversationListScope } from "@/lib/community/conversation-qualification"export { channelMessagesQueryFn } from "@/lib/community/message-window"@@ -120,10 +120,11 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undeficonst 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- useQuery({ ...(repairOptions?.queryFn ? repairOptions : messageReconcileOptions(client, {+ const repair = useQuery({ ...(repairOptions?.queryFn ? repairOptions : messageReconcileOptions(client, {kind: serverId === null ? "dm" : "channel", scopeId: channelId ?? "__none__", serverId: serverId ?? undefined,}, queryKey)),queryKey: repairKey, enabled: false, subscribed: enabled, notifyOnChangeProps: "all" })+ const repairQuery = client.getQueryCache().find({ queryKey: repairKey, exact: true })const originalQuery = client.getQueryCache().find({ queryKey, exact: true })const owner = useMemo(() => ({ present, retries, query: originalQuery, enabled: enabled && presented }), [present, retries, originalQuery, enabled, presented])const committed = useRef<typeof owner | null>(null)@@ -225,25 +226,31 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undeficonst projectionError = projectionFailed || missingCanonical && !!projectionFailure && projectionFailure.window === query.data&& projectionFailure.attempt === retrySelection.attempt && projectionFailure.viewKey === viewKey ? INITIAL_ENTRY_ERROR : nullconst initialLoadError = windowAvailable ? projectionError : retrySelection.error ?? error ?? (entry.failed ? INITIAL_ENTRY_ERROR : null)+ const repairError = repairQuery && isFailedMessageRepair(client, repairQuery) ? repair.error : null+ const targetLoadError = windowAvailable && !selection.window && !entry.isFetching && entry.error?.name !== "AbortError"+ ? (!entry.targetCovered ? entry.error : null) ?? repairError : nullconst loading = !!channelId && (windowAvailable ? projection.canonicalMessages === undefined : !initialLoadError && !entry.denied && !entry.anchorMissing)const entryWindow = entry.window, retryEntry = entry.retry, refetchWindow = query.refetchconst retryInitialLoad = useCallback(() => {- if (committed.current?.retries !== retries || retries.get().pending) return+ if (!channelId || committed.current?.retries !== retries || retries.get().pending) returnconst attempt = {}const token = channelId ? captureChannelMetadataToken(client, channelId) : nullconst current = () => committed.current?.retries === retries && retries.get().attempt === attempt && !!token && isChannelMetadataTokenCurrent(token)retries.setState(() => ({ attempt, pending: true, error: null }))- const request = entryWindow ? refetchWindow({ cancelRefetch: false }) : retryEntry()+ const request = repairError ? reconcileWindow(client, {+ kind: serverId === null ? "dm" : "channel", scopeId: channelId, serverId: serverId ?? undefined,+ }, queryKey).then(() => ({ error: null }), error => ({ error: error instanceof Error ? error : new Error("Could not repair this message window") }))+ : entryWindow && entry.targetCovered ? refetchWindow({ cancelRefetch: false }) : retryEntry()void request.then(result => {if (!current()) returnretries.setState(() => ({ attempt, pending: false, error: result.error }))})- }, [channelId, client, entryWindow, retryEntry, refetchWindow, retries])+ }, [channelId, client, entryWindow, entry.targetCovered, queryKey, repairError, retryEntry, refetchWindow, retries, serverId])const targetPositionDataState: MessagePositionState = retrySelection.pending ? "pending"- : initialLoadError || retrySelection.error || entry.denied || !windowAvailable && entry.anchorMissing && !entry.isFetching ? "error"+ : initialLoadError || targetLoadError || retrySelection.error || entry.denied || !windowAvailable && entry.anchorMissing && !entry.isFetching ? "error": !windowAvailable || loading || missingCanonical || !!anchorMessageId && !entry.targetCovered && !selection.window && !entry.anchorMissing ? "pending": messages.length ? "ready" : "empty"- const positionDataState: MessagePositionState = targetPositionDataState === "error" ? "error"+ const positionDataState: MessagePositionState = targetPositionDataState === "error" && !targetLoadError ? "error": !windowAvailable || !entry.snapshot || loading || readSnapshotFetching || retrySelection.pending ? "pending": messages.length ? "ready" : "empty"return {@@ -252,15 +259,18 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefimessages, canonicalMessages: canonicalBase, canonicalById,latestSeq, hasMoreOlder, hasMoreNewer, historyStartKnown, hasMore: hasMoreOlder,isLoading: loading, isPending: loading, isError: !!initialLoadError && !query.data,- error, initialLoadError, isFetching: entry.isFetching || query.isFetching,+ error, initialLoadError, targetLoadError, isFetching: entry.isFetching || query.isFetching,isFetchingOlder: query.isFetchingNextPage,isFetchingNewer: query.isFetchingPreviousPage || selection.pending,fetchOlder, fetchNewer, jumpToPresent, presentVersion: selection.version, presentRequest: selection.request,anchorReconciled: entry.targetCovered || !!selection.window,navigationBlocked: !entry.windowReady,readSnapshot: entry.snapshot, readSnapshotFetching,+ initialDisplayReady: windowAvailable && !loading && !missingCanonical && !initialLoadError,+ preserveInitialPresentation: !!retrySelection.attempt && windowAvailable,initialPositionKnown: windowAvailable && entry.snapshot !== null && !loading && !missingCanonical && !initialLoadError && !retrySelection.pending && !entry.initialPositionPending,initialPositionMessageId: entry.initialPositionMessageId, positionEntry, positionScope, positionDataState, targetPositionDataState, messageWindow: query.data,+ onUserTakeover: entry.retainWindow,retryInitialLoad, retryingInitialLoad: entry.isFetching || query.isFetching,entryCanRead: entry.canRead, entryDenied: entry.denied, entryAnchorMissing: entry.anchorMissing,}diff --git a/src/web/src/hooks/community/use-scroll-anchor.target-retirement.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.target-retirement.dom.test.tsindex 57f265c8e..8cb505603 100644--- a/src/web/src/hooks/community/use-scroll-anchor.target-retirement.dom.test.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.target-retirement.dom.test.ts@@ -1,6 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"-import { act } from "@/test/react-dom-harness"-import { installMessageScrollFixture, restoreMessageScrollFixture, message, mount, runFrames, scrollFixture } from "@/test/message-scroll-fixture"+import { act, fireEvent } from "@/test/react-dom-harness"+import { installMessageScrollFixture, restoreMessageScrollFixture, message, mount, resize, runFrames, scrollFixture } from "@/test/message-scroll-fixture"beforeEach(installMessageScrollFixture)afterEach(restoreMessageScrollFixture)@@ -74,7 +74,11 @@ describe("current ready-window target retirement through the native position own})act(() => vi.advanceTimersByTime(20000))expect(scrollFixture.frames.size).toBe(0)- expect(settled).not.toHaveBeenCalled()+ if (kind === "explicit") {+ expect(settled).toHaveBeenCalledExactlyOnceWith("success")+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ expect(scrollFixture.latest.paginationEnabled).toBe(false)+ } else expect(settled).not.toHaveBeenCalled()const index = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToIndex")h.update({ positionDataState: "ready", items: [...h.input.items, message("missing")] })expect(index).toHaveBeenCalledOnce()@@ -99,3 +103,46 @@ describe("current ready-window target retirement through the native position ownexpect(scrollFixture.latest.readPositionReady).toBe(false)})})+++it("reveals local cache while the explicit target is pending and retires that deferred target on real user takeover", () => {+ const settled = vi.fn(), cancelled = vi.fn(), positioned = vi.fn()+ const h = mount({ initialScrollReady: true, positionDataState: "pending", targetPositionDataState: "pending", scrollToMessageId: "later",+ onInitialPositionSettled: settled, onScrollTargetCancelled: cancelled, onScrollTargetPositioned: positioned })+ expect(settled).toHaveBeenCalledExactlyOnceWith("success")+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ expect(scrollFixture.latest.paginationEnabled).toBe(false)+ fireEvent.wheel(h.root, { deltaY: -20 })+ const offset = h.root.scrollTop+ expect(cancelled).toHaveBeenCalledExactlyOnceWith("later")+ h.update({ positionDataState: "ready", targetPositionDataState: "ready", items: [...h.input.items, message("later")] })+ expect(h.root.scrollTop).toBe(offset)+ expect(positioned).not.toHaveBeenCalled()+ expect(settled).toHaveBeenCalledOnce()+})++it("cancels a failed explicit target once while the local cache awaits its first viewport", () => {+ scrollFixture.height = 0+ const settled = vi.fn(), cancelled = vi.fn(), positioned = vi.fn()+ const h = mount({ initialScrollReady: true, positionDataState: "pending", targetPositionDataState: "error", scrollToMessageId: "later",+ onInitialPositionSettled: settled, onScrollTargetCancelled: cancelled, onScrollTargetPositioned: positioned }, false, undefined, undefined, 0)+ const native = scrollFixture.latest.virtualizer+ const end = vi.spyOn(native, "scrollToEnd"), index = vi.spyOn(native, "scrollToIndex")+ expect(cancelled).toHaveBeenCalledExactlyOnceWith("later")+ expect(settled).not.toHaveBeenCalled()+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ expect(scrollFixture.latest.paginationEnabled).toBe(false)+ scrollFixture.height = 500+ resize()+ expect(end).toHaveBeenCalledOnce()+ expect(native.isAtEnd(1)).toBe(true)+ expect(settled).toHaveBeenCalledExactlyOnceWith("success")+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ expect(scrollFixture.latest.paginationEnabled).toBe(false)+ expect(index).not.toHaveBeenCalled()+ h.update({ targetPositionDataState: "ready", items: [...h.input.items, message("later")] })+ expect(cancelled).toHaveBeenCalledExactlyOnceWith("later")+ expect(positioned).not.toHaveBeenCalled()+ expect(index).not.toHaveBeenCalled()+ expect(settled).toHaveBeenCalledOnce()+})diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.tsindex 93209a371..842b17367 100644--- a/src/web/src/hooks/community/use-scroll-anchor.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.ts@@ -86,6 +86,7 @@ export function useScrollAnchor({items,newDividerBefore,initialScrollReady,+ preserveInitialPresentation = false,positionDataState,targetPositionDataState,messageWindow,@@ -106,10 +107,12 @@ export function useScrollAnchor({localSubmitVersion,tailPaddingEnd = MESSAGE_RAIL_TAIL_PADDING_END_PX,onInitialPositionSettled,+ onUserTakeover,}: {items: FlatItem[]newDividerBefore?: stringinitialScrollReady: boolean+ preserveInitialPresentation?: booleanpositionDataState?: MessagePositionStatetargetPositionDataState?: MessagePositionStatemessageWindow?: object@@ -130,6 +133,7 @@ export function useScrollAnchor({localSubmitVersion?: numbertailPaddingEnd?: numberonInitialPositionSettled?: (outcome: PositionOutcome) => void+ onUserTakeover?: () => void}) {type Kind = "initial" | "late-new" | "target" | "present" | "idle"type Intent = {@@ -196,6 +200,7 @@ export function useScrollAnchor({const entryResolvedRef = useRef(false)const initialRetiredRef = useRef(false)const lateNewRef = useRef({ allowed: true, consumed: false })+ const localTargetRef = useRef<string | null>(null)const initialSettleFrameRef = useRef<number | null>(null)const semanticIntentRef = useRef<Intent | null>(null)const committedRowsRef = useRef<{@@ -214,6 +219,7 @@ export function useScrollAnchor({const onTargetPositionedRef = useRef(onScrollTargetPositioned)const onTargetCancelledRef = useRef(onScrollTargetCancelled)const settleCallbackRef = useRef(onInitialPositionSettled)+ const userTakeoverRef = useRef(onUserTakeover)useLayoutEffect(() => {if (entryActivationRef.current.entry !== positionEntry) entryActivationRef.current = { entry: positionEntry, seen: visible }else if (visible) entryActivationRef.current.seen = true@@ -222,9 +228,10 @@ export function useScrollAnchor({onTargetPositionedRef.current = onScrollTargetPositionedonTargetCancelledRef.current = onScrollTargetCancelledsettleCallbackRef.current = onInitialPositionSettled+ userTakeoverRef.current = onUserTakeovercontextRef.current = { dataState, targetDataState, initialScrollReady, messageWindow, isFetchingOlder, isFetchingNewer, visible, newDividerBefore }positionScopeRef.current = positionScope- }, [items, positionEntry, positionScope, initialScrollReady, newDividerBefore, onScrollTargetPositioned, onScrollTargetCancelled, onInitialPositionSettled, dataState, targetDataState, messageWindow, isFetchingOlder, isFetchingNewer, visible])+ }, [items, positionEntry, positionScope, initialScrollReady, newDividerBefore, onScrollTargetPositioned, onScrollTargetCancelled, onInitialPositionSettled, onUserTakeover, dataState, targetDataState, messageWindow, isFetchingOlder, isFetchingNewer, visible])const followSuspension = useCreateAtom(false)const [followSuspended, setFollowSuspended] = useAtom(followSuspension)const acceptedGeometryRef = useRef<Geometry | null>(null)@@ -311,11 +318,8 @@ export function useScrollAnchor({}, [])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 = false- const intent = semanticIntentRef.current- const cancelledTarget = positionKind.get() === "target"- ? intent?.notifyTarget ? intent.id- : !intent && positionedTargetRef.current !== targetIntentRef.current ? targetIntentRef.current : null- : null+ const cancelledTarget = (positionKind.get() === "target" || userHandover) && positionedTargetRef.current !== targetIntentRef.current+ ? targetIntentRef.current : nullconst wasReadable = positionKind.get() === "idle" && readReady.get()finishPosition(reason)claimPosition("idle")@@ -323,7 +327,10 @@ export function useScrollAnchor({retireInitialPosition()positionedTargetRef.current = targetIntentRef.currentif (cancelledTarget) onTargetCancelledRef.current?.(cancelledTarget)- if (userHandover) userInputRef.current.handover = true+ if (userHandover) {+ userInputRef.current.handover = true+ userTakeoverRef.current?.()+ }settlePresentation(outcome)scheduleGeometryRef.current()}, [claimPosition, finishPosition, positionKind, readReady, retireInitialPosition, setReadPositionReady, settlePresentation])@@ -654,34 +661,51 @@ export function useScrollAnchor({if (committedEntry === positionEntry) returnsetCommittedEntry(() => positionEntry)finishPosition("entry_changed")- claimPosition("initial")- entryResolvedRef.current = false- initialRetiredRef.current = false- setPositionOutcome("pending")+ const preserve = preserveInitialPresentation && presentation.get() !== "pending"+ claimPosition(preserve ? "idle" : "initial")+ entryResolvedRef.current = preserve+ initialRetiredRef.current = preserve+ if (!preserve) setPositionOutcome("pending")lateNewRef.current = { allowed: true, consumed: false }+ localTargetRef.current = nulltargetIntentRef.current = nullpositionedTargetRef.current = nullconsumedPresentVersionRef.current = presentVersion ?? 0consumedLocalSubmitVersionRef.current = localSubmitVersion ?? 0userInputRef.current.handover = falsesetFollowSuspended(false)- }, [claimPosition, committedEntry, finishPosition, localSubmitVersion, positionEntry, presentVersion, setFollowSuspended, setPositionOutcome])+ }, [claimPosition, committedEntry, finishPosition, localSubmitVersion, positionEntry, presentation, preserveInitialPresentation, presentVersion, setFollowSuspended, setPositionOutcome])useLayoutEffect(() => {const target = scrollToMessageId ?? nullif (!visible && target) return- if (targetIntentRef.current === target) return+ const changed = targetIntentRef.current !== target+ if (!changed && (!target || positionedTargetRef.current === target || positionKind.get() === "target")) returntargetIntentRef.current = targetif (!target) {if (positionKind.get() === "target") releasePosition()positionedTargetRef.current = nullreturn}+ lateNewRef.current.allowed = false+ if (changed) positionedTargetRef.current = null+ if (targetDataState === "pending") {+ if (changed && (entryResolvedRef.current || positionKind.get() !== "initial" || semanticIntentRef.current)) {+ claimPosition("target")+ retireInitialPosition()+ if (initialScrollReady) settlePresentation("cancelled")+ }+ return+ }+ if (targetDataState === "error" && initialScrollReady && presentation.get() === "pending") {+ positionedTargetRef.current = target+ onTargetCancelledRef.current?.(target)+ return+ }claimPosition("target")retireInitialPosition()- positionedTargetRef.current = nullif (targetDataState === "ready" && visible) startIntent("target", target, "auto", true)- }, [claimPosition, targetDataState, items.length, positionEntry, positionKind, releasePosition, retireInitialPosition, scrollToMessageId, startIntent, visible])+ }, [claimPosition, initialScrollReady, presentation, targetDataState, items.length, positionEntry, positionKind, releasePosition, retireInitialPosition, scrollToMessageId, settlePresentation, startIntent, visible])useLayoutEffect(() => {const intent = semanticIntentRef.current@@ -1150,6 +1174,16 @@ export function useScrollAnchor({}, [dataState, hasMessages, hasMoreNewer, isFetchingNewer, messageWindow, positionKind, presentVersion, releasePosition, requestRevision, retireInitialPosition, setFollowSuspended, setReadPositionReady, startIntent])const virtualItems = virtualizer.getVirtualItems()+ useLayoutEffect(() => {+ if (!initialPositionMessageId || localTargetRef.current || !lateNewRef.current.allowed || !entryResolvedRef.current+ || !visible || !initialScrollReady || !hasMessages+ || positionKind.get() !== "idle" && positionKind.get() !== "initial"+ || findMessageIndex(items, initialPositionMessageId) === null) return+ localTargetRef.current = initialPositionMessageId+ if (newDividerBefore) lateNewRef.current.consumed = true+ claimPosition("initial")+ startIntent("target", initialPositionMessageId)+ }, [claimPosition, hasMessages, initialPositionMessageId, initialScrollReady, items, newDividerBefore, positionEntry, positionKind, startIntent, visible])useLayoutEffect(() => {const late = lateNewRef.currentif (!late.allowed || late.consumed || !newDividerBefore || !entryResolvedRef.current@@ -1175,6 +1209,7 @@ export function useScrollAnchor({if (positionKind.get() !== "initial" || initialRetiredRef.current || !hasMessages) returnif (!entryResolvedRef.current) {entryResolvedRef.current = true+ localTargetRef.current = initialPositionMessageId ?? nullif (newDividerBefore) lateNewRef.current.consumed = truestartIntent(initialPositionMessageId ? "target" : newDividerBefore ? "unread" : "end", initialPositionMessageId ?? newDividerBefore ?? null)} else scheduleInitialPositionSettled()diff --git a/src/web/src/lib/community/conversation-entry.ts b/src/web/src/lib/community/conversation-entry.tsindex a2ce696b5..ce19a3773 100644--- a/src/web/src/lib/community/conversation-entry.ts+++ b/src/web/src/lib/community/conversation-entry.ts@@ -4,7 +4,7 @@ import { channelHref } from "./community-route"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 { COMMUNITY_CONTRACT_HEADER, CommunityConversationEntryReadSchema, CommunityResourceProfileSchema, type CommunityConversationEntryRead, type CommunityReadStateResource } from "@alook/shared"import { apiFetch, type ApiRequestOptions } from "@/lib/api/client"import { communityKeys } from "@/lib/query-keys"import { communityRequestOptions } from "./account-cache-lifecycle"@@ -156,8 +156,9 @@ function conversationDisplayWindows(client: QueryClient, target: ConversationEntif (!thread || typeof thread.id !== "string" || !thread.id) return trueconst child = byId.get(thread.id)const opener = thread.openerMessageId ? messages.get(thread.openerMessageId) : undefined- return !child || child.type !== "thread" || child.serverId !== channel.serverId || child.parentChannelId !== channel.id- || !!thread.openerMessageId && (!opener || opener.channelId !== channel.id)+ return !child || child.pending || child.type !== "thread" || child.serverId !== channel.serverId || child.parentChannelId !== channel.id+ || !opener || opener.channelId !== channel.id || child.parentMessageId !== opener.id+ || !Array.isArray(thread.participantIds) || thread.participantIds.some(id => !CommunityResourceProfileSchema.strip().safeParse(registry.collections.profiles.get(id)).success)}))) returnconst retained = feed.pages.flatMap(page => page.threads.flatMap(thread => {const child = byId.get(thread.id)