Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(community): make jump to present deterministic

Gener1565d60b839d
diff --git a/src/web/src/app/c/me/[dmId]/page.tsx b/src/web/src/app/c/me/[dmId]/page.tsx
index c84a07d4b..214c33a35 100644
--- a/src/web/src/app/c/me/[dmId]/page.tsx
+++ b/src/web/src/app/c/me/[dmId]/page.tsx
@@ -101,6 +101,7 @@ function DmView() {
fetchOlder: fetchOlderMessages,
fetchNewer: fetchNewerMessages,
jumpToPresent,
+ presentVersion,
latestSeq,
} = useDmMessages(dmId, {
lastReadMessageId: readSnapshotFetching
@@ -398,6 +399,7 @@ function DmView() {
isFetchingNewer={isFetchingNewerMessages}
onLoadNewer={fetchNewerMessages}
onJumpToPresent={jumpToPresent}
+ presentVersion={presentVersion}
unreadCount={unreadCount}
hero={
<>
diff --git a/src/web/src/components/community/message-list.tsx b/src/web/src/components/community/message-list.tsx
index a9e96f429..dd7fb57a7 100644
--- a/src/web/src/components/community/message-list.tsx
+++ b/src/web/src/components/community/message-list.tsx
@@ -27,7 +27,7 @@ export function MessageList({
resolveUserName, scrollToMessageId, hero, variant = "channel", onScrollRoot, viewerUserId, initialScrollReady = true,
onScrollTargetConsumed,
hasMore, isFetchingOlder, onLoadOlder,
- hasMoreNewer, isFetchingNewer, onLoadNewer, onJumpToPresent, unreadCount,
+ hasMoreNewer, isFetchingNewer, onLoadNewer, onJumpToPresent, presentVersion, unreadCount,
}: {
channel: string
messages: Msg[]
@@ -96,6 +96,7 @@ export function MessageList({
// window, clicking jumps back to the present. Falls back to the DOM
// `belowCount` scroll-to-bottom when we're already tail-attached.
onJumpToPresent?: () => void
+ presentVersion?: number
// Server-derived unread count (`latestSeq - viewerLastReadSeq`). Drives
// the `↓ N` badge when `hasMoreNewer` is true — DOM math can't see rows
// that haven't been fetched yet.
@@ -219,6 +220,7 @@ export function MessageList({
newDividerBefore,
initialScrollReady: scrollAnchorReady,
hasMoreNewer,
+ presentVersion,
viewerUserId,
heroHeight,
heroMeasured,
diff --git a/src/web/src/components/community/text-channel-surface.tsx b/src/web/src/components/community/text-channel-surface.tsx
index ed1f504e3..1275d5357 100644
--- a/src/web/src/components/community/text-channel-surface.tsx
+++ b/src/web/src/components/community/text-channel-surface.tsx
@@ -129,6 +129,7 @@ export function TextChannelSurface({
isFetchingNewer={feed.isFetchingNewer}
onLoadNewer={feed.fetchNewer}
onJumpToPresent={feed.jumpToPresent}
+ presentVersion={feed.presentVersion}
unreadCount={feed.unreadCount}
/>
<div data-onboarding-target="channel-composer" className="shrink-0">
diff --git a/src/web/src/components/community/thread-channel-surface.tsx b/src/web/src/components/community/thread-channel-surface.tsx
index c709ce968..7191a4eff 100644
--- a/src/web/src/components/community/thread-channel-surface.tsx
+++ b/src/web/src/components/community/thread-channel-surface.tsx
@@ -230,6 +230,7 @@ export function ThreadChannelSurface({
isFetchingNewer={controller.feed.isFetchingNewer}
onLoadNewer={controller.feed.fetchNewer}
onJumpToPresent={controller.feed.jumpToPresent}
+ presentVersion={controller.feed.presentVersion}
unreadCount={controller.feed.unreadCount}
/>
<div data-onboarding-target="channel-composer" className="shrink-0">
diff --git a/src/web/src/hooks/community/use-messages.jump-to-present.test.ts b/src/web/src/hooks/community/use-messages.jump-to-present.test.ts
new file mode 100644
index 000000000..411c0e321
--- /dev/null
+++ b/src/web/src/hooks/community/use-messages.jump-to-present.test.ts
@@ -0,0 +1,401 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import React from "react"
+import TestRenderer, { act } from "react-test-renderer"
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
+import { communityKeys } from "@/lib/query-keys"
+import { useDmMessages, useMessages, type MessagesPage } from "./use-messages"
+import { useMessageStreamStore } from "@/stores/community/message-stream"
+
+const apiFetchMock = vi.fn()
+vi.mock("@/lib/api/client", () => ({
+ apiFetch: (...args: unknown[]) => apiFetchMock(...args),
+}))
+
+type Snapshot = {
+ hasMoreNewer: boolean
+ ids: string[]
+ isFetchingNewer: boolean
+ jumpToPresent: () => void
+}
+
+function ChannelCapture({
+ anchorMessageId,
+ channelId,
+ lastReadMessageId,
+ onRender,
+}: {
+ anchorMessageId?: string | null
+ channelId: string
+ lastReadMessageId: string | null
+ onRender: (snapshot: Snapshot) => void
+}) {
+ const result = useMessages(channelId, {
+ anchorMessageId,
+ lastReadMessageId,
+ serverId: "server_1",
+ })
+ onRender({
+ hasMoreNewer: result.hasMoreNewer,
+ ids: result.messages.map((message) => message.id),
+ isFetchingNewer: result.isFetchingNewer,
+ jumpToPresent: result.jumpToPresent,
+ })
+ return null
+}
+
+function DmCapture({
+ dmId,
+ lastReadMessageId,
+ onRender,
+}: {
+ dmId: string
+ lastReadMessageId: string | null
+ onRender: (snapshot: Snapshot) => void
+}) {
+ const result = useDmMessages(dmId, { lastReadMessageId })
+ onRender({
+ hasMoreNewer: result.hasMoreNewer,
+ ids: result.messages.map((message) => message.id),
+ isFetchingNewer: result.isFetchingNewer,
+ jumpToPresent: result.jumpToPresent,
+ })
+ return null
+}
+
+function createClient(): QueryClient {
+ return new QueryClient({
+ defaultOptions: {
+ queries: {
+ refetchOnMount: false,
+ retry: false,
+ },
+ },
+ })
+}
+
+function seedAnchor(
+ queryClient: QueryClient,
+ queryKey: readonly unknown[],
+ anchorId: string,
+): void {
+ queryClient.setQueryData(queryKey, {
+ pages: [{
+ messages: [{ id: anchorId, seq: 1, createdAt: "2026-08-09T00:00:00.000Z" }],
+ hasMoreOlder: false,
+ hasMoreNewer: true,
+ newerCursor: anchorId,
+ latestSeq: 36,
+ }],
+ pageParams: [{ mode: "anchor", anchor: anchorId }],
+ })
+}
+
+function newestPage(id: string): MessagesPage {
+ return {
+ messages: [{ id, seq: 36, createdAt: "2026-08-09T00:01:00.000Z" }],
+ hasMore: false,
+ latestSeq: 36,
+ }
+}
+
+function render(
+ queryClient: QueryClient,
+ element: React.ReactElement,
+): TestRenderer.ReactTestRenderer {
+ let renderer!: TestRenderer.ReactTestRenderer
+ act(() => {
+ renderer = TestRenderer.create(
+ React.createElement(QueryClientProvider, { client: queryClient }, element),
+ )
+ })
+ return renderer
+}
+
+function update(
+ renderer: TestRenderer.ReactTestRenderer,
+ queryClient: QueryClient,
+ element: React.ReactElement,
+): void {
+ act(() => {
+ renderer.update(
+ React.createElement(QueryClientProvider, { client: queryClient }, element),
+ )
+ })
+}
+
+async function waitFor(predicate: () => boolean, tries = 80): Promise<void> {
+ for (let i = 0; i < tries; i++) {
+ if (predicate()) return
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 5))
+ })
+ }
+ expect(predicate()).toBe(true)
+}
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>((done) => { resolve = done })
+ return { promise, resolve }
+}
+
+beforeEach(() => {
+ apiFetchMock.mockReset()
+ useMessageStreamStore.getState().resetAll()
+})
+
+describe("useMessages jumpToPresent", () => {
+ it("resets once, fetches newest once, and keeps the old last-read anchor suppressed", async () => {
+ const queryClient = createClient()
+ const queryKey = communityKeys.channelMessages("channel_1")
+ seedAnchor(queryClient, queryKey, "anchor_1")
+ apiFetchMock.mockResolvedValue(newestPage("latest_1"))
+ const resetSpy = vi.spyOn(queryClient, "resetQueries")
+ let latest!: Snapshot
+ const onRender = (snapshot: Snapshot) => { latest = snapshot }
+ const renderer = render(
+ queryClient,
+ React.createElement(ChannelCapture, {
+ channelId: "channel_1",
+ lastReadMessageId: "anchor_1",
+ onRender,
+ }),
+ )
+
+ act(() => latest.jumpToPresent())
+ await waitFor(() => latest.ids[0] === "latest_1" && !latest.isFetchingNewer)
+
+ expect(resetSpy).toHaveBeenCalledTimes(1)
+ expect(resetSpy).toHaveBeenCalledWith({ queryKey, exact: true })
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/channel_1/messages")
+ expect(latest.hasMoreNewer).toBe(false)
+
+ act(() => latest.jumpToPresent())
+ await act(async () => { await Promise.resolve() })
+ expect(resetSpy).toHaveBeenCalledTimes(1)
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+
+ update(
+ renderer,
+ queryClient,
+ React.createElement(ChannelCapture, {
+ channelId: "channel_1",
+ lastReadMessageId: "stale_anchor_update",
+ onRender,
+ }),
+ )
+ await waitFor(() => latest.ids[0] === "latest_1")
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+ renderer.unmount()
+ })
+
+ it("treats repeated clicks during one pending attempt as idempotent", async () => {
+ const queryClient = createClient()
+ const queryKey = communityKeys.channelMessages("channel_pending")
+ seedAnchor(queryClient, queryKey, "anchor_pending")
+ const response = deferred<MessagesPage>()
+ apiFetchMock.mockReturnValue(response.promise)
+ const resetSpy = vi.spyOn(queryClient, "resetQueries")
+ let latest!: Snapshot
+ const renderer = render(
+ queryClient,
+ React.createElement(ChannelCapture, {
+ channelId: "channel_pending",
+ lastReadMessageId: "anchor_pending",
+ onRender: (snapshot) => { latest = snapshot },
+ }),
+ )
+
+ act(() => latest.jumpToPresent())
+ await waitFor(() => latest.isFetchingNewer && apiFetchMock.mock.calls.length === 1)
+ act(() => latest.jumpToPresent())
+ await act(async () => { await Promise.resolve() })
+ expect(resetSpy).toHaveBeenCalledTimes(1)
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+
+ response.resolve(newestPage("latest_pending"))
+ await waitFor(() => latest.ids[0] === "latest_pending" && !latest.isFetchingNewer)
+ renderer.unmount()
+ })
+
+ it("clears the override across A to B to A navigation", async () => {
+ const queryClient = createClient()
+ seedAnchor(queryClient, communityKeys.channelMessages("channel_a"), "anchor_a")
+ seedAnchor(queryClient, communityKeys.channelMessages("channel_b"), "anchor_b")
+ apiFetchMock.mockImplementation((url: string) => {
+ if (url === "/api/community/channels/channel_a/messages") {
+ return Promise.resolve(newestPage("latest_a"))
+ }
+ if (url === "/api/community/channels/channel_a/messages?anchor=anchor_a") {
+ return Promise.resolve({
+ messages: [{ id: "anchor_a", seq: 1, createdAt: "2026-08-09T00:00:00.000Z" }],
+ hasMoreOlder: false,
+ hasMoreNewer: true,
+ newerCursor: "anchor_a",
+ latestSeq: 36,
+ } satisfies MessagesPage)
+ }
+ throw new Error(`unexpected URL: ${url}`)
+ })
+ let latest!: Snapshot
+ const onRender = (snapshot: Snapshot) => { latest = snapshot }
+ const renderer = render(
+ queryClient,
+ React.createElement(ChannelCapture, {
+ channelId: "channel_a",
+ lastReadMessageId: "anchor_a",
+ onRender,
+ }),
+ )
+
+ act(() => latest.jumpToPresent())
+ await waitFor(() => latest.ids[0] === "latest_a")
+ update(
+ renderer,
+ queryClient,
+ React.createElement(ChannelCapture, {
+ channelId: "channel_b",
+ lastReadMessageId: "anchor_b",
+ onRender,
+ }),
+ )
+ await waitFor(() => latest.ids[0] === "anchor_b")
+ update(
+ renderer,
+ queryClient,
+ React.createElement(ChannelCapture, {
+ channelId: "channel_a",
+ lastReadMessageId: "anchor_a",
+ onRender,
+ }),
+ )
+ await waitFor(() => apiFetchMock.mock.calls.some(
+ ([url]) => url === "/api/community/channels/channel_a/messages?anchor=anchor_a",
+ ))
+ await waitFor(() => latest.ids[0] === "anchor_a")
+ expect(apiFetchMock.mock.calls.filter(
+ ([url]) => url === "/api/community/channels/channel_a/messages",
+ )).toHaveLength(1)
+ renderer.unmount()
+ })
+
+ it("re-arms when the explicit jump target changes", async () => {
+ const queryClient = createClient()
+ const queryKey = communityKeys.channelMessages("channel_target")
+ seedAnchor(queryClient, queryKey, "target_a")
+ apiFetchMock.mockImplementation((url: string) => {
+ if (url === "/api/community/channels/channel_target/messages") {
+ return Promise.resolve(newestPage("latest_target"))
+ }
+ if (url === "/api/community/channels/channel_target/messages?anchor=target_b") {
+ return Promise.resolve({
+ messages: [{ id: "target_b", seq: 20, createdAt: "2026-08-09T00:00:30.000Z" }],
+ hasMoreOlder: true,
+ hasMoreNewer: true,
+ newerCursor: "target_b",
+ latestSeq: 36,
+ } satisfies MessagesPage)
+ }
+ throw new Error(`unexpected URL: ${url}`)
+ })
+ let latest!: Snapshot
+ const onRender = (snapshot: Snapshot) => { latest = snapshot }
+ const renderer = render(
+ queryClient,
+ React.createElement(ChannelCapture, {
+ anchorMessageId: "target_a",
+ channelId: "channel_target",
+ lastReadMessageId: "read_anchor",
+ onRender,
+ }),
+ )
+
+ act(() => latest.jumpToPresent())
+ await waitFor(() => latest.ids[0] === "latest_target")
+ update(
+ renderer,
+ queryClient,
+ React.createElement(ChannelCapture, {
+ anchorMessageId: "target_b",
+ channelId: "channel_target",
+ lastReadMessageId: "read_anchor",
+ onRender,
+ }),
+ )
+ await waitFor(() => latest.ids[0] === "target_b")
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/channels/channel_target/messages?anchor=target_b",
+ )
+ renderer.unmount()
+ })
+
+ it("restores the anchored window after failure and lets the user retry", async () => {
+ const queryClient = createClient()
+ const queryKey = communityKeys.channelMessages("channel_retry")
+ seedAnchor(queryClient, queryKey, "anchor_retry")
+ apiFetchMock
+ .mockRejectedValueOnce(new Error("newest failed"))
+ .mockResolvedValueOnce(newestPage("latest_retry"))
+ const resetSpy = vi.spyOn(queryClient, "resetQueries")
+ let latest!: Snapshot
+ const renderer = render(
+ queryClient,
+ React.createElement(ChannelCapture, {
+ channelId: "channel_retry",
+ lastReadMessageId: "anchor_retry",
+ onRender: (snapshot) => { latest = snapshot },
+ }),
+ )
+
+ act(() => latest.jumpToPresent())
+ await waitFor(() => latest.ids[0] === "anchor_retry" && !latest.isFetchingNewer)
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+
+ act(() => latest.jumpToPresent())
+ await waitFor(() => latest.ids[0] === "latest_retry" && !latest.isFetchingNewer)
+ expect(resetSpy).toHaveBeenCalledTimes(2)
+ expect(apiFetchMock).toHaveBeenCalledTimes(2)
+ renderer.unmount()
+ })
+})
+
+describe("useDmMessages jumpToPresent", () => {
+ it("uses the same one-reset present override for DMs", async () => {
+ const queryClient = createClient()
+ const queryKey = communityKeys.dmMessages("dm_1")
+ seedAnchor(queryClient, queryKey, "dm_anchor")
+ apiFetchMock.mockResolvedValue(newestPage("dm_latest"))
+ const resetSpy = vi.spyOn(queryClient, "resetQueries")
+ let latest!: Snapshot
+ const onRender = (snapshot: Snapshot) => { latest = snapshot }
+ const renderer = render(
+ queryClient,
+ React.createElement(DmCapture, {
+ dmId: "dm_1",
+ lastReadMessageId: "dm_anchor",
+ onRender,
+ }),
+ )
+
+ act(() => latest.jumpToPresent())
+ await waitFor(() => latest.ids[0] === "dm_latest" && !latest.isFetchingNewer)
+ expect(resetSpy).toHaveBeenCalledTimes(1)
+ expect(resetSpy).toHaveBeenCalledWith({ queryKey, exact: true })
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+ expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/dm_1/messages")
+
+ update(
+ renderer,
+ queryClient,
+ React.createElement(DmCapture, {
+ dmId: "dm_1",
+ lastReadMessageId: "dm_old_update",
+ onRender,
+ }),
+ )
+ await waitFor(() => latest.ids[0] === "dm_latest")
+ expect(apiFetchMock).toHaveBeenCalledTimes(1)
+ renderer.unmount()
+ })
+})
diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.ts
index f86774192..e5c4ab321 100644
--- a/src/web/src/hooks/community/use-messages.ts
+++ b/src/web/src/hooks/community/use-messages.ts
@@ -169,6 +169,7 @@ type MessagesReturn = Omit<UseInfiniteQueryResult<PageCache, Error>, "isLoading"
fetchOlder: () => void
fetchNewer: () => void
jumpToPresent: () => void
+ presentVersion: number
// Legacy alias — mirrors `hasMoreOlder`. Kept so consumers not yet migrated
// off the older-only API still compile until every call site is updated.
hasMore: boolean
@@ -203,6 +204,12 @@ type ChannelMessagesOpts = MessagesOpts & {
serverId: string
}
+type PresentOverride = {
+ attemptId: number
+ phase: "requested" | "present"
+ viewKey: string
+}
+
// Shared pagination + reducer used by both channel and DM hooks. Kept inline
// as a hook because both variants need the same TanStack setup — factoring
// out a plain function would leak query internals; a hook stays clean.
@@ -224,11 +231,19 @@ function useMessagesInner(
// Jump target wins over the read pointer for the initial anchor window.
const anchorId = opts?.anchorMessageId ?? opts?.lastReadMessageId ?? null
const enabled = !!scopeId && anchorResolved
-
- // Force-newest override — flipped by `jumpToPresent`. Held in state so
- // React re-renders with the new options before the reset fires (see the
- // useEffect below). Cleared once the first newest page arrives.
- const [forceNewest, setForceNewest] = useState(false)
+ const viewKey = useMemo(
+ () => JSON.stringify([queryKey, opts?.anchorMessageId ?? null]),
+ [queryKey, opts?.anchorMessageId],
+ )
+ const attemptIdRef = useRef(0)
+ const snapshotRef = useRef<{
+ attemptId: number
+ data: PageCache | undefined
+ viewKey: string
+ } | null>(null)
+ const [presentOverride, setPresentOverride] = useState<PresentOverride | null>(null)
+ const forceNewest = presentOverride?.viewKey === viewKey
+ const jumpPending = forceNewest && presentOverride?.phase === "requested"
const initialPageParam = useMemo<MessagesPageParam>(() => {
if (forceNewest) return { mode: "newest" }
@@ -277,7 +292,7 @@ function useMessagesInner(
// persisted pageParam can replace or discard the existing history.
staleTime: (cachedQuery) => cachedWindowNeedsAnchor(
(cachedQuery.state.data as PageCache | undefined)?.pages,
- anchorId,
+ forceNewest ? null : anchorId,
) ? Infinity : 0,
})
@@ -291,25 +306,47 @@ function useMessagesInner(
}
}, [scopeId])
- // Two-phase reset: setForceNewest triggers a render that updates
- // `initialPageParam` to newest. THIS effect fires on that render and
- // actually clears the query, so the refetch reads the newest-mode options
- // rather than the pre-flip anchor options.
useEffect(() => {
- if (!forceNewest) return
- void queryClient.resetQueries({ queryKey })
- }, [forceNewest, queryClient, queryKey])
+ setPresentOverride((current) => current?.viewKey === viewKey ? current : null)
+ }, [viewKey])
- // Clear the flag once a newest-shape page lands — anchor pages carry
- // `hasMoreOlder`/`hasMoreNewer`; legacy newest carries `hasMore`. If the
- // first cached page reads as legacy, the jump succeeded.
useEffect(() => {
- if (!forceNewest) return
+ if (!jumpPending || !presentOverride) return
+ snapshotRef.current = {
+ attemptId: presentOverride.attemptId,
+ data: queryClient.getQueryData<PageCache>(queryKey),
+ viewKey,
+ }
+ void queryClient.resetQueries({ queryKey, exact: true })
+ }, [jumpPending, presentOverride, queryClient, queryKey, viewKey])
+
+ useEffect(() => {
+ if (!jumpPending || !presentOverride) return
const first = query.data?.pages[0]
if (!first) return
const isNewestShape = first.hasMore !== undefined && first.hasMoreOlder === undefined
- if (isNewestShape) setForceNewest(false)
- }, [forceNewest, query.data])
+ if (!isNewestShape) return
+ snapshotRef.current = null
+ setPresentOverride((current) =>
+ current?.attemptId === presentOverride.attemptId
+ ? { ...current, phase: "present" }
+ : current)
+ }, [jumpPending, presentOverride, query.data])
+
+ useEffect(() => {
+ if (!jumpPending || !presentOverride || !query.isError) return
+ const snapshot = snapshotRef.current
+ if (
+ snapshot?.attemptId === presentOverride.attemptId
+ && snapshot.viewKey === viewKey
+ && snapshot.data
+ ) {
+ queryClient.setQueryData<PageCache>(queryKey, snapshot.data)
+ }
+ snapshotRef.current = null
+ setPresentOverride((current) =>
+ current?.attemptId === presentOverride.attemptId ? null : current)
+ }, [jumpPending, presentOverride, query.isError, queryClient, queryKey, viewKey])
// Fix 3 — anchor re-validation.
//
@@ -339,6 +376,7 @@ function useMessagesInner(
const anchorResetKeyRef = useRef<string | null>(null)
useEffect(() => {
if (!enabled) return
+ if (forceNewest) return
if (!anchorId) return
if (query.isFetching) return
if (query.isPending) return
@@ -411,6 +449,7 @@ function useMessagesInner(
})
}, [
enabled,
+ forceNewest,
anchorId,
scopeId,
query.data,
@@ -459,8 +498,14 @@ function useMessagesInner(
}, [query])
const jumpToPresent = useCallback(() => {
- setForceNewest(true)
- }, [])
+ if (!enabled || forceNewest) return
+ attemptIdRef.current += 1
+ setPresentOverride({
+ attemptId: attemptIdRef.current,
+ phase: "requested",
+ viewKey,
+ })
+ }, [enabled, forceNewest, viewKey])
return {
...query,
@@ -488,10 +533,13 @@ function useMessagesInner(
hasMoreOlder,
hasMoreNewer,
isFetchingOlder: query.isFetchingNextPage,
- isFetchingNewer: query.isFetchingPreviousPage,
+ isFetchingNewer: query.isFetchingPreviousPage || jumpPending,
fetchOlder,
fetchNewer,
jumpToPresent,
+ presentVersion: forceNewest && presentOverride?.phase === "present"
+ ? presentOverride.attemptId
+ : 0,
hasMore: hasMoreOlder,
}
}
@@ -506,12 +554,18 @@ export function useMessages(
channelId: string | null,
opts: ChannelMessagesOpts,
): MessagesReturn {
- const baseKey = communityKeys.channelMessages(channelId ?? "__none__")
- const queryKey = opts.tag ? [...baseKey, "tag", opts.tag] as const : baseKey
+ const queryKey = useMemo(() => {
+ const baseKey = communityKeys.channelMessages(channelId ?? "__none__")
+ return opts.tag ? [...baseKey, "tag", opts.tag] as const : baseKey
+ }, [channelId, opts.tag])
+ const queryFn = useMemo(
+ () => channelMessagesQueryFn(channelId ?? "__none__", opts.tag),
+ [channelId, opts.tag],
+ )
const base = useMessagesInner(
channelId,
queryKey,
- channelMessagesQueryFn(channelId ?? "__none__", opts?.tag),
+ queryFn,
opts,
)
const scope = useMemo<MessageScope>(() => ({
@@ -548,11 +602,18 @@ export function useDmMessages(
dmId: string | null,
opts?: MessagesOpts,
): MessagesReturn {
- const queryKey = communityKeys.dmMessages(dmId ?? "__none__")
+ const queryKey = useMemo(
+ () => communityKeys.dmMessages(dmId ?? "__none__"),
+ [dmId],
+ )
+ const queryFn = useMemo(
+ () => dmMessagesQueryFn(dmId ?? "__none__"),
+ [dmId],
+ )
const base = useMessagesInner(
dmId,
queryKey,
- dmMessagesQueryFn(dmId ?? "__none__"),
+ queryFn,
opts,
)
const scope = useMemo<MessageScope>(() => ({
diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.ts
index f0ba88540..d56610b8c 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.ts
@@ -327,6 +327,7 @@ export function useScrollAnchor({
newDividerBefore,
initialScrollReady,
hasMoreNewer,
+ presentVersion,
viewerUserId,
heroHeight,
heroMeasured,
@@ -335,6 +336,7 @@ export function useScrollAnchor({
newDividerBefore?: string
initialScrollReady: boolean
hasMoreNewer?: boolean
+ presentVersion?: number
viewerUserId?: string
// Current measured height (px) of the non-virtualized hero block that
// renders above the virtualized range (the "Beginning of the channel…"
@@ -359,6 +361,7 @@ export function useScrollAnchor({
const scrollRef = useRef<HTMLDivElement>(null)
const stateRef = useRef<ScrollAnchorState>(createScrollAnchorState())
const messages = extractScrollAnchorMessages(items)
+ const tailId = messages[messages.length - 1]?.id ?? null
// eslint-disable-next-line react-hooks/incompatible-library -- library limitation, same as member-list.tsx
const virtualizer = useVirtualizer({
@@ -437,6 +440,20 @@ export function useScrollAnchor({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [items, newDividerBefore, initialScrollReady, heroMeasured, hasMoreNewer, viewerUserId, virtualizer])
+ const consumedPresentVersionRef = useRef(0)
+ useLayoutEffect(() => {
+ if (!presentVersion || !tailId || hasMoreNewer) return
+ if (consumedPresentVersionRef.current === presentVersion) return
+ consumedPresentVersionRef.current = presentVersion
+ stateRef.current = {
+ didInitialScroll: true,
+ didDividerConverge: true,
+ lastTailId: tailId,
+ }
+ wasAtEndRef.current = true
+ virtualizer.scrollToEnd()
+ }, [hasMoreNewer, presentVersion, tailId, virtualizer])
+
// Hero-swap compensation — NOT delegated to `scrollMargin` (verified it
// never triggers a `scrollOffset` write on its own). Tracks the hero's
// height across renders and adjusts `el.scrollTop` by the delta whenever
diff --git a/src/web/src/test/e2e-ui/16-jump-to-present.spec.ts b/src/web/src/test/e2e-ui/16-jump-to-present.spec.ts
new file mode 100644
index 000000000..c38639955
--- /dev/null
+++ b/src/web/src/test/e2e-ui/16-jump-to-present.spec.ts
@@ -0,0 +1,52 @@
+import { test, expect, sessionCookie } from "./_fixtures/community-fixture"
+import { seedChannel, seedJoinServer, seedMessage, seedServer } from "./_fixtures/seed"
+import { tid } from "./_fixtures/testids"
+import { WEB_URL } from "./_setup/paths"
+
+test("anchored channel jumps to the newest tail with one request", async ({ asUser }) => {
+ test.setTimeout(120_000)
+ const serverId = await seedServer("alice", `Jump Present ${Date.now()}`)
+ await seedJoinServer("alice", "bob", serverId)
+ await seedJoinServer("alice", "carol", serverId)
+ const channelId = await seedChannel("alice", serverId, `jump-present-${Date.now()}`)
+ const anchorId = await seedMessage("alice", channelId, "jump anchor")
+ let latestId = ""
+ for (let index = 1; index <= 36; index++) {
+ latestId = await seedMessage(index % 2 === 0 ? "bob" : "carol", channelId, `newer message ${index}`)
+ }
+ const readResponse = await fetch(`${WEB_URL}/api/community/channels/${channelId}/read`, {
+ method: "PUT",
+ headers: {
+ Cookie: sessionCookie("alice"),
+ "Content-Type": "application/json",
+ Origin: WEB_URL,
+ },
+ body: JSON.stringify({ lastReadMessageId: anchorId }),
+ })
+ expect(readResponse.ok).toBe(true)
+
+ const { page } = await asUser("alice")
+ await page.goto(`/c/channels/${serverId}/${channelId}`)
+ await expect(page.getByTestId(tid.message(anchorId))).toBeVisible({ timeout: 30_000 })
+ const jumpButton = page.getByRole("button", { name: /^Jump to present, \d+ unread below$/ })
+ await expect(jumpButton).toBeVisible({ timeout: 20_000 })
+
+ let newestGets = 0
+ let anchorGets = 0
+ page.on("request", (request) => {
+ if (request.method() !== "GET") return
+ const url = new URL(request.url())
+ if (url.pathname !== `/api/community/channels/${channelId}/messages`) return
+ if (url.search === "") newestGets += 1
+ if (url.searchParams.has("anchor")) anchorGets += 1
+ })
+
+ await jumpButton.click()
+ await expect(page.getByTestId(tid.message(latestId))).toBeVisible({ timeout: 30_000 })
+ await expect(jumpButton).toBeHidden()
+ await expect(page.getByText("Loading newer messages…", { exact: true })).toHaveCount(0)
+ await expect.poll(() => newestGets).toBe(1)
+ await page.waitForTimeout(1_000)
+ expect(newestGets).toBe(1)
+ expect(anchorGets).toBe(0)
+})