Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): streamline conversation entry and member search (#1019)

Generd104c209d995
diff --git a/src/web/src/app/c/layout.dom.test.ts b/src/web/src/app/c/layout.dom.test.ts
index 17ee5f540..2ff0f1425 100644
--- a/src/web/src/app/c/layout.dom.test.ts
+++ b/src/web/src/app/c/layout.dom.test.ts
@@ -121,7 +121,10 @@ describe("CommunityLayout session boundary", () => {
"src/app/c/me/layout.tsx",
), "utf8")
expect(source).not.toContain("useDmRouteVerification")
- expect(source).toContain('<DmRoute key={`${currentUser.id}/${dmId}`} dmId={dmId} />')
+ expect(source).not.toContain("<DmRoute")
+ const host = readFileSync(resolve(process.cwd(), process.cwd().endsWith("/src/web") ? "" : "src/web", "src/components/community/shell/shell-frame-view.tsx"), "utf8")
+ expect(host).toContain('checkpoint.main.kind === "dm-route"')
+ expect(host).toContain("routeCommitted={routeCommitted}")
expect(source).not.toMatch(/isFetching:\s*dmsFetching/)
})
diff --git a/src/web/src/app/c/me/[dmId]/page.test.ts b/src/web/src/app/c/me/[dmId]/page.test.ts
index 07a80381e..8d0d58f09 100644
--- a/src/web/src/app/c/me/[dmId]/page.test.ts
+++ b/src/web/src/app/c/me/[dmId]/page.test.ts
@@ -40,7 +40,7 @@ describe("DM page loading ownership", () => {
it("owns lazy channel-directory state and retry inside the keyed DM view", () => {
const source = readFileSync(new URL("../../../../components/community/channels/dm-view.tsx", import.meta.url), "utf8")
- expect(source).toContain("export function DmView({ dmId }")
+ expect(source).toContain("export function DmView({ dmId, routeCommitted")
expect(source).toContain("useChannelRefDirectory(channelRefDirectoryEnabled)")
expect(source).toContain("loading: !channelRefDirectoryResolved")
expect(source).toContain("failed: channelRefDirectoryError")
diff --git a/src/web/src/app/c/me/layout.route-memory.dom.test.ts b/src/web/src/app/c/me/layout.route-memory.dom.test.ts
index fca1b7d6d..057349089 100644
--- a/src/web/src/app/c/me/layout.route-memory.dom.test.ts
+++ b/src/web/src/app/c/me/layout.route-memory.dom.test.ts
@@ -173,12 +173,13 @@ describe("MeLayout route memory", () => {
expect(mocks.setLastMeLocation).toHaveBeenCalledWith(`/c/me/${leaf}`)
})
- it("uses its own committed DM child instead of another slot's DM param", () => {
+ it("leaves the DM body to the shared checkpoint instead of mounting another slot's DM", () => {
mocks.pathname = "/c/me/own-dm"
mocks.childSegments = ["own-dm"]
mocks.dmId = "foreign-slot-dm"
const rendered = renderLayout()
- expect(rendered.getByTestId("target-dm")).toHaveAttribute("data-channel-id", "own-dm")
+ expect(rendered.queryByTestId("target-dm")).toBeNull()
+ expect(rendered.getByTestId("static-content")).toBeVisible()
expect(mocks.setLastMeLocation).not.toHaveBeenCalled()
})
@@ -201,21 +202,21 @@ describe("MeLayout route memory", () => {
expect(mocks.replace).not.toHaveBeenCalled()
})
- it("mounts each target DM while Next children stay on the neutral root, without saving last in layout", () => {
+ it("keeps neutral Next children while the shared checkpoint owns changing DM bodies", () => {
mocks.pathname = "/c/me/dm-a"
mocks.dmId = "dm-a"
const client = layoutClient
const tree = () => createElement(QueryClientProvider, { client, userId: "viewer-1" },
createElement(MeLayout, null, createElement("div", { "data-testid": "neutral-leaf" }, "Loading your space")))
const rendered = render(tree())
- expect(rendered.getByTestId("target-dm").getAttribute("data-channel-id")).toBe("dm-a")
- expect(rendered.queryByTestId("neutral-leaf")).toBeNull()
+ expect(rendered.queryByTestId("target-dm")).toBeNull()
+ expect(rendered.getByTestId("neutral-leaf")).toBeVisible()
mocks.pathname = "/c/me/dm-b"
mocks.dmId = "dm-b"
rendered.rerender(tree())
- expect(rendered.getByTestId("target-dm").getAttribute("data-channel-id")).toBe("dm-b")
+ expect(rendered.queryByTestId("target-dm")).toBeNull()
expect(rendered.queryByText("dm-a")).toBeNull()
- expect(rendered.queryByTestId("neutral-leaf")).toBeNull()
+ expect(rendered.getByTestId("neutral-leaf")).toBeVisible()
expect(mocks.setLastMeLocation).not.toHaveBeenCalled()
expect(mocks.commitLastCommunityRoute).not.toHaveBeenCalled()
rendered.unmount()
diff --git a/src/web/src/app/c/me/layout.tsx b/src/web/src/app/c/me/layout.tsx
index 3698f6753..8d2aa424c 100644
--- a/src/web/src/app/c/me/layout.tsx
+++ b/src/web/src/app/c/me/layout.tsx
@@ -2,7 +2,6 @@
import { useEffect, type ReactNode } from "react"
import { useSelectedLayoutSegments, usePathname } from "next/navigation"
-import { DmRoute } from "@/components/community/channels/dm-route"
import { useCurrentUser } from "@/contexts/community/current-user"
import { isRememberableMeLocation, setLastMeLocation } from "@/lib/community/last-me-location"
import { commitLastCommunityRoute } from "@/lib/community/last-community-route"
@@ -20,7 +19,5 @@ export default function MeLayout({ children }: { children: ReactNode }) {
setLastMeLocation(pathname)
commitLastCommunityRoute(currentUser.id, pathname)
}, [currentUser.id, dmId, pathname])
- return dmId
- ? <DmRoute key={`${currentUser.id}/${dmId}`} dmId={dmId} />
- : children
+ return children
}
diff --git a/src/web/src/components/community/channels/dm-route.dom.test.ts b/src/web/src/components/community/channels/dm-route.dom.test.ts
index 7e7471b63..12a5ae700 100644
--- a/src/web/src/components/community/channels/dm-route.dom.test.ts
+++ b/src/web/src/components/community/channels/dm-route.dom.test.ts
@@ -103,6 +103,17 @@ describe("DM target main owns identity, retry and fallback", () => {
expect(mocks.clear).not.toHaveBeenCalled()
})
+ it("does not replace or clear memory for a denied pending target before route publication", () => {
+ mocks.verification.status = "denied"
+ const view = render(React.createElement(DmRoute, { dmId: "dm-a", routeCommitted: false }))
+ expect(mocks.replace).not.toHaveBeenCalled()
+ expect(mocks.clear).not.toHaveBeenCalled()
+ expect(mocks.cancel).not.toHaveBeenCalled()
+ view.rerender(React.createElement(DmRoute, { dmId: "dm-a", routeCommitted: true }))
+ expect(mocks.replace).toHaveBeenCalledExactlyOnceWith("/c/me")
+ expect(mocks.clear).toHaveBeenCalledOnce()
+ })
+
it.each([false, true])("exits an unknown denied target and retires only matching last memory, cold=%s", (cold) => {
mocks.verification.status = "denied"
mocks.cold = cold
diff --git a/src/web/src/components/community/channels/dm-route.tsx b/src/web/src/components/community/channels/dm-route.tsx
index c5e42a1d6..63b9241e1 100644
--- a/src/web/src/components/community/channels/dm-route.tsx
+++ b/src/web/src/components/community/channels/dm-route.tsx
@@ -17,7 +17,7 @@ import {
consumeCommunityColdEntryFailure,
} from "@/lib/community/last-community-route"
-export function DmRoute({ dmId }: { dmId: string }) {
+export function DmRoute({ dmId, routeCommitted = true }: { dmId: string; routeCommitted?: boolean }) {
const runtime = useCommunityRuntime()
const router = useRouter()
const currentUser = useCurrentUser()
@@ -25,7 +25,7 @@ export function DmRoute({ dmId }: { dmId: string }) {
const knownDm = useDmProjection()?.some(dm => dm.id === dmId) === true
const exitedTarget = useRef<string | null>(null)
useEffect(() => {
- if (verification.status !== "denied" || verification.identityKnown || knownDm) return
+ if (!routeCommitted || verification.status !== "denied" || verification.identityKnown || knownDm) return
const target = JSON.stringify([currentUser.id, dmId])
if (exitedTarget.current === target) return
exitedTarget.current = target
@@ -36,7 +36,7 @@ export function DmRoute({ dmId }: { dmId: string }) {
if (getLastMeLeaf() === dmId) clearLastMeLocation()
runtime.ui.get().uiHandlers.cancelPendingNavigation?.()
router.replace(destination)
- }, [currentUser.id, dmId, router, runtime, verification.status, verification.identityKnown, knownDm])
+ }, [currentUser.id, dmId, routeCommitted, router, runtime, verification.status, verification.identityKnown, knownDm])
if (verification.status === "retryable-error" && !verification.identityKnown && !knownDm) {
return <DmRouteErrorFrame onRetry={verification.retry} retrying={verification.retrying}
@@ -45,5 +45,5 @@ export function DmRoute({ dmId }: { dmId: string }) {
if (!verification.identityKnown && !knownDm && verification.status !== "readable") {
return <DmLoadingFrame reserveBackSlot />
}
- return <DmView dmId={dmId} />
+ return <DmView dmId={dmId} routeCommitted={routeCommitted} />
}
diff --git a/src/web/src/components/community/channels/dm-view.tsx b/src/web/src/components/community/channels/dm-view.tsx
index 1cb3b793f..b0abd0ff8 100644
--- a/src/web/src/components/community/channels/dm-view.tsx
+++ b/src/web/src/components/community/channels/dm-view.tsx
@@ -80,7 +80,7 @@ function resolveDmLoadingOwnership({
}
}
-export function DmView({ dmId }: { dmId: string }) {
+export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCommitted?: boolean }) {
const communityRuntime = useCommunityRuntime()
const sendView = useCommunityViewSource(`dm-send:${dmId}`)
const bp = useBreakpoint()
@@ -90,9 +90,6 @@ export function DmView({ dmId }: { dmId: string }) {
const notifications = useNotificationSettings()
const setNotification = useSetChannelNotif()
- // MeLayout owns the canonical cold DMs fetch. This second observer consumes
- // that result without treating it as stale on mount; explicit WS/query
- // invalidation still refetches the active canonical key.
const dmsQuery = useDms()
const dms = dmsQuery.dms
const dmsLoading = dmsQuery.isLoading
@@ -153,7 +150,7 @@ export function DmView({ dmId }: { dmId: string }) {
const [contextSheetSeq, setContextSheetSeq] = useAtom(useCreateAtom<number | null>(null))
useDmSeqContext({ dmId, historyAllowed,
- navigationAllowed: !navigationBlocked,
+ navigationAllowed: routeCommitted && !navigationBlocked,
setContextSeq: setContextSheetSeq,
})
// DM composer has no "current server" — flatten every member server's
@@ -404,13 +401,13 @@ export function DmView({ dmId }: { dmId: string }) {
const routeReady = historyAllowed && !navigationBlocked && !loadingOwnership.fullFramePending
&& !loadingOwnership.missingPeer && !!dm
useEffect(() => {
- if (!routeReady) return
+ if (!routeCommitted || !routeReady) return
commitCommunityChannelRoute(currentUser.id, null, dmId)
- }, [currentUser.id, dmId, routeReady])
+ }, [currentUser.id, dmId, routeCommitted, routeReady])
useNativeSystemNotificationConversationDismissal(currentUser.id, {
kind: "dm",
channelId: dmId,
- }, routeReady)
+ }, routeCommitted && routeReady)
if (!dm && !metadata.revoked && !metadata.denied && !dmBlocked && navigationBlocked && !initialLoadError && metadata.status !== "retryable-error") {
return <DmLoadingFrame reserveBackSlot />
diff --git a/src/web/src/components/community/members/channel-member-view-model.tsx b/src/web/src/components/community/members/channel-member-view-model.tsx
index 909416464..da584c07d 100644
--- a/src/web/src/components/community/members/channel-member-view-model.tsx
+++ b/src/web/src/components/community/members/channel-member-view-model.tsx
@@ -292,6 +292,7 @@ export function useChannelMemberViewModel({
searchQuery: membersHook.searchQuery,
searchStatus: membersHook.searchStatus,
loadMore: membersHook.loadMore,
+ retry: membersHook.refresh,
search: membersHook.searchMembers,
},
[
@@ -301,6 +302,7 @@ export function useChannelMemberViewModel({
membersHook.failed,
membersHook.hasMore,
membersHook.loadMore,
+ membersHook.refresh,
membersHook.loading,
membersHook.loadingMore,
membersHook.searchMembers,
@@ -325,6 +327,11 @@ export function useChannelMemberViewModel({
}
: undefined
+ const searchLocalMembers = useCallback((query: string) => {
+ setMemberUi(current => current.channelId === channelId && current.query === query ? current
+ : { channelId, query, dialogOpen: current.channelId === channelId && current.dialogOpen })
+ }, [channelId, setMemberUi])
+
const memberPanelProps: ChannelMemberPanelProps = {
memberScopeId: `${serverId}:${channelId}`,
members: panelMembers,
@@ -333,7 +340,7 @@ export function useChannelMemberViewModel({
membersHasMore: scopedDrawer ? false : membersHook.hasMore,
onLoadMoreMembers: scopedDrawer ? undefined : membersHook.loadMore,
onSearchMembers: scopedDrawer
- ? (query) => setMemberUi({ channelId, query, dialogOpen: manageMembersOpen })
+ ? searchLocalMembers
: membersHook.searchMembers,
onAddMember: scopedDrawer
? () => setMemberUi({ channelId, query: memberQuery, dialogOpen: true })
diff --git a/src/web/src/components/community/members/member-list.tsx b/src/web/src/components/community/members/member-list.tsx
index cbf95c404..b64b669b6 100644
--- a/src/web/src/components/community/members/member-list.tsx
+++ b/src/web/src/components/community/members/member-list.tsx
@@ -167,14 +167,9 @@ export function MemberList({
if (manageConfirm && !manageTarget) setManageConfirm(null)
}, [kickTargetId, kickTarget, manageConfirm, manageTarget, command.status, pending, setKickTargetId, setManageConfirm])
- // Debounced search — 200ms mirrors the hook's own debounce for consistency
- // (the hook debounces the network call; this debounces the callback fire
- // so we don't spam the hook on every keystroke).
useEffect(() => {
if (!onSearch) return
- const assert = source.capture()
- const t = setTimeout(() => { try { assert(); onSearch(query) } catch {} }, 200)
- return () => clearTimeout(t)
+ try { source.capture()(); onSearch(query) } catch {}
}, [query, onSearch, source.signal, source])
const items = useMemo(() => flattenGroups(members), [members])
diff --git a/src/web/src/components/community/messages/composer-suggestion-popups.dom.test.ts b/src/web/src/components/community/messages/composer-suggestion-popups.dom.test.ts
index 398bbdff4..479d0737b 100644
--- a/src/web/src/components/community/messages/composer-suggestion-popups.dom.test.ts
+++ b/src/web/src/components/community/messages/composer-suggestion-popups.dom.test.ts
@@ -1,6 +1,6 @@
import { createElement } from "react"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import { fireEvent, render } from "@/test/react-dom-harness"
+import { act, fireEvent, render } from "@/test/react-dom-harness"
const mocks = vi.hoisted(() => ({
createPortal: vi.fn(),
@@ -105,6 +105,36 @@ describe("Composer suggestion popups", () => {
descriptors.clear()
})
+ it("loads mention continuations only at the popup edge and retires queued callbacks", () => {
+ const observers: Array<{ callback: IntersectionObserverCallback; options?: IntersectionObserverInit; observe: ReturnType<typeof vi.fn>; disconnect: ReturnType<typeof vi.fn> }> = []
+ class Observer {
+ observe = vi.fn()
+ disconnect = vi.fn()
+ constructor(callback: IntersectionObserverCallback, options?: IntersectionObserverInit) { observers.push({ callback, options, observe: this.observe, disconnect: this.disconnect }) }
+ }
+ vi.stubGlobal("IntersectionObserver", Observer)
+ const loadMore = vi.fn()
+ const retry = vi.fn()
+ const state: MentionPopupState = { items: [{ kind: "everyone", id: "everyone", label: "everyone" }], query: "", selectedIndex: 0, command: vi.fn(), getRect: () => rect(120) }
+ const pagination = { loading: false, failed: false, hasMore: true, loadMore, retry }
+ const view = render(createElement(CommunityMentionList, { state, presentation: { status: "ready" }, pagination }))
+ const edge = observers.at(-1)!
+ expect(loadMore).not.toHaveBeenCalled()
+ expect(edge.options?.root).toBe(view.container.querySelector(".overflow-y-auto"))
+ expect(edge.observe).toHaveBeenCalledOnce()
+ act(() => edge.callback([{ isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver))
+ expect(loadMore).toHaveBeenCalledOnce()
+ view.rerender(createElement(CommunityMentionList, { state, presentation: { status: "loading-more" }, pagination: { ...pagination, loadingMore: true } }))
+ expect(edge.disconnect).toHaveBeenCalled()
+ act(() => edge.callback([{ isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver))
+ expect(loadMore).toHaveBeenCalledOnce()
+ view.rerender(createElement(CommunityMentionList, { state, presentation: { status: "error" }, pagination: { ...pagination, failed: true } }))
+ fireEvent.click(view.getByRole("button", { name: "Retry" }))
+ expect(retry).toHaveBeenCalledOnce()
+ view.unmount()
+ vi.unstubAllGlobals()
+ })
+
it("self-nulls while closed and preserves viewport placement", async () => {
const mention = render(createElement(CommunityMentionList, {
state: EMPTY_MENTION_STATE,
diff --git a/src/web/src/components/community/messages/composer-suggestion-popups.tsx b/src/web/src/components/community/messages/composer-suggestion-popups.tsx
index 2eaa35a36..9c51619f8 100644
--- a/src/web/src/components/community/messages/composer-suggestion-popups.tsx
+++ b/src/web/src/components/community/messages/composer-suggestion-popups.tsx
@@ -21,6 +21,8 @@ import type {
MentionPopupState,
} from "@/lib/community/mention-extension"
+import type { MentionCandidateSource } from "./composer-types"
+
const POPUP_WIDTH = 256
const POPUP_MAX_HEIGHT = 240
@@ -39,11 +41,14 @@ function scrollSelectedRowIntoView(list: HTMLDivElement | null): void {
export function CommunityMentionList({
state,
presentation,
+ pagination,
}: {
state: MentionPopupState
presentation: MentionCandidatePresentation
+ pagination?: MentionCandidateSource
}) {
const listRef = useRef<HTMLDivElement>(null)
+ const sentinelRef = useRef<HTMLDivElement>(null)
const { items, selectedIndex, command, getRect } = state
const geometry = useAnchoredPopover(
getRect,
@@ -52,6 +57,19 @@ export function CommunityMentionList({
useEffect(() => {
scrollSelectedRowIntoView(listRef.current)
}, [selectedIndex, geometry])
+ useEffect(() => {
+ const root = listRef.current
+ const sentinel = sentinelRef.current
+ if (!geometry || !command || !root || !sentinel || !pagination?.hasMore
+ || pagination.loading || pagination.loadingMore || pagination.failed
+ || presentation.status === "loading" || !pagination.loadMore) return
+ let active = true
+ const observer = new IntersectionObserver((entries) => {
+ if (active && entries.some(entry => entry.isIntersecting)) pagination.loadMore?.()
+ }, { root, rootMargin: "100px" })
+ observer.observe(sentinel)
+ return () => { active = false; observer.disconnect() }
+ }, [geometry, command, pagination, presentation.status])
if (!geometry || !command) return null
const firstMemberIndex = items.findIndex((item) => item.kind === "member")
@@ -84,6 +102,11 @@ export function CommunityMentionList({
onSelect={() => command({ id: item.id, label: item.label })}
/>
))}
+ {pagination?.hasMore && <div ref={sentinelRef} aria-hidden="true" className="h-px" />}
+ {pagination?.failed && pagination.retry && (
+ <button type="button" className="h-11 w-full text-sm sm:h-9"
+ onMouseDown={event => event.preventDefault()} onClick={pagination.retry}>Retry</button>
+ )}
{presentation.status !== "ready" && (
<MentionStatus status={presentation.status} hasItems={items.length > 0} />
)}
diff --git a/src/web/src/components/community/messages/composer-types.ts b/src/web/src/components/community/messages/composer-types.ts
index d80813af5..506d1ffaa 100644
--- a/src/web/src/components/community/messages/composer-types.ts
+++ b/src/web/src/components/community/messages/composer-types.ts
@@ -31,6 +31,7 @@ export type MentionCandidateSource = {
| "empty"
| "error"
loadMore?: () => void
+ retry?: () => void
search?: (query: string) => void
}
diff --git a/src/web/src/components/community/messages/composer-view.tsx b/src/web/src/components/community/messages/composer-view.tsx
index 09fa96c25..3b9e4d843 100644
--- a/src/web/src/components/community/messages/composer-view.tsx
+++ b/src/web/src/components/community/messages/composer-view.tsx
@@ -28,7 +28,7 @@ import {
ChannelRefList,
CommunityMentionList,
} from "./composer-suggestion-popups"
-import type { ComposerReplyTarget } from "./composer-types"
+import type { ComposerReplyTarget, MentionCandidateSource } from "./composer-types"
import { SendStrokeRoundedIcon } from "./send-stroke-rounded-icon"
const COMPOSER_OUTER_CLASS =
@@ -43,6 +43,7 @@ export type ComposerViewProps = {
onDrop: DragEventHandler<HTMLDivElement>
mentionPopup: MentionPopupState
mentionPresentation: MentionCandidatePresentation
+ mentionPagination?: MentionCandidateSource
channelRefPopup: ChannelRefPopupState
channelRefPresentation?: ChannelRefCandidatePresentation
replyingTo?: ComposerReplyTarget
@@ -70,6 +71,7 @@ export function ComposerView({
onDrop,
mentionPopup,
mentionPresentation,
+ mentionPagination,
channelRefPopup,
channelRefPresentation,
replyingTo,
@@ -110,6 +112,7 @@ export function ComposerView({
<CommunityMentionList
state={mentionPopup}
presentation={mentionPresentation}
+ pagination={mentionPagination}
/>
<ChannelRefList
state={channelRefPopup}
diff --git a/src/web/src/components/community/messages/initial-position-transition.dom.test.ts b/src/web/src/components/community/messages/initial-position-transition.dom.test.ts
index 410453bac..604cbf1ff 100644
--- a/src/web/src/components/community/messages/initial-position-transition.dom.test.ts
+++ b/src/web/src/components/community/messages/initial-position-transition.dom.test.ts
@@ -1,142 +1,43 @@
import React from "react"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
-import { act, render } from "@/test/react-dom-harness"
-import {
- INITIAL_POSITION_CROSSFADE_MS,
- useInitialPositionTransition,
-} from "./initial-position-transition"
-import { INITIAL_POSITION_TIMEOUT_MS } from "@/hooks/community/use-scroll-anchor"
-
-type Input = {
- firstWindowReady: boolean
- authoritativeEmpty: boolean
- positionSettled: boolean
- documentWindowReady?: boolean
-}
+import { render } from "@/test/react-dom-harness"
+import { useInitialPositionTransition } from "./initial-position-transition"
+type Input = Parameters<typeof useInitialPositionTransition>[0]
let latest: ReturnType<typeof useInitialPositionTransition>
-
function Probe(input: Input) {
- const transition = useInitialPositionTransition(input)
- React.useLayoutEffect(() => { latest = transition }, [transition])
- return React.createElement("div", { "data-phase": transition.phase })
+ const presentation = useInitialPositionTransition(input)
+ React.useLayoutEffect(() => { latest = presentation }, [presentation])
+ return React.createElement("div", { "data-phase": presentation.phase })
}
-
-const pending = (): Input => ({
- firstWindowReady: true,
- authoritativeEmpty: false,
- positionSettled: false,
-})
-
-describe("useInitialPositionTransition", () => {
- beforeEach(() => {
- vi.useFakeTimers()
- vi.setSystemTime(new Date(0))
- })
-
- afterEach(() => {
- vi.useRealTimers()
- })
-
- it("shows a qualified document window without claiming position or interaction readiness", () => {
- const renderer = render(React.createElement(Probe, { ...pending(), documentWindowReady: true }))
- expect(latest).toMatchObject({ phase: "positioning", showSkeleton: false, contentVisible: true, contentInteractive: false })
+const pending: Input = { firstWindowReady: true, authoritativeEmpty: false, positionSettled: false }
+
+describe("immediate initial message presentation", () => {
+ beforeEach(() => vi.useFakeTimers())
+ afterEach(() => vi.useRealTimers())
+ it("shows a qualified first window and accepts user takeover before position settles", () => {
+ render(React.createElement(Probe, pending))
+ expect(latest).toEqual({ phase: "positioning", showSkeleton: false, contentVisible: true, contentInteractive: true })
expect(vi.getTimerCount()).toBe(0)
- renderer.rerender(React.createElement(Probe, { ...pending(), documentWindowReady: true, firstWindowReady: false }))
- expect(latest).toMatchObject({ phase: "skeleton", showSkeleton: true, contentVisible: false, contentInteractive: false })
- renderer.unmount()
})
-
- it("holds the skeleton until the first window and reveals an authoritative empty window immediately", () => {
- const renderer = render(React.createElement(Probe, {
- firstWindowReady: false,
- authoritativeEmpty: false,
- positionSettled: false,
- }))
- expect(latest).toMatchObject({ phase: "skeleton", showSkeleton: true })
-
- renderer.rerender(React.createElement(Probe, {
- firstWindowReady: true,
- authoritativeEmpty: true,
- positionSettled: false,
- }))
- expect(latest).toMatchObject({
- phase: "revealed",
- showSkeleton: false,
- contentVisible: true,
- })
+ it("holds the skeleton until the first window is qualified and reveals an empty window immediately", () => {
+ const view = render(React.createElement(Probe, { ...pending, firstWindowReady: false }))
+ expect(latest).toEqual({ phase: "skeleton", showSkeleton: true, contentVisible: false, contentInteractive: false })
+ view.rerender(React.createElement(Probe, { ...pending, authoritativeEmpty: true }))
+ expect(latest).toMatchObject({ phase: "revealed", showSkeleton: false, contentVisible: true })
expect(vi.getTimerCount()).toBe(0)
})
-
- it("crossfades as soon as position settles", () => {
- const renderer = render(React.createElement(Probe, pending()))
- expect(latest.phase).toBe("positioning")
-
- act(() => vi.advanceTimersByTime(799))
- expect(latest.phase).toBe("positioning")
- renderer.rerender(React.createElement(Probe, { ...pending(), positionSettled: true }))
- expect(latest).toMatchObject({
- phase: "revealing",
- contentVisible: true,
- contentInteractive: true,
- })
-
- act(() => vi.advanceTimersByTime(INITIAL_POSITION_CROSSFADE_MS))
- expect(latest.phase).toBe("revealed")
- })
-
- it("does not let the timeout expose content before position settlement", () => {
- const renderer = render(React.createElement(Probe, pending()))
- act(() => vi.advanceTimersByTime(INITIAL_POSITION_TIMEOUT_MS))
- expect(latest).toMatchObject({
- phase: "positioning",
- contentVisible: false,
- contentInteractive: false,
- })
-
- renderer.rerender(React.createElement(Probe, { ...pending(), positionSettled: true }))
- act(() => vi.advanceTimersByTime(0))
- expect(latest).toMatchObject({
- phase: "revealing",
- contentVisible: true,
- contentInteractive: true,
- })
-
- act(() => vi.advanceTimersByTime(INITIAL_POSITION_CROSSFADE_MS))
- expect(latest).toMatchObject({ phase: "revealed", showSkeleton: false })
- })
-
- it("preserves the crossfade when settlement arrives after the timeout window", () => {
- const renderer = render(React.createElement(Probe, pending()))
- act(() => vi.advanceTimersByTime(
- INITIAL_POSITION_TIMEOUT_MS + INITIAL_POSITION_CROSSFADE_MS,
- ))
- expect(latest).toMatchObject({
- phase: "positioning",
- contentVisible: false,
- contentInteractive: false,
- })
-
- renderer.rerender(React.createElement(Probe, { ...pending(), positionSettled: true }))
- act(() => vi.advanceTimersByTime(0))
- expect(latest).toMatchObject({
- phase: "revealing",
- contentVisible: true,
- contentInteractive: true,
- })
-
- act(() => vi.advanceTimersByTime(INITIAL_POSITION_CROSSFADE_MS - 1))
- expect(latest.phase).toBe("revealing")
- act(() => vi.advanceTimersByTime(1))
- expect(latest).toMatchObject({ phase: "revealed" })
- })
-
- it("has no independent position timer and cleans the crossfade when a keyed mount leaves", () => {
- const renderer = render(React.createElement(Probe, pending()))
+ it("records actual position settlement without a timed revealing phase", () => {
+ const view = render(React.createElement(Probe, pending))
+ view.rerender(React.createElement(Probe, { ...pending, positionSettled: true }))
+ expect(latest).toMatchObject({ phase: "revealed", contentVisible: true, contentInteractive: true })
expect(vi.getTimerCount()).toBe(0)
- renderer.rerender(React.createElement(Probe, { ...pending(), positionSettled: true }))
- expect(vi.getTimerCount()).toBe(1)
- renderer.unmount()
+ view.unmount()
expect(vi.getTimerCount()).toBe(0)
})
+ it("hides content again if its first-window qualification is lost", () => {
+ const view = render(React.createElement(Probe, { ...pending, positionSettled: true }))
+ view.rerender(React.createElement(Probe, { ...pending, firstWindowReady: false }))
+ expect(latest).toMatchObject({ showSkeleton: true, contentVisible: false, contentInteractive: false })
+ })
})
diff --git a/src/web/src/components/community/messages/initial-position-transition.ts b/src/web/src/components/community/messages/initial-position-transition.ts
index 13245dfbc..bfadcbb97 100644
--- a/src/web/src/components/community/messages/initial-position-transition.ts
+++ b/src/web/src/components/community/messages/initial-position-transition.ts
@@ -1,79 +1,22 @@
"use client"
-import { useMemo } from "react";
-import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useEffect, useLayoutEffect, useRef } from "react"
-
-export const INITIAL_POSITION_CROSSFADE_MS = 300
-
-export type InitialPositionPhase =
- | "skeleton"
- | "positioning"
- | "revealing"
- | "revealed"
+type InitialPositionPhase = "skeleton" | "positioning" | "revealed"
export function useInitialPositionTransition({
firstWindowReady,
authoritativeEmpty,
positionSettled,
- documentWindowReady = false,
}: {
firstWindowReady: boolean
authoritativeEmpty: boolean
positionSettled: boolean
- documentWindowReady?: boolean
}) {
- const initiallyRevealed = firstWindowReady && (authoritativeEmpty || positionSettled)
- const [phase, setPhase] = useAtom(useCreateAtom<InitialPositionPhase>(useMemo<InitialPositionPhase>(() => (
- !firstWindowReady ? "skeleton" : initiallyRevealed ? "revealed" : "positioning"
- ), [firstWindowReady, initiallyRevealed])))
- const revealedRef = useRef(initiallyRevealed)
-
- useLayoutEffect(() => {
- if (revealedRef.current) return
- if (!firstWindowReady) {
- setPhase("skeleton")
- return
- }
- if (authoritativeEmpty) {
- revealedRef.current = true
- setPhase("revealed")
- return
- }
- if (positionSettled) {
- revealedRef.current = true
- setPhase("revealing")
- return
- }
- if (phase === "skeleton") setPhase("positioning")
- }, [authoritativeEmpty, firstWindowReady, phase, positionSettled, setPhase])
-
- useEffect(() => {
- if (phase === "revealing") {
- const crossfadeTimer = window.setTimeout(
- () => setPhase("revealed"),
- INITIAL_POSITION_CROSSFADE_MS,
- )
- return () => window.clearTimeout(crossfadeTimer)
- }
- }, [phase, setPhase])
-
- // The first renderable window must mount its real DOM in the same commit
- // that clears loading. Waiting for the layout effect above to persist the
- // phase would leave the skeleton branch mounted for that commit, so the
- // controller's one-shot hero measurement effect would observe no node and
- // initial anchoring would never arm. This projection changes presentation
- // only; settlement still comes exclusively from the action-owned callback.
- const renderedPhase = !firstWindowReady ? "skeleton" : phase === "skeleton"
- ? authoritativeEmpty || positionSettled ? "revealed" : "positioning"
- : phase
-
+ const phase: InitialPositionPhase = !firstWindowReady ? "skeleton"
+ : authoritativeEmpty || positionSettled ? "revealed" : "positioning"
return {
- phase: renderedPhase,
- showSkeleton: renderedPhase === "skeleton",
- contentVisible: firstWindowReady && documentWindowReady || (authoritativeEmpty || positionSettled)
- && (renderedPhase === "revealing" || renderedPhase === "revealed"),
- contentInteractive: (authoritativeEmpty || positionSettled)
- && (renderedPhase === "revealing" || renderedPhase === "revealed"),
+ phase,
+ showSkeleton: !firstWindowReady,
+ contentVisible: firstWindowReady,
+ contentInteractive: firstWindowReady,
}
}
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.ts
index dc4de162f..27e6a137c 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
@@ -6,7 +6,6 @@ import { act, render as rtlRender } from "@/test/react-dom-harness"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { useMessageListController, type MessageListController } from "./message-list-controller"
import type { ResolvedMessageListProps } from "./message-list-types"
-import { INITIAL_POSITION_CROSSFADE_MS } from "./initial-position-transition"
import { MESSAGE_RAIL_TAIL_PADDING_END_PX } from "@/lib/community/conversation-layout"
const webRoot = resolve(dirname(fileURLToPath(import.meta.url)), "../../../..")
@@ -49,9 +48,7 @@ vi.mock("@/hooks/community/use-scroll-anchor", () => ({
readPositionReady: false,
paginationEnabled: false,
captureOlderPageAnchor: mocks.captureOlderPageAnchor,
- isOlderPageAnchorSettling: false,
captureNewerPageAnchor: mocks.captureNewerPageAnchor,
- isNewerPageAnchorSettling: false,
}
},
}))
@@ -227,7 +224,6 @@ describe("useMessageListController", () => {
enabled: false,
hasMore: undefined,
isFetching: undefined,
- isSettling: false,
isError: false,
onBeforeLoad: mocks.captureOlderPageAnchor,
onLoad: undefined,
@@ -239,7 +235,6 @@ describe("useMessageListController", () => {
enabled: false,
hasMore: undefined,
isFetching: undefined,
- isSettling: false,
isError: false,
hasMoreAtStart: undefined,
onBeforeLoad: mocks.captureNewerPageAnchor,
@@ -314,17 +309,16 @@ describe("useMessageListController", () => {
})
expect(latest.initialPosition).toMatchObject({
phase: "positioning",
- contentVisible: false,
+ contentVisible: true,
})
const settle = (mocks.scrollInputs.at(-1) as {
onInitialPositionSettled: () => void
}).onInitialPositionSettled
act(() => settle())
expect(latest.initialPosition).toMatchObject({
- phase: "revealing",
+ phase: "revealed",
contentVisible: true,
})
- act(() => vi.advanceTimersByTime(INITIAL_POSITION_CROSSFADE_MS))
expect(latest.initialPosition.phase).toBe("revealed")
})
@@ -373,7 +367,6 @@ describe("useMessageListController", () => {
enabled: false,
hasMore: true,
isFetching: true,
- isSettling: false,
isError: false,
onBeforeLoad: mocks.captureOlderPageAnchor,
onLoad: loadOlder,
@@ -385,7 +378,6 @@ describe("useMessageListController", () => {
enabled: false,
hasMore: true,
isFetching: true,
- isSettling: false,
isError: false,
hasMoreAtStart: true,
onBeforeLoad: mocks.captureNewerPageAnchor,
@@ -439,11 +431,10 @@ describe("useMessageListController", () => {
onInitialPositionSettled: () => void
}).onInitialPositionSettled
act(() => settleAnchor())
- expect(latest.initialPosition.phase).toBe("revealing")
+ expect(latest.initialPosition.phase).toBe("revealed")
visibleMessageIds = ["m2"]
runNextFrame()
- expect(latest.initialPosition.phase).toBe("revealing")
- act(() => vi.advanceTimersByTime(INITIAL_POSITION_CROSSFADE_MS))
+ expect(latest.initialPosition.phase).toBe("revealed")
expect(latest.initialPosition.phase).toBe("revealed")
act(() => {
latest.onEnterSelectId("m2")
@@ -667,8 +658,7 @@ describe("useMessageListController", () => {
act(() => (mocks.scrollInputs.at(-1) as {
onInitialPositionSettled: () => void
}).onInitialPositionSettled())
- expect(latest.initialPosition.phase).toBe("revealing")
- act(() => vi.advanceTimersByTime(INITIAL_POSITION_CROSSFADE_MS))
+ expect(latest.initialPosition.phase).toBe("revealed")
expect(latest.initialPosition.phase).toBe("revealed")
act(() => latest.jumpTo("m1", "auto"))
for (let index = 0; index < 120; index += 1) runNextFrame()
diff --git a/src/web/src/components/community/messages/message-list-controller.ts b/src/web/src/components/community/messages/message-list-controller.ts
index f3b6bd665..32d0e1f48 100644
--- a/src/web/src/components/community/messages/message-list-controller.ts
+++ b/src/web/src/components/community/messages/message-list-controller.ts
@@ -29,7 +29,6 @@ export function useMessageListController({
unreadCount,
onScrollRoot,
onScrollTargetConsumed,
- observation,
}: ResolvedMessageListProps) {
const [jumpRevision, setJumpRevision] = useAtom(useCreateAtom(0))
const [jumped, setJumped] = useAtom(useCreateAtom<string | null>(null))
@@ -94,9 +93,7 @@ export function useMessageListController({
readPositionReady,
paginationEnabled,
captureOlderPageAnchor,
- isOlderPageAnchorSettling,
captureNewerPageAnchor,
- isNewerPageAnchorSettling,
} = useScrollAnchor({
items,
newDividerBefore,
@@ -115,7 +112,6 @@ export function useMessageListController({
const initialPosition = useInitialPositionTransition({
firstWindowReady: !isLoading && (messages.length > 0 || !initialLoadError),
authoritativeEmpty,
- documentWindowReady: observation?.snapshot_source === "rsc",
positionSettled: anchorPositionSettled,
})
@@ -131,7 +127,6 @@ export function useMessageListController({
enabled: paginationEnabled,
hasMore,
isFetching: isFetching || isFetchingOlder || isFetchingNewer,
- isSettling: isOlderPageAnchorSettling || isNewerPageAnchorSettling,
isError: !!initialLoadError,
onBeforeLoad: captureOlderPageAnchor,
onLoad: onLoadOlder,
@@ -144,7 +139,6 @@ export function useMessageListController({
hasMore: hasMoreNewer,
hasMoreAtStart: hasMore,
isFetching: isFetching || isFetchingOlder || isFetchingNewer,
- isSettling: isOlderPageAnchorSettling || isNewerPageAnchorSettling,
isError: !!initialLoadError,
onBeforeLoad: captureNewerPageAnchor,
onLoad: onLoadNewer,
diff --git a/src/web/src/components/community/messages/message-list-view.dom.test.ts b/src/web/src/components/community/messages/message-list-view.dom.test.ts
index 2c9a69fd1..608fab0de 100644
--- a/src/web/src/components/community/messages/message-list-view.dom.test.ts
+++ b/src/web/src/components/community/messages/message-list-view.dom.test.ts
@@ -155,41 +155,28 @@ describe("renderMessageListView", () => {
expect(renderer.container.querySelectorAll(".mb-6")).toHaveLength(1)
expect(renderer.container.querySelectorAll("[data-message-typing-space]")).toHaveLength(0)
const content = renderer.container.querySelector<HTMLElement>("[data-message-list-content]")!
- expect(content).toHaveClass("opacity-100")
+ expect(content).not.toHaveClass("opacity-0")
expect(content).not.toHaveClass("transition-opacity", "duration-300")
expect(content.querySelector("[data-message-list-skeleton-tail]")).toHaveClass("shrink-0")
expect(content.querySelector("[data-message-list-skeleton-tail]")).toHaveStyle({ height: "40px" })
})
- it("keeps positioned rows measurable but inert and hidden until reveal starts", () => {
+ it("shows real rows during positioning while retaining separate read eligibility", () => {
const renderRows = vi.fn(() => React.createElement("virtual-rows"))
const renderer = render(renderMessageListView(
props({ loading: false }),
- controller({
- initialPosition: initialPosition({
- phase: "positioning",
- contentVisible: false,
- contentInteractive: false,
- }),
- }),
+ controller({ readPositionReady: false, initialPosition: initialPosition({ phase: "positioning" }) }),
renderRows,
))
const content = renderer.container.querySelector<HTMLElement>("[data-message-list-content]")!
expect(renderRows).toHaveBeenCalledOnce()
expect(renderer.container.querySelector("virtual-rows")).toBeInTheDocument()
expect(content).toHaveAttribute("data-initial-position-phase", "positioning")
- expect(content).toHaveAttribute("aria-hidden", "true")
- expect(content).toHaveAttribute("inert")
- expect(content).toHaveClass("pointer-events-none", "opacity-0")
- expect(content).not.toHaveClass("transition-opacity", "duration-300")
- expect(mockedRail).not.toHaveBeenCalled()
- const skeleton = renderer.container.querySelector("[data-message-positioning-skeleton]")!
- expect(skeleton).toHaveClass(
- "absolute", "inset-0", "z-20", "pointer-events-none", "opacity-100",
- )
- expect(skeleton.querySelector('[data-slot="skeleton"]')).toBeInTheDocument()
- expect(skeleton.querySelector("[data-message-list-skeleton-tail]")).toHaveClass("shrink-0")
- expect(skeleton.querySelector("[data-message-list-skeleton-tail]")).toHaveStyle({ height: "40px" })
+ expect(content).toHaveAttribute("data-read-position-ready", "false")
+ expect(content).toHaveAttribute("aria-hidden", "false")
+ expect(content).not.toHaveAttribute("inert")
+ expect(content).not.toHaveClass("opacity-0", "transition-opacity", "duration-300")
+ expect(renderer.container.querySelector("[data-message-positioning-skeleton]")).toBeNull()
})
it("reserves the shared 40px rail tail in the standalone skeleton", () => {
@@ -204,54 +191,21 @@ describe("renderMessageListView", () => {
expect(content).toHaveClass("pl-(--community-composer-inline-start)", "pr-(--community-composer-inline-end)")
})
- it("keeps the typed positioning skeleton through a timeout until settlement", () => {
+ it("updates read readiness without an opacity overlay or fade", () => {
const renderer = render(renderMessageListView(
props({ loading: false }),
- controller({
- initialPosition: initialPosition({
- phase: "positioning",
- contentVisible: false,
- contentInteractive: false,
- }),
- }),
- () => React.createElement("virtual-rows"),
- ))
- const content = () => renderer.container.querySelector<HTMLElement>("[data-message-list-content]")!
- expect(content()).toHaveClass("opacity-0")
- expect(content()).not.toHaveClass("transition-opacity", "duration-300")
- expect(renderer.container.querySelector("[data-message-positioning-skeleton]")).toHaveClass("opacity-100")
- expect(renderer.container.querySelector("[data-message-positioning-skeleton]"))
- .toBeInTheDocument()
-
- renderer.rerender(renderMessageListView(
- props({ loading: false }),
- controller({
- initialPosition: initialPosition({
- phase: "revealing",
- contentVisible: false,
- contentInteractive: false,
- }),
- }),
+ controller({ readPositionReady: false, initialPosition: initialPosition({ phase: "positioning" }) }),
() => React.createElement("virtual-rows"),
))
- expect(content()).toHaveClass("opacity-0")
- expect(content()).not.toHaveClass("transition-opacity", "duration-300")
- const boundary = renderer.container.querySelector("[data-message-scroller-boundary]")!
- expect(boundary).toHaveClass("isolate")
- expect(renderer.getByTestId("community-message-scroller")).toHaveClass("relative", "z-10")
- expect(boundary.querySelector("accessory-rail")).not.toBeInTheDocument()
- expect(content()).toHaveAttribute("aria-hidden", "true")
- expect(content()).toHaveAttribute("inert")
-
+ const content = renderer.container.querySelector<HTMLElement>("[data-message-list-content]")!
+ expect(content).toHaveAttribute("data-read-position-ready", "false")
renderer.rerender(renderMessageListView(
- props({ loading: false }),
- controller({ initialPosition: initialPosition({ phase: "revealing" }) }),
- () => React.createElement("virtual-rows"),
+ props({ loading: false }), controller(), () => React.createElement("virtual-rows"),
))
- expect(content()).toHaveClass("opacity-100", "transition-opacity", "duration-300")
- expect(content()).toHaveAttribute("aria-hidden", "false")
- expect(content()).not.toHaveAttribute("inert")
- expect(renderer.container.querySelector("[data-message-positioning-skeleton]")).toHaveClass("opacity-0")
+ expect(content).toHaveAttribute("data-read-position-ready", "true")
+ expect(content).not.toHaveClass("opacity-0", "transition-opacity", "duration-300")
+ expect(content).not.toHaveAttribute("inert")
+ expect(renderer.container.querySelector("[data-message-positioning-skeleton]")).toBeNull()
})
it("routes typing through the rail without adding a dynamic flex sibling", () => {
diff --git a/src/web/src/components/community/messages/message-list-view.tsx b/src/web/src/components/community/messages/message-list-view.tsx
index eca6753f4..28eb9762c 100644
--- a/src/web/src/components/community/messages/message-list-view.tsx
+++ b/src/web/src/components/community/messages/message-list-view.tsx
@@ -56,13 +56,7 @@ export function renderMessageListView(
data-read-position-ready={controller.readPositionReady ? "true" : "false"}
aria-hidden={!controller.initialPosition.showSkeleton && !controller.initialPosition.contentVisible}
inert={!controller.initialPosition.showSkeleton && !controller.initialPosition.contentInteractive}
- className={`${props.messages.length === 0 ? "flex min-h-full flex-col justify-end pt-8" : ""} pl-(--community-composer-inline-start) pr-(--community-composer-inline-end) ${
- controller.initialPosition.phase === "revealing" && controller.initialPosition.contentVisible
- ? "opacity-100 transition-opacity duration-300 ease-linear motion-reduce:transition-opacity"
- : controller.initialPosition.showSkeleton || controller.initialPosition.contentVisible
- ? "opacity-100"
- : "pointer-events-none opacity-0"
- }`}
+ className={`${props.messages.length === 0 ? "flex min-h-full flex-col justify-end pt-8" : ""} pl-(--community-composer-inline-start) pr-(--community-composer-inline-end)`}
>
{props.messages.length === 0 && props.initialLoadError ? (
<ConversationResolutionErrorFrame as="div" retrying={!!props.retryingInitialLoad}
@@ -81,23 +75,7 @@ export function renderMessageListView(
)}
</div>
</div>
- {!controller.initialPosition.showSkeleton && (
- !controller.initialPosition.contentVisible || controller.initialPosition.phase === "revealing"
- ) && (
- <div
- aria-hidden="true"
- data-message-positioning-skeleton
- className={`pointer-events-none absolute inset-0 z-20 flex flex-col overflow-hidden bg-(--app-bg) ${
- controller.initialPosition.contentVisible
- ? "opacity-0 transition-opacity duration-300 ease-linear motion-reduce:transition-opacity"
- : "opacity-100"
- }`}
- >
- <div className="flex min-h-full flex-col justify-end pl-(--community-composer-inline-start) pr-(--community-composer-inline-end) pt-8">
- <MessageListSkeletonContent variant={props.variant} />
- </div>
- </div>
- )}
+
</div>
</div>
)
diff --git a/src/web/src/components/community/messages/use-composer-controller.ts b/src/web/src/components/community/messages/use-composer-controller.ts
index af2f5aa77..343e0f6b1 100644
--- a/src/web/src/components/community/messages/use-composer-controller.ts
+++ b/src/web/src/components/community/messages/use-composer-controller.ts
@@ -365,6 +365,7 @@ export function useComposerController(
onDrop: handleDrop,
mentionPopup: suggestions.mentionPopup,
mentionPresentation: suggestions.mentionPresentation,
+ mentionPagination: suggestions.mentionPagination,
channelRefPopup: suggestions.channelRefPopup,
channelRefPresentation: suggestions.channelRefPresentation,
replyingTo,
diff --git a/src/web/src/components/community/messages/use-composer-suggestions.dom.test.ts b/src/web/src/components/community/messages/use-composer-suggestions.dom.test.ts
index b5c74cdb0..28da665cb 100644
--- a/src/web/src/components/community/messages/use-composer-suggestions.dom.test.ts
+++ b/src/web/src/components/community/messages/use-composer-suggestions.dom.test.ts
@@ -487,7 +487,7 @@ describe("useComposerSuggestions", () => {
expect(resultRef.current!.mentionPopup.selectedIndex).toBe(0)
})
- it("loads bare-@ pages serially and exposes first search pages while loading more", async () => {
+ it("leaves bare-@ continuation to the popup edge and exposes first search pages while loading more", async () => {
const resultRef: { current: Result | null } = { current: null }
const search = vi.fn()
const loadMore = vi.fn()
@@ -512,8 +512,9 @@ describe("useComposerSuggestions", () => {
getRect: null,
})
})
- expect(loadMore).toHaveBeenCalledOnce()
- expect(resultRef.current!.mentionPresentation.status).toBe("loading-more")
+ expect(loadMore).not.toHaveBeenCalled()
+ expect(resultRef.current!.mentionPresentation.status).toBe("ready")
+ expect(resultRef.current!.mentionPagination).toMatchObject({ hasMore: true, loadMore })
const firstSearchItem = {
kind: "member" as const,
diff --git a/src/web/src/components/community/messages/use-composer-suggestions.ts b/src/web/src/components/community/messages/use-composer-suggestions.ts
index a3d38b974..35f9330e3 100644
--- a/src/web/src/components/community/messages/use-composer-suggestions.ts
+++ b/src/web/src/components/community/messages/use-composer-suggestions.ts
@@ -292,16 +292,6 @@ export function useComposerSuggestions({
})
}, [context, members, mentionCandidates, isOpenEditor, publishMention])
- useEffect(() => {
- const current = mentionPopupRef.current
- if (!isOpenEditor()) return
- if (!current.command || current.query.trim()) return
- if (!mentionCandidates?.hasMore) return
- if (mentionCandidates.loading || mentionCandidates.loadingMore) return
- if (mentionCandidates.failed) return
- mentionCandidates.loadMore?.()
- }, [mentionCandidates, mentionPopup.command, mentionPopup.query, isOpenEditor])
-
const mentionPresentation: MentionCandidatePresentation = (() => {
if (!mentionCandidates) {
return { status: mentionPopup.items.length > 0 ? "ready" : "empty" }
@@ -313,7 +303,7 @@ export function useComposerSuggestions({
const searchStatus = query && mentionCandidates.search ? mentionCandidates.searchStatus : undefined
if (mentionCandidates.failed || searchStatus === "error") return { status: "error" }
if (mentionCandidates.loading || searchStatus === "loading" || searchStatus === "idle") return { status: "loading" }
- if (mentionCandidates.loadingMore || mentionCandidates.hasMore || searchStatus === "loading-more") {
+ if (mentionCandidates.loadingMore || searchStatus === "loading-more") {
return { status: "loading-more" }
}
return { status: mentionPopup.items.length > 0 ? "ready" : "empty" }
@@ -322,6 +312,7 @@ export function useComposerSuggestions({
return {
mentionPopup,
mentionPresentation,
+ mentionPagination: mentionCandidates,
mentionPopupRef,
mentionExtension,
channelRefPopup,
diff --git a/src/web/src/components/community/settings/server-settings.tsx b/src/web/src/components/community/settings/server-settings.tsx
index 6a1d253f9..4b1cae59b 100644
--- a/src/web/src/components/community/settings/server-settings.tsx
+++ b/src/web/src/components/community/settings/server-settings.tsx
@@ -235,8 +235,7 @@ function SettingsMembers({ members, loading, loadingMore, hasMore, total, onLoad
useEffect(() => {
if (!onSearch) return
- const t = setTimeout(() => onSearch(query), 200)
- return () => clearTimeout(t)
+ onSearch(query)
}, [query, onSearch])
// TanStack Virtual returns unstable function refs — React Compiler skips memoization.
diff --git a/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts b/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts
index 00901c93a..70647895e 100644
--- a/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts
+++ b/src/web/src/components/community/shell/community-inbox-popover.dom.test.ts
@@ -5,6 +5,8 @@ import { InboxPopover } from "./community-inbox-popover"
import type { UnreadDm, UnreadServer } from "@/lib/community/models/inbox"
import { tid } from "@/lib/community/testids"
+vi.mock("next/link", async () => ({ default: (await import("@/test/community-link-mock")).CommunityLinkMock }))
+
const mocks = vi.hoisted(() => ({ tabs: vi.fn() }))
vi.mock("@/components/ui/tabs", () => ({
@@ -361,7 +363,13 @@ describe("InboxPopover DM rows", () => {
onOpenDm,
}))
- fireEvent.click(renderer.getByTestId(tid.inboxUnreadDm(dm.channelId)))
+ const row = renderer.getByTestId(tid.inboxUnreadDm(dm.channelId))
+ expect(row).toHaveAttribute("href", "/c/me/dm-new")
+ expect(row).toHaveAttribute("data-prefetch", "false")
+ fireEvent.pointerEnter(row)
+ expect(row).toHaveAttribute("data-prefetch", "true")
+ expect(onOpenDm).not.toHaveBeenCalled()
+ fireEvent.click(row)
expect(onOpenDm).toHaveBeenCalledWith(dm)
})
diff --git a/src/web/src/components/community/shell/community-inbox-popover.tsx b/src/web/src/components/community/shell/community-inbox-popover.tsx
index 3e5bbc60d..7f74919a3 100644
--- a/src/web/src/components/community/shell/community-inbox-popover.tsx
+++ b/src/web/src/components/community/shell/community-inbox-popover.tsx
@@ -6,6 +6,7 @@ import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs"
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from "@/components/ui/dropdown-menu"
import { Skeleton } from "@/components/ui/skeleton"
import { Button } from "@/components/ui/button"
+import { CommunityNavigationLink } from "./community-navigation-link"
import { Avatar } from "../avatar"
import { ChannelIcon } from "../channels/channel-icon"
import { EmptyState } from "../empty-state"
@@ -251,16 +252,17 @@ function UnreadsTab({ friendRequests, servers, dms, loading, error, onRetry, onO
d.otherUserId,
)
return (
- <button
+ <CommunityNavigationLink
key={d.channelId}
data-testid={tid.inboxUnreadDm(d.channelId)}
- onClick={() => onOpenDm?.(d)}
+ href={`/c/me/${encodeURIComponent(d.channelId)}`}
+ onActivate={() => onOpenDm?.(d)}
className="flex w-full items-center gap-2 rounded-md px-2 py-2 text-left text-sm hover:bg-accent"
>
<Avatar label={profile.avatar} seed={d.otherUserId} size={24} />
<span className="min-w-0 flex-1 truncate">{profile.name}</span>
<ChevronRight className="size-4 shrink-0 text-muted-foreground" />
- </button>
+ </CommunityNavigationLink>
)
})}
</div>
diff --git a/src/web/src/components/community/shell/community-route-frame.dom.test.tsx b/src/web/src/components/community/shell/community-route-frame.dom.test.tsx
index 0fed40fb1..979bd7516 100644
--- a/src/web/src/components/community/shell/community-route-frame.dom.test.tsx
+++ b/src/web/src/components/community/shell/community-route-frame.dom.test.tsx
@@ -62,6 +62,7 @@ vi.mock("./server-rail", () => ({ ServerRail: () => <div data-testid="rail"><but
vi.mock("./user-bar", () => ({ UserBar: () => <div data-testid="userbar">{mocks.userId}</div> }))
vi.mock("./community-inbox-popover", () => ({ InboxPopover: () => null }))
vi.mock("./shell-frame-overlays", () => ({ ShellFrameOverlays: () => null }))
+vi.mock("@/components/community/channels/dm-route", () => ({ DmRoute: ({ dmId, routeCommitted }: { dmId: string; routeCommitted: boolean }) => createElement("main", { "data-dm-target": dmId, "data-committed": String(routeCommitted) }) }))
vi.mock("@/components/community/channels/channel-route", () => ({
ChannelRoute: (props: { serverParam: string; channelId: string }) => {
mocks.channel(props)
@@ -145,6 +146,28 @@ describe("common committed community frame", () => {
expect(view.getByTestId("sidebar")).toHaveAttribute("data-server-id", "b")
})
+ it.each(["url-first", "segments-first"])("gates DM query effects on exact publication in %s order", order => {
+ mocks.segments = ["me", "dm-a"]
+ mocks.pathname = "/c/me/dm-a"
+ const view = render(tree())
+ expect(view.container.querySelector('[data-dm-target="dm-a"]')).toHaveAttribute("data-committed", "true")
+ act(() => owner.runtime.ui.get().uiHandlers.navigatePath?.("/c/me/dm-b?seq=7"))
+ const body = view.container.querySelector('[data-dm-target="dm-b"]')!
+ expect(body).toHaveAttribute("data-committed", "false")
+ if (order === "url-first") { mocks.pathname = "/c/me/dm-b"; mocks.search = "seq=7" }
+ else mocks.segments = ["me", "dm-b"]
+ view.rerender(tree())
+ expect(view.container.querySelector('[data-dm-target="dm-b"]')).toBe(body)
+ expect(body).toHaveAttribute("data-committed", "false")
+ mocks.segments = ["me", "dm-b"]
+ mocks.pathname = "/c/me/dm-b"
+ mocks.search = "seq=7"
+ view.rerender(tree())
+ expect(view.container.querySelector('[data-dm-target="dm-b"]')).toBe(body)
+ expect(body).toHaveAttribute("data-committed", "true")
+ expect(mocks.push).toHaveBeenCalledExactlyOnceWith("/c/me/dm-b?seq=7")
+ })
+
it("preserves hidden global mobile nodes and rebuilds them for a new account", async () => {
mocks.breakpoint = "mobile"
mocks.segments = ["me"]
diff --git a/src/web/src/components/community/shell/shell-frame-view.dom.test.ts b/src/web/src/components/community/shell/shell-frame-view.dom.test.ts
index cac06b8b7..f38ebf117 100644
--- a/src/web/src/components/community/shell/shell-frame-view.dom.test.ts
+++ b/src/web/src/components/community/shell/shell-frame-view.dom.test.ts
@@ -11,6 +11,8 @@ import {
const mocks = vi.hoisted(() => ({
onLayoutChanged: vi.fn(),
+ dmMount: vi.fn(),
+ dmUnmount: vi.fn(),
defaultLayout: {
current: undefined as { sidebar: number; main: number } | undefined,
},
@@ -40,6 +42,12 @@ const mocks = vi.hoisted(() => ({
runningBots: [] as Array<{ id: string }>,
}))
+vi.mock("@/components/community/channels/dm-route", () => ({
+ DmRoute: ({ dmId, routeCommitted }: { dmId: string; routeCommitted: boolean }) => {
+ useLayoutEffect(() => { mocks.dmMount(dmId); return () => { mocks.dmUnmount(dmId) } }, [dmId])
+ return createElement("main", { "data-dm-target": dmId, "data-committed": String(routeCommitted) }, "Cached DM")
+ },
+}))
vi.mock("react-resizable-panels", () => ({
useDefaultLayout: (options: Record<string, unknown>) => {
mocks.defaultLayoutOptions(options)
@@ -223,6 +231,8 @@ describe("ShellFrameView", () => {
beforeEach(() => {
vi.unstubAllGlobals()
mocks.onLayoutChanged.mockClear()
+ mocks.dmMount.mockClear()
+ mocks.dmUnmount.mockClear()
mocks.groupProps.mockClear()
mocks.handleProps.mockClear()
mocks.panelProps.mockClear()
@@ -256,6 +266,30 @@ describe("ShellFrameView", () => {
vi.unstubAllGlobals()
})
+ it("mounts the selected DM before Next publication and retains the same body at commit", () => {
+ const props = (dmId: string, routeCommitted = false) => ({
+ ...extensionProps, breakpoint: "desktop" as const, routeCommitted, rail, profile, inbox,
+ sidebar: () => createElement("sidebar-content"),
+ checkpoint: { ...committedCheckpoint(`/c/me/${dmId}`, "detail"),
+ main: { kind: "dm-route" as const, dmId, href: `/c/me/${dmId}` } },
+ })
+ const view = render(createElement(ShellFrameView, props("a"), createElement("old-next-page")))
+ const body = view.container.querySelector('[data-dm-target="a"]')!
+ expect(body).toHaveAttribute("data-committed", "false")
+ expect(view.container.querySelector("old-next-page")).toBeNull()
+ view.rerender(createElement(ShellFrameView, props("a", true), createElement("new-next-page")))
+ expect(view.container.querySelector('[data-dm-target="a"]')).toBe(body)
+ expect(body).toHaveAttribute("data-committed", "true")
+ expect(mocks.dmMount).toHaveBeenCalledExactlyOnceWith("a")
+ view.rerender(createElement(ShellFrameView, props("b")))
+ view.rerender(createElement(ShellFrameView, props("c")))
+ expect(view.container.querySelectorAll("[data-dm-target]")).toHaveLength(1)
+ expect(view.container.querySelector('[data-dm-target="c"]')).toHaveAttribute("data-committed", "false")
+ expect(mocks.dmUnmount.mock.calls.map(([id]) => id)).toEqual(["a", "b"])
+ view.rerender(createElement(ShellFrameView, props("a", true)))
+ expect(view.container.querySelector('[data-dm-target="a"]')).toHaveAttribute("data-committed", "true")
+ })
+
it("keeps responsive detail shell zones while the breakpoint is unknown", async () => {
const renderer = render(createElement(ShellFrameView, {
...extensionProps,
diff --git a/src/web/src/components/community/shell/shell-frame-view.tsx b/src/web/src/components/community/shell/shell-frame-view.tsx
index 6717d8870..cc1d01028 100644
--- a/src/web/src/components/community/shell/shell-frame-view.tsx
+++ b/src/web/src/components/community/shell/shell-frame-view.tsx
@@ -1,5 +1,6 @@
"use client"
+import { DmRoute } from "@/components/community/channels/dm-route"
import { ChannelSidebarSkeleton } from "@/components/community/channels/channel-sidebar"
import { DmSidebarSkeleton } from "@/components/community/channels/dm-sidebar"
import { CommunityPendingFrame } from "./community-pending-frame"
@@ -25,6 +26,7 @@ import { ProfileRunningBotsCard } from "@/components/community/social/profile-ru
type Props = Pick<ShellFrameProps, "sidebar" | "children" | "extraDialogs"> & {
breakpoint: Breakpoint
+ routeCommitted?: boolean
checkpoint: CommunityCheckpointPlan
rail: ReturnType<typeof useShellRailController>
profile: ReturnType<typeof useShellProfileController>
@@ -40,6 +42,7 @@ type Props = Pick<ShellFrameProps, "sidebar" | "children" | "extraDialogs"> & {
export function ShellFrameView({
breakpoint,
+ routeCommitted = true,
checkpoint,
sidebar,
children,
@@ -114,7 +117,10 @@ export function ShellFrameView({
? <ChannelSidebarSkeleton targetServerId={checkpoint.sidebar.serverId} />
: checkpoint.sidebar.kind === "me-skeleton" ? <DmSidebarSkeleton /> : null}
</>}
- main={checkpoint.main.kind === "keep" || checkpoint.main.kind === "server-route" ? children : (
+ main={checkpoint.main.kind === "dm-route" ? (
+ <DmRoute key={`${profile.currentUser.id}/${checkpoint.main.dmId}`} dmId={checkpoint.main.dmId}
+ routeCommitted={routeCommitted} />
+ ) : checkpoint.main.kind === "keep" || checkpoint.main.kind === "server-route" ? children : (
<CommunityPendingFrame
href={checkpoint.targetHref}
reserveBackSlot={surface === "detail"}
diff --git a/src/web/src/components/community/shell/shell-frame.tsx b/src/web/src/components/community/shell/shell-frame.tsx
index 891ae157c..e348280b1 100644
--- a/src/web/src/components/community/shell/shell-frame.tsx
+++ b/src/web/src/components/community/shell/shell-frame.tsx
@@ -364,6 +364,7 @@ const [committedFrame, setCommittedFrame] = useAtom(useCreateAtom(initialCommitt
<ShellFrameView
breakpoint={breakpoint}
checkpoint={checkpoint}
+ routeCommitted={isPublishedNonStructuralCommit(committedFrame, navigation.publishedHref, navigation.pendingHref ?? navigation.publishedHref)}
sidebar={sidebar}
extraDialogs={extraDialogs}
rail={rail}
diff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.ts
index 869b21cfe..f9793a126 100644
--- a/src/web/src/hooks/community/community-ws/reconnect-messages.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.ts
@@ -1,4 +1,4 @@
-import { CancelledError, queryOptions, type InfiniteData, type QueryClient, type QueryKey } from "@tanstack/react-query"
+import { CancelledError, hashKey, queryOptions, type InfiniteData, type QueryClient, type QueryKey } from "@tanstack/react-query"
import { apiFetchCommunity } from "@/lib/community/account-cache-lifecycle"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken, publishCommunityMessages, retireCommunityChannelReading } from "@/lib/community-db/sync"
@@ -33,7 +33,7 @@ function mergeWindow(cache: MessageCache, refreshed: MessagesPage, catchUp: Mess
return { ...cache, pages }
}
-export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepairScope, key: QueryKey) {
+export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepairScope, key: QueryKey, landing?: { page: MessagesPage; param: MessagesPageParam }) {
const scopeId = scope.scopeId
const token = captureCommunityLiveSnapshotToken(queryClient, scopeId), registry = getCommunityDbRegistry(queryClient)
const channel = registry?.collections.channels.get(scopeId)
@@ -54,6 +54,7 @@ export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepa
assert()
const tag = messageWindowIdentity(key)?.tag ?? null
const load = async (param: MessagesPageParam) => { assert(); const page = await apiFetchCommunity<MessagesPage>(url(scopeId, param, tag), { signal, assertActive: assert }, token); assert(); return page }
+ let landingPage = landing
let highWater = latest(data)
let paginationReplayed = false
try {
@@ -61,7 +62,10 @@ export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepa
const target = () => queryClient.getQueryData<number>(targetKey(key)) ?? 0
const current = originalQuery?.state.data
if (!isMessageCache(current) || !current.pageParams[0]) return { latestSeq: highWater }
- const refreshed = await load(current.pageParams[0]), catchUp: MessagesPage[] = []
+ const refreshed = landingPage && hashKey([landingPage.param]) === hashKey([current.pageParams[0]])
+ ? landingPage.page : await load(current.pageParams[0])
+ landingPage = undefined
+ const catchUp: MessagesPage[] = []
if (!isMessageCache(originalQuery?.state.data)) return { latestSeq: highWater }
let nextCursor = cursor(current)
highWater = Math.max(highWater, refreshed.latestSeq ?? 0)
@@ -100,23 +104,34 @@ export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepa
})
}
+function reconcileWindow(queryClient: QueryClient, scope: GapRepairScope, key: QueryKey, target = 0, landing?: { page: MessagesPage; param: MessagesPageParam }) {
+ const query = queryClient.getQueryCache().find({ queryKey: key, exact: true })
+ if (!query) return Promise.resolve()
+ queryClient.setQueryData<number>(targetKey(key), (current) => Math.max(current ?? 0, target))
+ if (!isMessageCache(query.state.data)) return query.fetch().then(() => undefined)
+ const repairKey = [...key, "reconcile"]
+ const repair = queryClient.getQueryCache().find({ queryKey: repairKey, exact: true })
+ const receipt = repair?.meta?.communityMessageRepair as { token: ReturnType<typeof captureCommunityLiveSnapshotToken>; window: typeof query } | undefined
+ if (receipt) {
+ let current = receipt.window === query
+ try { assertCommunityLiveSnapshotTokenCurrent(queryClient, receipt.token, undefined) } catch { current = false }
+ if (!current) queryClient.removeQueries({ queryKey: repairKey, exact: true })
+ }
+ return queryClient.query({ ...messageReconcileOptions(queryClient, scope, key, landing), select: undefined }).then(() => undefined).catch((error: unknown) => {
+ if (!isAbortError(error) && !(error instanceof CancelledError)) throw error
+ })
+}
+
+export function reconcileConversationLanding(queryClient: QueryClient, scope: GapRepairScope, key: QueryKey, page: MessagesPage, param: MessagesPageParam) {
+ const data = queryClient.getQueryData(key)
+ const highWater = page.latestSeq ?? 0
+ if (!isMessageCache(data) || highWater <= latest(data)) return Promise.resolve()
+ return reconcileWindow(queryClient, scope, key, highWater, { page, param })
+}
+
function reconcile(queryClient: QueryClient, scope: GapRepairScope, target = 0) {
const queries = queryClient.getQueryCache().findAll({ queryKey: messagesKey(scope), type: "active" }).filter((query) => isWindowKey(query.queryKey))
- return Promise.all(queries.map((query) => {
- queryClient.setQueryData<number>(targetKey(query.queryKey), (current) => Math.max(current ?? 0, target))
- if (!isMessageCache(query.state.data)) return query.fetch()
- const repairKey = [...query.queryKey, "reconcile"]
- const repair = queryClient.getQueryCache().find({ queryKey: repairKey, exact: true })
- const receipt = repair?.meta?.communityMessageRepair as { token: ReturnType<typeof captureCommunityLiveSnapshotToken>; window: typeof query } | undefined
- if (receipt) {
- let current = receipt.window === query
- try { assertCommunityLiveSnapshotTokenCurrent(queryClient, receipt.token, undefined) } catch { current = false }
- if (!current) queryClient.removeQueries({ queryKey: repairKey, exact: true })
- }
- return queryClient.query({ ...messageReconcileOptions(queryClient, scope, query.queryKey), select: undefined }).catch((error: unknown) => {
- if (!isAbortError(error) && !(error instanceof CancelledError)) throw error
- })
- })).then(() => undefined)
+ return Promise.all(queries.map(query => reconcileWindow(queryClient, scope, query.queryKey, target))).then(() => undefined)
}
export function scheduleFocusedMessageGapRepair(queryClient: QueryClient, scope: GapRepairScope, incomingSeq: number): Promise<void> | null {
diff --git a/src/web/src/hooks/community/use-messages.activation-refetch.dom.test.tsx b/src/web/src/hooks/community/use-messages.activation-refetch.dom.test.tsx
index 9d422181a..6854ef5f7 100644
--- a/src/web/src/hooks/community/use-messages.activation-refetch.dom.test.tsx
+++ b/src/web/src/hooks/community/use-messages.activation-refetch.dom.test.tsx
@@ -6,6 +6,8 @@ import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { conversationEntryFixture as fixture, dmConversationEntryFixture } from "@/test/conversation-entry-fixtures"
import { CommunityDbProvider } from "@/lib/community-db/projections"
import { ingestReadStateSnapshot } from "@/lib/community-db/sync"
+import { communityKeys } from "@/lib/query-keys"
+import type { MessageWindowData } from "@/lib/community/message-window"
import { ConversationReadTimeoutError } from "@/lib/community/conversation-read"
import { useMessages, useDmMessages } from "./use-messages"
@@ -43,6 +45,54 @@ describe("entry-owned message activation", () => {
returned.unmount()
})
+ it("revalidates a stale landing once without replaying its three cached pages", async () => {
+ const { wrapper, client } = await setup()
+ load.mockResolvedValue(fixture())
+ const first = renderHook(() => useMessages("c1", { serverId: "s1" }), { wrapper })
+ await waitFor(() => expect(first.result.current.initialPositionKnown).toBe(true))
+ const key = communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "m1" })
+ const cached = client.getQueryData<MessageWindowData>(key)!
+ const pages = [cached.pages[0], { ...cached.pages[0], messages: [], olderCursor: "old-2" }, { ...cached.pages[0], messages: [], hasMoreOlder: false }]
+ await act(async () => client.setQueryData(key, { pages, pageParams: [{ mode: "anchor", anchor: "m1" }, { mode: "older", cursor: "old-1" }, { mode: "older", cursor: "old-2" }] }))
+ first.unmount()
+ const clock = vi.spyOn(Date, "now").mockReturnValue(Date.now() + 6000)
+ try {
+ const returned = renderHook(() => useMessages("c1", { serverId: "s1" }), { wrapper })
+ await waitFor(() => expect(load).toHaveBeenCalledTimes(2))
+ await waitFor(() => expect(returned.result.current.isFetching).toBe(false))
+ expect(load.mock.calls.every(([url]) => String(url).includes("entry=1"))).toBe(true)
+ expect(client.getQueryData<MessageWindowData>(key)?.pages).toEqual(pages)
+ expect(returned.result.current.messages.map(row => row.id)).toEqual(["m1"])
+ returned.unmount()
+ } finally { clock.mockRestore() }
+ })
+
+ it("feeds a new landing tail into the existing gap repair without reloading the anchor page", async () => {
+ const { wrapper, client } = await setup()
+ const packet = fixture()
+ load.mockResolvedValueOnce(packet)
+ const first = renderHook(() => useMessages("c1", { serverId: "s1" }), { wrapper })
+ await waitFor(() => expect(first.result.current.initialPositionKnown).toBe(true))
+ first.unmount()
+ const m2 = { ...packet.messages[0], id: "m2", seq: 2, content: "Missed message", createdAt: "2026-10-01T00:00:02.000Z" }
+ const m3 = { ...m2, id: "m3", seq: 3, content: "New landing", createdAt: "2026-10-01T00:00:03.000Z" }
+ load.mockImplementation((url: string) => url.includes("entry=1")
+ ? Promise.resolve({ ...packet, messages: [packet.messages[0], m3], page: { ...packet.page, latestSeq: 3 } })
+ : Promise.resolve({ messages: [m2, m3], latestSeq: 3, hasMoreNewer: false, hasMoreOlder: true }))
+ const clock = vi.spyOn(Date, "now").mockReturnValue(Date.now() + 6000)
+ try {
+ const returned = renderHook(() => useMessages("c1", { serverId: "s1" }), { wrapper })
+ await waitFor(() => expect(returned.result.current.messages.map(row => row.id)).toEqual(["m1", "m2", "m3"]))
+ const urls = load.mock.calls.map(([url]) => String(url))
+ expect(urls).toHaveLength(3)
+ expect(urls.filter(url => url.includes("entry=1"))).toHaveLength(2)
+ expect(urls[2]).toContain("since=")
+ expect(urls.filter(url => url.includes("anchor="))).toHaveLength(0)
+ expect(client.getQueryData<MessageWindowData>(communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "m1" }))?.pages).toHaveLength(1)
+ returned.unmount()
+ } finally { clock.mockRestore() }
+ })
+
it("freezes a confirmed never-visited pointer through a later canonical advance", async () => {
const { wrapper, registry } = await setup()
const packet = fixture()
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.ts
index 956750029..d01426482 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
@@ -49,16 +49,13 @@ describe("native pagination and original semantic epoch", () => {
expect(bodyTop(h.root, "m7")).toBeCloseTo(before, 0)
expect(offset).not.toHaveBeenCalled()
expect(index).not.toHaveBeenCalled()
- expect(scrollFixture.latest.isNewerPageAnchorSettling).toBe(false)
})
it("does not treat a divider update as observed fetch completion", () => {
const h = mount()
act(() => scrollFixture.latest.captureOlderPageAnchor())
h.update({ items: [...h.input.items] })
- expect(scrollFixture.latest.isOlderPageAnchorSettling).toBe(true)
h.update({ isFetchingOlder: true })
h.update({ isFetchingOlder: false })
- expect(scrollFixture.latest.isOlderPageAnchorSettling).toBe(false)
})
it("finishes a replacement window without inventing preservation of a removed key or following its historical tail", () => {
const h = mount()
@@ -67,7 +64,6 @@ describe("native pagination and original semantic epoch", () => {
act(() => scrollFixture.latest.captureNewerPageAnchor())
h.update({ isFetchingNewer: true })
h.update({ items: Array.from({ length: 12 }, (_, i) => message(`replacement${i}`, "me")), isFetchingNewer: false })
- expect(scrollFixture.latest.isNewerPageAnchorSettling).toBe(false)
expect(h.root.querySelector('[data-msg-id="m5"]')).toBeNull()
expect(end).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.ts
index c2b6ad89b..908e95887 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
@@ -147,7 +147,6 @@ describe("locked native adapter and existing message scroll owner", () => {
resize()
h.update({ items: [message("older"), ...h.input.items], isFetchingOlder: false })
expect(bodyTop(h.root, "m0")).toBeCloseTo(before, 0)
- expect(scrollFixture.latest.isOlderPageAnchorSettling).toBe(false)
})
it("does not restore the old origin after a reader scroll with a rejected pending row position", () => {
const h = mount({ items: Array.from({ length: 28 }, (_, i) => message(`m${i}`)) })
@@ -537,7 +536,6 @@ describe("locked native adapter and existing message scroll owner", () => {
const before = bodyTop(h.root, "m0")
h.update({ items: [message("older-0"), message("older-1"), message("older-2"), ...h.input.items], isFetchingOlder: false })
expect(bodyTop(h.root, "m0")).toBeCloseTo(before, 0)
- expect(scrollFixture.latest.isOlderPageAnchorSettling).toBe(false)
expect(scrollFixture.latest.readPositionReady).toBe(false)
expect(scrollFixture.latest.paginationEnabled).toBe(true)
expect(scrollFixture.latest.virtualizer.options).toMatchObject({ anchorTo: "start", followOnAppend: false })
@@ -561,7 +559,6 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(bodyTop(h.root, id)).toBeCloseTo(before, 0)
expect(index).not.toHaveBeenCalled()
expect(scrollFixture.latest.readPositionReady).toBe(false)
- expect(scrollFixture.latest.isOlderPageAnchorSettling).toBe(false)
expect(scrollFixture.latest.virtualizer.options).toMatchObject({ anchorTo: "start", followOnAppend: false })
const settledOffset = h.root.scrollTop
h.update({ items: [...h.input.items, message("late-peer")] })
@@ -591,7 +588,6 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(bodyTop(h.root, "m5")).toBeCloseTo(top, 0)
expect(index).not.toHaveBeenCalled()
expect(offset).not.toHaveBeenCalled()
- expect(scrollFixture.latest.isOlderPageAnchorSettling).toBe(false)
})
it("keeps quote smooth on the native index command without a per-frame offset rewrite", () => {
const h = mount()
@@ -629,31 +625,29 @@ describe("locked native adapter and existing message scroll owner", () => {
h.update({ items: [...older, ...h.input.items], isFetchingOlder: false })
expect(bodyTop(h.root, "m0")).toBe(currentTop)
})
- it("keeps the page settlement gate after the fetch ends until native geometry settles", () => {
+ it("leaves semantic pagination enabled while native prepend geometry converges", () => {
const h = mount()
h.move(0)
act(() => scrollFixture.latest.captureOlderPageAnchor())
h.update({ isFetchingOlder: true })
const older = Array.from({ length: 30 }, (_, index) => message(`older-${index}`))
h.stage({ items: [...older, ...h.input.items], isFetchingOlder: false })
- expect(scrollFixture.latest.isOlderPageAnchorSettling).toBe(true)
+ expect(scrollFixture.latest.paginationEnabled).toBe(true)
resize(2)
- expect(scrollFixture.latest.isOlderPageAnchorSettling).toBe(true)
+ expect(scrollFixture.latest.paginationEnabled).toBe(true)
runFrames()
- expect(scrollFixture.latest.isOlderPageAnchorSettling).toBe(false)
+ expect(scrollFixture.latest.paginationEnabled).toBe(true)
})
it.each(["wheel", "target"])("retires a pending header page when %s takes ownership before the response", input => {
const h = mount()
h.move(0)
act(() => scrollFixture.latest.captureOlderPageAnchor())
h.update({ isFetchingOlder: true })
- expect(scrollFixture.latest.isOlderPageAnchorSettling).toBe(true)
if (input === "wheel") h.move(350)
else {
act(() => scrollFixture.latest.jumpTo("m8", "auto"))
runFrames()
}
- expect(scrollFixture.latest.isOlderPageAnchorSettling).toBe(false)
const before = bodyTop(h.root, input === "wheel" ? "m3" : "m8")
const index = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToIndex")
const older = Array.from({ length: 30 }, (_, index) => message(`older-${index}`))
@@ -676,6 +670,26 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(bodyTop(h.root, "older-29")).toBe(readingTop)
expect(bodyTop(h.root, "m0")).toBe(restoredTop + 8)
})
+ it("retires header-fold measurement policy when the viewport shrinks before the next restore frame", () => {
+ const h = mount()
+ h.move(0)
+ const restoredTop = bodyTop(h.root, "m0")
+ act(() => scrollFixture.latest.captureOlderPageAnchor())
+ h.update({ isFetchingOlder: true })
+ const older = Array.from({ length: 30 }, (_, index) => message(`older-${index}`))
+ h.stage({ items: [...older, ...h.input.items], isFetchingOlder: false })
+ resize(0)
+ expect(scrollFixture.latest.virtualizer.shouldAdjustScrollPositionOnItemSizeChange).toBeTypeOf("function")
+ scrollFixture.height -= 40
+ resize()
+ expect(bodyTop(h.root, "m0")).toBe(restoredTop)
+ expect(scrollFixture.latest.virtualizer.shouldAdjustScrollPositionOnItemSizeChange).toBeUndefined()
+ const readingTop = bodyTop(h.root, "older-29")
+ scrollFixture.bodyHeights.set("older-29", 108)
+ resize()
+ expect(bodyTop(h.root, "older-29")).toBe(readingTop)
+ expect(bodyTop(h.root, "m0")).toBe(restoredTop + 8)
+ })
it("lets the reader keep the new spanning row after taking over a header-fold restore", () => {
const h = mount()
h.move(0)
@@ -979,7 +993,7 @@ describe("locked native adapter and existing message scroll owner", () => {
resize()
expect(h.root.scrollTop).toBe(before)
})
- it.each(["commit", "discard"])("retires a width request after a rendered tail suspends before %s", async outcome => {
+ it.each(["commit", "discard"])("keeps native width positioning across a suspended tail before %s", async outcome => {
let suspend = false
let resume!: () => void
const pending = new Promise<void>(resolve => { resume = resolve })
@@ -1001,7 +1015,7 @@ describe("locked native adapter and existing message scroll owner", () => {
const offset = vi.spyOn(native, "scrollToOffset")
scrollFixture.width = 266
resize(0)
- expect(end).not.toHaveBeenCalled()
+ expect(end).toHaveBeenCalledOnce()
const committedLayouts = layouts
suspend = true
await act(async () => {
@@ -1019,7 +1033,7 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(layouts).toBe(committedLayouts)
expect(h.root.querySelector('[data-msg-id="pending-tail"]')).toBeNull()
expect(h.view.queryByTestId("pending-tail")).toBeNull()
- expect(end).not.toHaveBeenCalled()
+ expect(end).toHaveBeenCalledOnce()
expect(offset).not.toHaveBeenCalled()
suspend = false
if (outcome === "discard") h.stage({ items: originalItems })
@@ -1029,10 +1043,11 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(h.root.querySelector('[data-msg-id="pending-tail"]') !== null).toBe(outcome === "commit")
expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)
expect(scrollFixture.latest.readPositionReady).toBe(true)
- if (outcome === "discard") expect(end).not.toHaveBeenCalled()
- else expect(end).toHaveBeenCalledOnce()
+ const commands = end.mock.calls.length
+ runFrames()
+ expect(end).toHaveBeenCalledTimes(commands)
})
- it("does not revive a committed width request from late public frame callbacks", () => {
+ it("leaves a changed tail to native positioning without an application width wait", () => {
scrollFixture.width = 639
const h = mount({ tailPaddingEnd: 40 })
const native = scrollFixture.latest.virtualizer
@@ -1040,13 +1055,13 @@ describe("locked native adapter and existing message scroll owner", () => {
const offset = vi.spyOn(native, "scrollToOffset")
const cancel = vi.spyOn(native, "cancelScroll")
scrollFixture.width = 266
- resize(2)
+ resize(0)
expect(end).toHaveBeenCalledOnce()
cancel.mockClear()
const pending = [...scrollFixture.frames.values()]
expect(pending.length).toBeGreaterThan(0)
h.stage({ items: [...h.input.items.slice(0, -1), message("replacement")] })
- expect(cancel).toHaveBeenCalledOnce()
+ expect(cancel).not.toHaveBeenCalled()
expect(offset).not.toHaveBeenCalled()
expect(h.root.querySelector('[data-msg-id="replacement"]')).not.toBeNull()
resize()
@@ -1058,54 +1073,39 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(h.root.querySelector('[data-msg-id="replacement"]')).not.toBeNull()
expect(scrollFixture.latest.readPositionReady).toBe(true)
})
- it.each(["timer", "frame"])("ends a width request at its original deadline through repeated appends and %s delivery", async delivery => {
+ it("keeps native tail follow through repeated appends without an application width deadline", async () => {
let pending: Promise<void> | null = null
- function Gate() {
- if (pending) use(pending)
- return null
- }
+ function Gate() { if (pending) use(pending); return null }
function Wrapper({ children }: PropsWithChildren) {
- return createElement(Suspense, { fallback: createElement("div", { "data-testid": "pending-width" }) },
- children, createElement(Gate))
+ return createElement(Suspense, { fallback: createElement("div", { "data-testid": "pending-width" }) }, children, createElement(Gate))
}
scrollFixture.width = 639
const h = mount({ tailPaddingEnd: 40 }, false, undefined, Wrapper)
- const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")
+ const native = scrollFixture.latest.virtualizer
+ const end = vi.spyOn(native, "scrollToEnd")
scrollFixture.width = 266
- resize(0)
- const startedAt = Date.now()
+ resize()
+ expect(end).toHaveBeenCalledOnce()
+ expect(scrollFixture.latest.paginationEnabled).toBe(true)
for (let i = 0; i < 5; i++) {
let resume!: () => void
pending = new Promise<void>(resolve => { resume = resolve })
- await act(async () => {
- startTransition(() => h.stage({ items: [...h.input.items, message(`deadline-tail-${i}`)] }))
- })
+ await act(async () => { startTransition(() => h.stage({ items: [...h.input.items, message(`tail-${i}`)] })) })
+ const beforeCommit = end.mock.calls.length
runFrames(1)
- expect(end).not.toHaveBeenCalled()
- await act(async () => {
- pending = null
- resume()
- })
- expect(h.root.querySelector(`[data-msg-id="deadline-tail-${i}"]`)).not.toBeNull()
- expect(scrollFixture.latest.paginationEnabled).toBe(false)
+ expect(end).toHaveBeenCalledTimes(beforeCommit)
+ await act(async () => { pending = null; resume() })
+ resize()
+ expect(h.root.querySelector(`[data-msg-id="tail-${i}"]`)).not.toBeNull()
+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)
+ expect(scrollFixture.latest.paginationEnabled).toBe(true)
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
act(() => vi.advanceTimersByTime(350))
}
- act(() => vi.advanceTimersByTime(1_999 - (Date.now() - startedAt)))
- expect(scrollFixture.latest.paginationEnabled).toBe(false)
- expect(scrollFixture.latest.readPositionReady).toBe(false)
- act(() => {
- if (delivery === "timer") vi.advanceTimersByTime(1)
- else {
- const callbacks = [...scrollFixture.frames.values()]
- expect(callbacks.length).toBeGreaterThan(0)
- vi.setSystemTime(startedAt + 2_000)
- for (const callback of callbacks) callback(performance.now())
- }
- })
- expect(scrollFixture.latest.paginationEnabled).toBe(true)
- expect(scrollFixture.latest.readPositionReady).toBe(true)
- h.update({ items: [...h.input.items, message("after-width-deadline")] })
- expect(end).not.toHaveBeenCalled()
+ const commands = end.mock.calls.length
+ act(() => vi.advanceTimersByTime(2000))
+ runFrames()
+ expect(end).toHaveBeenCalledTimes(commands)
expect(scrollFixture.latest.paginationEnabled).toBe(true)
})
it("preserves a two-pixel DM tail distance through consecutive composer resizes", () => {
@@ -1484,7 +1484,6 @@ describe("current composer intent and native passive ownership", () => {
h.stage({ isFetchingOlder: true })
h.update({ isFetchingOlder: false, items: [message("older-after-supersession"), ...h.input.items] })
expect(bodyTop(h.root, "received-after-supersession")).toBeCloseTo(top, 0)
- expect(scrollFixture.latest.isOlderPageAnchorSettling).toBe(false)
expect(scrollFixture.latest.paginationEnabled).toBe(true)
})
it("does not complete a local history submission from tail attachment without its newest-window receipt", () => {
diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.ts
index 323402000..5a012d920 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.ts
@@ -5,7 +5,7 @@ import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS } 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"
-export const INITIAL_POSITION_TIMEOUT_MS = 2_000
+const INITIAL_POSITION_TIMEOUT_MS = 2_000
export const MESSAGE_LIST_DISPLAY_END_THRESHOLD_PX = 100
const VIEWPORT_RESIZE_TAIL_DISTANCE_PX = 100
type ViewportResizeAnchor = "tail" | "start"
@@ -108,11 +108,9 @@ export function useScrollAnchor({
type: "unread" | "target" | "end"
id: string | null
index: number | null
- stableFrames: number
behavior: ScrollBehavior
notifyTarget: boolean
loadedTailPresent: boolean
- singleEnd: { key: string | null; index: number; retired: boolean } | null
viewport: { width: number; height: number }
}
type Geometry = {
@@ -160,19 +158,20 @@ export function useScrollAnchor({
const consumedPresentVersionRef = useRef(presentVersion ?? 0)
const consumedLocalSubmitVersionRef = useRef(localSubmitVersion ?? 0)
const currentItemsRef = useRef(items)
- currentItemsRef.current = items
const initialScrollReadyRef = useRef(initialScrollReady)
- initialScrollReadyRef.current = initialScrollReady
const onTargetPositionedRef = useRef(onScrollTargetPositioned)
- onTargetPositionedRef.current = onScrollTargetPositioned
const onTargetCancelledRef = useRef(onScrollTargetCancelled)
- onTargetCancelledRef.current = onScrollTargetCancelled
const settleCallbackRef = useRef(onInitialPositionSettled)
- settleCallbackRef.current = onInitialPositionSettled
+ useLayoutEffect(() => {
+ currentItemsRef.current = items
+ initialScrollReadyRef.current = initialScrollReady
+ onTargetPositionedRef.current = onScrollTargetPositioned
+ onTargetCancelledRef.current = onScrollTargetCancelled
+ settleCallbackRef.current = onInitialPositionSettled
+ }, [items, initialScrollReady, onScrollTargetPositioned, onScrollTargetCancelled, onInitialPositionSettled])
const followSuspension = useCreateAtom(false)
const [followSuspended, setFollowSuspended] = useAtom(followSuspension)
const acceptedGeometryRef = useRef<Geometry | null>(null)
- const geometrySampleRef = useRef<{ value: string; frames: number } | null>(null)
const geometryFrameRef = useRef<number | null>(null)
const scheduleGeometryRef = useRef<() => void>(() => {})
const reconcileViewportRef = useRef<() => void>(() => {})
@@ -183,7 +182,7 @@ export function useScrollAnchor({
const holdNativeOrigin = useCallback((key: string | number | bigint | null) => {
setNativeOriginKey(key)
const native = virtualizerRef.current
- if (key !== null && native) native.setOptions({ ...native.options, anchorTo: "start" })
+ if (key !== null && native && !paginationRef.current) native.setOptions({ ...native.options, anchorTo: "start" })
}, [setNativeOriginKey])
const cancelFrame = useCallback(() => {
if (initialSettleFrameRef.current !== null) window.cancelAnimationFrame(initialSettleFrameRef.current)
@@ -213,9 +212,9 @@ export function useScrollAnchor({
const owner = positionOwnerRef.current
virtualizerRef.current?.cancelScroll()
clearOlderMeasurementAnchor()
+ scrollPaddingStartRef.current = 0
paginationRef.current = null
setPaginationDirection(null)
- scrollPaddingStartRef.current = 0
owner.epoch += 1
setOwnerKind(kind)
cancelFrame()
@@ -223,7 +222,6 @@ export function useScrollAnchor({
semanticIntentRef.current = null
acceptedGeometryRef.current = null
holdNativeOrigin(null)
- geometrySampleRef.current = null
presentIntentRef.current = null
setReadPositionReady(false)
return owner.epoch
@@ -238,9 +236,9 @@ export function useScrollAnchor({
? intent?.notifyTarget ? intent.id
: !intent && positionedTargetRef.current !== targetIntentRef.current ? targetIntentRef.current : null
: null
- const wasReadable = (positionKind.get() === "idle" && readReady.get()) || !!intent?.singleEnd
+ const wasReadable = positionKind.get() === "idle" && readReady.get()
claimPosition("idle")
- if ((userHandover || intent?.singleEnd) && wasReadable) setReadPositionReady(true)
+ if (userHandover && wasReadable) setReadPositionReady(true)
retireInitialPosition()
positionedTargetRef.current = targetIntentRef.current
if (cancelledTarget) onTargetCancelledRef.current?.(cancelledTarget)
@@ -376,7 +374,6 @@ export function useScrollAnchor({
}, [followSuspension, nativeOrigin])
const scheduleInitialPositionSettled = useCallback(() => {
if (initialSettleFrameRef.current !== null) return
- if (semanticIntentRef.current?.loadedTailPresent) semanticIntentRef.current.stableFrames = 0
const epoch = positionOwnerRef.current.epoch
const settle = () => {
const owner = positionOwnerRef.current
@@ -386,48 +383,25 @@ export function useScrollAnchor({
const root = scrollRef.current
const native = virtualizerRef.current
if (!intent || intent.epoch !== owner.epoch || !root || !native) return
- if (intent.singleEnd && initialDeadlineRef.current !== null && Date.now() >= initialDeadlineRef.current.at) {
- releasePosition()
- return
- }
- if (intent.singleEnd?.retired) return
- const index = currentItemsRef.current.length - 1
- if (intent.singleEnd && (index < 0 || intent.singleEnd.index !== index
- || intent.singleEnd.key !== currentItemsRef.current[index]?.key)) {
- intent.singleEnd.retired = true
- native.cancelScroll()
- return
- }
const viewport = root.getBoundingClientRect()
- if (root.clientHeight <= 0 || viewport.height <= 0) {
- if (!intent.loadedTailPresent || intent.singleEnd) initialSettleFrameRef.current = window.requestAnimationFrame(settle)
- return
- }
- if (intent.singleEnd && intent.index === null) {
- const geometry = readGeometry()
- const value = geometry ? JSON.stringify(geometry) : null
- const sample = geometrySampleRef.current
- geometrySampleRef.current = value === null ? null
- : { value, frames: sample?.value === value ? sample.frames + 1 : 1 }
- if (geometrySampleRef.current && geometrySampleRef.current.frames >= 2) {
- intent.index = index
- geometrySampleRef.current = null
- native.scrollToEnd({ behavior: intent.behavior })
- }
- initialSettleFrameRef.current = window.requestAnimationFrame(settle)
- return
- }
+ if (root.clientHeight <= 0 || viewport.height <= 0) return
let landed = false
if (intent.type === "end") {
- landed = native.isAtEnd(1) && (!intent.singleEnd
- || Math.abs(Math.max(0, root.scrollHeight - root.clientHeight) - root.scrollTop) <= 1)
+ const tail = currentItemsRef.current.findLast(item => item.kind === "message")
+ const body = tail?.kind === "message" ? Array.from(root.querySelectorAll<HTMLElement>("[data-msg-id]"))
+ .find(element => element.dataset.msgId === tail.m.id) : undefined
+ const rect = body?.getBoundingClientRect()
+ const wrapper = body?.closest("[data-index]")?.getBoundingClientRect()
+ landed = native.isAtEnd(1)
+ && Math.abs(Math.max(0, root.scrollHeight - root.clientHeight) - root.scrollTop) <= 1
+ && !!rect && rect.height > 0 && !!wrapper && wrapper.height > 0
+ && rect.bottom > viewport.top + 1 && rect.top < viewport.bottom - 1
} else if (intent.id) {
const index = intent.type === "unread"
? findMountScrollTargetIndex(currentItemsRef.current, intent.id)
: findMessageIndex(currentItemsRef.current, intent.id)
if (index !== null && index !== intent.index) {
intent.index = index
- intent.stableFrames = 0
native.scrollToIndex(index, { align: "center", behavior: intent.behavior })
}
const row = Array.from(root.querySelectorAll<HTMLElement>("[data-msg-id]"))
@@ -438,24 +412,17 @@ export function useScrollAnchor({
: row
const rect = boundary?.getBoundingClientRect()
const body = row?.getBoundingClientRect()
- if (rect && body && rect.height > 0 && body.height > 0) {
+ const wrapper = row?.closest("[data-index]")?.getBoundingClientRect()
+ if (rect && body && wrapper && wrapper.height > 0 && rect.height > 0 && body.height > 0) {
const targetOffset = index === null ? undefined : native.getOffsetForIndex(index, "center")?.[0]
landed = targetOffset !== undefined && Math.abs(root.scrollTop - targetOffset) <= 1
&& rect.bottom > viewport.top + 1 && rect.top < viewport.bottom - 1
&& body.bottom > viewport.top + 1 && body.top < viewport.bottom - 1
}
}
- intent.stableFrames = landed ? intent.stableFrames + 1 : 0
- if (intent.stableFrames >= 2 && intent.type !== "end" && root.scrollTop <= 1) holdNativeOrigin(currentItemsRef.current[0]?.key ?? null)
- const geometry = (intent.singleEnd || intent.stableFrames >= 2) ? readGeometry() : null
- if (intent.singleEnd) {
- const value = landed && geometry?.pinEligible ? JSON.stringify(geometry) : null
- const sample = geometrySampleRef.current
- geometrySampleRef.current = value === null ? null
- : { value, frames: sample?.value === value ? sample.frames + 1 : 1 }
- intent.stableFrames = geometrySampleRef.current?.frames ?? 0
- }
- if (intent.stableFrames >= 2 && geometry) {
+ if (landed) {
+ const geometry = readGeometry()
+ if (intent.type !== "end" && root.scrollTop <= 1) holdNativeOrigin(currentItemsRef.current[0]?.key ?? null)
settlePresentation()
if (positionKind.get() === "initial" && !initialScrollReadyRef.current) return
acceptedGeometryRef.current = geometry
@@ -471,30 +438,29 @@ export function useScrollAnchor({
scheduleGeometryRef.current()
return
}
- if (!intent.loadedTailPresent || intent.singleEnd || (landed && intent.stableFrames < 2)) {
+ if (!intent.loadedTailPresent) {
initialSettleFrameRef.current = window.requestAnimationFrame(settle)
}
}
initialSettleFrameRef.current = window.requestAnimationFrame(settle)
- }, [clearBudget, holdNativeOrigin, positionKind, readGeometry, releasePosition, retireInitialPosition, setOwnerKind, setReadPositionReady, settlePresentation])
+ }, [clearBudget, holdNativeOrigin, positionKind, readGeometry, retireInitialPosition, setOwnerKind, setReadPositionReady, settlePresentation])
- const startIntent = useCallback((type: Intent["type"], id: string | null, behavior: ScrollBehavior = "auto", notifyTarget = false, loadedTailPresent = false, singleEnd = false) => {
+ const startIntent = useCallback((type: Intent["type"], id: string | null, behavior: ScrollBehavior = "auto", notifyTarget = false, loadedTailPresent = false) => {
const owner = positionOwnerRef.current
const index = type === "end" ? currentItemsRef.current.length - 1
: id ? type === "unread" ? findMountScrollTargetIndex(currentItemsRef.current, id)
: findMessageIndex(currentItemsRef.current, id) : null
semanticIntentRef.current = {
- epoch: owner.epoch, type, id, index: singleEnd ? null : index, stableFrames: 0, behavior, notifyTarget, loadedTailPresent,
- singleEnd: singleEnd ? { key: currentItemsRef.current[index ?? -1]?.key ?? null, index: index ?? -1, retired: false } : null,
+ epoch: owner.epoch, type, id, index, behavior, notifyTarget, loadedTailPresent,
viewport: { width: scrollRef.current?.clientWidth ?? 0, height: scrollRef.current?.clientHeight ?? 0 },
}
- if (type === "end" && !singleEnd) {
+ if (type === "end") {
virtualizerRef.current?.scrollToEnd({ behavior })
}
- else if (type !== "end" && index !== null) {
+ else if (index !== null) {
virtualizerRef.current?.scrollToIndex(index, { align: "center", behavior })
}
- if (!loadedTailPresent || singleEnd) armBudget()
+ if (!loadedTailPresent) armBudget()
scheduleInitialPositionSettled()
}, [armBudget, scheduleInitialPositionSettled])
@@ -503,8 +469,7 @@ export function useScrollAnchor({
owner.active = true
const intent = semanticIntentRef.current
if (intent && intent.epoch !== owner.epoch) {
- if (intent.singleEnd) releasePosition()
- else startIntent(intent.type, intent.id, intent.behavior, intent.notifyTarget, intent.loadedTailPresent)
+ 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()
@@ -593,71 +558,69 @@ export function useScrollAnchor({
const viewportResized = previous?.epoch === owner.epoch
&& (previous.clientHeight !== root.clientHeight || previous.clientWidth !== root.clientWidth
|| previous.paddingEnd !== (native.options.paddingEnd ?? 0))
- if (!viewportResized && !input.handover && paginationRef.current?.phase !== "settling") {
- if (next) observeGeometry(next)
- return false
- }
- const clampedByResize = viewportResized && !previous.isScrolling && previous.scrollTop > max
- && Math.abs(root.scrollTop - max) <= 1
- if (!readReady.get() && !input.handover && !paginationRef.current
- && (!next || (native.isScrolling && !clampedByResize))) return false
- if (input.touch || input.pointers.size > 0 || (native.isScrolling && !clampedByResize)
- || root.scrollTop < 0 || root.scrollTop > max + 1
- ) return true
- if (previous?.epoch === owner.epoch && readReady.get() && previous.pinEligible
- && previous.clientWidth !== root.clientWidth && !paginationRef.current) {
- claimPosition("present")
- retireInitialPosition()
- startIntent("end", null, "auto", false, true, true)
- return false
- }
- if (!next) return native.getVirtualItems().length > 0
- const virtualItems = native.getVirtualItems()
- const value = JSON.stringify(next)
- const sample = geometrySampleRef.current
- geometrySampleRef.current = { value, frames: sample?.value === value ? sample.frames + 1 : 1 }
- if (!viewportResized && paginationRef.current?.phase === "settling" && geometrySampleRef.current.frames < 2) return true
- let offset = root.scrollTop
- let originHeld = false
- if (viewportResized && previous?.epoch === owner.epoch) {
- originHeld = !previous.pinEligible && previous.scrollTop <= 1
- && previous.key === currentItemsRef.current[0]?.key && previous.itemStart <= 1
- if (originHeld) offset = previous.scrollTop
- else if (previous.clientHeight !== next.clientHeight || previous.clientWidth !== next.clientWidth || previous.paddingEnd !== next.paddingEnd) {
- const previousFold = virtualItems.find((candidate) => candidate.key === previous.key)
- if (previousFold) {
- const totalDelta = next.total - previous.total - (next.paddingEnd - previous.paddingEnd)
- const adjustedPreviousOffset = previous.scrollTop
- + (previous.pinEligible ? totalDelta : previousFold.start - previous.itemStart)
- const resized = resolveViewportResizeAnchor({
- previousClientHeight: previous.clientHeight,
- nextClientHeight: next.clientHeight,
- previousScrollHeight: previous.scrollHeight + totalDelta,
- nextScrollHeight: next.scrollHeight,
- previousScrollTop: adjustedPreviousOffset,
- })
- offset = resized.scrollTop
+ if (!viewportResized && !input.handover) {
+ if (!next) return false
+ observeGeometry(next)
+ } else {
+ const clampedByResize = viewportResized && !previous.isScrolling && previous.scrollTop > max
+ && Math.abs(root.scrollTop - max) <= 1
+ if (!readReady.get() && !input.handover
+ && (!next || (native.isScrolling && !clampedByResize))) return false
+ if (input.touch || input.pointers.size > 0 || (native.isScrolling && !clampedByResize)
+ || root.scrollTop < 0 || root.scrollTop > max + 1
+ ) return true
+ if (previous?.epoch === owner.epoch && readReady.get() && previous.pinEligible
+ && previous.clientWidth !== root.clientWidth && !isFetchingOlder && !isFetchingNewer) {
+ claimPosition("present")
+ retireInitialPosition()
+ startIntent("end", null, "auto", false, true)
+ return false
+ }
+ if (!next) return native.getVirtualItems().length > 0
+ const virtualItems = native.getVirtualItems()
+ let offset = root.scrollTop
+ let originHeld = false
+ if (viewportResized && previous?.epoch === owner.epoch) {
+ originHeld = !previous.pinEligible && previous.scrollTop <= 1
+ && previous.key === currentItemsRef.current[0]?.key && previous.itemStart <= 1
+ if (originHeld) offset = previous.scrollTop
+ else if (previous.clientHeight !== next.clientHeight || previous.clientWidth !== next.clientWidth || previous.paddingEnd !== next.paddingEnd) {
+ const previousFold = virtualItems.find((candidate) => candidate.key === previous.key)
+ if (previousFold) {
+ const totalDelta = next.total - previous.total - (next.paddingEnd - previous.paddingEnd)
+ const adjustedPreviousOffset = previous.scrollTop
+ + (previous.pinEligible ? totalDelta : previousFold.start - previous.itemStart)
+ const resized = resolveViewportResizeAnchor({
+ previousClientHeight: previous.clientHeight,
+ nextClientHeight: next.clientHeight,
+ previousScrollHeight: previous.scrollHeight + totalDelta,
+ nextScrollHeight: next.scrollHeight,
+ previousScrollTop: adjustedPreviousOffset,
+ })
+ offset = resized.scrollTop
+ }
}
}
+ offset = Math.max(0, Math.min(offset, max))
+ acceptedGeometryRef.current = {
+ ...next, scrollTop: offset, pinEligible: !originHeld && next.pinEligible && max - offset <= 1,
+ isScrolling: clampedByResize ? previous.isScrolling : next.isScrolling,
+ }
+ holdNativeOrigin(originHeld || (offset <= 1 && !acceptedGeometryRef.current.pinEligible) ? currentItemsRef.current[0]?.key ?? null : null)
+ if (input.handover) {
+ input.handover = false
+ setReadPositionReady(true)
+ }
+ if (Math.abs(offset - root.scrollTop) > 0.5) native.scrollToOffset(offset, { behavior: "auto" })
}
- offset = Math.max(0, Math.min(offset, max))
- acceptedGeometryRef.current = {
- ...next, scrollTop: offset, pinEligible: !originHeld && next.pinEligible && max - offset <= 1,
- isScrolling: clampedByResize ? previous.isScrolling : next.isScrolling,
- }
- holdNativeOrigin(originHeld || (offset <= 1 && !acceptedGeometryRef.current.pinEligible) ? currentItemsRef.current[0]?.key ?? null : null)
- if (input.handover) {
- input.handover = false
- setReadPositionReady(true)
- }
- if (Math.abs(offset - root.scrollTop) > 0.5) native.scrollToOffset(offset, { behavior: "auto" })
- if (olderMeasurementAnchorRef.current) clearOlderMeasurementAnchor()
if (paginationRef.current?.phase === "settling") {
paginationRef.current = null
setPaginationDirection(null)
+ clearOlderMeasurementAnchor()
}
+
return false
- }, [claimPosition, clearOlderMeasurementAnchor, holdNativeOrigin, observeGeometry, positionKind, readGeometry, readReady, retireInitialPosition, setPaginationDirection, setReadPositionReady, setShortGap, startIntent])
+ }, [claimPosition, clearOlderMeasurementAnchor, holdNativeOrigin, isFetchingOlder, isFetchingNewer, observeGeometry, positionKind, readGeometry, readReady, retireInitialPosition, setPaginationDirection, setReadPositionReady, setShortGap, startIntent])
reconcileViewportRef.current = () => {
const intent = semanticIntentRef.current
const root = scrollRef.current
@@ -665,9 +628,7 @@ export function useScrollAnchor({
if (intent && root && native && intent.epoch === positionOwnerRef.current.epoch
&& (intent.viewport.width !== root.clientWidth || intent.viewport.height !== root.clientHeight)) {
intent.viewport = { width: root.clientWidth, height: root.clientHeight }
- intent.stableFrames = 0
- if (intent.singleEnd) geometrySampleRef.current = null
- else if (intent.type !== "end" && intent.index !== null && root.clientHeight > 0) {
+ if (intent.type !== "end" && intent.index !== null && root.clientHeight > 0) {
native.scrollToIndex(intent.index, { align: "center", behavior: intent.behavior })
}
scheduleInitialPositionSettled()
@@ -806,7 +767,6 @@ export function useScrollAnchor({
}, [holdNativeOrigin, nativeOrigin, observeGeometry, positionKind, readGeometry, readReady, reconcileGeometry, releasePosition, scheduleGeometry, scheduleInitialPositionSettled, setFollowSuspended])
const capturePageAnchor = useCallback((direction: "older" | "newer") => {
- if (semanticIntentRef.current?.singleEnd) releasePosition()
clearOlderMeasurementAnchor()
let anchor: NonNullable<typeof paginationRef.current>["anchor"]
if (positionKind.get() === "idle") {
@@ -828,7 +788,7 @@ export function useScrollAnchor({
}
paginationRef.current = { direction, phase: "pending", anchor }
setPaginationDirection(direction)
- }, [clearOlderMeasurementAnchor, positionKind, readGeometry, readPageMessageGeometry, releasePosition, setPaginationDirection])
+ }, [clearOlderMeasurementAnchor, positionKind, readGeometry, readPageMessageGeometry, setPaginationDirection])
const captureOlderPageAnchor = useCallback(() => capturePageAnchor("older"), [capturePageAnchor])
const captureNewerPageAnchor = useCallback(() => capturePageAnchor("newer"), [capturePageAnchor])
useLayoutEffect(() => {
@@ -838,7 +798,7 @@ export function useScrollAnchor({
if (fetching) { page.phase = "fetching"; return }
if (page.phase !== "fetching") return
page.phase = "settling"
- geometrySampleRef.current = null
+ let restoringBody = false
if (page.anchor && page.anchor.epoch === positionOwnerRef.current.epoch
&& positionKind.get() === "idle"
&& items.find(item => item.kind === "message")?.key !== page.anchor.firstKey) {
@@ -854,11 +814,16 @@ export function useScrollAnchor({
acceptedGeometryRef.current = null
holdNativeOrigin(null)
native.scrollToIndex(index, { align: "start" })
+ restoringBody = true
}
}
+ if (!restoringBody) {
+ paginationRef.current = null
+ setPaginationDirection(null)
+ }
scheduleInitialPositionSettled()
scheduleGeometry()
- }, [adjustOlderMeasurement, holdNativeOrigin, isFetchingNewer, isFetchingOlder, items, positionKind, scheduleGeometry, scheduleInitialPositionSettled])
+ }, [adjustOlderMeasurement, holdNativeOrigin, isFetchingNewer, isFetchingOlder, items, positionKind, scheduleGeometry, scheduleInitialPositionSettled, setPaginationDirection])
useLayoutEffect(() => {
const version = localSubmitVersion ?? 0
@@ -907,23 +872,6 @@ export function useScrollAnchor({
const root = scrollRef.current
const viewportReady = !!root && root.clientHeight > 0 && virtualItems.length > 0
&& !!root.querySelector("[data-index]")
- const intent = semanticIntentRef.current
- const singleEnd = intent?.singleEnd
- if (intent && singleEnd && (singleEnd.retired || singleEnd.index !== items.length - 1 || singleEnd.key !== items.at(-1)?.key)) {
- const committedAppend = singleEnd.retired && intent.index === null
- && singleEnd.index < items.length - 1 && items[singleEnd.index]?.key === singleEnd.key
- && initialDeadlineRef.current !== null && Date.now() < initialDeadlineRef.current.at
- if (!committedAppend) releasePosition()
- else {
- cancelFrame()
- singleEnd.index = items.length - 1
- singleEnd.key = items.at(-1)?.key ?? null
- singleEnd.retired = false
- intent.stableFrames = 0
- geometrySampleRef.current = null
- scheduleInitialPositionSettled()
- }
- }
if (positionKind.get() !== "initial" || initialRetiredRef.current || !hasMessages || !viewportReady) return
if (initialScrollReady && !entryResolvedRef.current) {
entryResolvedRef.current = true
@@ -960,7 +908,5 @@ export function useScrollAnchor({
scrollRef, virtualizer, readPositionReady, paginationEnabled: ownerKind === "idle" && !awaitingTarget, belowCount,
scrollToBottom, requestPresentPosition, jumpTo,
captureOlderPageAnchor, captureNewerPageAnchor,
- isOlderPageAnchorSettling: paginationDirection === "older",
- isNewerPageAnchorSettling: paginationDirection === "newer",
}
}
diff --git a/src/web/src/hooks/community/use-server-members.dom.test.ts b/src/web/src/hooks/community/use-server-members.dom.test.ts
index 50a02a382..d0be285fb 100644
--- a/src/web/src/hooks/community/use-server-members.dom.test.ts
+++ b/src/web/src/hooks/community/use-server-members.dom.test.ts
@@ -431,6 +431,43 @@ describe("native member subscriptions", () => {
})
describe("useServerMembers search lifecycle", () => {
+ it("ignores search effects and retained callbacks after the member view is disabled", async () => {
+ apiFetchMock.mockResolvedValue(makeEnvelope([], false, 0))
+ const harness = await mountServerMembers()
+ const retired = harness.resultRef.current!
+ function SearchConsumer({ serverId }: { serverId: string | null }) {
+ const result = useServerMembers(serverId)
+ const { searchMembers } = result
+ useEffect(() => { searchMembers("") }, [searchMembers])
+ useEffect(() => { harness.resultRef.current = result }, [result])
+ return null
+ }
+ try {
+ await act(async () => harness.renderer.rerender(createElement(
+ QueryClientProvider,
+ { client: harness.queryClient },
+ createElement(SearchConsumer, { serverId: "srv_1" }),
+ )))
+ const reads = apiFetchMock.mock.calls.length
+ await act(async () => harness.renderer.rerender(createElement(
+ QueryClientProvider,
+ { client: harness.queryClient },
+ createElement(SearchConsumer, { serverId: null }),
+ )))
+ await act(async () => {
+ retired.searchMembers("retired")
+ harness.resultRef.current!.searchMembers("disabled")
+ })
+ await flushEffects()
+ expect(harness.resultRef.current).toMatchObject({ members: [], searchQuery: "", searchStatus: "idle" })
+ expect(apiFetchMock).toHaveBeenCalledTimes(reads)
+ expect(toastApiErrorMock).not.toHaveBeenCalled()
+ } finally {
+ await act(async () => harness.renderer.unmount())
+ harness.queryClient.clear()
+ }
+ })
+
it("does not carry an earlier query failure into the next query debounce", async () => {
vi.useFakeTimers()
apiFetchMock.mockImplementation((url: unknown) => isSearchUrl(url) ? Promise.reject(new Error("controlled search error")) : Promise.resolve(makeEnvelope([], false, 0)))
@@ -466,7 +503,7 @@ describe("useServerMembers search lifecycle", () => {
expect(apiFetchMock).not.toHaveBeenCalled()
} finally { restore.resolve(); renderer.unmount(); await registry.cleanup(); queryClient.clear() }
})
- it("debounces the first page, serially appends continuation pages, and ignores duplicate search calls", async () => {
+ it("debounces once, leaves the first page ready, and appends only requested continuation pages", async () => {
vi.useFakeTimers()
const first = deferred<{ members: Member[]; hasMore: boolean; cursor?: string; limit: number }>()
const second = deferred<{ members: Member[]; hasMore: boolean; cursor?: string; limit: number }>()
@@ -501,8 +538,13 @@ describe("useServerMembers search lifecycle", () => {
await flushEffects()
expect(harness.resultRef.current).toMatchObject({
members: [m("a"), m("b")],
- searchStatus: "loading-more",
+ searchStatus: "ready",
+ hasMore: true,
+ loadingMore: false,
})
+ expect(apiFetchMock.mock.calls.filter(([url]) => isSearchUrl(url))).toHaveLength(1)
+ await act(async () => { harness.resultRef.current!.loadMore(); await vi.advanceTimersByTimeAsync(1) })
+ expect(harness.resultRef.current!.loadingMore).toBe(true)
expect(apiFetchMock.mock.calls.filter(([url]) => isSearchUrl(url))).toEqual([
["/api/community/servers/srv_1/members/search?q=ad", expect.objectContaining({ authenticationAccount: "viewer", signal: expect.any(AbortSignal) })],
["/api/community/servers/srv_1/members/search?cursor=cur_2&q=ad", expect.objectContaining({ authenticationAccount: "viewer", signal: expect.any(AbortSignal) })],
@@ -611,6 +653,8 @@ describe("useServerMembers search lifecycle", () => {
first.resolve({ members: [m("a")], hasMore: true, cursor: "next", limit: 50 })
await flushEffects()
await act(async () => { await vi.advanceTimersByTimeAsync(1) })
+ expect(searchCall).toBe(1)
+ await act(async () => harness.resultRef.current!.loadMore())
expect(searchCall).toBe(2)
continuation.reject(new Error("current failure"))
await flushEffects()
diff --git a/src/web/src/hooks/community/use-server-members.ts b/src/web/src/hooks/community/use-server-members.ts
index f82fd7f5b..3d8b70a4f 100644
--- a/src/web/src/hooks/community/use-server-members.ts
+++ b/src/web/src/hooks/community/use-server-members.ts
@@ -408,10 +408,6 @@ export function useServerMembers(serverId: string | null): UseServerMembers {
try { assertActive = source.capture(); assertActive() } catch { return }
toastApiError(search.error, "Search failed", assertActive)
}, [searchReady, search.error, search.isFetching, source])
- const fetchNextSearchPage = search.fetchNextPage
- useEffect(() => {
- if (searchReady && search.hasNextPage && !search.isFetching && !search.isError) void fetchNextSearchPage({ cancelRefetch: false })
- }, [searchReady, search.hasNextPage, search.isFetching, search.isError, search.data, fetchNextSearchPage])
const data = searching ? searchReady ? search.data : undefined : infinite.data
const identities = useMemo(() => {
const seen = new Set<string>()
@@ -446,11 +442,14 @@ export function useServerMembers(serverId: string | null): UseServerMembers {
loadingMore: active.isFetchingNextPage, hasMore: active.hasNextPage,
total: Math.max(0, (infinite.data?.pages.at(-1)?.total ?? 0) - pendingKicks.reduce<number>((sum, value) => sum + value, 0)), isSearching: searching,
searchQuery: searching ? searchIntent.query : "",
- searchStatus: !searching ? "idle" : readState.failed ? "error" : readState.loading ? "loading" : search.isFetchingNextPage || search.hasNextPage ? "loading-more" : members.length ? "ready" : "empty",
+ searchStatus: !searching ? "idle" : readState.failed ? "error" : readState.loading ? "loading" : search.isFetchingNextPage ? "loading-more" : members.length ? "ready" : "empty",
failed: readState.failed,
- loadMore: () => { assertView(); if (active.hasNextPage && !active.isFetchingNextPage) void active.fetchNextPage({ cancelRefetch: false }) },
+ loadMore: () => { assertView(); if ((!searching || searchReady) && active.hasNextPage && !active.isFetching) void active.fetchNextPage({ cancelRefetch: false }) },
reset: () => { assertView(); intent.setState((state) => ({ ...state, query: "", debounced: "" })) },
refresh: () => { assertView(); void queryClient.invalidateQueries({ queryKey: key }, { cancelRefetch: false }) },
- searchMembers: (query) => { assertView(); intent.setState((state) => { const trimmed = query.trim(); return state.query === trimmed ? state : { ...state, query: trimmed, debounced: trimmed ? state.debounced : "" } }) },
+ searchMembers: (query) => {
+ try { assertView() } catch { return }
+ intent.setState((state) => { const trimmed = query.trim(); return state.query === trimmed ? state : { ...state, query: trimmed, debounced: trimmed ? state.debounced : "" } })
+ },
}
}
diff --git a/src/web/src/hooks/community/use-virtual-cursor-pagination.dom.test.ts b/src/web/src/hooks/community/use-virtual-cursor-pagination.dom.test.ts
index 141876be9..95cdb1d33 100644
--- a/src/web/src/hooks/community/use-virtual-cursor-pagination.dom.test.ts
+++ b/src/web/src/hooks/community/use-virtual-cursor-pagination.dom.test.ts
@@ -59,12 +59,12 @@ describe.each(["start", "end"] as const)("native virtual cursor pagination (%s)"
expect(f.onLoad).toHaveBeenCalledTimes(2)
})
- it("waits for anchor settlement and then rechecks the current range", () => {
- const f = fixture({ isSettling: true })
+ it("retains semantic eligibility and rechecks the native range when the target becomes ready", () => {
+ const f = fixture({ enabled: false })
f.setRange(...boundary)
f.rerender()
expect(f.onLoad).not.toHaveBeenCalled()
- f.rerender({ isSettling: false })
+ f.rerender({ enabled: true })
expect(f.onLoad).toHaveBeenCalledOnce()
})
diff --git a/src/web/src/hooks/community/use-virtual-cursor-pagination.ts b/src/web/src/hooks/community/use-virtual-cursor-pagination.ts
index 71b2e4674..7d41d6569 100644
--- a/src/web/src/hooks/community/use-virtual-cursor-pagination.ts
+++ b/src/web/src/hooks/community/use-virtual-cursor-pagination.ts
@@ -4,7 +4,7 @@ import { useEffect } from "react"
import type { VirtualItem } from "@tanstack/react-virtual"
export function useVirtualCursorPagination({
- virtualizer, count, enabled = true, hasMore, hasMoreAtStart, isFetching, isSettling, isError,
+ virtualizer, count, enabled = true, hasMore, hasMoreAtStart, isFetching, isError,
onBeforeLoad, onLoad, edge,
}: {
virtualizer: { getVirtualItems: () => VirtualItem[] }
@@ -13,7 +13,6 @@ export function useVirtualCursorPagination({
hasMore?: boolean
hasMoreAtStart?: boolean
isFetching?: boolean
- isSettling?: boolean
isError?: boolean
onBeforeLoad?: () => void
onLoad?: () => void
@@ -22,10 +21,10 @@ export function useVirtualCursorPagination({
const virtualItems = virtualizer.getVirtualItems()
useEffect(() => {
const boundary = edge === "start" ? virtualItems[0] : virtualItems.at(-1)
- if (!enabled || !boundary || count === 0 || !hasMore || isFetching || isSettling || isError || !onLoad) return
+ if (!enabled || !boundary || count === 0 || !hasMore || isFetching || isError || !onLoad) return
if (edge === "start" ? boundary.index > 0 : boundary.index < count - 1) return
if (edge === "end" && hasMoreAtStart && virtualItems[0]?.index === 0) return
onBeforeLoad?.()
onLoad()
- }, [count, edge, enabled, hasMore, hasMoreAtStart, isFetching, isSettling, isError, onBeforeLoad, onLoad, virtualItems])
+ }, [count, edge, enabled, hasMore, hasMoreAtStart, isFetching, isError, onBeforeLoad, onLoad, virtualItems])
}
diff --git a/src/web/src/lib/community/community-route.test.ts b/src/web/src/lib/community/community-route.test.ts
index e7b0de014..d5f94a8ec 100644
--- a/src/web/src/lib/community/community-route.test.ts
+++ b/src/web/src/lib/community/community-route.test.ts
@@ -213,11 +213,11 @@ describe("community route", () => {
})
})
- it("retains the DM target skeleton inside the same me scope", () => {
+ it("selects the DM route host before publication inside the same me scope", () => {
expect(resolveCommunityCheckpointPlan({
committedFrame: { ...normalizeCommunityHref("/c/me/dm1"), revision: 2 },
targetHref: "/c/me/dm2", pending: true, targetReady: true,
- }).main).toEqual({ kind: "target-skeleton", href: "/c/me/dm2" })
+ }).main).toEqual({ kind: "dm-route", href: "/c/me/dm2", dmId: "dm2" })
})
it("keeps committed A as the source after the router publishes B", () => {
diff --git a/src/web/src/lib/community/community-route.ts b/src/web/src/lib/community/community-route.ts
index ffd82bc47..bd089d75d 100644
--- a/src/web/src/lib/community/community-route.ts
+++ b/src/web/src/lib/community/community-route.ts
@@ -71,7 +71,7 @@ export type CommunityCheckpointPlan = {
| { kind: "keep" }
| { kind: "server-skeleton"; serverId: string }
| { kind: "me-skeleton" }
- main: { kind: "keep" } | { kind: "server-route"; href: string } | {
+ main: { kind: "keep" } | { kind: "server-route"; href: string } | { kind: "dm-route"; href: string; dmId: string } | {
kind: "target-skeleton"
href: string
conversationSubtype?: "text" | "forum" | "thread"
@@ -312,8 +312,19 @@ export function resolveCommunityCheckpointPlan({
rail: { kind: "keep" }, sidebar: { kind: "keep" },
main: { kind: "target-skeleton", href: target.href } }
}
+ if (targetModule.main.kind === "dm") {
+ const plan = committedPlan(committedFrame, target.href)
+ return {
+ ...plan,
+ mode: communityScopeEqual(committedFrame.scope, target.scope) ? "same-scope-leaf" : targetReady ? "warm-scope" : "cold-scope",
+ surface: target.surface,
+ rail: target.scope.kind === "me" && committedFrame.scope.kind !== "me" ? { kind: "target", view: "dm" } : plan.rail,
+ sidebar: committedFrame.scope.kind !== "me" ? { kind: "me-skeleton" } : plan.sidebar,
+ main: { kind: "dm-route", href: target.href, dmId: targetModule.main.dmId },
+ }
+ }
const targetMainKind = targetModule.main.kind
- const isConversationTarget = targetMainKind === "server-conversation" || targetMainKind === "dm"
+ const isConversationTarget = targetMainKind === "server-conversation"
if (target.scope.kind === "unknown" || target.leafKey === committedFrame.leafKey) {
return committedPlan(committedFrame, target.href)
}
@@ -376,13 +387,14 @@ function committedPlan(
frame: CommunityCommittedFrame,
targetHref = frame.href,
): CommunityCheckpointPlan {
+ const main = resolveCommunityModulePlan(frame.href).main
return {
mode: "committed",
surface: frame.surface,
targetHref,
rail: { kind: "keep" },
sidebar: { kind: "keep" },
- main: { kind: "keep" },
+ main: main.kind === "dm" ? { kind: "dm-route", href: targetHref, dmId: main.dmId } : { kind: "keep" },
}
}
diff --git a/src/web/src/lib/community/conversation-entry.ts b/src/web/src/lib/community/conversation-entry.ts
index a175518cf..ad230c2bb 100644
--- a/src/web/src/lib/community/conversation-entry.ts
+++ b/src/web/src/lib/community/conversation-entry.ts
@@ -1,3 +1,4 @@
+import { reconcileConversationLanding } from "@/hooks/community/community-ws/reconnect-messages"
import { channelHref } from "./community-route"
import { currentPageObservation, navigationForHref } from "@/lib/observability/context"
import { hashKey, notifyManager, queryOptions, type QueryClient, type QueryKey } from "@tanstack/react-query"
@@ -182,13 +183,25 @@ export function conversationEntryOptions(client: QueryClient, target: Conversati
throw error
}
assert()
- return publishConversationEntry(client, target, entry, { token, signal })
+ const initial: InitialMessageWindow = entry.selection.anchorMessageId
+ ? { mode: "anchor", anchor: entry.selection.anchorMessageId } : { mode: "newest" }
+ const windowKey = communityKeys.channelMessagesWindow(target.channelId, initial, target.tag)
+ const hadWindow = !!client.getQueryData<MessageWindowData>(windowKey)?.pages.length
+ const resource = publishConversationEntry(client, target, entry, { token, signal })
+ if (hadWindow && !entry.forumFeed) {
+ await reconcileConversationLanding(client, {
+ kind: target.serverId === null ? "dm" : "channel", scopeId: target.channelId,
+ serverId: target.serverId ?? undefined,
+ }, resource.windowKey, { ...entry.page, olderCursor: entry.page.olderCursor ?? undefined, newerCursor: entry.page.newerCursor ?? undefined, messages: entry.messages }, initial)
+ assert()
+ }
+ return resource
},
staleTime: (query) => {
const resource = query.state.data
if (!resource) return 0
const pointer = knownPointer && resource.readStateRevision <= (knownPointer.observedRevision ?? -1) ? knownPointer : resource.readStateAtEntry
- return findConversationEntryWindow(client, target, resource, pointer) ? Infinity : 0
+ return findConversationEntryWindow(client, target, resource, pointer) ? 5_000 : 0
},
gcTime: typeof window === "undefined" ? Infinity : 5 * 60 * 1000,
retry: target.serverId === null ? false : retryConversationRead,
diff --git a/src/web/src/lib/community/message-window.ts b/src/web/src/lib/community/message-window.ts
index ba40e997b..c3faa3e99 100644
--- a/src/web/src/lib/community/message-window.ts
+++ b/src/web/src/lib/community/message-window.ts
@@ -127,6 +127,7 @@ export function messageWindowOptions(
getPreviousPageParam: (first) => first.hasMoreNewer && first.newerCursor ? { mode: "newer", cursor: first.newerCursor } : undefined,
staleTime: 5_000,
refetchOnReconnect: false,
+ refetchOnMount: false,
retry: conversationReadRetryPolicy(client.defaultQueryOptions({ queryKey }).retry),
networkMode: "always",
})
diff --git a/src/web/src/lib/use-user-ws.test.ts b/src/web/src/lib/use-user-ws.test.ts
index 36b6a58f7..a3176cd2d 100644
--- a/src/web/src/lib/use-user-ws.test.ts
+++ b/src/web/src/lib/use-user-ws.test.ts
@@ -2156,7 +2156,7 @@ describe("useUserWs", () => {
expect(ws.closed).toBe(false)
})
- it("notifies foreground data work before validation and again for changed targets during a pending probe", async () => {
+ it("repairs on actual recovery while ordinary focus only shares connection validation", async () => {
setupTokenFetch()
let finish!: () => void
const dataWork = new Promise<void>((resolve) => { finish = resolve })
@@ -2174,7 +2174,7 @@ describe("useUserWs", () => {
dispatchWindowFocus()
mockDocument.dispatch("resume")
dispatchPageShow(true)
- expect(onForeground).toHaveBeenCalledTimes(4)
+ expect(onForeground).toHaveBeenCalledTimes(3)
expect(connectionPings(ws)).toHaveLength(1)
const [{ nonce }] = connectionPings(ws)
@@ -2186,22 +2186,28 @@ describe("useUserWs", () => {
await flushPromises()
})
- it("notifies foreground data work while token or authentication is still pending", async () => {
+ it("skips ordinary focus data work and retains resume work while token or authentication is pending", async () => {
const token = deferred<Response>()
mockFetch.mockReturnValueOnce(token.promise)
const onForeground = vi.fn()
await mountHook(vi.fn(), { onForeground, requestDaemonStatusOnAuth: false })
dispatchWindowFocus()
+ expect(onForeground).not.toHaveBeenCalled()
+ mockDocument.dispatch("resume")
expect(onForeground).toHaveBeenCalledOnce()
expect(MockWebSocket.instances).toHaveLength(0)
token.resolve({ ok: true, json: async () => ({ userId: "user-1", token: "test-token" }) } as Response)
await flushPromises()
const ws = MockWebSocket.instances[0]!
dispatchWindowFocus()
+ expect(onForeground).toHaveBeenCalledOnce()
+ mockDocument.dispatch("resume")
expect(onForeground).toHaveBeenCalledTimes(2)
expect(ws.readyState).toBe(MockWebSocket.CONNECTING)
ws.simulateOpen()
dispatchWindowFocus()
+ expect(onForeground).toHaveBeenCalledTimes(2)
+ mockDocument.dispatch("resume")
expect(onForeground).toHaveBeenCalledTimes(3)
expect(connectionPings(ws)).toHaveLength(0)
})
diff --git a/src/web/src/lib/use-user-ws.ts b/src/web/src/lib/use-user-ws.ts
index 241280eb3..ecf00f56e 100644
--- a/src/web/src/lib/use-user-ws.ts
+++ b/src/web/src/lib/use-user-ws.ts
@@ -1077,7 +1077,7 @@ export function useUserWs(
const recoveryNeeded = forceValidation || connectionValidationNeededRef.current
if (!recoveryNeeded) return
- runLifecycleCallback("foreground", onForegroundRef.current)
+ if (trigger !== "focus" || connectionValidationNeededRef.current) runLifecycleCallback("foreground", onForegroundRef.current)
if (isOffline() || isPageHidden()) return
if (pendingTokenRef.current) return
diff --git a/src/web/src/test/e2e-ui/31-mention-candidate-pagination.spec.ts b/src/web/src/test/e2e-ui/31-mention-candidate-pagination.spec.ts
index 23aba6b3f..7607a9c88 100644
--- a/src/web/src/test/e2e-ui/31-mention-candidate-pagination.spec.ts
+++ b/src/web/src/test/e2e-ui/31-mention-candidate-pagination.spec.ts
@@ -68,7 +68,9 @@ test("@ candidates page to completion and shared popups stay anchored through vi
const browse = Array.from({ length: 12 }, (_, index) => candidate("Browse", index + 1))
const matches = Array.from({ length: 205 }, (_, index) => candidate("CapMatch", index + 1))
+ const browseCursors: Array<string | null> = []
const searchReads = new Map<string, number>()
+ const searchCursors = new Map<string, Array<string | null>>()
let releaseSearchTail!: () => void
const searchTailReleased = new Promise<void>((resolve) => {
releaseSearchTail = resolve
@@ -86,6 +88,7 @@ test("@ candidates page to completion and shared popups stay anchored through vi
const query = url.searchParams.get("q") ?? ""
searchReads.set(query, (searchReads.get(query) ?? 0) + 1)
const cursor = url.searchParams.get("cursor")
+ searchCursors.set(query, [...(searchCursors.get(query) ?? []), cursor])
if (query === "Fail") {
await route.fulfill({ status: 500, json: { error: "forced failure" } })
return
@@ -116,6 +119,7 @@ test("@ candidates page to completion and shared popups stay anchored through vi
}
const cursor = url.searchParams.get("cursor")
+ browseCursors.push(cursor)
await route.fulfill({
json: cursor
? { members: browse.slice(8), limit: 8, total: 12, hasMore: false }
@@ -139,17 +143,41 @@ test("@ candidates page to completion and shared popups stay anchored through vi
).join(" ")
await editable.fill(wrappedPrefix)
await editable.pressSequentially(" @")
+ const mentionPopup = page.getByTestId(tid.mentionPopup)
+ const mentionOptions = mentionPopup.getByRole("option")
+ await expect(page.getByTestId(tid.mentionOption(browse[7]!.id))).toHaveCount(1)
+ await expect(page.getByTestId(tid.mentionStatus)).toHaveCount(0)
+ await page.evaluate(() => new Promise<void>((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()))
+ }))
+ expect(browseCursors).toEqual([null])
+ await expect(page.getByTestId(tid.mentionOption(browse[11]!.id))).toHaveCount(0)
+ const popupBounds = await mentionPopup.boundingBox()
+ expect(popupBounds).not.toBeNull()
+ await page.mouse.move(popupBounds!.x + popupBounds!.width / 2, popupBounds!.y + popupBounds!.height / 2)
+ await page.mouse.wheel(0, 800)
await expect(page.getByTestId(tid.mentionOption(browse[11]!.id))).toHaveCount(1)
+ expect(browseCursors).toEqual([null, "browse-page-2"])
await editable.pressSequentially("CapMatch")
- await searchTailRequested
await expect(page.getByTestId(tid.mentionOption(matches[0]!.id))).toBeVisible()
- const mentionOptions = page.getByTestId(tid.mentionPopup).getByRole("option")
await expect(mentionOptions).toHaveCount(200)
+ await expect(page.getByTestId(tid.mentionStatus)).toHaveCount(0)
+ await page.evaluate(() => new Promise<void>((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()))
+ }))
+ expect(searchCursors.get("CapMatch")).toEqual([null])
+ await expect(page.getByTestId(tid.mentionOption(matches[0]!.id))).toHaveAttribute("aria-selected", "true")
+ await editable.press("ArrowUp")
+ await expect(page.getByTestId(tid.mentionOption(matches[199]!.id))).toHaveAttribute("aria-selected", "true")
+ await expect(page.getByTestId(tid.mentionOption(matches[199]!.id))).toBeVisible()
+ await searchTailRequested
+ expect(searchCursors.get("CapMatch")).toEqual([null, "search-page-2"])
await expect(page.getByTestId(tid.mentionStatus)).toHaveAttribute("data-state", "loading-more")
releaseSearchTail()
await expect(page.getByTestId(tid.mentionOption(matches[204]!.id))).toHaveCount(1)
await expect(mentionOptions).toHaveCount(205)
+ await expect(page.getByTestId(tid.mentionStatus)).toHaveCount(0)
const readBounds = (popupTestId: string) => page.getByTestId(popupTestId).evaluate((element) => {
const popup = element.getBoundingClientRect()
@@ -252,4 +280,14 @@ test("@ candidates page to completion and shared popups stay anchored through vi
await expect(page.getByTestId(tid.mentionPopup).getByRole("option")).toHaveCount(205)
await expect(page.getByTestId(tid.mentionStatus)).toHaveCount(0)
expect(searchReads.get("CapMatch")).toBe(2)
+ await editable.press("ArrowUp")
+ const lastOption = page.getByTestId(tid.mentionOption(matches[204]!.id))
+ await expect(lastOption).toHaveAttribute("aria-selected", "true")
+ await expect(lastOption).toBeVisible()
+ await expect(lastOption).toHaveAttribute("title", `${matches[204]!.name}#${matches[204]!.discriminator}`)
+ await editable.press("Enter")
+ const insertedMention = editable.locator('[data-type="mention"]')
+ await expect(insertedMention).toHaveCount(1)
+ await expect(insertedMention).toHaveAttribute("data-id", matches[204]!.userId)
+ await expect(insertedMention).toHaveAttribute("data-label", `${matches[204]!.name}#${matches[204]!.discriminator}`)
})
diff --git a/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts b/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts
index cae61c434..09166ba49 100644
--- a/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts
+++ b/src/web/src/test/e2e-ui/40-server-rail-unread.spec.ts
@@ -334,11 +334,18 @@ test("server unread owns exact rail geometry, folder aggregation, read clear, an
const clearResponse = page.waitForResponse((response) => (
response.request().method() === "PUT"
&& new URL(response.url()).pathname === `/api/community/channels/${backgroundChannel}/read`
+ && (response.request().postDataJSON() as { lastReadMessageId?: string } | null)?.lastReadMessageId === lastMessageId
))
void clearResponse.catch(() => {})
await page.getByTestId(tid.channelRow(backgroundChannel)).click()
await expect(page.getByTestId(tid.message(lastMessageId))).toBeVisible()
- expect((await clearResponse).status()).toBe(200)
+ await expect(page.getByTestId(tid.newDivider)).toBeInViewport()
+ await expect(page.getByTestId(tid.message(lastMessageId))).not.toBeInViewport({ ratio: 0.2 })
+ await page.getByTestId(tid.scrollToPresent).click()
+ await expect(page.getByTestId(tid.message(lastMessageId))).toBeInViewport({ ratio: 0.2 })
+ const cleared = await clearResponse
+ expect(cleared.status()).toBe(200)
+ expect(await cleared.json()).toMatchObject({ targetSeq: 13 })
await expect(badge).toHaveCount(0)
await expectPrimaryCount("read-clear", 0)
await capture("read-clear", 0)