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): bind conversation positioning to qualified outcomes (#1040)
Gener3a09de852ca4
diff --git a/src/web/src/components/community/bots/model-field.tsx b/src/web/src/components/community/bots/model-field.tsxindex f804b74b9..6a33c25ab 100644--- a/src/web/src/components/community/bots/model-field.tsx+++ b/src/web/src/components/community/bots/model-field.tsx@@ -142,7 +142,7 @@ export function ModelField({</SelectTrigger><BotSelectMenuContentalignItemWithTrigger={false}- className="flex flex-col overflow-y-hidden [&>[role=listbox]]:flex [&>[role=listbox]]:min-h-0 [&>[role=listbox]]:flex-col"+ className="flex flex-col overflow-y-hidden *:[[role=listbox]]:flex *:[[role=listbox]]:min-h-0 *:[[role=listbox]]:flex-col">{discovery?.isPending && (<p role="status" className="flex shrink-0 items-center gap-2 px-2 py-2 text-xs text-muted-foreground">diff --git a/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.ts b/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.tsindex 2ecec3100..db5704680 100644--- a/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.ts+++ b/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.ts@@ -6,13 +6,13 @@ import { createCommunityQueryOwner } from "@/test/community-query-owner"import { CommunityTestProvider } from "@/test/community-owner-fixture"import { DmView } from "./dm-view"-const mocks = vi.hoisted(() => ({ api: vi.fn(), advance: vi.fn(), failed: true, breakpoint: "mobile" }))+const mocks = vi.hoisted(() => ({ api: vi.fn(), advance: vi.fn(), list: vi.fn(), positionEntry: null as object | null, failed: true, breakpoint: "mobile" }))vi.mock("@/lib/api/client", () => ({ apiFetch: mocks.api, toastApiError: vi.fn() }))vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => mocks.breakpoint }))vi.mock("@/contexts/community/current-user", () => ({ useCurrentUser: () => ({ id: "u_me", name: "Me", avatar: "M" }) }))vi.mock("@/hooks/community/use-dms", () => ({ useDms: () => ({ dms: ["dm_1", "dm_2"].map(id => ({ id, userId: "peer", name: "Peer", avatar: "P" })), isLoading: false, isFetching: false }) }))vi.mock("@/hooks/community/use-friends", () => ({ useFriends: () => ({ friends: [], blocked: [] }) }))-vi.mock("@/hooks/community/use-messages", () => ({ useDmMessages: () => ({ messages: mocks.failed ? [{ id: "failed", clientNonce: "retry_nonce", authorId: "u_me", type: "chat", content: "retry" }] : [], isLoading: false, isPending: false, isError: false, latestSeq: 0 }) }))+vi.mock("@/hooks/community/use-messages", () => ({ useDmMessages: () => ({ messages: mocks.failed ? [{ id: "failed", clientNonce: "retry_nonce", authorId: "u_me", type: "chat", content: "retry" }] : [], positionEntry: mocks.positionEntry, positionDataState: "ready", isLoading: false, isPending: false, isError: false, latestSeq: 0 }) }))vi.mock("@/hooks/community/use-channel-metadata", () => ({ useChannelMetadata: () => ({ canRead: true, status: "readable" }) }))vi.mock("@/hooks/community/use-dm-watermark", () => ({ useDmWatermark: vi.fn() }))vi.mock("@/hooks/community/use-channel-ref-directory", () => ({ useChannelRefDirectory: () => ({ directory: [], isResolved: true }) }))@@ -28,11 +28,31 @@ vi.mock("@/components/community/avatar", () => ({ Avatar: () => null }))vi.mock("@/components/community/messages/message-context-sheet", () => ({ MessageContextSheet: () => null }))vi.mock("@/components/community/messages/conversation-footer-shell", () => ({ ConversationFooterSlotProvider: ({ children }: PropsWithChildren) => children, ConversationFooterShell: ({ children }: PropsWithChildren) => children }))vi.mock("@/components/community/messages/composer", () => ({ ComposerSkeleton: () => null, Composer: ({ onAcceptSend }: { onAcceptSend: (text: string) => boolean }) => React.createElement("button", { onClick: () => onAcceptSend("hello") }, "Send") }))-vi.mock("@/components/community/messages/message-list", () => ({ MessageList: ({ onRetry }: { onRetry: (id: string) => void }) => React.createElement("button", { onClick: () => onRetry("failed") }, "Retry") }))+vi.mock("@/components/community/messages/message-list", () => ({ MessageList: (props: { onRetry: (id: string) => void }) => {+ mocks.list(props)+ return React.createElement("button", { onClick: () => props.onRetry("failed") }, "Retry")+} }))-beforeEach(() => { mocks.api.mockReset(); mocks.advance.mockReset(); mocks.failed = true; mocks.breakpoint = "mobile" })+beforeEach(() => { mocks.api.mockReset(); mocks.advance.mockReset(); mocks.list.mockReset(); mocks.positionEntry = null; mocks.failed = true; mocks.breakpoint = "mobile" })describe("real DmView accepted send UI lifecycle", () => {+ it("passes a fresh same-DM position attempt and route activity to the retained message list", async () => {+ const owner = await createCommunityQueryOwner("u_me")+ const wrapper = ({ children }: PropsWithChildren) => React.createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry, userId: "u_me", retainOwner: true }, children)+ mocks.positionEntry = {}+ const first = mocks.positionEntry+ const view = render(React.createElement(DmView, { dmId: "dm_1" }), { wrapper })+ expect(mocks.list.mock.lastCall?.[0]).toMatchObject({ positionEntry: first, active: true, positionDataState: "ready" })+ view.rerender(React.createElement(DmView, { dmId: "dm_1", routeCommitted: false }))+ expect(mocks.list.mock.lastCall?.[0]).toMatchObject({ positionEntry: first, active: false })+ view.rerender(React.createElement(DmView, { dmId: "dm_1", routeCommitted: true }))+ expect(mocks.list.mock.lastCall?.[0].positionEntry).toBe(first)+ mocks.positionEntry = {}+ view.rerender(React.createElement(DmView, { dmId: "dm_1" }))+ expect(mocks.list.mock.lastCall?.[0].positionEntry).toBe(mocks.positionEntry)+ expect(mocks.list.mock.lastCall?.[0].positionEntry).not.toBe(first)+ view.unmount()+ })it.each(["send", "retry"] as const)("continues %s after target view retires without advancing old onboarding", async action => {const owner = await createCommunityQueryOwner("u_me")owner.runtime.messageStream.actions.accept({ kind: "dm", id: "dm_1" }, { nonce: "retry_nonce", tempId: "temp_retry", message: { type: "chat", authorId: "u_me", content: "retry" }, localUploads: [] })diff --git a/src/web/src/components/community/channels/dm-view.tsx b/src/web/src/components/community/channels/dm-view.tsxindex 40cb39968..dc4de4f54 100644--- a/src/web/src/components/community/channels/dm-view.tsx+++ b/src/web/src/components/community/channels/dm-view.tsx@@ -133,7 +133,7 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeComfetchOlder: fetchOlderMessages,fetchNewer: fetchNewerMessages,jumpToPresent,- presentVersion,+ presentVersion, presentRequest,latestSeq,isPending: messagesPending,isError: messagesError,@@ -142,7 +142,7 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeComnavigationBlocked,anchorReconciled,readSnapshot, readSnapshotFetching, initialPositionKnown,- initialLoadError, retryInitialLoad, retryingInitialLoad, observation,+ initialLoadError, retryInitialLoad, retryingInitialLoad, observation, positionEntry, positionDataState, messageWindow,} = useDmMessages(dmId, {enabled: !dmBlocked && !metadata.revoked && !metadata.denied,viewerUserId: currentUser.id,@@ -379,8 +379,8 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom},})if (!receipt.accepted) return false- setLocalSubmitVersion((version) => version + 1)if (hasMoreNewerMessages) jumpToPresent()+ setLocalSubmitVersion((version) => version + 1)void receipt.committed.then((result) => {try { assertActive() } catch { return }if (result.ok) advanceOnboardingAfterSend()@@ -472,6 +472,10 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeComhasMore={hasMoreMessages}historyStartKnown={historyStartKnown}initialPositionMessageId={initialPositionMessageId}+ positionEntry={positionEntry}+ positionDataState={positionDataState}+ messageWindow={messageWindow}+ active={routeCommitted}isFetching={messagesFetching}isFetchingOlder={isFetchingOlderMessages}onLoadOlder={fetchOlderMessages}@@ -480,6 +484,7 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeComonLoadNewer={fetchNewerMessages}onJumpToPresent={jumpToPresent}presentVersion={presentVersion}+ presentRequest={presentRequest}localSubmitVersion={localSubmitVersion}unreadCount={unreadCount}typingUsers={typingUsers.map((id) => typingNames[id] ?? resolveUserName(id))}diff --git a/src/web/src/components/community/channels/text-channel-surface.tsx b/src/web/src/components/community/channels/text-channel-surface.tsxindex 55236feb1..538249672 100644--- a/src/web/src/components/community/channels/text-channel-surface.tsx+++ b/src/web/src/components/community/channels/text-channel-surface.tsx@@ -162,6 +162,8 @@ export function TextChannelSurface({historyStartKnown={feed.historyStartKnown}initialPositionMessageId={feed.initialPositionMessageId}positionEntry={feed.positionEntry}+ positionDataState={feed.positionDataState}+ messageWindow={feed.messageWindow}isFetching={feed.isFetching}isFetchingOlder={feed.isFetchingOlder}onLoadOlder={feed.fetchOlder}@@ -170,6 +172,7 @@ export function TextChannelSurface({onLoadNewer={feed.fetchNewer}onJumpToPresent={feed.jumpToPresent}presentVersion={feed.presentVersion}+ presentRequest={feed.presentRequest}localSubmitVersion={controller.localSubmitVersion}unreadCount={feed.unreadCount}typingUsers={controller.typingUsers}diff --git a/src/web/src/components/community/channels/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsxindex 1d19a1878..4cf1e29c2 100644--- a/src/web/src/components/community/channels/thread-channel-surface.tsx+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx@@ -274,6 +274,8 @@ export function ThreadChannelSurface({historyStartKnown={controller.feed.historyStartKnown}initialPositionMessageId={controller.feed.initialPositionMessageId}positionEntry={controller.feed.positionEntry}+ positionDataState={controller.feed.positionDataState}+ messageWindow={controller.feed.messageWindow}isFetching={controller.feed.isFetching}isFetchingOlder={controller.feed.isFetchingOlder}onLoadOlder={controller.feed.fetchOlder}@@ -282,6 +284,7 @@ export function ThreadChannelSurface({onLoadNewer={controller.feed.fetchNewer}onJumpToPresent={controller.feed.jumpToPresent}presentVersion={controller.feed.presentVersion}+ presentRequest={controller.feed.presentRequest}localSubmitVersion={controller.localSubmitVersion}unreadCount={controller.feed.unreadCount}typingUsers={controller.typingUsers}diff --git a/src/web/src/components/community/messages/image-lightbox.tsx b/src/web/src/components/community/messages/image-lightbox.tsxindex 18fab3f54..4922b1e57 100644--- a/src/web/src/components/community/messages/image-lightbox.tsx+++ b/src/web/src/components/community/messages/image-lightbox.tsx@@ -152,7 +152,7 @@ export function ImageLightbox({ image, onClose }: { image: ImagePreview | null;onOpenChangeComplete={(open) => { if (!open) setRetained(null) }}><DialogContentaria-label={displayed.name}- className="top-[max(1rem,env(safe-area-inset-top))] right-[max(1rem,env(safe-area-inset-right))] left-[max(1rem,env(safe-area-inset-left))] flex h-[calc(100dvh_-_max(1rem,env(safe-area-inset-top))_-_max(1rem,env(safe-area-inset-bottom)))] w-auto max-w-none translate-x-0 translate-y-0 overflow-visible border-none bg-transparent p-0 shadow-none ring-0 sm:max-w-none"+ className="top-[max(1rem,env(safe-area-inset-top))] right-[max(1rem,env(safe-area-inset-right))] left-[max(1rem,env(safe-area-inset-left))] flex h-[calc(100dvh-max(1rem,env(safe-area-inset-top))-max(1rem,env(safe-area-inset-bottom)))] w-auto max-w-none translate-x-0 translate-y-0 overflow-visible border-none bg-transparent p-0 shadow-none ring-0 sm:max-w-none"showCloseButton={false}><PreviewFramediff --git a/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts b/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.tsindex d58117640..359ede87a 100644--- a/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts+++ b/src/web/src/components/community/messages/message-channel-controller-facade.contract.test.ts@@ -121,7 +121,8 @@ describe("MessageChannelController facade contract", () => {"const router = useRouter()","const searchParams = useSearchParams()","const [replyTo, setReplyTo] = useAtom(useCreateAtom<ReplyTarget | null>(null))",- "const [scrollTargetId, setScrollTargetId] = useAtom(useMemo(() => createAtom<string | null>(anchorMessageId), [anchorMessageId, feed.positionEntry]))",+ "const targetEntry = useMemo(() => ({ entry: feed.positionEntry, atom: createAtom<string | null>(anchorMessageId) }), [anchorMessageId, feed.positionEntry])",+ "const [scrollTargetId, setScrollTargetId] = useAtom(targetEntry.atom)","const [contextTarget, setContextTarget] = useAtom(useCreateAtom<MessageContextTarget | null>(null))","useSendMessage()","useToggleReactionApi()",diff --git a/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts b/src/web/src/components/community/messages/message-channel-controller-state.dom.test.tsindex 9af01e1a7..10bb2a35b 100644--- a/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts+++ b/src/web/src/components/community/messages/message-channel-controller-state.dom.test.ts@@ -401,6 +401,18 @@ describe("useMessageChannelController", () => {expect(latest.contextTarget).toMatchObject({ channelId: "channel_1", seq: 1 })})+ it("renews the same consumed anchor only when the feed admits a fresh entry", () => {+ const entry = {}, nextEntry = {}+ const value = props({ feed: { ...feed, positionEntry: entry } })+ const view = rtlRender(React.createElement(Probe, { value }))+ act(() => latest.consumeScrollTarget("m1"))+ expect(latest.scrollTargetId).toBeNull()+ view.rerender(React.createElement(Probe, { value: { ...value, feed: { ...value.feed } } }))+ expect(latest.scrollTargetId).toBeNull()+ view.rerender(React.createElement(Probe, { value: { ...value, feed: { ...value.feed, positionEntry: nextEntry } } }))+ expect(latest.scrollTargetId).toBe("m1")+ })+it("clears missing anchors only on authoritative error and consumes only the matching target", () => {const missingFeed = { ...feed, messages: [], isError: false }let renderer: ReturnType<typeof rtlRender>diff --git a/src/web/src/components/community/messages/message-channel-controller-state.ts b/src/web/src/components/community/messages/message-channel-controller-state.tsindex f163afb95..b2b03be14 100644--- a/src/web/src/components/community/messages/message-channel-controller-state.ts+++ b/src/web/src/components/community/messages/message-channel-controller-state.ts@@ -75,7 +75,8 @@ export function useMessageChannelController({const searchParams = useSearchParams()const [replyTo, setReplyTo] = useAtom(useCreateAtom<ReplyTarget | null>(null))const [localSubmitVersion, setLocalSubmitVersion] = useAtom(useCreateAtom(0))- const [scrollTargetId, setScrollTargetId] = useAtom(useMemo(() => createAtom<string | null>(anchorMessageId), [anchorMessageId, feed.positionEntry]))+ const targetEntry = useMemo(() => ({ entry: feed.positionEntry, atom: createAtom<string | null>(anchorMessageId) }), [anchorMessageId, feed.positionEntry])+ const [scrollTargetId, setScrollTargetId] = useAtom(targetEntry.atom)const [contextTarget, setContextTarget] = useAtom(useCreateAtom<MessageContextTarget | null>(null))const { mutateAsync: sendMessageAsync } = useSendMessage()const toggleReactionApi = useToggleReactionApi()@@ -235,6 +236,7 @@ export function useMessageChannelController({runAcceptedIntent,}), [communityRuntime, actionContext, getMessage, source.capture, serverId, channelId, viewer.id, setReplyTo, toggleReactionApi, addReactionApi, unpinMessageMutate, pinMessageMutate, toggleMark, createThreadAsync, editMessage, messageScope, runAcceptedIntent])+ const { hasMoreNewer, jumpToPresent } = feedconst acceptMessage = useCallback((markdown: string,attachments?: SendAttachment[],@@ -254,11 +256,11 @@ export function useMessageChannelController({clearReply: () => setReplyTo(null),})if (accepted) {+ if (hasMoreNewer) jumpToPresent()setLocalSubmitVersion((version) => version + 1)- if (feed.hasMoreNewer) feed.jumpToPresent()}return accepted- }, [captureSendCommand, channelId, communityRuntime, feed.hasMoreNewer, feed.jumpToPresent, messageScope, replyTo, runAcceptedIntent, setLocalSubmitVersion, setReplyTo, viewer.avatar, viewer.id, viewer.name])+ }, [captureSendCommand, channelId, communityRuntime, hasMoreNewer, jumpToPresent, messageScope, replyTo, runAcceptedIntent, setLocalSubmitVersion, setReplyTo, viewer.avatar, viewer.id, viewer.name])return useMemo<MessageChannelControllerValue>(() => ({feed,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 27e6a137c..132852ab6 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@@ -173,6 +173,20 @@ describe("useMessageListController", () => {return entry[0]}+ it("requires a new positioning settlement for a fresh entry on the retained list", () => {+ const value = props({ positionEntry: {} })+ const view = rtlRender(React.createElement(Probe, { value }))+ const settled = () => (mocks.scrollInputs.at(-1) as { onInitialPositionSettled: () => void }).onInitialPositionSettled()+ act(settled)+ expect(latest.initialPosition.phase).toBe("revealed")+ view.rerender(React.createElement(Probe, { value: { ...value } }))+ expect(latest.initialPosition.phase).toBe("revealed")+ view.rerender(React.createElement(Probe, { value: { ...value, positionEntry: {} } }))+ expect(latest.initialPosition.phase).toBe("positioning")+ act(settled)+ expect(latest.initialPosition.phase).toBe("revealed")+ })+it("passes only the current composer acceptance version through loading and loaded commits", () => {const value = props({ messages: [], loading: true, localSubmitVersion: 7, presentVersion: 3 })const view = rtlRender(React.createElement(Probe, { value }))@@ -205,6 +219,11 @@ describe("useMessageListController", () => {items: expect.any(Array),newDividerBefore: undefined,initialScrollReady: true,+ positionDataState: "pending",+ positionEntry: undefined,+ initialPositionMessageId: undefined,+ messageWindow: undefined,+ active: undefined,hasMoreNewer: undefined,isFetchingOlder: undefined,isFetchingNewer: undefined,diff --git a/src/web/src/components/community/messages/message-list-controller.ts b/src/web/src/components/community/messages/message-list-controller.tsindex 5ac1c9495..13a8e83b5 100644--- a/src/web/src/components/community/messages/message-list-controller.ts+++ b/src/web/src/components/community/messages/message-list-controller.ts@@ -17,6 +17,9 @@ export function useMessageListController({scrollToMessageId,initialPositionMessageId,positionEntry,+ positionDataState,+ messageWindow,+ active,initialScrollReady,hasMore,hasMoreNewer,@@ -27,6 +30,7 @@ export function useMessageListController({onLoadNewer,onJumpToPresent,presentVersion,+ presentRequest,localSubmitVersion,unreadCount,onScrollRoot,@@ -34,7 +38,8 @@ export function useMessageListController({}: ResolvedMessageListProps) {const [jumpRevision, setJumpRevision] = useAtom(useCreateAtom(0))const [jumped, setJumped] = useAtom(useCreateAtom<string | null>(null))- const [anchorPositionSettled, setAnchorPositionSettled] = useAtom(useMemo(() => createAtom(false), [positionEntry]))+ const settledEntry = useMemo(() => ({ entry: positionEntry, atom: createAtom(false) }), [positionEntry])+ const [anchorPositionSettled, setAnchorPositionSettled] = useAtom(settledEntry.atom)const items = useMemo(() => flattenMessageItems(messages, newDividerBefore, !!hasMore, !!hasMoreNewer),@@ -88,12 +93,14 @@ export function useMessageListController({const {scrollRef,virtualizer,+ onRowsLayoutCommit,belowCount,scrollToBottom,requestPresentPosition,jumpTo: jumpToIndex,readPositionReady,paginationEnabled,+ paginationRequestPending,captureOlderPageAnchor,captureNewerPageAnchor,} = useScrollAnchor({@@ -103,12 +110,16 @@ export function useMessageListController({scrollToMessageId,initialPositionMessageId,positionEntry,+ positionDataState: positionDataState ?? (initialLoadError ? "error" : loading ? "pending" : undefined),+ messageWindow,+ active,onScrollTargetCancelled: onScrollTargetConsumed,onScrollTargetPositioned: (id) => { setJumped(id); setJumpRevision((value) => value + 1); onScrollTargetConsumed?.(id) },hasMoreNewer,isFetchingOlder,isFetchingNewer,presentVersion,+ presentRequest,localSubmitVersion,hasMoreOlder: hasMore,onInitialPositionSettled: settleAnchorPosition,@@ -128,18 +139,19 @@ export function useMessageListController({useVirtualCursorPagination({virtualizer,count: items.length,- enabled: paginationEnabled,+ enabled: paginationEnabled && !paginationRequestPending,hasMore,isFetching: isFetching || isFetchingOlder || isFetchingNewer,isError: !!initialLoadError,onBeforeLoad: captureOlderPageAnchor,onLoad: onLoadOlder,edge: "start",+ requestKey: messageWindow,})useVirtualCursorPagination({virtualizer,count: items.length,- enabled: paginationEnabled,+ enabled: paginationEnabled && !paginationRequestPending,hasMore: hasMoreNewer,hasMoreAtStart: hasMore,isFetching: isFetching || isFetchingOlder || isFetchingNewer,@@ -147,6 +159,7 @@ export function useMessageListController({onBeforeLoad: captureNewerPageAnchor,onLoad: onLoadNewer,edge: "end",+ requestKey: messageWindow,})const jumpClearTimerRef = useRef<number | null>(null)@@ -206,8 +219,7 @@ export function useMessageListController({const jumpMode = !!hasMoreNewerconst pillCount = jumpMode ? ((unreadCount ?? belowCount) || 0) : belowCountconst jumpToPresent = useCallback(() => {- requestPresentPosition()- onJumpToPresent?.()+ requestPresentPosition(onJumpToPresent?.())}, [onJumpToPresent, requestPresentPosition])const pillOnClick = jumpMode && onJumpToPresent ? jumpToPresent : scrollToBottom@@ -232,6 +244,7 @@ export function useMessageListController({onToggleSelectId,scrollRef,virtualizer,+ onRowsLayoutCommit,readPositionReady,paginationEnabled,jumpTo,diff --git a/src/web/src/components/community/messages/message-list-types.ts b/src/web/src/components/community/messages/message-list-types.tsindex 624222a75..2e52ee12b 100644--- a/src/web/src/components/community/messages/message-list-types.ts+++ b/src/web/src/components/community/messages/message-list-types.ts@@ -1,6 +1,7 @@import type { ReactNode } from "react"import type { FileAttachment, ImagePreview, Msg } from "@/lib/community/models/message"import type { OpenProfile } from "@/components/community/social/profile-types"+import type { MessagePositionState, MessageRequest } from "@/lib/community/message-position"export type MessageListProps = {observation?: import("@/lib/observability/regions").ResourceObservation@@ -33,6 +34,9 @@ export type MessageListProps = {scrollToMessageId?: string | nullinitialPositionMessageId?: string | nullpositionEntry?: object | null+ positionDataState?: MessagePositionState+ messageWindow?: object+ active?: booleanhero?: ReactNodevariant?: "channel" | "dm"onScrollRoot?: (el: HTMLDivElement | null) => void@@ -43,12 +47,13 @@ export type MessageListProps = {historyStartKnown?: booleanisFetching?: booleanisFetchingOlder?: boolean- onLoadOlder?: () => void+ onLoadOlder?: () => MessageRequest | voidhasMoreNewer?: booleanisFetchingNewer?: boolean- onLoadNewer?: () => void- onJumpToPresent?: () => void+ onLoadNewer?: () => MessageRequest | void+ onJumpToPresent?: () => MessageRequest | voidpresentVersion?: number+ presentRequest?: MessageRequest | nulllocalSubmitVersion?: numberunreadCount?: number}diff --git a/src/web/src/components/community/messages/message-list.jump-target.dom.test.ts b/src/web/src/components/community/messages/message-list.jump-target.dom.test.tsindex 5ec9fa469..8cafb07ae 100644--- a/src/web/src/components/community/messages/message-list.jump-target.dom.test.ts+++ b/src/web/src/components/community/messages/message-list.jump-target.dom.test.ts@@ -16,7 +16,7 @@ const unrelated = { ...target, id: "m_other", content: "Other" }const newer = { ...target, id: "m_newer", content: "Newer", createdAt: new Date(1).toISOString() }const consumed = vi.fn()function view(messages: typeof target[], scrollToMessageId: string | null) {- return React.createElement(MessageList, { channel: "general", messages, loading: false, initialScrollReady: false, hasMoreNewer: true, scrollToMessageId, onScrollTargetConsumed: consumed, onOpenThread: vi.fn() })+ return React.createElement(MessageList, { channel: "general", messages, loading: false, initialScrollReady: false, positionDataState: "ready", hasMoreNewer: true, scrollToMessageId, onScrollTargetConsumed: consumed, onOpenThread: vi.fn() })}function highlighted(container: HTMLElement) {return container.querySelector('[data-row-id="m_target"]')?.getAttribute("data-highlighted") === "true"diff --git a/src/web/src/components/community/messages/message-list.older-load.dom.test.ts b/src/web/src/components/community/messages/message-list.older-load.dom.test.tsindex 3a7a3903b..3e7444dd2 100644--- a/src/web/src/components/community/messages/message-list.older-load.dom.test.ts+++ b/src/web/src/components/community/messages/message-list.older-load.dom.test.ts@@ -14,14 +14,14 @@ describe("MessageList native range pagination", () => {it("loads and settles ordinary older pages after the position deadline while read remains closed", () => {const messages = Array.from({ length: 50 }, (_, i) => ({ id: `m${i}`, authorId: "alice", authorName: "Alice", content: "hi", createdAt: new Date(0).toISOString() }))const onLoadOlder = vi.fn()- const view = (isFetchingOlder: boolean) => React.createElement(MessageList, { channel: "general", messages, initialScrollReady: false, hasMore: true, onLoadOlder, isFetchingOlder, onOpenThread: vi.fn() })+ const view = (isFetchingOlder: boolean) => React.createElement(MessageList, { channel: "general", messages, initialScrollReady: true, scrollToMessageId: "not-loaded", hasMore: true, onLoadOlder, isFetchingOlder, onOpenThread: vi.fn() })const renderer = render(view(false))resize()const scroller = renderer.getByTestId(tid.messageScroller)act(() => { scroller.scrollTo({ top: 0 }) })runFrames()expect(onLoadOlder).not.toHaveBeenCalled()- act(() => vi.advanceTimersByTime(2000))+ act(() => vi.advanceTimersByTime(5000))runFrames()act(() => { scroller.scrollTo({ top: 0 }) })resize()@@ -43,10 +43,10 @@ describe("MessageList native range pagination", () => {const message = (i: number) => ({ id: `m${i}`, type: "chat" as const, authorId: "alice", authorName: "Alice", content: "hi", createdAt: new Date(i * 1000).toISOString() })let messages = Array.from({ length: 50 }, (_, i) => message(i + 40))const onLoadOlder = vi.fn()- const view = (isFetchingOlder: boolean, hasMore = true) => React.createElement(MessageList, { channel: "general", messages, initialScrollReady: false, hasMore, onLoadOlder, isFetchingOlder, onOpenThread: vi.fn() })+ const view = (isFetchingOlder: boolean, hasMore = true) => React.createElement(MessageList, { channel: "general", messages, initialScrollReady: true, scrollToMessageId: "not-loaded", hasMore, onLoadOlder, isFetchingOlder, onOpenThread: vi.fn() })const renderer = render(view(false, fold === "header" || pendingMove))resize()- act(() => vi.advanceTimersByTime(2000))+ act(() => vi.advanceTimersByTime(5000))runFrames()const root = renderer.getByTestId(tid.messageScroller)act(() => root.scrollTo({ top: 0 }))diff --git a/src/web/src/components/community/messages/message-list.retry-entry.dom.test.tsx b/src/web/src/components/community/messages/message-list.retry-entry.dom.test.tsxnew file mode 100644index 000000000..939192d33--- /dev/null+++ b/src/web/src/components/community/messages/message-list.retry-entry.dom.test.tsx@@ -0,0 +1,73 @@+import { createElement, type PropsWithChildren } from "react"+import { describe, expect, it, vi } from "vitest"+import { QueryClientProvider } from "@tanstack/react-query"+import { act, fireEvent, render } from "@/test/react-dom-harness"+import { createCommunityQueryOwner } from "@/test/community-query-owner"+import { conversationEntryFixture, dmConversationEntryFixture } from "@/test/conversation-entry-fixtures"+import { CommunityDbProvider } from "@/lib/community-db/projections"+import { ConversationReadTimeoutError } from "@/lib/community/conversation-read"+import { useDmMessages, useMessages } from "@/hooks/community/use-messages"+import { installMessageScrollFixture, resize, restoreMessageScrollFixture, scrollFixture } from "@/test/message-scroll-fixture"+import { MessageList } from "./message-list"++const load = vi.hoisted(() => vi.fn())+vi.mock("@/lib/api/client", async original => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: (...args: unknown[]) => load(...args) }))+vi.mock("@/hooks/use-mobile", () => ({ useBreakpoint: () => "desktop" }))+vi.mock("./message-row", () => ({ MessageRow: () => createElement("div") }))+vi.mock("@/components/ui/number-ticker", () => ({ NumberTicker: ({ value }: { value: number }) => createElement("span", null, value) }))++describe("existing Retry button starts a bound positioning attempt", () => {+ it.each(["channel", "dm"] as const)("recovers a failed %s without remounting its scroller or replaying on background refetch", async kind => {+ const owner = await createCommunityQueryOwner()+ load.mockReset().mockRejectedValue(new ConversationReadTimeoutError())+ installMessageScrollFixture()+ let latest!: ReturnType<typeof useMessages>+ const useFeed = kind === "channel" ? () => useMessages("c1", { serverId: "s1" }) : () => useDmMessages("c1")+ function Surface() {+ const feed = useFeed()+ latest = feed+ return createElement(MessageList, {+ channel: "test", messages: feed.messages, loading: feed.isLoading, initialLoadError: feed.initialLoadError,+ onRetryInitialLoad: feed.retryInitialLoad, retryingInitialLoad: feed.retryingInitialLoad,+ positionEntry: feed.positionEntry, positionDataState: feed.positionDataState, messageWindow: feed.messageWindow,+ initialScrollReady: feed.initialPositionKnown, initialPositionMessageId: feed.initialPositionMessageId,+ onOpenThread: () => {},+ })+ }+ const wrapper = ({ children }: PropsWithChildren) => createElement(QueryClientProvider, { client: owner.client }, createElement(CommunityDbProvider, { registry: owner.registry }, children))+ const view = render(createElement(Surface), { wrapper })+ const flush = async () => {+ for (let index = 0; index < 5; index++) {+ await act(async () => { await vi.advanceTimersByTimeAsync(1) })+ resize()+ }+ }+ try {+ await flush()+ const root = view.getByTestId("community-message-scroller")+ expect(latest.positionDataState).toBe("error")+ const failed = latest.positionEntry+ const packet = kind === "channel" ? conversationEntryFixture() : dmConversationEntryFixture()+ packet.messages = Array.from({ length: 14 }, (_, index) => ({ ...packet.messages[0], id: `m${index + 1}`, seq: index + 1 }))+ packet.page = { ...packet.page, latestSeq: 14, hasMoreNewer: false }+ load.mockResolvedValue(packet)+ fireEvent.click(view.getByRole("button", { name: "Retry" }))+ await flush()+ expect(latest.positionEntry).not.toBe(failed)+ expect(latest.positionDataState).toBe("ready")+ expect(view.getByTestId("community-message-scroller")).toBe(root)+ expect(root.querySelector('[data-read-position-ready]')).toHaveAttribute("data-read-position-ready", "true")+ expect(root.scrollTop).toBe(root.scrollHeight - root.clientHeight)+ const attempt = latest.positionEntry+ const writes = scrollFixture.scrollCalls.length+ load.mockResolvedValue({ messages: packet.messages, latestSeq: 14, hasMoreOlder: false, hasMoreNewer: false })+ await act(async () => { await latest.refetch() })+ await flush()+ expect(latest.positionEntry).toBe(attempt)+ expect(scrollFixture.scrollCalls).toHaveLength(writes)+ } finally {+ view.unmount()+ restoreMessageScrollFixture()+ }+ })+})diff --git a/src/web/src/components/community/messages/message-list.tsx b/src/web/src/components/community/messages/message-list.tsxindex f1a37004b..752960cf5 100644--- a/src/web/src/components/community/messages/message-list.tsx+++ b/src/web/src/components/community/messages/message-list.tsx@@ -11,6 +11,7 @@ import type { MessageListProps, ResolvedMessageListProps } from "./message-list-import { renderMessageListRow } from "./message-list-row"import { renderMessageListView } from "./message-list-view"import { VirtualRows } from "./virtual-cursor-list"+import { useConversationActivity } from "@/contexts/community/conversation-activity"export function MessageList({variant = "channel",@@ -18,12 +19,14 @@ export function MessageList({...props}: MessageListProps) {const hoverCapable = useHoverCapable()+ const conversationActive = useConversationActivity()const resolvedProps: ResolvedMessageListProps = {...props,messages: isConversationAccessError(props.initialLoadError) ? [] : props.messages,variant,initialScrollReady,hoverCapable,+ active: conversationActive && props.active !== false,}const controller = useMessageListController(resolvedProps)const visible = visibleVirtualItems(controller.virtualizer).flatMap(item => { const row = controller.items[item.index]; return row?.kind === "message" ? [row.m] : [] })@@ -39,6 +42,7 @@ export function MessageList({reactLayoutitems={controller.items}virtualizer={controller.virtualizer}+ onLayoutCommit={controller.onRowsLayoutCommit}renderItem={(item, index) => renderMessageListRow(item, resolvedProps, controller, index)}/>), footerSlot?.target ?? null, footerSlot?.accessoryTarget ?? null)diff --git a/src/web/src/components/community/messages/message.tsx b/src/web/src/components/community/messages/message.tsxindex cc42f52d3..a6abaf44f 100644--- a/src/web/src/components/community/messages/message.tsx+++ b/src/web/src/components/community/messages/message.tsx@@ -663,7 +663,7 @@ function MessageImpl({<div className="flex gap-2">{m.grouped ? (- <div className="w-[40px] shrink-0" />+ <div className="w-10 shrink-0" />) : (<button{...avatarMention}diff --git a/src/web/src/components/community/messages/virtual-cursor-list.dom.test.tsx b/src/web/src/components/community/messages/virtual-cursor-list.dom.test.tsxindex 2972ad9b6..70762e33b 100644--- a/src/web/src/components/community/messages/virtual-cursor-list.dom.test.tsx+++ b/src/web/src/components/community/messages/virtual-cursor-list.dom.test.tsx@@ -25,6 +25,7 @@ function List({ direct, mode, ready }: {scrollTo: { configurable: true, value: ({ top = 0 }: ScrollToOptions) => { node.scrollTop = top } },})}, [])+ // eslint-disable-next-line react-hooks/incompatible-library -- Native mutable Virtualizer cannot be safely memoized; this fixture tests its actual React adapter.const virtualizer = useVirtualizer<HTMLDivElement, Element>({...COMMUNITY_VIRTUALIZER_REACT_OPTIONS,directDomUpdates: direct,diff --git a/src/web/src/components/community/messages/virtual-cursor-list.tsx b/src/web/src/components/community/messages/virtual-cursor-list.tsxindex 132bd0048..9ed809b1a 100644--- a/src/web/src/components/community/messages/virtual-cursor-list.tsx+++ b/src/web/src/components/community/messages/virtual-cursor-list.tsx@@ -2,8 +2,9 @@/* eslint-disable react-hooks/refs -- TanStack Virtual exposes an imperative instance whose render-time getters and ref callbacks are its supported React API. */-import type { ReactNode } from "react"+import { useLayoutEffect, type ReactNode } from "react"import type { ReactVirtualizer } from "@tanstack/react-virtual"+import type { VirtualRowsLayoutSnapshot } from "@/hooks/community/virtualizer-react-options"export function VirtualRows<T>({items,@@ -14,6 +15,7 @@ export function VirtualRows<T>({directDomUpdatesMode = "transform",children,getRowAttributes,+ onLayoutCommit,}: {items: T[]virtualizer: ReactVirtualizer<HTMLDivElement, Element>@@ -23,18 +25,32 @@ export function VirtualRows<T>({directDomUpdatesMode?: "transform" | "position"children?: ReactNodegetRowAttributes?: (item: T, index: number) => Record<`data-${string}`, string | number | undefined>+ onLayoutCommit?: (snapshot: VirtualRowsLayoutSnapshot | null) => void}) {+ const totalSize = reactLayout ? virtualizer.getTotalSize() : null+ const virtualRows = virtualizer.getVirtualItems()+ const rows = onLayoutCommit && reactLayout ? virtualRows.map(row => ({ ...row })) : virtualRows+ const layout: VirtualRowsLayoutSnapshot | null = onLayoutCommit && reactLayout ? {+ totalSize: totalSize!,+ scrollMargin: virtualizer.options.scrollMargin,+ rows,+ } : null+ useLayoutEffect(() => {+ if (!layout || !onLayoutCommit) return+ onLayoutCommit(layout)+ return () => onLayoutCommit(null)+ })return (<divref={virtualizer.containerRef}style={{position: "relative",width: "100%",- ...(reactLayout ? { height: virtualizer.getTotalSize() } : {}),+ ...(reactLayout ? { height: totalSize! } : {}),}}>{children}- {virtualizer.getVirtualItems().map((virtualRow) => {+ {rows.map((virtualRow) => {const item = items[virtualRow.index]return (<div@@ -48,7 +64,7 @@ export function VirtualRows<T>({...(reactLayout || directDomUpdatesMode === "transform" ? { top: 0 } : {}),left: 0,width: "100%",- ...(reactLayout ? { transform: `translate3d(0, ${virtualRow.start - virtualizer.options.scrollMargin}px, 0)` } : {}),+ ...(reactLayout ? { transform: `translate3d(0, ${virtualRow.start - (layout?.scrollMargin ?? virtualizer.options.scrollMargin)}px, 0)` } : {}),}}>{renderItem(item, virtualRow.index)}diff --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 779b21857..6659684fb 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@@ -226,6 +226,26 @@ describe("conversation entry selection", () => {expect(load).not.toHaveBeenCalled()hook.unmount()})+ it("verifies a newly selected revoked target but does not retry a later access withdrawal", async () => {+ const { wrapper, registry } = await setup()+ const request = deferred<ReturnType<typeof fixture>>()+ load.mockReturnValue(request.promise)+ const hook = renderHook(({ selected }) => useConversationEntry(selected), {+ wrapper, initialProps: { selected: null as typeof target | null },+ })+ await act(async () => registry.runtime.ws.actions.revokeChannelAccess("s1", "c1"))+ hook.rerender({ selected: target })+ expect(hook.result.current.denied).toBe(false)+ await waitFor(() => expect(load).toHaveBeenCalledOnce())+ await act(async () => request.resolve(fixture()))+ await waitFor(() => expect(hook.result.current.canRead).toBe(true))+ await act(async () => registry.runtime.ws.actions.revokeChannelAccess("s1", "c1"))+ expect(hook.result.current.canRead).toBe(false)+ expect(hook.result.current.denied).toBe(true)+ expect(load).toHaveBeenCalledOnce()+ hook.unmount()+ })+it("withdraws a completed proof and exactly refetches after its real registry registration retires", async () => {const { wrapper, publish, registry, client } = await setup()const original = publish()@@ -327,6 +347,7 @@ describe("conversation entry return during accepted reading", () => {createElement("div", { "data-message-list-content": "", "data-read-position-ready": String(controller.readPositionReady) },createElement(VirtualRows<FlatItem>, {items: controller.items, virtualizer: controller.virtualizer, reactLayout: true,+ onLayoutCommit: controller.onRowsLayoutCommit,renderItem: (item, index) => item.kind === "leading" ? renderMessageListRow(item, props, controller, index) : createElement("div", {"data-message-row-key": item.key, "data-fixture-kind": item.kind,"data-fixture-date": String(item.kind === "divider" && !!item.dateLabel),diff --git a/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx b/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsxindex cd9279844..f5455bf2f 100644--- a/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx+++ b/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx@@ -12,10 +12,10 @@ import { createCommunityQueryOwner } from "@/test/community-query-owner"import { conversationEntryFixture } from "@/test/conversation-entry-fixtures"import { seedConversationEntry } from "@/test/conversation-entry-fixtures"import { act, fireEvent, render } from "@/test/react-dom-harness"-import { installMessageScrollFixture, restoreMessageScrollFixture, resize } from "@/test/message-scroll-fixture"+import { installMessageScrollFixture, restoreMessageScrollFixture, resize, scrollFixture } from "@/test/message-scroll-fixture"import { captureCommunityLiveSnapshotToken, ingestReadStateSnapshot, publishAccountAttentionSnapshot } from "@/lib/community-db/sync"import { currentConversationReadState } from "@/lib/community/conversation-entry"-import { disposeReadCoordinator, getLocalReadingPosition, getReadCoordinator } from "./read-coordinator"+import { disposeReadCoordinator, getLocalReadingPosition, getReadCoordinator, READ_COORDINATOR_DEBOUNCE_MS } from "./read-coordinator"import { disposeAccountReadStateReconciliation, type AccountReadStateSnapshot } from "./community-ws/read-state-reconciliation"const navigationMock = vi.hoisted(() => ({ href: "/c/channels/s1/c1", replace: vi.fn() }))@@ -64,6 +64,7 @@ function Conversation({ channelId, kind, anchorMessageId }: { channelId: string;newDividerBefore: feed.newDividerBefore, initialPositionMessageId: feed.initialPositionMessageId,initialScrollReady: !feed.readSnapshotFetching && feed.anchorInCache,positionEntry: feed.positionEntry,+ positionDataState: feed.positionDataState, messageWindow: feed.messageWindow, presentRequest: feed.presentRequest,scrollToMessageId: channel.scrollTargetId, onScrollTargetConsumed: channel.consumeScrollTarget,hasMore: feed.hasMoreOlder, hasMoreNewer: feed.hasMoreNewer, historyStartKnown: feed.historyStartKnown,isFetching: feed.isFetching, isFetchingOlder: feed.isFetchingOlder, isFetchingNewer: feed.isFetchingNewer,@@ -102,6 +103,7 @@ async function setup(kind: Kind, ownTail = false, strict = false, options: {refresh?: Promise<ReturnType<typeof entry>>refreshWindow?: Promise<ReturnType<typeof entry>>readPointer?: AccountReadStateSnapshot["readStates"][number]+ initialActive?: boolean} = {}) {owner = await createCommunityQueryOwner()await seedConversationEntry(owner.client, options.cached ?? entry(kind, "c1", ownTail))@@ -132,7 +134,7 @@ async function setup(kind: Kind, ownTail = false, strict = false, options: {if (url === "/api/community/users/me/attention") return Promise.resolve({ scopes: [], items: [], limit: 100, truncated: false })throw new Error(`Unexpected entry-position transport: ${url}`)})- let channelId = "c1", active = true, anchorMessageId: string | null = null+ let channelId = "c1", active = options.initialActive ?? true, anchorMessageId: string | null = nullconst navigation = { entryIntent: { href: "/c/channels/s1/c1" } as { href: string; resume?: boolean } }const content = () => <QueryClientProvider client={owner.client}><CommunityDbProvider registry={owner.registry}><CurrentUserProvider initialUser={viewer}>@@ -177,7 +179,13 @@ async function setup(kind: Kind, ownTail = false, strict = false, options: {await act(async () => {})expect(visible("m42")).toBe(true)}- return { root, visible, navigate, canonical, tail }+ const setActivity = async (next: boolean) => {+ active = next+ mounted!.rerender(element())+ resize()+ await act(async () => {})+ }+ return { root, visible, navigate, canonical, tail, setActivity }}function intersection(row: Element, ratio = 1): IntersectionObserverEntry {@@ -217,6 +225,49 @@ afterEach(async () => {})describe("conversation entry positioning through real reading owners", () => {+ it.each(["inactive", "document-hidden"])("opens the real read transport after a laid-out short entry becomes visible from %s", async mode => {+ scrollFixture.firstPrefix = 120+ if (mode === "document-hidden") visibility = "hidden"+ const cached = entry("channel")+ cached.messages = cached.messages.slice(0, 1)+ cached.channel.messageCount = 1+ cached.page.latestSeq = 1+ cached.readState = { channelId: "c1", lastReadMessageId: null, lastReadSeq: 0, lastReadAt: null }+ cached.selection = { reason: "tail", anchorMessageId: null }+ const view = await setup("channel", false, false, { cached, initialActive: mode !== "inactive" })+ expect(view.root().querySelector('[data-read-position-ready]')).toHaveAttribute("data-read-position-ready", "false")+ expect(load.mock.calls.some(([, options]) => options?.method === "PUT")).toBe(false)+ if (mode === "document-hidden") {+ visibility = "visible"+ fireEvent(document, new Event("visibilitychange"))+ resize()+ } else await view.setActivity(true)+ expect(view.root().querySelector('[data-read-position-ready]')).toHaveAttribute("data-read-position-ready", "true")+ const row = view.root().querySelector('[data-msg-id="m1"]')!+ const observer = boundObserver(row)+ act(() => observer.callback([intersection(row)], {} as IntersectionObserver))+ expect(getReadCoordinator(owner.client, viewer.id).state.get().scopes.get("timeline:c1")?.accepted?.intent.seq).toBe(1)+ await act(async () => vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS))+ expect(load).toHaveBeenCalledWith("/api/community/channels/c1/read", expect.objectContaining({+ method: "PUT", body: JSON.stringify({ lastReadMessageId: "m1" }),+ }))+ })++ it("keeps a precommitted entry unread while inactive and admits its real observer on first activation", async () => {+ const view = await setup("channel", false, false, { initialActive: false })+ const entry = latest.feed.positionEntry+ expect(view.root().querySelector('[data-read-position-ready]')).toHaveAttribute("data-read-position-ready", "false")+ expect(load.mock.calls.some(([, options]) => options?.method === "PUT")).toBe(false)+ await view.setActivity(true)+ expect(latest.feed.positionEntry).toBe(entry)+ expect(view.visible("m31")).toBe(true)+ expect(view.root().querySelector('[data-read-position-ready]')).toHaveAttribute("data-read-position-ready", "true")+ const row = view.root().querySelector('[data-msg-id="m31"]')!+ const observer = boundObserver(row)+ act(() => observer.callback([intersection(row)], {} as IntersectionObserver))+ expect(getReadCoordinator(owner.client, viewer.id).state.get().scopes.get("timeline:c1")?.accepted?.intent.seq).toBe(31)+ })+it.each([{ delayCanonical: false, previousTail: false }, { delayCanonical: true, previousTail: false }, { delayCanonical: false, previousTail: true }])("keeps a cached read tail visible until native data is complete, delayed canonical=$delayCanonical, previous tail=$previousTail", async ({ delayCanonical, previousTail }) => {const fresh = entry("channel")fresh.messages = fresh.messages.slice(0, 13)@@ -256,6 +307,8 @@ describe("conversation entry positioning through real reading owners", () => {await act(async () => { finishRefresh(fresh); await vi.advanceTimersByTimeAsync(0) })resize()if (delayCanonical) {+ await act(async () => vi.advanceTimersByTimeAsync(6000))+ resize()expect({ latestSeq: latest.feed.latestSeq, messages: latest.feed.messages.map(message => message.id),fetching: latest.feed.isFetching, readSnapshotFetching: latest.feed.readSnapshotFetching,readReady: view.root().querySelector("[data-message-list-content]")!.getAttribute("data-read-position-ready"),diff --git a/src/web/src/hooks/community/use-conversation-entry.ts b/src/web/src/hooks/community/use-conversation-entry.tsindex 79d9b8ec6..0f4c1c191 100644--- a/src/web/src/hooks/community/use-conversation-entry.ts+++ b/src/web/src/hooks/community/use-conversation-entry.ts@@ -40,28 +40,36 @@ export function useConversationResource(target: ConversationEntryTarget | null,const preferTail = target?.preferTail === trueconst enabled = target !== nullconst baseInput = useMemo(() => ({ channelId, serverId, anchorMessageId, tag, preferTail }), [channelId, serverId, anchorMessageId, tag, preferTail])- const cachedResource = useMemo(() => {+ const qualification = useMemo(() => ({ accountEpoch, accessEpoch, generation, parentGeneration }), [accountEpoch, accessEpoch, generation, parentGeneration])+ const cachedSelection = useMemo(() => {const cached = client.getQueryData<ConversationEntryResource>(conversationEntryOptions(client, baseInput).queryKey)- return cached && isChannelMetadataTokenCurrent(cached.proof) ? cached : getQualifiedConversationEntry(client, channelId)- }, [client, baseInput, channelId, accountEpoch, accessEpoch, generation, parentGeneration, intent])+ return { qualification, intent, resource: cached && isChannelMetadataTokenCurrent(cached.proof) ? cached : getQualifiedConversationEntry(client, channelId) }+ }, [client, baseInput, channelId, qualification, intent])+ const cachedResource = cachedSelection.resourceconst landing = useMemo(() => {const search = new URLSearchParams(intent?.href.split("?")[1] ?? "")const position = useLocalPosition && enabled && !anchorMessageId && !tag && !preferTail && !intent?.resume && !search.has("msg") && !search.has("seq")? getLocalReadingPosition(client, channelId) : nullconst pointer = currentConversationReadState(client, channelId)- if (!position || !pointer || pointer.lastReadSeq >= position.seq) return { input: baseInput, requestInput: baseInput, position: null }+ if (!position || !pointer || pointer.lastReadSeq >= position.seq) return { qualification: cachedSelection.qualification, input: baseInput, requestInput: baseInput, position: null }const input = { ...baseInput, anchorMessageId: position.messageId }- const covered = cachedResource && findConversationEntryWindow(client, input, cachedResource, pointer)- return { input, requestInput: covered ? baseInput : input, position }- }, [client, baseInput, cachedResource, accountEpoch, accessEpoch, generation, parentGeneration, intent, useLocalPosition, enabled, anchorMessageId, channelId, tag, preferTail])+ const covered = cachedSelection.resource && findConversationEntryWindow(client, input, cachedSelection.resource, pointer)+ return { qualification: cachedSelection.qualification, input, requestInput: covered ? baseInput : input, position }+ }, [client, baseInput, cachedSelection, intent, useLocalPosition, enabled, anchorMessageId, channelId, tag, preferTail])const input = landing.input- const options = useMemo(() => conversationEntryOptions(client, landing.requestInput), [client, landing, accountEpoch, accessEpoch, generation, parentGeneration, intent])+ const options = useMemo(() => conversationEntryOptions(client, landing.requestInput), [client, landing])const parentId = canonical?.parentChannelId ?? undefined- const verification = useMemo(() => ({ needed: !serverRevoked && runtime.ws.actions.isChannelAccessRevoked(channelId, serverId, parentId), generation }), [runtime, channelId, serverId])+ const [verification, setVerification] = useState(() => ({ runtime, channelId, serverId,+ needed: !serverRevoked && runtime.ws.actions.isChannelAccessRevoked(channelId, serverId, parentId), generation }))+ if (verification.runtime !== runtime || verification.channelId !== channelId || verification.serverId !== serverId) {+ setVerification({ runtime, channelId, serverId,+ needed: !serverRevoked && runtime.ws.actions.isChannelAccessRevoked(channelId, serverId, parentId), generation })+ }const query = useQuery({ ...options, enabled: !!target && !revoked, refetchOnReconnect: false, refetchOnWindowFocus: false })const anchorMissing = isConversationAnchorMissingError(query.error)const fallbackInput = useMemo(() => ({ ...baseInput, anchorMessageId: null }), [baseInput])- const fallbackOptions = useMemo(() => conversationEntryOptions(client, fallbackInput), [client, fallbackInput, accountEpoch, accessEpoch, generation, parentGeneration])+ const fallbackRequest = useMemo(() => ({ qualification, options: conversationEntryOptions(client, fallbackInput) }), [client, fallbackInput, qualification])+ const fallbackOptions = fallbackRequest.optionsconst fallback = useQuery({ ...fallbackOptions, enabled: !!target && anchorMissing && !revoked, subscribed: !!target && anchorMissing,refetchOnReconnect: false, refetchOnWindowFocus: false })const resource = query.data && isChannelMetadataTokenCurrent(query.data.proof) ? query.data@@ -81,7 +89,7 @@ export function useConversationResource(target: ConversationEntryTarget | null,if (!target || !intent || revoked || !query.data || query.isFetching || query.isError) returnconst pointer = currentConversationReadState(client, channelId)if (pointer && !findConversationEntryWindow(client, input, query.data, pointer)) void client.query({ ...options, select: undefined }).catch(() => undefined)- }, [client, intent, input, options, revoked])+ }, [client, channelId, intent, input, options, query.data, query.isFetching, query.isError, revoked, target])return { client, cachedResource, input: anchorMissing && landing.position ? baseInput : input, options, query, canonical, resource: qualified ? resource : undefined, canRead: qualified, revoked,localPosition: anchorMissing ? null : landing.position,denied: serverRevoked || revoked && (!verification.needed || generation !== verification.generation) || isConversationAccessError(query.error) && Number((query.error as { status?: unknown } | null)?.status) !== 401, anchorMissing,@@ -111,7 +119,7 @@ export function useConversationEntry(target: ConversationEntryTarget | null) {const pointer = cachedResource && isChannelMetadataTokenCurrent(cachedResource.proof) ? currentConversationReadState(client, input.channelId) : undefinedconst window = cachedResource && pointer ? findConversationEntryWindow(client,localPosition && pointer.lastReadSeq >= localPosition.seq ? canonicalInput : input, cachedResource, pointer) : undefined- return { knownRevision: pointer?.observedRevision ?? -1, state: createStore<{ snapshot: CommunityReadStateResource | null; window: EntryWindow | null }>({+ return { intent, knownRevision: pointer?.observedRevision ?? -1, state: createStore<{ snapshot: CommunityReadStateResource | null; window: EntryWindow | null }>({snapshot: window ? pointer! : null,window: window ?? null,}) }@@ -144,7 +152,7 @@ export function useConversationEntry(target: ConversationEntryTarget | null) {}, [canRead, client, input.channelId, input.serverId, resource, window])const activeQuery = needsCanonicalWindow ? canonicalQuery : queryconst refetch = activeQuery.refetch- const retry = useCallback(() => { void refetch({ cancelRefetch: false }) }, [refetch])+ const retry = useCallback(() => refetch({ cancelRefetch: false }), [refetch])return { ...activeQuery, intent, resource, canonical, canRead, window, snapshot, revoked, denied, anchorMissing,initialPositionMessageId: window && localPosition && snapshot && snapshot.lastReadSeq < localPosition.seq ? localPosition.messageId : null,isPending: !!target && !window && !denied && !anchorMissing && !activeQuery.isError && activeQuery.errorUpdatedAt === 0,diff --git a/src/web/src/hooks/community/use-messages.anchor-retry.dom.test.ts b/src/web/src/hooks/community/use-messages.anchor-retry.dom.test.tsindex db9bc4aae..033faac5d 100644--- a/src/web/src/hooks/community/use-messages.anchor-retry.dom.test.ts+++ b/src/web/src/hooks/community/use-messages.anchor-retry.dom.test.ts@@ -34,10 +34,13 @@ describe("entry failure and explicit recovery", () => {await act(async () => { onlineManager.setOnline(false); onlineManager.setOnline(true) })expect(load).toHaveBeenCalledTimes(kind === "dm" ? 1 : 2)load.mockResolvedValue(kind === "channel" ? conversationEntryFixture() : dmConversationEntryFixture())+ const failedAttempt = returned.result.current.positionEntryawait act(async () => returned.result.current.retryInitialLoad())await waitFor(() => expect(returned.result.current.initialPositionKnown).toBe(true))expect(returned.result.current.messages.map(row => row.id)).toEqual(["m1"])expect(returned.result.current.readSnapshot?.lastReadMessageId).toBe("m1")+ expect(returned.result.current.positionEntry).not.toBe(failedAttempt)+ expect(returned.result.current.positionDataState).toBe("ready")expect(load).toHaveBeenCalledTimes(kind === "dm" ? 2 : 3)returned.unmount()})@@ -50,16 +53,42 @@ describe("entry failure and explicit recovery", () => {const hook = renderHook(() => useMessages("c1", { serverId: "s1" }), { wrapper })await waitFor(() => expect(hook.result.current.initialPositionKnown).toBe(true))const pointer = hook.result.current.readSnapshot+ const positionEntry = hook.result.current.positionEntryload.mockRejectedValue(new ConversationReadTimeoutError())await act(async () => { await hook.result.current.refetch() })expect(hook.result.current.isLoading).toBe(false)expect(hook.result.current.initialLoadError).toBeNull()expect(hook.result.current.initialPositionKnown).toBe(true)expect(hook.result.current.readSnapshot).toBe(pointer)+ expect(hook.result.current.positionEntry).toBe(positionEntry)+ expect(hook.result.current.positionDataState).toBe(empty ? "empty" : "ready")expect(hook.result.current.messages).toHaveLength(empty ? 0 : 1)hook.unmount()})+ it("binds an explicit Retry to its own result even when a prior valid window remains", async () => {+ const { wrapper } = await setup()+ load.mockResolvedValue(conversationEntryFixture())+ const hook = renderHook(() => useMessages("c1", { serverId: "s1" }), { wrapper })+ await waitFor(() => expect(hook.result.current.positionDataState).toBe("ready"))+ const first = hook.result.current.positionEntry+ let fail!: (error: Error) => void+ load.mockReturnValue(new Promise((_, reject) => { fail = reject }))+ await act(async () => hook.result.current.retryInitialLoad())+ const retry = hook.result.current.positionEntry+ expect(retry).not.toBe(first)+ expect(hook.result.current.positionDataState).toBe("pending")+ await act(async () => fail(new ConversationReadTimeoutError()))+ await waitFor(() => expect(hook.result.current.positionDataState).toBe("error"))+ expect(hook.result.current.messages.map(row => row.id)).toEqual(["m1"])+ expect(hook.result.current.positionEntry).toBe(retry)+ load.mockResolvedValue({ messages: conversationEntryFixture().messages, latestSeq: 1, hasMoreOlder: false, hasMoreNewer: false })+ await act(async () => hook.result.current.retryInitialLoad())+ await waitFor(() => expect(hook.result.current.positionDataState).toBe("ready"))+ expect(hook.result.current.positionEntry).not.toBe(retry)+ hook.unmount()+ })+it("keeps a missing explicit message local while a fallback qualifies the channel", async () => {const { wrapper, registry } = await setup()load.mockRejectedValueOnce(new ApiError("missing anchor", 404, [COMMUNITY_CONVERSATION_ANCHOR_MISSING])).mockResolvedValue(conversationEntryFixture())diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.tsindex 1167e0b0c..bb6972a60 100644--- a/src/web/src/hooks/community/use-messages.ts+++ b/src/web/src/hooks/community/use-messages.ts@@ -1,6 +1,6 @@"use client"-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react"+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"import { createStore, useSelector } from "@tanstack/react-store"import { hashKey, useInfiniteQuery, useQuery, useQueryClient } from "@tanstack/react-query"import type { ApiRequestOptions } from "@/lib/api/client"@@ -15,6 +15,8 @@ import { materializeMessageStream, type MessageScope } from "@/lib/community/mesimport { messageWindowOptions, type InitialMessageWindow, type MessageWindowData } from "@/lib/community/message-window"import { knownConversationLatestSeq, type findConversationEntryWindow } from "@/lib/community/conversation-entry"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"export { channelMessagesQueryFn } from "@/lib/community/message-window"@@ -69,7 +71,7 @@ type MessagesOpts = {type ChannelMessagesOpts = MessagesOpts & { serverId: string }type DisplayWindow = NonNullable<ReturnType<typeof findConversationEntryWindow>>-type PresentSelection = { attempt: number; pending: boolean; window: DisplayWindow | null; version: number; error: Error | null }+type PresentSelection = { attempt: number; pending: boolean; window: DisplayWindow | null; version: number; error: Error | null; request: MessageRequest | null }export function useMessages(channelId: string | null, opts: ChannelMessagesOpts) {return useMessageSurface(channelId, opts, opts.serverId)@@ -88,9 +90,15 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undeficonst viewKey = hashKey([channelId, serverId, anchorMessageId, tag, proof?.accountEpoch ?? -1, proof?.accessEpoch ?? -1,channelId ? proof?.channelScopes.get(channelId)?.generation ?? 0 : 0])const present = useMemo(() => ({ viewKey, intent: entry.intent,- state: createStore<PresentSelection>({ attempt: 0, pending: false, window: null, version: 0, error: null }),+ state: createStore<PresentSelection>({ attempt: 0, pending: false, window: null, version: 0, error: null, request: null }),}), [viewKey, entry.intent]).stateconst selection = useSelector(present, (state) => state)+ const retries = useMemo(() => ({ client, channelId, serverId, anchorMessageId, tag, intent: entry.intent,+ state: createStore<{ attempt: object | null; pending: boolean; error: Error | null }>({ attempt: null, pending: false, error: null }),+ }), [client, channelId, serverId, anchorMessageId, tag, entry.intent]).state+ const retrySelection = useSelector(retries, state => state)+ const positionEntry = useMemo(() => retrySelection.attempt ? { intent: entry.intent, retry: retrySelection.attempt } : entry.intent,+ [entry.intent, retrySelection.attempt])const selectedWindow = entry.canRead ? selection.window ?? entry.window : nullconst enabled = !!channelId && !!selectedWindow && entry.canReadconst initial: InitialMessageWindow = selectedWindow?.initial ?? { mode: "newest" }@@ -106,7 +114,7 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undeficonst query = useInfiniteQuery({ ...options, queryKey, enabled, subscribed: enabled })const reconciliation = useQuery({ ...messageReconcileOptions(client, { kind: serverId === null ? "dm" : "channel", scopeId: channelId ?? "__none__", serverId: serverId ?? undefined }, queryKey), enabled: false, subscribed: enabled })const originalQuery = client.getQueryCache().find({ queryKey, exact: true })- const owner = useMemo(() => ({ present, query: originalQuery, enabled }), [present, originalQuery, enabled])+ const owner = useMemo(() => ({ present, retries, query: originalQuery, enabled }), [present, retries, originalQuery, enabled])const committed = useRef<typeof owner | null>(null)useLayoutEffect(() => {committed.current = owner@@ -120,6 +128,18 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undeficonst projection = useMessageWindowProjection(entry.canRead ? channelId : null, ids, overlay.liveIds)const canonicalById = useMemo(() => new Map((projection.canonicalMessages ?? []).flatMap((message) =>typeof message.seq === "number" ? [[message.id, { ...message, seq: message.seq }] as const] : [])), [projection.canonicalMessages])+ const missingCanonical = ids.some(id => !canonicalById.has(id))+ const projectionFailed = projection.status === "error"+ const [projectionFailure, setProjectionFailure] = useState<{ window: object; attempt: object | null; viewKey: string } | null>(null)+ useEffect(() => {+ if (!entry.canRead || !query.data || !missingCanonical || projectionFailed) return+ const window = query.data, attempt = retrySelection.attempt+ const controller = new AbortController()+ void withConversationReadDeadline(controller.signal, () => new Promise<never>(() => {})).catch(error => {+ if (!controller.signal.aborted && error instanceof ConversationReadTimeoutError) setProjectionFailure({ window, attempt, viewKey })+ })+ return () => controller.abort()+ }, [entry.canRead, missingCanonical, projectionFailed, query.data, retrySelection.attempt, viewKey])const canonicalBase = useMemo(() => projection.windowIds.flatMap((id) => {const message = canonicalById.get(id)return message ? [message] : []@@ -141,26 +161,28 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undeficonst hasMoreOlder = (oldest?.hasMoreOlder ?? oldest?.hasMore) ?? falseconst historyStartKnown = !!selectedWindow && (oldest?.hasMoreOlder ?? oldest?.hasMore) === falseconst hasMoreNewer = newest?.hasMoreNewer ?? false- const fetchPage = useCallback((direction: "older" | "newer") => {+ const fetchPage = useCallback((direction: "older" | "newer"): MessageRequest => {const original = committed.current- if (!channelId || !original?.enabled || !original.query || original !== owner) return- if (direction === "older" ? !query.hasNextPage || query.isFetchingNextPage : !query.hasPreviousPage || query.isFetchingPreviousPage) return+ if (!channelId || !original?.enabled || !original.query || original !== owner) return { accepted: false }+ if (direction === "older" ? !query.hasNextPage || query.isFetchingNextPage : !query.hasPreviousPage || query.isFetchingPreviousPage) return { accepted: false }const token = captureChannelMetadataToken(client, channelId)const isCurrent = () => committed.current === original && isChannelMetadataTokenCurrent(token)&& client.getQueryCache().get(original.query!.queryHash) === original.query- const fetch = async () => {+ const fetch = async (): Promise<MessageRequestResult> => {while (isCurrent() && original.query!.state.fetchStatus !== "idle") await query.refetch({ cancelRefetch: false })- if (!isCurrent()) return- if (direction === "older") await query.fetchNextPage({ cancelRefetch: false })- else await query.fetchPreviousPage({ cancelRefetch: false })+ if (!isCurrent()) return { status: "retired" }+ const result = direction === "older" ? await query.fetchNextPage({ cancelRefetch: false })+ : await query.fetchPreviousPage({ cancelRefetch: false })+ if (!isCurrent()) return { status: "retired" }+ return result.isError || !result.data ? { status: "error" } : { status: "success", window: result.data }}- void fetch().catch(() => {})+ return { accepted: true, completed: fetch().catch(() => ({ status: "error" })) }}, [channelId, client, owner, query])const fetchOlder = useCallback(() => fetchPage("older"), [fetchPage])const fetchNewer = useCallback(() => fetchPage("newer"), [fetchPage])- const jumpToPresent = useCallback(() => {+ const jumpToPresent = useCallback((): MessageRequest => {const original = committed.current- if (!channelId || !original?.enabled || original !== owner || present.get().pending) return+ if (!channelId || !original?.enabled || original !== owner || present.get().pending) return { accepted: false }const token = captureChannelMetadataToken(client, channelId)const tail = messageWindowOptions(client, channelId, { mode: "newest" }, tag, { observation })const captured = client.getQueryCache().build<unknown, Error, unknown>(client, { queryKey: tail.queryKey })@@ -168,24 +190,43 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undeficonst attempt = present.get().attemptconst isCurrent = () => committed.current === original && isChannelMetadataTokenCurrent(token)&& client.getQueryCache().get(captured.queryHash) === captured- void client.infiniteQuery({ ...tail, staleTime: 0, select: undefined }).then(() => {- if (!isCurrent()) return+ const completed = client.infiniteQuery({ ...tail, staleTime: 0, select: undefined }).then((data): MessageRequestResult => {+ if (!isCurrent()) return { status: "retired" }present.setState((state) => ({ ...state, pending: false, version: attempt,window: { key: tail.queryKey, initial: { mode: "newest" }, tag } }))+ return { status: "success", window: data }}, (error: unknown) => {- if (!isCurrent()) return+ if (!isCurrent()) return { status: "retired" } as constpresent.setState((state) => ({ ...state, pending: false, error: error instanceof Error ? error : new Error("Could not load recent messages") }))+ return { status: "error" } as const})+ const request: MessageRequest = { accepted: true, completed }+ present.setState(state => ({ ...state, request }))+ return request}, [channelId, client, observation, owner, present, tag])const error = query.error ?? entry.errorconst windowAvailable = !!selectedWindow && query.data !== undefined- const initialLoadError = windowAvailable ? null : error ?? (entry.failed ? INITIAL_ENTRY_ERROR : null)+ const projectionError = projectionFailed || missingCanonical && !!projectionFailure && projectionFailure.window === query.data+ && projectionFailure.attempt === retrySelection.attempt && projectionFailure.viewKey === viewKey ? INITIAL_ENTRY_ERROR : null+ const initialLoadError = windowAvailable ? projectionError : retrySelection.error ?? error ?? (entry.failed ? INITIAL_ENTRY_ERROR : null)const loading = !!channelId && (windowAvailable ? projection.canonicalMessages === undefined : !initialLoadError && !entry.denied && !entry.anchorMissing)const entryWindow = entry.window, retryEntry = entry.retry, refetchWindow = query.refetchconst retryInitialLoad = useCallback(() => {- if (entryWindow) void refetchWindow({ cancelRefetch: false })- else retryEntry()- }, [entryWindow, retryEntry, refetchWindow])+ if (committed.current?.retries !== retries || retries.get().pending) return+ const attempt = {}+ const token = channelId ? captureChannelMetadataToken(client, channelId) : null+ const 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()+ void request.then(result => {+ if (!current()) return+ retries.setState(() => ({ attempt, pending: false, error: result.error }))+ })+ }, [channelId, client, entryWindow, retryEntry, refetchWindow, retries])+ const positionDataState: MessagePositionState = retrySelection.pending ? "pending"+ : initialLoadError || retrySelection.error || entry.denied || !windowAvailable && entry.anchorMissing && !entry.isFetching ? "error"+ : !windowAvailable || !entry.snapshot || loading || readSnapshotFetching ? "pending"+ : messages.length ? "ready" : "empty"return {...query, observation: { snapshot_source: entry.resource?.source ?? "unknown" as const, target_coverage: windowAvailable ? "covered" as const : "uncovered" as const,wait_reason: !entry.canRead ? "entry" as const : !windowAvailable ? "window" as const : loading ? "projection" as const : "none" as const },@@ -195,12 +236,12 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefierror, initialLoadError, isFetching: entry.isFetching || query.isFetching,isFetchingOlder: query.isFetchingNextPage,isFetchingNewer: query.isFetchingPreviousPage || selection.pending,- fetchOlder, fetchNewer, jumpToPresent, presentVersion: selection.version,+ fetchOlder, fetchNewer, jumpToPresent, presentVersion: selection.version, presentRequest: selection.request,anchorReconciled: !!selectedWindow,navigationBlocked: !entry.canRead,readSnapshot: entry.snapshot, readSnapshotFetching,initialPositionKnown: !!selectedWindow && entry.snapshot !== null && !loading && !readSnapshotFetching,- initialPositionMessageId: entry.initialPositionMessageId, positionEntry: entry.intent,+ initialPositionMessageId: entry.initialPositionMessageId, positionEntry, positionDataState, messageWindow: query.data,retryInitialLoad, retryingInitialLoad: entry.isFetching || query.isFetching,entryCanRead: entry.canRead, entryDenied: entry.denied, entryAnchorMissing: entry.anchorMissing,}diff --git a/src/web/src/hooks/community/use-messages.window.dom.test.tsx b/src/web/src/hooks/community/use-messages.window.dom.test.tsxindex 8bc5b60cf..1a8b8f3f2 100644--- a/src/web/src/hooks/community/use-messages.window.dom.test.tsx+++ b/src/web/src/hooks/community/use-messages.window.dom.test.tsx@@ -32,6 +32,22 @@ async function setup() {const options = { serverId: target.serverId, viewerUserId: "viewer" }describe("native conversation windows", () => {+ it("bounds missing canonical rows with the existing conversation read deadline", async () => {+ const { wrapper, registry } = await setup()+ load.mockResolvedValue(fixture())+ const hook = renderHook(() => useMessages("c1", options), { wrapper })+ await waitFor(() => expect(hook.result.current.positionDataState).toBe("ready"))+ vi.useFakeTimers()+ try {+ await act(async () => registry.collections.messages.utils.writeDelete("m1"))+ await act(async () => vi.advanceTimersByTimeAsync(14999))+ expect(hook.result.current.positionDataState).toBe("pending")+ await act(async () => vi.advanceTimersByTimeAsync(1))+ expect(hook.result.current.positionDataState).toBe("error")+ expect(hook.result.current.initialLoadError).toBeTruthy()+ expect(hook.result.current.readSnapshot?.lastReadMessageId).toBe("m1")+ } finally { hook.unmount(); vi.useRealTimers() }+ })it("renders the cold entry window without a second GET and keeps only references in Query", async () => {const { wrapper, client } = await setup()load.mockResolvedValue(fixture())@@ -67,6 +83,56 @@ describe("native conversation windows", () => {hook.unmount()})+ it("returns an older-page failure and accepts a later request on the same window", async () => {+ const { wrapper } = await setup()+ load.mockResolvedValue(fixture())+ const hook = renderHook(() => useMessages("c1", options), { wrapper })+ await waitFor(() => expect(hook.result.current.positionDataState).toBe("ready"))+ const original = hook.result.current.data+ load.mockRejectedValue(new ConversationReadTimeoutError())+ const failed = hook.result.current.fetchOlder()+ expect(failed.accepted).toBe(true)+ if (!failed.accepted) throw new Error("Older request was rejected")+ await act(async () => expect(await failed.completed).toEqual({ status: "error" }))+ expect(hook.result.current.data).toBe(original)+ expect(hook.result.current.messages.map(row => row.id)).toEqual(["m1"])+ load.mockResolvedValue(page("m0", 0))+ const retried = hook.result.current.fetchOlder()+ expect(retried.accepted).toBe(true)+ if (!retried.accepted) throw new Error("Older retry was rejected")+ await act(async () => expect((await retried.completed).status).toBe("success"))+ await waitFor(() => expect(hook.result.current.messages.map(row => row.id)).toEqual(["m0", "m1"]))+ hook.unmount()+ })++ it.each(["success", "error"] as const)("returns a real newer cursor request's %s receipt", async status => {+ const { wrapper } = await setup()+ const packet = fixture()+ packet.page.hasMoreNewer = true+ packet.page.newerCursor = "newer"+ load.mockResolvedValue(packet)+ const hook = renderHook(() => useMessages("c1", options), { wrapper })+ await waitFor(() => expect(hook.result.current.positionDataState).toBe("ready"))+ const original = hook.result.current.data+ load.mockImplementation(() => status === "success" ? Promise.resolve(page("m2", 2)) : Promise.reject(new ConversationReadTimeoutError()))+ let accepted!: ReturnType<typeof hook.result.current.fetchNewer>+ await act(async () => { accepted = hook.result.current.fetchNewer() })+ const pending = accepted+ expect(pending.accepted).toBe(true)+ if (!pending.accepted) throw new Error("Newer request was rejected")+ await act(async () => expect((await pending.completed).status).toBe(status))+ expect(load.mock.calls.at(-1)?.[0]).toBe("/api/community/channels/c1/messages?since=newer")+ if (status === "success") {+ await waitFor(() => expect(hook.result.current.messages.map(row => row.id)).toEqual(["m1", "m2"]))+ expect(hook.result.current.data?.pageParams).toEqual([{ mode: "newer", cursor: "newer" }, { mode: "anchor", anchor: "m1" }])+ expect(hook.result.current.hasMoreNewer).toBe(false)+ } else {+ expect(hook.result.current.data).toBe(original)+ expect(hook.result.current.messages.map(row => row.id)).toEqual(["m1"])+ }+ hook.unmount()+ })+it("keeps the old window during Jump, preserves it on failure, and switches only after a successful tail read", async () => {const { wrapper, client } = await setup()const first = deferred<MessagesPage>()diff --git a/src/web/src/hooks/community/use-scroll-anchor.lifecycle.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.lifecycle.dom.test.tsnew file mode 100644index 000000000..6c5c448f3--- /dev/null+++ b/src/web/src/hooks/community/use-scroll-anchor.lifecycle.dom.test.ts@@ -0,0 +1,380 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { act, fireEvent } from "@/test/react-dom-harness"+import { bodyTop, installMessageScrollFixture, message, mount, resize, restoreMessageScrollFixture, runFrames, scrollFixture } from "@/test/message-scroll-fixture"+import type { MessageRequest, MessageRequestResult } from "@/lib/community/message-position"++beforeEach(installMessageScrollFixture)+afterEach(restoreMessageScrollFixture)++function request() {+ let finish!: (result: MessageRequestResult) => void+ const value: MessageRequest = { accepted: true, completed: new Promise(resolve => { finish = resolve }) }+ return { value, finish }+}++describe("qualified positioning lifecycle", () => {+ it.each(["visible", "inactive", "document-hidden", "size-change"])("measures a laid-out row on first activation from %s", mode => {+ scrollFixture.firstPrefix = 120+ const visibility = vi.spyOn(document, "visibilityState", "get")+ visibility.mockReturnValue(mode === "document-hidden" ? "hidden" : "visible")+ if (mode === "size-change") scrollFixture.firstPrefix = 0+ const h = mount({ active: mode !== "inactive" && mode !== "size-change", hasMoreOlder: false,+ items: [{ ...message("first"), newDivider: true }], newDividerBefore: "first" })+ if (mode === "document-hidden") {+ visibility.mockReturnValue("visible")+ fireEvent(document, new Event("visibilitychange"))+ resize()+ } else if (mode !== "visible") {+ if (mode === "size-change") scrollFixture.firstPrefix = 120+ h.update({ active: true })+ }+ expect({+ measured: scrollFixture.latest.virtualizer.getVirtualItems().find(item => item.key === "rail:leading")?.size,+ ready: scrollFixture.latest.readPositionReady,+ }).toEqual({ measured: 120, ready: true })+ expect(h.root.scrollTop).toBe(0)+ })++ it("preserves native cached measurements when a hidden row has no physical box", () => {+ const h = mount({ items: [message("first")], hasMoreOlder: false })+ const native = scrollFixture.latest.virtualizer+ const row = h.root.querySelector<HTMLElement>('[data-message-row-key="rail:leading"]')!.closest<HTMLElement>('[data-index]')!+ const measured = native.getVirtualItems().find(item => item.key === "rail:leading")!.size+ h.stage({ active: false })+ vi.spyOn(row, "getBoundingClientRect").mockReturnValue(DOMRect.fromRect())+ const entry = { target: row, borderBoxSize: [{ blockSize: 0, inlineSize: 0 }] } as unknown as ResizeObserverEntry+ expect(native.options.measureElement(row, entry, native)).toBe(measured)+ expect(native.options.measureElement(row, undefined, native)).toBe(measured)+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ })++ it.each(["end", "target"])("admits an initially inactive %s only on its first visible commit", target => {+ const positioned = vi.fn(), cancelled = vi.fn()+ const h = mount({ active: false, ...(target === "target" ? { scrollToMessageId: "m5" } : {}),+ onScrollTargetPositioned: positioned, onScrollTargetCancelled: cancelled })+ const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")+ const index = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToIndex")+ act(() => vi.advanceTimersByTime(6500))+ expect(h.root.scrollTop).toBe(0)+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ expect(cancelled).not.toHaveBeenCalled()+ h.update({ active: true })+ expect(scrollFixture.latest.readPositionReady).toBe(true)+ if (target === "end") expect(end).toHaveBeenCalledOnce()+ else {+ expect(index).toHaveBeenCalled()+ expect(positioned).toHaveBeenCalledExactlyOnceWith("m5")+ }+ })++ it("admits a fresh entry staged while its retained pane is inactive", () => {+ const h = mount({ positionEntry: {}, initialPositionMessageId: "m4" })+ h.update({ active: false })+ h.update({ positionEntry: {}, initialPositionMessageId: "m10" })+ h.update({ active: true })+ expect(bodyTop(h.root, "m10")).toBeGreaterThan(0)+ expect(bodyTop(h.root, "m10")).toBeLessThan(h.root.clientHeight)+ expect(scrollFixture.latest.readPositionReady).toBe(true)+ })++ it.each(["end", "unread", "local"])("waits beyond five seconds for data before choosing %s", target => {+ const h = mount({ initialScrollReady: false })+ const native = scrollFixture.latest.virtualizer+ const end = vi.spyOn(native, "scrollToEnd")+ const index = vi.spyOn(native, "scrollToIndex")+ act(() => vi.advanceTimersByTime(6500))+ runFrames()+ expect(end).not.toHaveBeenCalled()+ expect(index).not.toHaveBeenCalled()+ expect(h.root.scrollTop).toBe(0)+ h.update({ initialScrollReady: true,+ ...(target === "local" ? { initialPositionMessageId: "m5" } : target === "unread" ? { newDividerBefore: "m5" } : {}),+ })+ expect(scrollFixture.latest.readPositionReady).toBe(true)+ expect(end).toHaveBeenCalledTimes(target === "end" ? 1 : 0)+ if (target !== "end") expect(bodyTop(h.root, "m5")).toBeGreaterThan(0)+ })++ it("does not revive initial positioning when data resolves after user takeover", () => {+ const h = mount({ initialScrollReady: false })+ h.move(320)+ const before = h.root.scrollTop+ const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")+ h.update({ initialScrollReady: true })+ expect(end).not.toHaveBeenCalled()+ expect(h.root.scrollTop).toBe(before)+ })++ it("keeps an explicit loaded-tail Present in data wait until the current window qualifies", () => {+ const h = mount({ initialScrollReady: false })+ const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")+ act(() => scrollFixture.latest.scrollToBottom())+ act(() => vi.advanceTimersByTime(6500))+ expect(end).not.toHaveBeenCalled()+ h.update({ initialScrollReady: true })+ expect(end).toHaveBeenCalledOnce()+ expect(scrollFixture.latest.readPositionReady).toBe(true)+ })++ it("retires a current data error without claiming a target success", () => {+ const positioned = vi.fn(), cancelled = vi.fn()+ const h = mount({ initialScrollReady: false, scrollToMessageId: "m5", onScrollTargetPositioned: positioned, onScrollTargetCancelled: cancelled })+ h.update({ positionDataState: "error" })+ expect(positioned).not.toHaveBeenCalled()+ expect(cancelled).toHaveBeenCalledExactlyOnceWith("m5")+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ })++ it("finishes an authorized empty window without a scroll and follows its first append", () => {+ const positioned = vi.fn()+ const h = mount({ items: [], positionDataState: "empty", onScrollTargetPositioned: positioned })+ expect(scrollFixture.scrollCalls.every(value => value === 0)).toBe(true)+ expect(positioned).not.toHaveBeenCalled()+ expect(scrollFixture.latest.readPositionReady).toBe(true)+ h.update({ positionDataState: "ready", items: Array.from({ length: 14 }, (_, index) => message(`first-${index}`)) })+ expect(h.root.scrollTop).toBe(h.root.scrollHeight - h.root.clientHeight)+ expect(positioned).not.toHaveBeenCalled()+ })++ it("rejects movement made in an earlier RAF before its scroll event is delivered", () => {+ window.requestAnimationFrame(() => document.querySelector<HTMLElement>('[data-testid="scroll"]')!.scrollTo({ top: 280 }))+ const h = mount({}, false, undefined, undefined, 0)+ const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")+ runFrames(1)+ expect(end).not.toHaveBeenCalled()+ runFrames()+ expect(h.root.scrollTop).toBe(280)+ expect(end).not.toHaveBeenCalled()+ })++ it.each([false, true])("bounds a qualified zero viewport once, including StrictMode=%s", strict => {+ scrollFixture.height = 0+ const h = mount({}, strict, undefined, undefined, 0)+ const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")+ act(() => vi.advanceTimersByTime(4999))+ expect(scrollFixture.latest.paginationEnabled).toBe(false)+ act(() => vi.advanceTimersByTime(1))+ expect(scrollFixture.latest.paginationEnabled).toBe(true)+ scrollFixture.height = 500+ resize()+ expect(end).not.toHaveBeenCalled()+ expect(h.root.scrollTop).toBe(0)+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ })++ it("bounds a qualified zero-width viewport without accepting a vertical-only landing", () => {+ scrollFixture.width = 0+ const h = mount({}, false, undefined, undefined, 0)+ const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")+ runFrames(320)+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ expect(scrollFixture.latest.paginationEnabled).toBe(true)+ scrollFixture.width = 320+ resize()+ expect(end).not.toHaveBeenCalled()+ expect(h.root.scrollTop).toBe(0)+ })++ it("gives a late native command only the remaining qualified budget", () => {+ scrollFixture.height = 0+ const h = mount({}, false, undefined, undefined, 0)+ act(() => vi.advanceTimersByTime(4800))+ scrollFixture.height = 500+ resize(0)+ vi.spyOn(h.root, "scrollTo").mockImplementation(() => {})+ const cancel = vi.spyOn(scrollFixture.latest.virtualizer, "cancelScroll")+ runFrames(1)+ act(() => vi.advanceTimersByTime(184))+ expect(cancel).toHaveBeenCalledOnce()+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ expect(scrollFixture.latest.paginationEnabled).toBe(true)+ })++ it("retires hidden unfinished work and ignores all of its old frames on resume", () => {+ const h = mount({}, false, undefined, undefined, 0)+ const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")+ const frames = [...scrollFixture.frames.values()]+ h.stage({ active: false })+ h.stage({ active: true })+ act(() => frames.forEach(frame => frame(performance.now())))+ resize()+ expect(end).not.toHaveBeenCalled()+ expect(h.root.scrollTop).toBe(0)+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ })++ it("retires pending work when the document becomes hidden", () => {+ const h = mount({}, false, undefined, undefined, 0)+ const visibility = vi.spyOn(document, "visibilityState", "get")+ const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")+ visibility.mockReturnValue("hidden")+ fireEvent(document, new Event("visibilitychange"))+ visibility.mockReturnValue("visible")+ fireEvent(document, new Event("visibilitychange"))+ resize()+ expect(end).not.toHaveBeenCalled()+ expect(h.root.scrollTop).toBe(0)+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ })++ it("preserves the confirmed reader and native row measurements through hiding", () => {+ const h = mount()+ h.move(420)+ const before = h.root.scrollTop+ const native = scrollFixture.latest.virtualizer+ const row = h.root.querySelector<HTMLElement>('[data-msg-id="m5"]')!.closest<HTMLElement>('[data-index]')!+ const cachedSize = native.getVirtualItems().find(item => item.key === "msg:m5")!.size+ const end = vi.spyOn(native, "scrollToEnd"), index = vi.spyOn(native, "scrollToIndex")+ h.stage({ active: false })+ expect(native.options.useCachedMeasurements).toBe(true)+ const entry = { target: row, borderBoxSize: [{ blockSize: 0, inlineSize: 0 }] } as unknown as ResizeObserverEntry+ expect(native.options.measureElement(row, entry, native)).toBe(cachedSize)+ scrollFixture.height = 0+ resize()+ scrollFixture.height = 500+ h.stage({ active: true })+ resize()+ expect(h.root.scrollTop).toBe(before)+ expect(scrollFixture.latest.readPositionReady).toBe(true)+ expect(end).not.toHaveBeenCalled()+ expect(index).not.toHaveBeenCalled()+ })++ it("uses current committed fetching conditions when an earlier geometry RAF executes", () => {+ const h = mount()+ const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")+ fireEvent.scroll(h.root)+ scrollFixture.width += 60+ h.stage({ isFetchingOlder: true })+ runFrames()+ expect(end).not.toHaveBeenCalled()+ expect(scrollFixture.latest.readPositionReady).toBe(true)+ })++ it("keeps resumed reading closed until the native viewport matches current geometry", () => {+ const h = mount()+ h.move(420)+ const before = h.root.scrollTop+ const native = scrollFixture.latest.virtualizer+ h.stage({ active: false })+ native.scrollRect = { width: 2, height: 2 }+ h.stage({ active: true })+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ scrollFixture.width += 1+ resize()+ expect(scrollFixture.latest.readPositionReady).toBe(true)+ expect(h.root.scrollTop).toBe(before)+ })++ it.each(["error", "retired", "success"] as const)("finishes a Present query with %s without an intermediate fetching render", async status => {+ const previous = {}, next = {}+ const h = mount({ messageWindow: previous, hasMoreNewer: true })+ h.move(300)+ const before = h.root.scrollTop+ const pending = request()+ act(() => scrollFixture.latest.requestPresentPosition(pending.value))+ act(() => vi.advanceTimersByTime(6500))+ expect(scrollFixture.latest.paginationEnabled).toBe(false)+ await act(async () => pending.finish(status === "success" ? { status, window: next } : { status }))+ if (status === "success") h.update({ messageWindow: next, hasMoreNewer: false })+ else expect(h.root.scrollTop).toBe(before)+ expect(scrollFixture.latest.paginationEnabled).toBe(true)+ expect(scrollFixture.latest.readPositionReady).toBe(status === "success")+ })++ it("finishes a Present request that commits an authorized empty window without scrolling", async () => {+ const previous = {}, next = {}+ const h = mount({ messageWindow: previous, hasMoreNewer: true })+ h.move(300)+ const pending = request()+ act(() => scrollFixture.latest.requestPresentPosition(pending.value))+ await act(async () => pending.finish({ status: "success", window: next }))+ const scroll = vi.spyOn(h.root, "scrollTo")+ h.update({ items: [], messageWindow: next, positionDataState: "empty", hasMoreNewer: false })+ expect(scrollFixture.latest.paginationEnabled).toBe(true)+ expect(scrollFixture.latest.readPositionReady).toBe(true)+ expect(scroll).not.toHaveBeenCalled()+ expect(h.root.querySelector("[data-msg-id]")).toBeNull()+ })++ it.each([null, { accepted: false } as const])("releases local submission when its Present request is not accepted: %s", presentRequest => {+ const h = mount({ hasMoreNewer: true, presentRequest: null })+ h.move(300)+ const before = h.root.scrollTop+ h.update({ localSubmitVersion: 1, presentRequest })+ expect(scrollFixture.latest.paginationEnabled).toBe(true)+ expect(scrollFixture.latest.readPositionReady).toBe(presentRequest !== null)+ expect(h.root.scrollTop).toBe(before)+ })++ it("does not let a superseded Present receipt consume a new target", async () => {+ const h = mount({ hasMoreNewer: true })+ const pending = request()+ act(() => scrollFixture.latest.requestPresentPosition(pending.value))+ h.update({ scrollToMessageId: "m4" })+ const before = h.root.scrollTop+ await act(async () => pending.finish({ status: "error" }))+ resize()+ expect(h.root.scrollTop).toBe(before)+ expect(scrollFixture.latest.readPositionReady).toBe(true)+ })++ it("retires a Present result superseded by a different committed window", async () => {+ const previous = {}, expected = {}, replacement = {}+ const h = mount({ messageWindow: previous, hasMoreNewer: true })+ h.move(300)+ const before = h.root.scrollTop+ const pending = request()+ act(() => scrollFixture.latest.requestPresentPosition(pending.value))+ h.update({ messageWindow: replacement })+ await act(async () => pending.finish({ status: "success", window: expected }))+ expect(scrollFixture.latest.paginationEnabled).toBe(true)+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ expect(h.root.scrollTop).toBe(before)+ })++ it("releases a completed page whose canonical projection failed", async () => {+ const previous = {}, next = {}+ const h = mount({ messageWindow: previous })+ h.move(0)+ const before = h.root.scrollTop+ const pending = request()+ act(() => scrollFixture.latest.captureOlderPageAnchor()(pending.value))+ expect(scrollFixture.latest.paginationRequestPending).toBe(true)+ await act(async () => pending.finish({ status: "success", window: next }))+ h.update({ messageWindow: next, positionDataState: "error" })+ expect(scrollFixture.latest.paginationRequestPending).toBe(false)+ expect(h.root.scrollTop).toBe(before)+ expect(scrollFixture.latest.virtualizer.options.anchorTo).toBe("start")+ })++ it.each(["error", "success"] as const)("binds local submission to its %s query result without a fetching render", async status => {+ const previous = {}, next = {}+ const h = mount({ messageWindow: previous, hasMoreNewer: true, presentRequest: null })+ h.move(300)+ const before = h.root.scrollTop+ const pending = request()+ h.update({ localSubmitVersion: 1, presentRequest: pending.value })+ await act(async () => pending.finish(status === "success" ? { status, window: next } : { status }))+ if (status === "success") h.update({ messageWindow: next, hasMoreNewer: false })+ else expect(h.root.scrollTop).toBe(before)+ expect(scrollFixture.latest.paginationEnabled).toBe(true)+ expect(scrollFixture.latest.readPositionReady).toBe(status === "success")+ })++ it.each(["rejected", "error", "retired", "empty", "prepend"])("finishes a %s page result without a fetching transition", async status => {+ const previous = {}, next = {}+ const h = mount({ messageWindow: previous })+ h.move(0)+ const before = bodyTop(h.root, "m0")+ const pending = request()+ act(() => scrollFixture.latest.captureOlderPageAnchor()(status === "rejected" ? { accepted: false } : pending.value))+ if (status !== "rejected") await act(async () => pending.finish(status === "error" || status === "retired" ? { status }+ : { status: "success", window: status === "empty" ? previous : next }))+ if (status === "prepend") h.update({ messageWindow: next, items: [message("older"), ...h.input.items] })+ else h.update({ items: [...h.input.items] })+ expect(scrollFixture.latest.virtualizer.options.anchorTo).toBe(status === "prepend" ? "end" : "start")+ expect(bodyTop(h.root, "m0")).toBeCloseTo(before, 0)+ expect(scrollFixture.latest.readPositionReady).toBe(true)+ })+})diff --git a/src/web/src/hooks/community/use-scroll-anchor.pagination.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.pagination.dom.test.tsindex d01426482..d57ca7233 100644--- a/src/web/src/hooks/community/use-scroll-anchor.pagination.dom.test.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.pagination.dom.test.ts@@ -200,7 +200,7 @@ describe("native pagination and original semantic epoch", () => {h.update({ scrollToMessageId: "not-loaded" })expect(scrollFixture.latest.readPositionReady).toBe(false)expect(consumed).not.toHaveBeenCalled()- act(() => vi.advanceTimersByTime(2000))+ act(() => vi.advanceTimersByTime(5000))expect(scrollFixture.latest.readPositionReady).toBe(false)h.update({ items: [...h.input.items, message("not-loaded")] })expect(consumed).not.toHaveBeenCalled()diff --git a/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.tsindex 1a228eec5..43411ede2 100644--- a/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.repin.dom.test.ts@@ -6,7 +6,187 @@ import { bodyTop, installMessageScrollFixture, restoreMessageScrollFixture, messbeforeEach(installMessageScrollFixture)afterEach(restoreMessageScrollFixture)+function retiredInitialReader(onInitialPositionSettled?: () => void) {+ const h = mount({ hasMoreNewer: true, onInitialPositionSettled }, false, undefined, undefined, 0)+ runFrames(1)+ act(() => h.root.scrollTo({ top: 0 }))+ runFrames(320)+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ expect(scrollFixture.latest.paginationEnabled).toBe(true)+ return h+}+describe("locked native adapter and existing message scroll owner", () => {+ it("sends the first initial end only against the measured React sizer and accepts a long final message", () => {+ scrollFixture.bodyHeights.set("m0", 1200)+ scrollFixture.bodyHeights.set("m13", 1000)+ const writes: Array<{ target: number; height: number; client: number }> = []+ const scrollTo = HTMLElement.prototype.scrollTo+ vi.spyOn(HTMLElement.prototype, "scrollTo").mockImplementation(function (this: HTMLElement, options: ScrollToOptions) {+ if ((options.top ?? 0) > 0) writes.push({+ target: options.top!,+ height: Number.parseFloat(this.querySelector<HTMLElement>('[data-message-list-content] > div')!.style.height),+ client: this.clientHeight,+ })+ scrollTo.call(this, options)+ })+ const h = mount({}, false, undefined, undefined, 0)+ const native = scrollFixture.latest.virtualizer+ const end = vi.spyOn(native, "scrollToEnd")+ expect(writes).toHaveLength(0)+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ runFrames()+ expect(end).toHaveBeenCalledOnce()+ expect(writes[0].height).toBe(native.getTotalSize())+ expect(writes[0].target).toBe(writes[0].height - writes[0].client)+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)+ const tail = h.root.querySelector<HTMLElement>('[data-msg-id="m13"]')!.getBoundingClientRect()+ expect(tail.height).toBeGreaterThan(h.root.clientHeight)+ expect(tail.bottom).toBeGreaterThan(1)+ expect(tail.top).toBeLessThan(h.root.clientHeight - 1)+ expect(scrollFixture.latest.readPositionReady).toBe(true)+ runFrames(140)+ expect(end).toHaveBeenCalledOnce()+ })+ it("lands against a changed client rect without requiring a rect-only React commit", () => {+ scrollFixture.bodyHeights.set("m0", 3000)+ let layouts = 0+ const h = mount({ items: [message("m0")], hasMoreOlder: false }, false, () => { layouts++ }, undefined, 0)+ const native = scrollFixture.latest.virtualizer+ const scrollToEnd = native.scrollToEnd.bind(native)+ const end = vi.spyOn(native, "scrollToEnd").mockImplementation(options => {+ expect(layouts).toBe(committed)+ scrollToEnd(options)+ })+ const range = { ...native.range }+ const committed = layouts+ scrollFixture.height += 40+ resize(0)+ expect(native.range).toEqual(range)+ expect(layouts).toBe(committed)+ expect(end).not.toHaveBeenCalled()+ runFrames()+ expect(end).toHaveBeenCalledOnce()+ expect(h.root.scrollTop).toBe(h.root.scrollHeight - h.root.clientHeight)+ expect(scrollFixture.latest.readPositionReady).toBe(true)+ })+ it.each(["wheel", "key", "pointer", "touch", "unlabelled"])("does not send a pending initial end after %s takeover or an old frame", input => {+ const h = mount({}, false, undefined, undefined, 0)+ const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")+ const pending = [...scrollFixture.frames.values()]+ if (input === "wheel") fireEvent.wheel(h.root, { deltaY: -20 })+ else if (input === "key") fireEvent.keyDown(h.root, { key: "PageUp" })+ else if (input === "pointer") fireEvent.pointerDown(h.root, { pointerId: 19 })+ else if (input === "touch") fireEvent.touchStart(h.root, { touches: [{ identifier: 19 }] })+ act(() => h.root.scrollTo({ top: 300 }))+ runFrames(1)+ act(() => { for (const frame of pending) frame(performance.now()) })+ runFrames()+ expect(end).not.toHaveBeenCalled()+ expect(h.root.scrollTop).toBe(300)+ })+ it("does not let a delayed frame send after the original nonempty-list budget expires", () => {+ const started = Date.now()+ scrollFixture.height = 0+ const shown = vi.fn()+ const h = mount({ onInitialPositionSettled: shown }, false, undefined, undefined, 0)+ const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")+ act(() => vi.advanceTimersByTime(4900))+ scrollFixture.height = 500+ resize(0)+ expect(shown).not.toHaveBeenCalled()+ vi.setSystemTime(started + 5001)+ runFrames(1)+ expect(end).not.toHaveBeenCalled()+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ act(() => vi.advanceTimersByTime(100))+ expect(shown).toHaveBeenCalledOnce()+ resize()+ expect(end).not.toHaveBeenCalled()+ expect(h.root.scrollTop).toBe(0)+ })+ it("does not reissue an initial end after an external scroll retires its first native command", () => {+ const h = mount({ items: Array.from({ length: 50 }, (_, index) => message(`m${index}`)) }, false, undefined, undefined, 0)+ const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")+ runFrames(1)+ expect(end).toHaveBeenCalledOnce()+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ const interrupted = h.root.scrollTop - 56+ act(() => h.root.scrollTo({ top: interrupted }))+ runFrames()+ expect(h.root.scrollTop).toBe(interrupted)+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ expect(end).toHaveBeenCalledOnce()+ runFrames(140)+ expect(h.root.scrollTop).toBe(interrupted)+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ expect(end).toHaveBeenCalledOnce()+ })+ it("waits for warm data qualification and issues the selected end once", () => {+ const h = mount({ initialScrollReady: false, items: Array.from({ length: 50 }, (_, index) => message(`m${index}`)) }, false, undefined, undefined, 0)+ const native = scrollFixture.latest.virtualizer+ const end = vi.spyOn(native, "scrollToEnd")+ runFrames(1)+ expect(end).not.toHaveBeenCalled()+ expect(scrollFixture.latest.readPositionReady).toBe(false)+ h.stage({ initialScrollReady: true })+ expect(end).not.toHaveBeenCalled()+ resize()+ expect(h.root.scrollTop).toBe(h.root.scrollHeight - h.root.clientHeight)+ expect(scrollFixture.latest.readPositionReady).toBe(true)+ runFrames(140)+ expect(end).toHaveBeenCalledOnce()+ })+ it.each(["entry", "unmount"])("invalidates an old pending first-end frame on %s", change => {+ const h = mount({ positionEntry: {} }, false, undefined, undefined, 0)+ const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")+ const pending = [...scrollFixture.frames.values()]+ if (change === "entry") h.stage({ positionEntry: {} })+ else h.view.unmount()+ act(() => { for (const frame of pending) frame(performance.now()) })+ expect(end).not.toHaveBeenCalled()+ runFrames()+ expect(end).toHaveBeenCalledTimes(change === "entry" ? 1 : 0)+ })+ it.each(["commit", "discard"])("keeps an uncommitted equal-total row layout out of the first end before %s", async outcome => {+ let resume!: () => void+ let suspended = false+ const pending = new Promise<void>(resolve => { resume = resolve })+ function Gate() { if (suspended) use(pending); return null }+ function Wrapper({ children }: PropsWithChildren) {+ return createElement(Suspense, { fallback: createElement("div", { "data-testid": "pending-first-layout" }) }, children, createElement(Gate))+ }+ const h = mount({}, false, undefined, Wrapper, 0)+ const native = scrollFixture.latest.virtualizer+ const end = vi.spyOn(native, "scrollToEnd")+ const original = h.input.items+ const total = native.getTotalSize()+ const rows = native.getVirtualItems()+ const first = rows.find(row => row.key === "msg:m0")!+ const second = rows.find(row => row.key === "msg:m1")!+ const secondStart = second.start+ suspended = true+ await act(async () => {+ startTransition(() => {+ native.resizeItem(first.index, first.size + 40)+ native.resizeItem(second.index, second.size - 40)+ h.stage({ items: [...original] })+ })+ })+ expect(native.getTotalSize()).toBe(total)+ expect(native.getVirtualItems().find(row => row.key === second.key)!.start).toBe(secondStart + 40)+ runFrames(2)+ expect(end).not.toHaveBeenCalled()+ await act(async () => {+ suspended = false+ if (outcome === "discard") h.stage({ items: original })+ resume()+ })+ resize()+ expect(end).toHaveBeenCalledOnce()+ expect(h.root.scrollTop).toBe(h.root.scrollHeight - h.root.clientHeight)+ expect(scrollFixture.latest.readPositionReady).toBe(true)+ })it("writes and clamps immediately, then coalesces native scroll delivery before frame callbacks", () => {const h = mount()const delivered = vi.fn(() => h.root.scrollTop)@@ -232,8 +412,7 @@ describe("locked native adapter and existing message scroll owner", () => {runFrames(3)expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)expect(scrollFixture.latest.readPositionReady).toBe(false)- runFrames(400)- expect(scrollFixture.frames.size).toBe(0)+ runFrames(20)bounds.mockImplementation(originalBounds)act(() => {if (event === "scroll") fireEvent.scroll(h.root)@@ -247,7 +426,7 @@ describe("locked native adapter and existing message scroll owner", () => {expect(scrollFixture.latest.readPositionReady).toBe(true)expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)})- it("uses auto for loaded-tail Present without the old timeout or pure viewport end reissue", () => {+ it("uses auto for loaded-tail Present and retires once at its finite deadline without reissue", () => {const h = mount()h.move(0)const native = scrollFixture.latest.virtualizer@@ -267,6 +446,8 @@ describe("locked native adapter and existing message scroll owner", () => {act(() => vi.advanceTimersByTime(2100))expect(offset).not.toHaveBeenCalled()expect(scrollFixture.latest.readPositionReady).toBe(false)+ expect(cancel).toHaveBeenCalledOnce()+ cancel.mockClear()fireEvent.wheel(h.root, { deltaY: -20 })expect(cancel).toHaveBeenCalledOnce()expect(offset).not.toHaveBeenCalled()@@ -444,11 +625,9 @@ describe("locked native adapter and existing message scroll owner", () => {expect(bodyTop(h.root, "first")).toBeLessThan(scrollFixture.height)expect(scrollFixture.latest.readPositionReady).toBe(true)})- it("shows after the original deadline while keeping read and peer follow closed", () => {+ it("retires failed qualified positioning while keeping read and peer follow closed", () => {const shown = vi.fn()- const h = mount({ initialScrollReady: false, hasMoreNewer: true, onInitialPositionSettled: shown })- act(() => vi.advanceTimersByTime(2000))- runFrames()+ const h = retiredInitialReader(shown)expect(shown).toHaveBeenCalledOnce()expect(scrollFixture.latest.readPositionReady).toBe(false)expect(scrollFixture.latest.paginationEnabled).toBe(true)@@ -461,9 +640,7 @@ describe("locked native adapter and existing message scroll owner", () => {expect(scrollFixture.latest.readPositionReady).toBe(true)})it.each([0, 2, 100, 300])("preserves a retired unconfirmed reader through composer shrink and grow at %ipx", distance => {- const h = mount({ initialScrollReady: false, hasMoreNewer: true })- act(() => vi.advanceTimersByTime(2000))- runFrames()+ const h = retiredInitialReader()const native = scrollFixture.latest.virtualizerconst end = vi.spyOn(native, "scrollToEnd")const index = vi.spyOn(native, "scrollToIndex")@@ -491,9 +668,7 @@ describe("locked native adapter and existing message scroll owner", () => {expect(index).not.toHaveBeenCalled()})it.each(["rectangle", "row"])("rejects an invalid %s during an unconfirmed reader resize", async invalid => {- const h = mount({ initialScrollReady: false, hasMoreNewer: true })- act(() => vi.advanceTimersByTime(2000))- runFrames()+ const h = retiredInitialReader()act(() => h.root.scrollTo({ top: h.root.scrollHeight - h.root.clientHeight }))runFrames()const native = scrollFixture.latest.virtualizer@@ -521,10 +696,7 @@ describe("locked native adapter and existing message scroll owner", () => {expect(native.options.followOnAppend).toBe(false)})it("preserves and settles a prefix page after deadline retirement without opening read or peer follow", () => {- const h = mount({ initialScrollReady: false, hasMoreNewer: true })- expect(scrollFixture.latest.paginationEnabled).toBe(false)- act(() => vi.advanceTimersByTime(2000))- runFrames()+ const h = retiredInitialReader()act(() => h.root.scrollTo({ top: 0 }))resize()act(() => scrollFixture.latest.captureOlderPageAnchor())@@ -539,9 +711,7 @@ describe("locked native adapter and existing message scroll owner", () => {expect(scrollFixture.latest.virtualizer.options).toMatchObject({ anchorTo: "start", followOnAppend: false })})it.each(["m0", "m1"])("uses native row anchoring when the pending page reaches %s with an unchanged body inset", id => {- const h = mount({ initialScrollReady: false, hasMoreNewer: true })- act(() => vi.advanceTimersByTime(2000))- runFrames()+ const h = retiredInitialReader()act(() => h.root.scrollTo({ top: 0 }))resize()act(() => scrollFixture.latest.captureOlderPageAnchor())@@ -563,15 +733,15 @@ describe("locked native adapter and existing message scroll owner", () => {expect(h.root.scrollTop).toBe(settledOffset)expect(scrollFixture.latest.readPositionReady).toBe(false)})- it("does not let pagination retire an unresolved initial intent or its deadline", () => {+ it("does not let pagination consume a data-waiting initial intent", () => {const shown = vi.fn()const h = mount({ initialScrollReady: false, hasMoreNewer: true, onInitialPositionSettled: shown })act(() => scrollFixture.latest.captureOlderPageAnchor())h.update({ isFetchingOlder: true })h.update({ isFetchingOlder: false })expect(scrollFixture.latest.virtualizer.options.anchorTo).toBe("start")- act(() => vi.advanceTimersByTime(2000))- expect(shown).toHaveBeenCalledOnce()+ act(() => vi.advanceTimersByTime(6000))+ expect(shown).not.toHaveBeenCalled()expect(scrollFixture.latest.readPositionReady).toBe(false)})it("uses stable native keys for ordinary prepend without a business index restore", () => {@@ -1388,10 +1558,10 @@ describe("locked native adapter and existing message scroll owner", () => {expect(end).toHaveBeenCalledOnce()expect(scrollFixture.latest.virtualizer.getVirtualItems().at(-1)?.key).toBe("client:send-1")})- it("keeps read closed at the early warm tail until the original unread boundary is proven", () => {+ it("keeps a warm position unchanged until the original unread boundary is qualified", () => {const h = mount({ initialScrollReady: false })expect(scrollFixture.latest.readPositionReady).toBe(false)- expect(h.root.scrollTop).toBe(h.root.scrollHeight - scrollFixture.height)+ expect(h.root.scrollTop).toBe(0)h.update({ initialScrollReady: true, newDividerBefore: "m4", items: h.input.items.map(item => ({ ...item, newDivider: item.m.id === "m4" })) })const marker = h.root.querySelector('[data-new-divider]')!.getBoundingClientRect()expect((marker.top + marker.bottom) / 2).toBeCloseTo(scrollFixture.height / 2, 0)diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.tsindex 981c76fc7..696601387 100644--- a/src/web/src/hooks/community/use-scroll-anchor.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.ts@@ -1,11 +1,12 @@import { useAtom, useCreateAtom } from "@tanstack/react-store";import { useCallback, useLayoutEffect, useRef, useState } from "react"import { measureElement, useVirtualizer, type ReactVirtualizer } from "@tanstack/react-virtual"-import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS } from "./virtualizer-react-options"+import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS, type VirtualRowsLayoutSnapshot } from "./virtualizer-react-options"import { estimateRowHeight, computeBelowCount, type FlatItem } from "@/lib/community/message-list-items"import { MESSAGE_RAIL_TAIL_PADDING_END_PX } from "@/lib/community/conversation-layout"+import type { MessagePositionState, MessageRequest, MessageRequestResult } from "@/lib/community/message-position"-const INITIAL_POSITION_TIMEOUT_MS = 2_000+const INITIAL_POSITION_TIMEOUT_MS = 5_000export const MESSAGE_LIST_DISPLAY_END_THRESHOLD_PX = 100const VIEWPORT_RESIZE_TAIL_DISTANCE_PX = 100type ViewportResizeAnchor = "tail" | "start"@@ -75,6 +76,9 @@ export function useScrollAnchor({items,newDividerBefore,initialScrollReady,+ positionDataState,+ messageWindow,+ active = true,scrollToMessageId,initialPositionMessageId,positionEntry,@@ -85,6 +89,7 @@ export function useScrollAnchor({isFetchingOlder,isFetchingNewer,presentVersion,+ presentRequest,localSubmitVersion,tailPaddingEnd = MESSAGE_RAIL_TAIL_PADDING_END_PX,onInitialPositionSettled,@@ -92,6 +97,9 @@ export function useScrollAnchor({items: FlatItem[]newDividerBefore?: stringinitialScrollReady: boolean+ positionDataState?: MessagePositionState+ messageWindow?: object+ active?: booleanscrollToMessageId?: string | nullinitialPositionMessageId?: string | nullpositionEntry?: object | null@@ -102,6 +110,7 @@ export function useScrollAnchor({isFetchingOlder?: booleanisFetchingNewer?: booleanpresentVersion?: number+ presentRequest?: MessageRequest | nulllocalSubmitVersion?: numbertailPaddingEnd?: numberonInitialPositionSettled?: () => void@@ -115,7 +124,9 @@ export function useScrollAnchor({behavior: ScrollBehaviornotifyTarget: booleanloadedTailPresent: boolean+ awaitingData: booleanviewport: { width: number; height: number }+ pendingInitialEnd: { root: HTMLDivElement | null; scrollTop: number } | null}type Geometry = {epoch: number@@ -133,6 +144,12 @@ export function useScrollAnchor({const scrollRef = useRef<HTMLDivElement>(null)const virtualizerRef = useRef<ReactVirtualizer<HTMLDivElement, Element> | null>(null)const positionOwnerRef = useRef({ epoch: 0, active: true })+ const [documentVisible, setDocumentVisible] = useState(() => typeof document === "undefined" || document.visibilityState !== "hidden")+ const visible = active && documentVisible+ const entryActivationRef = useRef({ entry: positionEntry, seen: visible })+ const dataState = positionDataState ?? (initialScrollReady ? items.some(item => item.kind === "message") ? "ready" : "empty" : "pending")+ const contextRef = useRef({ dataState, messageWindow, isFetchingOlder, isFetchingNewer, visible })+ const [requestRevision, setRequestRevision] = useState(0)const [committedEntry, setCommittedEntry] = useState(positionEntry)const entryChanged = committedEntry !== positionEntryconst positionKind = useCreateAtom<Kind>("initial")@@ -141,38 +158,50 @@ export function useScrollAnchor({const [nativeOriginKey, setNativeOriginKey] = useAtom(nativeOrigin)const readReady = useCreateAtom(false)const [readPositionReady, setReadPositionReady] = useAtom(readReady)+ const [resumeValidated, setResumeValidated] = useState(true)const [shortGap, setShortGap] = useAtom(useCreateAtom(0))const [paginationDirection, setPaginationDirection] = useAtom(useCreateAtom<"older" | "newer" | null>(null))const paginationRef = useRef<{direction: "older" | "newer"phase: "pending" | "fetching" | "settling"+ receipt?: { result?: MessageRequestResult; before?: object }anchor?: { key: string; viewportOffset: number; bodyInset: number; header: boolean; firstKey: string; epoch: number }} | null>(null)const scrollPaddingStartRef = useRef(0)const olderMeasurementAnchorRef = useRef<{ key: string; epoch: number } | null>(null)const entryResolvedRef = useRef(false)const initialRetiredRef = useRef(false)+ const initialEndIssuedRef = useRef(false)const initialPositionSettledRef = useRef(false)const initialDeadlineRef = useRef<{ handle: number; at: number } | null>(null)const initialSettleFrameRef = useRef<number | null>(null)const semanticIntentRef = useRef<Intent | null>(null)+ const committedRowsRef = useRef<{+ layout: VirtualRowsLayoutSnapshot+ native: ReactVirtualizer<HTMLDivElement, Element>+ entry: typeof positionEntry+ items: FlatItem[]+ } | null>(null)const targetIntentRef = useRef<string | null>(null)const positionedTargetRef = useRef<string | null>(null)- const presentIntentRef = useRef<{ epoch: number; allowAttachedTail: boolean; fetching: boolean } | null>(null)+ const presentIntentRef = useRef<{ epoch: number; allowAttachedTail: boolean; fetching: boolean; receipt?: { result?: MessageRequestResult; before?: object } } | null>(null)const consumedPresentVersionRef = useRef(presentVersion ?? 0)const consumedLocalSubmitVersionRef = useRef(localSubmitVersion ?? 0)const currentItemsRef = useRef(items)- const initialScrollReadyRef = useRef(initialScrollReady)+ const positionEntryRef = useRef(positionEntry)const onTargetPositionedRef = useRef(onScrollTargetPositioned)const onTargetCancelledRef = useRef(onScrollTargetCancelled)const settleCallbackRef = useRef(onInitialPositionSettled)useLayoutEffect(() => {+ if (entryActivationRef.current.entry !== positionEntry) entryActivationRef.current = { entry: positionEntry, seen: visible }+ else if (visible) entryActivationRef.current.seen = truecurrentItemsRef.current = items- initialScrollReadyRef.current = initialScrollReady+ positionEntryRef.current = positionEntryonTargetPositionedRef.current = onScrollTargetPositionedonTargetCancelledRef.current = onScrollTargetCancelledsettleCallbackRef.current = onInitialPositionSettled- }, [items, initialScrollReady, onScrollTargetPositioned, onScrollTargetCancelled, onInitialPositionSettled])+ contextRef.current = { dataState, messageWindow, isFetchingOlder, isFetchingNewer, visible }+ }, [items, positionEntry, initialScrollReady, onScrollTargetPositioned, onScrollTargetCancelled, onInitialPositionSettled, dataState, messageWindow, isFetchingOlder, isFetchingNewer, visible])const followSuspension = useCreateAtom(false)const [followSuspended, setFollowSuspended] = useAtom(followSuspension)const acceptedGeometryRef = useRef<Geometry | null>(null)@@ -181,7 +210,6 @@ export function useScrollAnchor({const reconcileViewportRef = useRef<() => void>(() => {})const userInputRef = useRef({ touch: false, pointers: new Set<number>(), handover: false })const hasMessages = items.some(item => item.kind === "message")- const hadMessagesRef = useRef(false)const pendingLocalSubmit = (localSubmitVersion ?? 0) > consumedLocalSubmitVersionRef.currentconst holdNativeOrigin = useCallback((key: string | number | bigint | null) => {setNativeOriginKey(key)@@ -251,13 +279,14 @@ export function useScrollAnchor({scheduleGeometryRef.current()}, [claimPosition, positionKind, readReady, retireInitialPosition, setReadPositionReady, settlePresentation])const armBudget = useCallback(() => {- if (initialDeadlineRef.current !== null) return+ if (!positionOwnerRef.current.active || !contextRef.current.visible || contextRef.current.dataState === "pending") return+ if (initialDeadlineRef.current?.handle) returnconst epoch = positionOwnerRef.current.epoch- const at = Date.now() + INITIAL_POSITION_TIMEOUT_MS+ const at = initialDeadlineRef.current?.at ?? Date.now() + INITIAL_POSITION_TIMEOUT_MSconst handle = window.setTimeout(() => {if (!positionOwnerRef.current.active || positionOwnerRef.current.epoch !== epoch) returnreleasePosition()- }, INITIAL_POSITION_TIMEOUT_MS)+ }, Math.max(0, at - Date.now()))initialDeadlineRef.current = { handle, at }}, [releasePosition])@@ -310,14 +339,18 @@ export function useScrollAnchor({count: items.length,getScrollElement: () => scrollRef.current,estimateSize,- measureElement: (element, entry, instance) => element.querySelector("[data-msg-id]")- ? measureMessageRow(element)- : measureElement(element, entry, instance),+ useCachedMeasurements: !visible,+ measureElement: (element, entry, instance) => {+ const rect = element.getBoundingClientRect()+ if (rect.width <= 0 || rect.height <= 0) return measureElement(element, entry, instance)+ return element.querySelector("[data-msg-id]") ? measureMessageRow(element)+ : Math.round(entry?.borderBoxSize?.[0]?.blockSize ?? rect.height)+ },getItemKey,scrollPaddingStart: scrollPaddingStartRef.current,anchorTo: !entryChanged && ownerKind === "idle" && !awaitingTarget && !pendingLocalSubmit&& (paginationDirection !== null || (readPositionReady && (nativeOriginKey === null || nativeOriginKey !== items[0]?.key))) ? "end" : "start",- followOnAppend: !entryChanged && ownerKind === "idle" && readPositionReady && !awaitingTarget && hasMessages && hadMessagesRef.current+ followOnAppend: visible && !entryChanged && ownerKind === "idle" && readPositionReady && !awaitingTarget&& !pendingLocalSubmit && !followSuspended && !hasMoreNewer&& !isFetchingOlder && !isFetchingNewer && paginationDirection === null&& (nativeOriginKey === null || nativeOriginKey !== items[0]?.key) ? "auto" : false,@@ -330,7 +363,6 @@ export function useScrollAnchor({})virtualizerRef.current = virtualizeruseLayoutEffect(() => { refreshPendingPageAnchor() })- useLayoutEffect(() => { hadMessagesRef.current = hasMessages }, [hasMessages])useLayoutEffect(() => {const anchor = olderMeasurementAnchorRef.currentif (anchor && !items.some(item => item.key === anchor.key)) clearOlderMeasurementAnchor()@@ -345,7 +377,7 @@ export function useScrollAnchor({&& (previous.clientHeight !== root?.clientHeight || previous.clientWidth !== root?.clientWidth)&& Math.abs((native?.scrollRect?.height ?? 0) - previous.clientHeight) <= 1&& Math.abs((native?.scrollRect?.width ?? 0) - previous.clientWidth) <= 1- if (!owner.active || !root || !native || root.clientHeight <= 0+ if (!owner.active || !root || !root.isConnected || !native || root.clientHeight <= 0 || root.clientWidth <= 0|| Math.abs((native.scrollOffset ?? 0) - root.scrollTop) > 1|| (!pendingViewportRect && (Math.abs((native.scrollRect?.height ?? 0) - root.clientHeight) > 1|| Math.abs((native.scrollRect?.width ?? 0) - root.clientWidth) > 1))) return null@@ -386,8 +418,40 @@ export function useScrollAnchor({const root = scrollRef.currentconst native = virtualizerRef.currentif (!intent || intent.epoch !== owner.epoch || !root || !native) return+ const pendingEnd = intent.pendingInitialEnd+ if (pendingEnd) {+ const deadline = initialDeadlineRef.current+ if (!deadline || Date.now() >= deadline.at) return+ if (pendingEnd.root !== root || Math.abs(root.scrollTop - pendingEnd.scrollTop) > 1) {+ releasePosition()+ return+ }+ const committed = committedRowsRef.current+ const layout = committed?.layout+ const rect = native.scrollRect+ const rows = native.getVirtualItems()+ const matches = committed?.native === native && committed.entry === positionEntryRef.current+ && committed.items === currentItemsRef.current && native.scrollElement === root && root.isConnected+ && layout && rect && root.clientHeight > 0 && root.clientWidth > 0+ && rect.width === root.clientWidth && rect.height === root.clientHeight+ && layout.totalSize === native.getTotalSize() && layout.scrollMargin === native.options.scrollMargin+ && layout.rows.length === rows.length && rows.length > 0+ && layout.rows.every((row, index) => {+ const current = rows[index]+ return row.key === current.key && row.index === current.index+ && row.start === current.start && row.size === current.size+ && row.end === current.end && row.lane === current.lane+ })+ if (!matches) {+ initialSettleFrameRef.current = window.requestAnimationFrame(settle)+ return+ }+ intent.pendingInitialEnd = null+ initialEndIssuedRef.current = true+ native.scrollToEnd({ behavior: intent.behavior })+ }const viewport = root.getBoundingClientRect()- if (root.clientHeight <= 0 || viewport.height <= 0) return+ if (root.clientHeight <= 0 || root.clientWidth <= 0 || viewport.height <= 0 || viewport.width <= 0) returnlet landed = falseif (intent.type === "end") {const tail = currentItemsRef.current.findLast(item => item.kind === "message")@@ -425,13 +489,18 @@ export function useScrollAnchor({}if (landed) {const geometry = readGeometry()+ if (!geometry) {+ initialSettleFrameRef.current = window.requestAnimationFrame(settle)+ return+ }if (intent.type !== "end" && root.scrollTop <= 1) holdNativeOrigin(currentItemsRef.current[0]?.key ?? null)settlePresentation()- if (positionKind.get() === "initial" && !initialScrollReadyRef.current) return+ if (contextRef.current.dataState === "pending") returnacceptedGeometryRef.current = geometrysemanticIntentRef.current = nullsetOwnerKind("idle")setReadPositionReady(true)+ setResumeValidated(true)retireInitialPosition()clearBudget()if (intent.notifyTarget && intent.id) {@@ -441,42 +510,53 @@ export function useScrollAnchor({scheduleGeometryRef.current()return}- if (!intent.loadedTailPresent) {- initialSettleFrameRef.current = window.requestAnimationFrame(settle)- }+ initialSettleFrameRef.current = window.requestAnimationFrame(settle)}initialSettleFrameRef.current = window.requestAnimationFrame(settle)- }, [clearBudget, holdNativeOrigin, positionKind, readGeometry, retireInitialPosition, setOwnerKind, setReadPositionReady, settlePresentation])+ }, [clearBudget, holdNativeOrigin, readGeometry, releasePosition, retireInitialPosition, setOwnerKind, setReadPositionReady, settlePresentation])++ const onRowsLayoutCommit = useCallback((layout: VirtualRowsLayoutSnapshot | null) => {+ committedRowsRef.current = layout ? { layout, native: virtualizer, entry: positionEntry, items } : null+ if (layout && positionOwnerRef.current.active && semanticIntentRef.current?.pendingInitialEnd) scheduleInitialPositionSettled()+ }, [items, positionEntry, scheduleInitialPositionSettled, virtualizer])const startIntent = useCallback((type: Intent["type"], id: string | null, behavior: ScrollBehavior = "auto", notifyTarget = false, loadedTailPresent = false) => {const owner = positionOwnerRef.current+ if (!owner.active || !contextRef.current.visible) returnconst index = type === "end" ? currentItemsRef.current.length - 1: id ? type === "unread" ? findMountScrollTargetIndex(currentItemsRef.current, id): findMessageIndex(currentItemsRef.current, id) : nullsemanticIntentRef.current = {epoch: owner.epoch, type, id, index, behavior, notifyTarget, loadedTailPresent,+ awaitingData: contextRef.current.dataState === "pending",viewport: { width: scrollRef.current?.clientWidth ?? 0, height: scrollRef.current?.clientHeight ?? 0 },+ pendingInitialEnd: type === "end" && positionKind.get() === "initial" && !loadedTailPresent && !initialEndIssuedRef.current+ ? { root: scrollRef.current, scrollTop: scrollRef.current?.scrollTop ?? 0 } : null,}+ if (semanticIntentRef.current.awaitingData) returnif (type === "end") {- virtualizerRef.current?.scrollToEnd({ behavior })+ if (!semanticIntentRef.current.pendingInitialEnd) virtualizerRef.current?.scrollToEnd({ behavior })}else if (index !== null) {virtualizerRef.current?.scrollToIndex(index, { align: "center", behavior })}- if (!loadedTailPresent) armBudget()+ armBudget()scheduleInitialPositionSettled()- }, [armBudget, scheduleInitialPositionSettled])+ }, [armBudget, positionKind, scheduleInitialPositionSettled])useLayoutEffect(() => {const owner = positionOwnerRef.currentowner.active = trueconst intent = semanticIntentRef.currentif (intent && intent.epoch !== owner.epoch) {- startIntent(intent.type, intent.id, intent.behavior, intent.notifyTarget, intent.loadedTailPresent)+ intent.epoch = owner.epoch+ if (intent.pendingInitialEnd) scheduleInitialPositionSettled()+ else startIntent(intent.type, intent.id, intent.behavior, intent.notifyTarget, intent.loadedTailPresent)} else if (positionKind.get() === "present" && presentIntentRef.current !== null) {presentIntentRef.current.epoch = owner.epoch- armBudget()}+ if (acceptedGeometryRef.current) acceptedGeometryRef.current.epoch = owner.epoch+ if (positionKind.get() === "initial" || semanticIntentRef.current) armBudget()return () => {owner.active = falseowner.epoch += 1@@ -484,11 +564,40 @@ export function useScrollAnchor({clearOlderMeasurementAnchor()paginationRef.current = nullcancelFrame()+ if (initialDeadlineRef.current) {+ window.clearTimeout(initialDeadlineRef.current.handle)+ initialDeadlineRef.current.handle = 0+ }+ if (geometryFrameRef.current !== null) window.cancelAnimationFrame(geometryFrameRef.current)+ geometryFrameRef.current = null+ }+ }, [armBudget, cancelFrame, clearOlderMeasurementAnchor, positionKind, scheduleInitialPositionSettled, startIntent])++ useLayoutEffect(() => {+ const update = () => setDocumentVisible(document.visibilityState !== "hidden")+ update()+ document.addEventListener("visibilitychange", update)+ return () => document.removeEventListener("visibilitychange", update)+ }, [])++ useLayoutEffect(() => {+ if (!visible) {+ setResumeValidated(false)+ if (entryActivationRef.current.seen && positionKind.get() !== "idle") releasePosition()+ positionOwnerRef.current.active = false+ virtualizerRef.current?.cancelScroll()+ cancelFrame()clearBudget()+ paginationRef.current = null+ setPaginationDirection(null)if (geometryFrameRef.current !== null) window.cancelAnimationFrame(geometryFrameRef.current)geometryFrameRef.current = null+ } else {+ positionOwnerRef.current.active = true+ if (!readReady.get() || readGeometry()) setResumeValidated(true)+ scheduleGeometryRef.current()}- }, [armBudget, cancelFrame, clearBudget, clearOlderMeasurementAnchor, positionKind, releasePosition, startIntent])+ }, [cancelFrame, clearBudget, positionKind, readGeometry, readReady, releasePosition, setPaginationDirection, visible])useLayoutEffect(() => {if (committedEntry === positionEntry) return@@ -496,6 +605,7 @@ export function useScrollAnchor({claimPosition("initial")entryResolvedRef.current = falseinitialRetiredRef.current = false+ initialEndIssuedRef.current = falseinitialPositionSettledRef.current = falsetargetIntentRef.current = nullpositionedTargetRef.current = null@@ -507,6 +617,7 @@ export function useScrollAnchor({useLayoutEffect(() => {const target = scrollToMessageId ?? null+ if (!visible && target) returnif (targetIntentRef.current === target) returntargetIntentRef.current = targetif (!target) {@@ -517,16 +628,21 @@ export function useScrollAnchor({claimPosition("target")retireInitialPosition()positionedTargetRef.current = null- if (items.length > 0) startIntent("target", target, "auto", true)- }, [claimPosition, items.length, positionEntry, positionKind, releasePosition, retireInitialPosition, scrollToMessageId, startIntent])+ if (dataState === "ready" && visible) startIntent("target", target, "auto", true)+ }, [claimPosition, dataState, items.length, positionEntry, positionKind, releasePosition, retireInitialPosition, scrollToMessageId, startIntent, visible])++ useLayoutEffect(() => {+ const intent = semanticIntentRef.current+ if (visible && dataState === "ready" && intent?.awaitingData) startIntent(intent.type, intent.id, intent.behavior, intent.notifyTarget, intent.loadedTailPresent)+ }, [dataState, startIntent, visible])useLayoutEffect(() => {- if (items.length === 0) return+ if (!visible || dataState !== "ready") returnif (positionKind.get() === "target") {if (!semanticIntentRef.current && targetIntentRef.current) startIntent("target", targetIntentRef.current, "auto", true)else scheduleInitialPositionSettled()- } else if (positionKind.get() === "initial") armBudget()- }, [armBudget, items, positionKind, scheduleInitialPositionSettled, startIntent])+ }+ }, [dataState, items, positionKind, scheduleInitialPositionSettled, startIntent, visible])const observeGeometry = useCallback((next: Geometry, scrollEvent = false) => {const previous = acceptedGeometryRef.current@@ -548,9 +664,10 @@ export function useScrollAnchor({acceptedGeometryRef.current = {...next, isScrolling: next.isScrolling && unchangedPosition ? previous.isScrolling : next.isScrolling,}+ if (readReady.get()) setResumeValidated(true)holdNativeOrigin(next.scrollTop <= 1 && !next.pinEligible ? currentItemsRef.current[0]?.key ?? null : null)}- }, [holdNativeOrigin, positionKind])+ }, [holdNativeOrigin, positionKind, readReady])const reconcileGeometry = useCallback((viewportOnly = false) => {const root = scrollRef.current@@ -588,7 +705,7 @@ export function useScrollAnchor({|| root.scrollTop < 0 || root.scrollTop > max + 1) return trueif (previous?.epoch === owner.epoch && readReady.get() && previous.pinEligible- && previous.clientWidth !== root.clientWidth && !isFetchingOlder && !isFetchingNewer) {+ && previous.clientWidth !== root.clientWidth && !contextRef.current.isFetchingOlder && !contextRef.current.isFetchingNewer && !paginationRef.current) {claimPosition("present")retireInitialPosition()startIntent("end", null, "auto", false, true)@@ -630,6 +747,7 @@ export function useScrollAnchor({setReadPositionReady(true)}if (Math.abs(offset - root.scrollTop) > 0.5) native.scrollToOffset(offset, { behavior: "auto" })+ else if (readReady.get()) setResumeValidated(true)}if (paginationRef.current?.phase === "settling") {paginationRef.current = null@@ -638,8 +756,8 @@ export function useScrollAnchor({}return false- }, [claimPosition, clearOlderMeasurementAnchor, holdNativeOrigin, isFetchingOlder, isFetchingNewer, observeGeometry, positionKind, readGeometry, readReady, retireInitialPosition, setPaginationDirection, setReadPositionReady, setShortGap, startIntent])- reconcileViewportRef.current = () => {+ }, [claimPosition, clearOlderMeasurementAnchor, holdNativeOrigin, observeGeometry, positionKind, readGeometry, readReady, retireInitialPosition, setPaginationDirection, setReadPositionReady, setShortGap, startIntent])+ const reconcileViewport = useCallback(() => {const intent = semanticIntentRef.currentconst root = scrollRef.currentconst native = virtualizerRef.current@@ -653,17 +771,22 @@ export function useScrollAnchor({}if (intent?.loadedTailPresent) scheduleInitialPositionSettled()reconcileGeometry(true)- }+ }, [reconcileGeometry, scheduleInitialPositionSettled])+ const reconcileGeometryRef = useRef(reconcileGeometry)+ useLayoutEffect(() => {+ reconcileGeometryRef.current = reconcileGeometry+ reconcileViewportRef.current = reconcileViewport+ }, [reconcileGeometry, reconcileViewport])const scheduleGeometry = useCallback(() => {if (geometryFrameRef.current !== null || !positionOwnerRef.current.active) returnconst accept = () => {geometryFrameRef.current = null- if (reconcileGeometry()) geometryFrameRef.current = window.requestAnimationFrame(accept)+ if (reconcileGeometryRef.current()) geometryFrameRef.current = window.requestAnimationFrame(accept)}geometryFrameRef.current = window.requestAnimationFrame(accept)- }, [reconcileGeometry])- scheduleGeometryRef.current = scheduleGeometry+ }, [])+ useLayoutEffect(() => { scheduleGeometryRef.current = scheduleGeometry }, [scheduleGeometry])useLayoutEffect(() => { scheduleGeometry() }, [items, ownerKind, readPositionReady, scheduleGeometry, shortGap, tailPaddingEnd])useLayoutEffect(() => {@@ -671,6 +794,8 @@ export function useScrollAnchor({if (!root) returnconst inputOwner = userInputRef.currentconst onScroll = () => {+ const pendingEnd = semanticIntentRef.current?.pendingInitialEnd+ if (pendingEnd?.root === root && Math.abs(root.scrollTop - pendingEnd.scrollTop) > 1) releasePosition()const previous = acceptedGeometryRef.currentconst native = virtualizerRef.currentif (positionKind.get() === "idle" && readReady.get()@@ -805,16 +930,45 @@ export function useScrollAnchor({}}paginationRef.current = { direction, phase: "pending", anchor }+ const page = paginationRef.currentsetPaginationDirection(direction)+ return (request: MessageRequest | void) => {+ if (paginationRef.current !== page || !request) return+ if (!request.accepted) {+ paginationRef.current = null+ setPaginationDirection(null)+ return+ }+ const receipt: NonNullable<typeof page.receipt> = { before: contextRef.current.messageWindow }+ page.receipt = receipt+ const complete = (result: MessageRequestResult) => {+ if (!positionOwnerRef.current.active || paginationRef.current !== page) return+ receipt.result = result+ setRequestRevision(value => value + 1)+ }+ void request.completed.then(complete, () => complete({ status: "error" }))+ }}, [clearOlderMeasurementAnchor, positionKind, readGeometry, readPageMessageGeometry, setPaginationDirection])const captureOlderPageAnchor = useCallback(() => capturePageAnchor("older"), [capturePageAnchor])const captureNewerPageAnchor = useCallback(() => capturePageAnchor("newer"), [capturePageAnchor])useLayoutEffect(() => {const page = paginationRef.currentif (!page || page.phase === "settling") return- const fetching = page.direction === "older" ? isFetchingOlder : isFetchingNewer- if (fetching) { page.phase = "fetching"; return }- if (page.phase !== "fetching") return+ if (page.receipt) {+ const result = page.receipt.result+ if (!result) return+ if (dataState === "error" || result.status !== "success" || result.window === page.receipt.before+ || messageWindow !== result.window && messageWindow !== page.receipt.before) {+ paginationRef.current = null+ setPaginationDirection(null)+ return+ }+ if (messageWindow !== result.window || dataState === "pending") return+ } else {+ const fetching = page.direction === "older" ? isFetchingOlder : isFetchingNewer+ if (fetching) { page.phase = "fetching"; return }+ if (page.phase !== "fetching") return+ }page.phase = "settling"let restoringBody = falseif (page.anchor && page.anchor.epoch === positionOwnerRef.current.epoch@@ -841,14 +995,37 @@ export function useScrollAnchor({}scheduleInitialPositionSettled()scheduleGeometry()- }, [adjustOlderMeasurement, holdNativeOrigin, isFetchingNewer, isFetchingOlder, items, positionKind, scheduleGeometry, scheduleInitialPositionSettled, setPaginationDirection])+ }, [adjustOlderMeasurement, dataState, holdNativeOrigin, isFetchingNewer, isFetchingOlder, items, messageWindow, positionKind, requestRevision, scheduleGeometry, scheduleInitialPositionSettled, setPaginationDirection])++ const requestPresentPosition = useCallback((request?: MessageRequest | void) => {+ if (!positionOwnerRef.current.active || !contextRef.current.visible) return+ if (request && !request.accepted) return+ const intent: NonNullable<typeof presentIntentRef.current> = { epoch: claimPosition("present"), allowAttachedTail: false, fetching: false }+ presentIntentRef.current = intent+ retireInitialPosition()+ if (request?.accepted) {+ const receipt: NonNullable<typeof intent.receipt> = { before: contextRef.current.messageWindow }+ intent.receipt = receipt+ const complete = (result: MessageRequestResult) => {+ if (!positionOwnerRef.current.active || presentIntentRef.current !== intent || positionOwnerRef.current.epoch !== intent.epoch) return+ receipt.result = result+ setRequestRevision(value => value + 1)+ }+ void request.completed.then(complete, () => complete({ status: "error" }))+ }+ }, [claimPosition, retireInitialPosition])useLayoutEffect(() => {const version = localSubmitVersion ?? 0if (version === consumedLocalSubmitVersionRef.current) returnconst accepted = version > consumedLocalSubmitVersionRef.currentconsumedLocalSubmitVersionRef.current = version- if (!accepted) return+ if (!accepted || !visible) return+ if ((hasMoreNewer || isFetchingNewer) && presentRequest !== undefined) {+ if (presentRequest) requestPresentPosition(presentRequest)+ else releasePosition()+ return+ }if (positionKind.get() === "target") releasePosition()const epoch = claimPosition("present")retireInitialPosition()@@ -856,9 +1033,8 @@ export function useScrollAnchor({if (hasMessages && !hasMoreNewer && !isFetchingNewer) startIntent("end", null)else {presentIntentRef.current = { epoch, allowAttachedTail: !hasMoreNewer && !isFetchingNewer, fetching: isFetchingNewer === true }- armBudget()}- }, [armBudget, claimPosition, hasMessages, hasMoreNewer, isFetchingNewer, localSubmitVersion, positionKind, releasePosition, retireInitialPosition, setFollowSuspended, startIntent])+ }, [claimPosition, hasMessages, hasMoreNewer, isFetchingNewer, localSubmitVersion, positionKind, presentRequest, releasePosition, requestPresentPosition, retireInitialPosition, setFollowSuspended, startIntent, visible])useLayoutEffect(() => {const completedWindow = hasMessages && !hasMoreNewer && !isFetchingNewer@@ -867,9 +1043,25 @@ export function useScrollAnchor({const owner = positionOwnerRef.currentconst intent = presentIntentRef.currentif (!owner.active || positionKind.get() !== "present" || intent?.epoch !== owner.epoch) return+ if (intent.receipt) {+ const result = intent.receipt.result+ if (!result) return+ if (result.status !== "success" || dataState === "error") { releasePosition(); return }+ if (messageWindow !== result.window && messageWindow !== intent.receipt.before) { releasePosition(); return }+ if (messageWindow !== result.window || dataState === "pending") return+ presentIntentRef.current = null+ if (dataState === "empty") {+ releasePosition()+ setReadPositionReady(true)+ } else {+ setFollowSuspended(false)+ startIntent("end", null)+ }+ return+ }+ if (dataState === "pending") returnif (isFetchingNewer) {intent.fetching = true- clearBudget()return}if (intent.fetching) armBudget()@@ -883,33 +1075,34 @@ export function useScrollAnchor({retireInitialPosition()setFollowSuspended(false)startIntent("end", null)- }, [armBudget, clearBudget, hasMessages, hasMoreNewer, isFetchingNewer, positionKind, presentVersion, releasePosition, retireInitialPosition, setFollowSuspended, startIntent])+ }, [armBudget, dataState, hasMessages, hasMoreNewer, isFetchingNewer, messageWindow, positionKind, presentVersion, releasePosition, requestRevision, retireInitialPosition, setFollowSuspended, setReadPositionReady, startIntent])const virtualItems = virtualizer.getVirtualItems()useLayoutEffect(() => {- const root = scrollRef.current- const viewportReady = !!root && root.clientHeight > 0 && virtualItems.length > 0- && !!root.querySelector("[data-index]")- if (positionKind.get() !== "initial" || initialRetiredRef.current || !hasMessages || !viewportReady) return- if (initialScrollReady && !entryResolvedRef.current) {+ if (!visible || positionKind.get() === "idle") return+ if (dataState === "error" || dataState === "empty") {+ releasePosition()+ if (dataState === "empty") setReadPositionReady(true)+ return+ }+ if (dataState === "pending") return+ if (positionKind.get() !== "initial" || initialRetiredRef.current || !hasMessages) return+ armBudget()+ if (!entryResolvedRef.current) {entryResolvedRef.current = truestartIntent(initialPositionMessageId ? "target" : newDividerBefore ? "unread" : "end", initialPositionMessageId ?? newDividerBefore ?? null)- } else if (!initialScrollReady && !hasMoreNewer && !semanticIntentRef.current) startIntent("end", null)- else scheduleInitialPositionSettled()- }, [cancelFrame, hasMessages, hasMoreNewer, initialScrollReady, initialPositionMessageId, items, newDividerBefore, positionEntry, positionKind, releasePosition, scheduleInitialPositionSettled, startIntent, virtualItems])+ } else scheduleInitialPositionSettled()+ }, [armBudget, dataState, hasMessages, initialPositionMessageId, items, newDividerBefore, positionEntry, positionKind, releasePosition, scheduleInitialPositionSettled, setReadPositionReady, startIntent, virtualItems, visible])- const requestPresentPosition = useCallback(() => {- presentIntentRef.current = { epoch: claimPosition("present"), allowAttachedTail: false, fetching: false }- retireInitialPosition()- armBudget()- }, [armBudget, claimPosition, retireInitialPosition])const scrollToBottom = useCallback(() => {+ if (!positionOwnerRef.current.active || !contextRef.current.visible) returnclaimPosition("present")retireInitialPosition()setFollowSuspended(false)startIntent("end", null, "auto", false, true)}, [claimPosition, retireInitialPosition, setFollowSuspended, startIntent])const jumpTo = useCallback((messageId: string, behavior: ScrollBehavior = "smooth") => {+ if (!positionOwnerRef.current.active || !contextRef.current.visible) returnif (findMessageIndex(currentItemsRef.current, messageId) === null) returnclaimPosition("target")retireInitialPosition()@@ -922,8 +1115,11 @@ export function useScrollAnchor({: -1const belowCount = root && virtualizer.isAtEnd(MESSAGE_LIST_DISPLAY_END_THRESHOLD_PX)? 0 : computeBelowCount(items, lastVisibleIndex)+ const pageReceipt = paginationRef.current?.receipt+ const paginationRequestPending = !!pageReceipt && (!pageReceipt.result || pageReceipt.result.status === "success" && messageWindow !== pageReceipt.result.window)return {- scrollRef, virtualizer, readPositionReady: !entryChanged && readPositionReady, paginationEnabled: !entryChanged && ownerKind === "idle" && !awaitingTarget, belowCount,+ scrollRef, virtualizer, onRowsLayoutCommit, readPositionReady: visible && resumeValidated && !entryChanged && readPositionReady, paginationEnabled: visible && dataState !== "pending" && dataState !== "error" && !entryChanged && ownerKind === "idle" && !awaitingTarget, belowCount,+ paginationRequestPending,scrollToBottom, requestPresentPosition, jumpTo,captureOlderPageAnchor, captureNewerPageAnchor,}diff --git a/src/web/src/hooks/community/use-virtual-cursor-pagination.ts b/src/web/src/hooks/community/use-virtual-cursor-pagination.tsindex 7d41d6569..672f6740a 100644--- a/src/web/src/hooks/community/use-virtual-cursor-pagination.ts+++ b/src/web/src/hooks/community/use-virtual-cursor-pagination.ts@@ -1,11 +1,12 @@"use client"-import { useEffect } from "react"+import { useEffect, useRef } from "react"import type { VirtualItem } from "@tanstack/react-virtual"+import type { MessageRequest } from "@/lib/community/message-position"export function useVirtualCursorPagination({virtualizer, count, enabled = true, hasMore, hasMoreAtStart, isFetching, isError,- onBeforeLoad, onLoad, edge,+ onBeforeLoad, onLoad, edge, requestKey,}: {virtualizer: { getVirtualItems: () => VirtualItem[] }count: number@@ -14,17 +15,25 @@ export function useVirtualCursorPagination({hasMoreAtStart?: booleanisFetching?: booleanisError?: boolean- onBeforeLoad?: () => void- onLoad?: () => void+ onBeforeLoad?: () => void | ((request: MessageRequest | void) => void)+ onLoad?: () => MessageRequest | voidedge: "start" | "end"+ requestKey?: object}) {const virtualItems = virtualizer.getVirtualItems()+ const attempted = useRef<{ count: number; key: VirtualItem["key"]; window?: object; legacy: boolean } | null>(null)useEffect(() => {const boundary = edge === "start" ? virtualItems[0] : virtualItems.at(-1)+ if (isFetching && attempted.current?.legacy) attempted.current = nullif (!enabled || !boundary || count === 0 || !hasMore || isFetching || isError || !onLoad) return- if (edge === "start" ? boundary.index > 0 : boundary.index < count - 1) return+ if (edge === "start" ? boundary.index > 0 : boundary.index < count - 1) { attempted.current = null; return }if (edge === "end" && hasMoreAtStart && virtualItems[0]?.index === 0) return- onBeforeLoad?.()- onLoad()- }, [count, edge, enabled, hasMore, hasMoreAtStart, isFetching, isError, onBeforeLoad, onLoad, virtualItems])+ if (attempted.current?.count === count && attempted.current.key === boundary.key && attempted.current.window === requestKey) return+ const attempt = { count, key: boundary.key, window: requestKey, legacy: false }+ attempted.current = attempt+ const receive = onBeforeLoad?.()+ const request = onLoad()+ attempt.legacy = !request+ receive?.(request)+ }, [count, edge, enabled, hasMore, hasMoreAtStart, isFetching, isError, onBeforeLoad, onLoad, requestKey, virtualItems])}diff --git a/src/web/src/hooks/community/virtualizer-react-options.ts b/src/web/src/hooks/community/virtualizer-react-options.tsindex d5f11cfe6..776228048 100644--- a/src/web/src/hooks/community/virtualizer-react-options.ts+++ b/src/web/src/hooks/community/virtualizer-react-options.ts@@ -1,3 +1,11 @@+import type { VirtualItem } from "@tanstack/react-virtual"++export type VirtualRowsLayoutSnapshot = {+ totalSize: number+ scrollMargin: number+ rows: VirtualItem[]+}+export const COMMUNITY_VIRTUALIZER_REACT_OPTIONS = {useFlushSync: true,directDomUpdates: true,diff --git a/src/web/src/lib/community-db/projections.ts b/src/web/src/lib/community-db/projections.tsindex cb60baacf..e128d85db 100644--- a/src/web/src/lib/community-db/projections.ts+++ b/src/web/src/lib/community-db/projections.ts@@ -309,7 +309,7 @@ export function useRouteChannelProjection(channelId: string | null) {function useJoinedMessageQuery(channelId: string | null | undefined, ids?: readonly string[]) {const registry = useOptionalCommunityDbRegistry()const result = useLiveQuery(communityJoinedMessagesQuery(registry, channelId, ids))- return { registry, data: result.data as Array<{ message: MessageRow; child?: ChannelRow }> | undefined }+ return { registry, data: result.data as Array<{ message: MessageRow; child?: ChannelRow }> | undefined, status: result.status }}export function useCanonicalMessagesById(ids?: readonly string[]): ReadonlyMap<string, Msg> | undefined {@@ -323,11 +323,11 @@ export function useCanonicalMessagesById(ids?: readonly string[]): ReadonlyMap<sexport function useMessageWindowProjection(channelId: string | null, ids: readonly string[], liveIds: readonly string[]) {const allIds = useMemo(() => [...new Set([...ids, ...liveIds])], [ids, liveIds])- const { data } = useJoinedMessageQuery(channelId, allIds)+ const { data, status } = useJoinedMessageQuery(channelId, allIds)const canonicalMessages = useMemo(() => !channelId || !data ? undefined : data.sort((a, b) => (a.message.seq ?? 0) - (b.message.seq ?? 0)).map(({ message, child }) => projectedCanonicalMessage(message, child)), [channelId, data])- return { canonicalMessages, windowIds: ids }+ return { canonicalMessages, windowIds: ids, status }}function useCollectionById<N extends "channels" | "servers">(name: N) {diff --git a/src/web/src/lib/community/message-position.ts b/src/web/src/lib/community/message-position.tsnew file mode 100644index 000000000..47e3eeccc--- /dev/null+++ b/src/web/src/lib/community/message-position.ts@@ -0,0 +1,9 @@+export type MessagePositionState = "pending" | "ready" | "empty" | "error"++export type MessageRequestResult =+ | { status: "success"; window: object }+ | { status: "error" | "retired" }++export type MessageRequest =+ | { accepted: false }+ | { accepted: true; completed: Promise<MessageRequestResult> }diff --git a/src/web/src/test/e2e-ui/01-auth.spec.ts b/src/web/src/test/e2e-ui/01-auth.spec.tsindex d2d5366ba..70b3342cf 100644--- a/src/web/src/test/e2e-ui/01-auth.spec.ts+++ b/src/web/src/test/e2e-ui/01-auth.spec.ts@@ -84,7 +84,7 @@ async function expectCenteredNativeOauthState(// global-setup, so this journey re-verifies the redirect/auth contract with a// FRESH context (no saved session) plus an authenticated landing.test.describe("auth & first screen", () => {- test("unauthenticated /c deep-link redirects to /sign-in with redirect param", async ({ browser, caseResources }) => {+ test("unauthenticated /c deep-link redirects to /sign-in with redirect param", async ({ caseResources }) => {const context = await caseResources.newContext() // no storageState — anonymousconst page = await context.newPage()await page.goto("/c/channels/does-not-matter/whatever")diff --git a/src/web/src/test/e2e-ui/15-mention-scope.spec.ts b/src/web/src/test/e2e-ui/15-mention-scope.spec.tsindex a7bfe7b33..22067bd44 100644--- a/src/web/src/test/e2e-ui/15-mention-scope.spec.ts+++ b/src/web/src/test/e2e-ui/15-mention-scope.spec.ts@@ -84,7 +84,7 @@ test.describe("mentions — candidate scope", () => {test("public top-level channel → whole server roster (bob AND carol), backed by servers/:id/members", async ({ caseActors }) => {const actors = await caseActors(["alice", "bob", "carol"])const { asUser } = actors- const { serverId, publicChannelId, alice, bob, carol, openMentionPopup } = await prepareCase1(actors)+ const { serverId, publicChannelId, alice, openMentionPopup } = await prepareCase1(actors)const { page } = await asUser("alice")// The channel-members endpoint must NOT be hit for a public channel — the@@ -119,7 +119,7 @@ test.describe("mentions — candidate scope", () => {test("private channel → audience only (bob present, carol absent), backed by channels/:id/members", async ({ caseActors }) => {const actors = await caseActors(["alice", "bob", "carol"])const { asUser } = actors- const { serverId, privateChannelId, bob, carol, openMentionPopup } = await prepareCase1(actors)+ const { serverId, privateChannelId, openMentionPopup } = await prepareCase1(actors)const { page } = await asUser("alice")const channelMembersReq = page.waitForRequest(@@ -145,7 +145,7 @@ test.describe("mentions — candidate scope", () => {test("thread in private channel → PARENT channel audience (bob mentionable though not a participant)", async ({ caseActors }) => {const actors = await caseActors(["alice", "bob", "carol"])const { asUser } = actors- const { serverId, threadId, bob, carol, openMentionPopup } = await prepareCase1(actors)+ const { serverId, threadId, openMentionPopup } = await prepareCase1(actors)const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${threadId}`)@@ -206,7 +206,7 @@ test.describe("mentions — candidate scope", () => {test("forum post reply → post audience (bob present, carol absent)", async ({ caseActors }) => {const actors = await caseActors(["alice", "bob", "carol"])const { asUser } = actors- const { serverId, privatePostId, bob, carol, openMentionPopup } = await prepareCase1(actors)+ const { serverId, privatePostId, openMentionPopup } = await prepareCase1(actors)const { page } = await asUser("alice")await page.goto(`/c/channels/${serverId}/${privatePostId}`)diff --git a/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts b/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.tsindex c1b28a71f..60b50c600 100644--- a/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts+++ b/src/web/src/test/e2e-ui/25-community-ws-reconnect-overlay.spec.ts@@ -249,7 +249,7 @@ test("a real WebSocket outage keeps cached content interactive and Retry reconne}})-test("an active onboarding form keeps focus priority during a reconnect", async ({ browser, caseResources }) => {+test("an active onboarding form keeps focus priority during a reconnect", async ({ caseResources }) => {test.setTimeout(90_000)const context = await caseResources.newContext({ viewport: { width: 390, height: 844 } })const page = await context.newPage()diff --git a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.tsindex 5d2efa535..101154c7f 100644--- a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts+++ b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts@@ -422,7 +422,7 @@ test("same message row recovers its action menu from mouse to touch", async ({ c))).toHaveLength(messageCreatesBefore)})-test("mobile reply, avatar mention, and typing rail keep exact backend and WS identity", async ({ caseActors }) => {+test("mobile reply, avatar mention, and typing rail keep exact backend and WS identity", async ({ caseActors }, testInfo) => {test.setTimeout(240_000)const actors = await caseActors(["alice", "bob"])const { asUser, userId } = actors@@ -1007,10 +1007,22 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS idconst navigationDraft = `navigation draft ${stamp}`const navigationEditable = composerEditable(alice.page)await navigationEditable.fill(navigationDraft)- const readingPosition = await scroller.evaluate((element) => {- element.scrollTop = Math.min(2200, Math.max(0, element.scrollHeight - element.clientHeight))+ await expect(scroller.locator("[data-message-list-content]")).toHaveAttribute("data-read-position-ready", "true")+ await expect.poll(() => scroller.evaluate((element) => (+ element.scrollHeight - element.clientHeight+ ))).toBeGreaterThanOrEqual(2200)+ const readingSample = await scroller.evaluate((element) => {+ const before = { time: performance.now(), top: element.scrollTop, height: element.scrollHeight, client: element.clientHeight }+ const target = Math.min(2200, Math.max(0, element.scrollHeight - element.clientHeight))+ element.scrollTop = target+ const assigned = element.scrollTopelement.dispatchEvent(new Event("scroll"))- return element.scrollTop+ const after = { time: performance.now(), top: element.scrollTop, height: element.scrollHeight, client: element.clientHeight }+ return { before, target, assigned, after }+ })+ const readingPosition = readingSample.after.top+ if (readingPosition !== 2200) await testInfo.attach("channel-reading-position", {+ body: JSON.stringify(readingSample), contentType: "application/json",})expect(readingPosition).toBe(2200)const channelReadState = await settledReadState(alice.page, channelId)diff --git a/src/web/src/test/e2e-ui/42-versioned-avatar-identity.spec.ts b/src/web/src/test/e2e-ui/42-versioned-avatar-identity.spec.tsindex f6f1cdf7c..20c52fc8d 100644--- a/src/web/src/test/e2e-ui/42-versioned-avatar-identity.spec.ts+++ b/src/web/src/test/e2e-ui/42-versioned-avatar-identity.spec.ts@@ -8,10 +8,9 @@ import {proxyCommunityWebSockets,type CapturedCommunityFrame,} from "./_fixtures/community-ws-proxy"-import type { CaseActors, CaseResources } from "./_fixtures/case-fixture"+import type { CaseResources } from "./_fixtures/case-fixture"-async function prepareCase(actors: CaseActors) {- const { userId } = actors+function prepareCase() {function identityEvents(frames: CapturedCommunityFrame[], subjectId: string) {return frames.flatMap(communityFrameEvents).filter((event) => (event.type === "community:identity.update"&& event.userId === subjectId))@@ -80,7 +79,7 @@ test("versioned avatars converge across live, stale, reconnect, cold, and concurconst actors = await caseActors(["alice", "bob", "dave"])const { asUser, userId, userName } = actorsconst { seedChannel, seedDm, seedDmMessage, seedFriendship, seedJoinServer, seedMessage, seedServer } = actors.seed- const { identityEvents } = await prepareCase(actors)+ const { identityEvents } = prepareCase()const stamp = Date.now()const aliceId = userId("alice")diff --git a/src/web/src/test/message-scroll-fixture.ts b/src/web/src/test/message-scroll-fixture.tsindex 01335b08b..d9a9719ba 100644--- a/src/web/src/test/message-scroll-fixture.ts+++ b/src/web/src/test/message-scroll-fixture.ts@@ -85,6 +85,7 @@ function Probe({ input, onLayout }: { input: Input; onLayout?: (result: Result)createElement("div", { "data-message-list-content": "", "data-read-position-ready": String(result.readPositionReady) },createElement(VirtualRows<FlatItem>, {items, virtualizer: result.virtualizer, reactLayout: true,+ onLayoutCommit: result.onRowsLayoutCommit,renderItem: (item) => createElement("div", {"data-message-row-key": item.key,"data-fixture-kind": item.kind,@@ -152,12 +153,12 @@ export function resize(frameCount = 26) {})runFrames(frameCount)}-export function mount(overrides: Partial<Input> = {}, strict = false, onLayout?: (result: Result) => void, wrapper?: RenderOptions["wrapper"]) {+export function mount(overrides: Partial<Input> = {}, strict = false, onLayout?: (result: Result) => void, wrapper?: RenderOptions["wrapper"], initialFrames = 26) {const input: Input = { items: Array.from({ length: 14 }, (_, i) => message(`m${i}`)), initialScrollReady: true, hasMoreOlder: true, ...overrides }const element = () => strict ? createElement(StrictMode, null, createElement(Probe, { input, onLayout })) : createElement(Probe, { input, onLayout })const view = render(element(), { wrapper })const root = view.getByTestId("scroll") as HTMLElement- resize()+ resize(initialFrames)const stage = (next: Partial<Input>) => { Object.assign(input, next); view.rerender(element()) }const update = (next: Partial<Input>) => { stage(next); resize() }const move = (offset: number) => {