Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): reveal cached positions without duplicate message reads (#1070)

Generfbc21fd2078f
diff --git a/src/web/src/components/community/channels/dm-view.tsx b/src/web/src/components/community/channels/dm-view.tsx
index 6f18acda7..47f684224 100644
--- a/src/web/src/components/community/channels/dm-view.tsx
+++ b/src/web/src/components/community/channels/dm-view.tsx
@@ -202,7 +202,7 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom
// comment for the Playwright-verified repro of the mount-vs-Fix-3 race
// this closes: two independently-evaluated expressions reading the same
// inputs aren't guaranteed to agree on every commit).
- const { newDividerBefore, anchorFound } = useMemo(() => {
+ const { newDividerBefore } = useMemo(() => {
if (!readSnapshot) return { newDividerBefore: undefined, anchorFound: false }
return resolveMessageReadProjection({
messages,
@@ -212,10 +212,6 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom
})
}, [anchorReconciled, messages, readSnapshot, currentUser.id])
- // Gates `<MessageList>`'s mount-time scroll action until the anchor is
- // actually present in the loaded `messages`.
- const anchorInCache = anchorFound
-
// Scroll root of the message list — needed so `useDmWatermark`'s
// IntersectionObserver measures against the correct viewport rather
// than the page viewport. Set once by `MessageList` via `onScrollRoot`.
@@ -465,10 +461,7 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom
resolveUserName={resolveUserName}
onScrollRoot={setScrollRootEl}
viewerUserId={currentUser.id}
- // Delay initial scroll until the read-state snapshot resolves AND
- // the anchor it names is actually present in `messages` — see
- // `anchorInCache`'s doc comment above.
- initialScrollReady={!readSnapshotFetching && (anchorInCache || initialPositionKnown)}
+ initialScrollReady={initialPositionKnown}
hasMore={hasMoreMessages}
historyStartKnown={historyStartKnown}
initialPositionMessageId={initialPositionMessageId}
diff --git a/src/web/src/components/community/channels/text-channel-surface.tsx b/src/web/src/components/community/channels/text-channel-surface.tsx
index 538249672..c242f3988 100644
--- a/src/web/src/components/community/channels/text-channel-surface.tsx
+++ b/src/web/src/components/community/channels/text-channel-surface.tsx
@@ -156,7 +156,7 @@ export function TextChannelSurface({
scrollToMessageId={controller.scrollTargetId}
onScrollRoot={feed.setScrollRootEl}
viewerUserId={viewer.id}
- initialScrollReady={!feed.readSnapshotFetching && feed.anchorInCache}
+ initialScrollReady={feed.initialPositionKnown}
onScrollTargetConsumed={controller.consumeScrollTarget}
hasMore={feed.hasMoreOlder}
historyStartKnown={feed.historyStartKnown}
diff --git a/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts b/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts
index 4c4460411..579aec95e 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts
+++ b/src/web/src/components/community/channels/thread-channel-surface.dom.test.ts
@@ -156,6 +156,7 @@ function feed(overrides: Record<string, unknown> = {}) {
jumpToPresent: vi.fn(),
readSnapshotFetching: false,
anchorInCache: true,
+ initialPositionKnown: true,
newDividerBefore: undefined,
unreadCount: 0,
setScrollRootEl: vi.fn(),
diff --git a/src/web/src/components/community/channels/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsx
index 4cf1e29c2..3f0b000e6 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.tsx
+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx
@@ -268,7 +268,7 @@ export function ThreadChannelSurface({
hero={opener}
onScrollRoot={controller.feed.setScrollRootEl}
viewerUserId={viewer.id}
- initialScrollReady={!controller.feed.readSnapshotFetching && controller.feed.anchorInCache}
+ initialScrollReady={controller.feed.initialPositionKnown}
onScrollTargetConsumed={controller.consumeScrollTarget}
hasMore={controller.feed.hasMoreOlder}
historyStartKnown={controller.feed.historyStartKnown}
diff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.coverage.test.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.coverage.test.ts
new file mode 100644
index 000000000..7374f9d02
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.coverage.test.ts
@@ -0,0 +1,236 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import { QueryObserver } from "@tanstack/react-query"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { conversationEntryFixture as fixture } from "@/test/conversation-entry-fixtures"
+import { conversationEntryOptions, publishConversationEntry } from "@/lib/community/conversation-entry"
+import { captureCommunityLiveSnapshotToken, ingestMessages } from "@/lib/community-db/sync"
+import { messageWindowPage, type MessagesPage } from "@/lib/community/models/message"
+import type { MessageWindowData } from "@/lib/community/message-window"
+import { prefetchCommunityLatestMessage, prefetchCommunityMessage } from "../use-message"
+import { reconcileConversationLanding, reconcileFocusedMessageQueries, reconcileWindow } from "./reconnect-messages"
+
+const load = vi.hoisted(() => vi.fn())
+vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => load(...args) }))
+beforeEach(() => { load.mockReset() })
+
+function row(seq: number) {
+ return { ...fixture().messages[0], id: `m${seq}`, seq,
+ createdAt: new Date(Date.UTC(2026, 9, 1, 0, 0, seq)).toISOString(),
+ authorName: "Peer", authorAvatar: "", authorAvatarVersion: 0,
+ content: `Body ${seq}`, resourceComplete: true as const, embeds: [], reactions: [],
+ }
+}
+function page(messages: ReturnType<typeof row>[], latestSeq: number): MessagesPage {
+ return { messages, latestSeq, hasMoreOlder: true, hasMoreNewer: false, olderCursor: "older" }
+}
+function suffix(cursor: number) { return `since=${encodeURIComponent(`${row(cursor).createdAt}|m${cursor}`)}` }
+
+async function setup(sequences = [98, 99, 100], tag: string | null = null) {
+ const owner = await createCommunityQueryOwner()
+ const target = { channelId: "c1", serverId: "s1", tag }
+ const messages = sequences.map(row)
+ const last = messages.at(-1)!
+ const packet = { ...fixture(), messages,
+ channel: { ...fixture().channel, messageCount: messages.length, createdAt: messages[0].createdAt, lastMessageAt: last.createdAt },
+ readState: { channelId: "c1", lastReadMessageId: last.id, lastReadAt: last.createdAt, lastReadSeq: last.seq },
+ selection: { reason: "tail" as const, anchorMessageId: null },
+ page: { ...fixture().page, latestSeq: last.seq, hasMoreOlder: true, hasMoreNewer: false },
+ }
+ const options = conversationEntryOptions(owner.client, target)
+ const resource = publishConversationEntry(owner.client, target, packet, { token: captureCommunityLiveSnapshotToken(owner.client, "c1") })
+ owner.client.setQueryData(options.queryKey, resource)
+ const key = resource.windowKey
+ const observer = new QueryObserver(owner.client, { queryKey: key, queryFn: vi.fn(), staleTime: Infinity })
+ const unsubscribe = observer.subscribe(() => {})
+ const read = () => owner.client.getQueryData<MessageWindowData>(key)!
+ const ids = () => read().pages.flatMap(part => part.messages.map(message => message.id))
+ const repairOwner = { query: owner.client.getQueryCache().find({ queryKey: options.queryKey, exact: true })!, signal: new AbortController().signal }
+ return { ...owner, target, key, resource, read, ids, unsubscribe, repairOwner }
+}
+
+describe("complete canonical coverage at the existing repair owner", () => {
+ it.each([false, true])("merges a matching complete landing without fetching its last message again (watermark ahead=%s)", async watermarkAhead => {
+ const h = await setup()
+ if (watermarkAhead) h.client.setQueryData<MessageWindowData>(h.key, current => current && ({ ...current, pages: current.pages.map(part => ({ ...part, latestSeq: 101 })) }))
+ const params = h.read().pageParams
+ const fresh = { ...fixture(), messages: [{ ...row(100), content: "edited" }, row(101)],
+ selection: { reason: "tail" as const, anchorMessageId: null }, page: { ...fixture().page, latestSeq: 101 },
+ }
+ publishConversationEntry(h.client, h.target, fresh, { token: captureCommunityLiveSnapshotToken(h.client, "c1") })
+ load.mockResolvedValue(page([row(101)], 101))
+ try {
+ await reconcileConversationLanding(h.client, { kind: "channel", scopeId: "c1", serverId: "s1" }, h.key,
+ page(fresh.messages, 101), { mode: "newest" }, h.repairOwner)
+ expect(load).not.toHaveBeenCalled()
+ expect(h.ids()).toEqual(["m98", "m99", "m100", "m101"])
+ expect(h.registry.collections.messages.get("m100")?.content).toBe("edited")
+ expect(h.read().pageParams).toEqual(params)
+ } finally { h.unsubscribe() }
+ })
+
+ it.each(["exact-ID", "latest"] as const)("reuses a real %s prefetch without giving prefetch a window writer", async hint => {
+ const h = await setup()
+ load.mockResolvedValueOnce(hint === "exact-ID" ? row(101) : page([row(101)], 101))
+ if (hint === "exact-ID") await prefetchCommunityMessage(h.client, "m101", { channelId: "c1", serverId: "s1" })
+ else await prefetchCommunityLatestMessage(h.client, "c1")
+ expect(h.registry.collections.messages.get("m101")?.resourceComplete).toBe(true)
+ expect(h.ids()).toEqual(["m98", "m99", "m100"])
+ load.mockReset().mockResolvedValue(page([{ ...row(100), content: "corrected" }], 101))
+ try {
+ await reconcileFocusedMessageQueries(h.client, "channel", "c1", "s1")
+ expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages"])
+ expect(h.ids()).toEqual(["m98", "m99", "m100", "m101"])
+ expect(h.registry.collections.messages.get("m100")?.content).toBe("corrected")
+ } finally { h.unsubscribe() }
+ })
+
+ it("publishes the available complete prefix before the remaining delta settles", async () => {
+ const h = await setup()
+ ingestMessages(h.registry, "c1", [row(101), row(103)])
+ let release!: (value: MessagesPage) => void
+ load.mockResolvedValueOnce(page([row(100)], 103))
+ .mockImplementationOnce(() => new Promise<MessagesPage>(resolve => { release = resolve }))
+ const pending = reconcileFocusedMessageQueries(h.client, "channel", "c1", "s1")
+ try {
+ await vi.waitFor(() => expect(load).toHaveBeenCalledTimes(2))
+ expect(h.ids()).toEqual(["m98", "m99", "m100", "m101"])
+ expect(h.read().pages[0].hasMoreNewer).toBe(true)
+ expect(h.read().pages[0].newerCursor).toBe(`${row(101).createdAt}|m101`)
+ release(page([row(102)], 103))
+ await pending
+ expect(h.ids()).toEqual(["m98", "m99", "m100", "m101", "m102", "m103"])
+ expect(h.read().pages[0].hasMoreNewer).toBe(false)
+ } finally {
+ release?.(page([row(102)], 103))
+ await pending
+ h.unsubscribe()
+ }
+ })
+
+ it("retains current-window correction of a deleted reply target even when creations are cached", async () => {
+ const h = await setup()
+ ingestMessages(h.registry, "c1", [{ ...row(100), replyTo: { id: "gone", authorName: "Peer", text: "old reply" } }, row(101)])
+ load.mockResolvedValueOnce(page([{ ...row(100), replyTo: { id: "gone", authorName: "Deleted user", text: "", deleted: true } }], 101))
+ try {
+ await reconcileFocusedMessageQueries(h.client, "channel", "c1", "s1")
+ expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages"])
+ expect(h.registry.collections.messages.get("m100")?.replyTo).toEqual({ id: "gone", authorName: "Deleted user", text: "", deleted: true })
+ expect(h.ids()).toEqual(["m98", "m99", "m100", "m101"])
+ } finally { h.unsubscribe() }
+ })
+
+ it("reads only beyond a proven canonical prefix while filling a hole before a higher cached seq", async () => {
+ const h = await setup()
+ ingestMessages(h.registry, "c1", [row(101), row(103)])
+ load.mockResolvedValueOnce(page([row(100)], 103)).mockResolvedValueOnce(page([row(102), row(103)], 103))
+ try {
+ await reconcileFocusedMessageQueries(h.client, "channel", "c1", "s1")
+ expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages", `/api/community/channels/c1/messages?${suffix(101)}`])
+ expect(h.ids()).toEqual(["m98", "m99", "m100", "m101", "m102", "m103"])
+ } finally { h.unsubscribe() }
+ })
+
+ it("reuses a higher cached full resource only after the delta fills the intervening hole", async () => {
+ const h = await setup()
+ ingestMessages(h.registry, "c1", [row(101), row(103)])
+ load.mockResolvedValueOnce(page([row(100)], 100)).mockResolvedValueOnce(page([row(102)], 102))
+ try {
+ await reconcileWindow(h.client, { kind: "channel", scopeId: "c1", serverId: "s1" }, h.key, 103)
+ expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages", `/api/community/channels/c1/messages?${suffix(101)}`])
+ expect(h.ids()).toEqual(["m98", "m99", "m100", "m101", "m102", "m103"])
+ expect(h.read().pages[0].hasMoreNewer).toBe(false)
+ } finally { h.unsubscribe() }
+ })
+
+ it("closes a resumable network page when complete cached rows prove its whole remainder", async () => {
+ const h = await setup()
+ ingestMessages(h.registry, "c1", [row(101), row(103), row(104)])
+ load.mockResolvedValueOnce(page([row(100)], 104)).mockResolvedValueOnce({
+ ...page([row(102)], 104), hasMoreNewer: true, newerCursor: `${row(102).createdAt}|m102`,
+ })
+ try {
+ await reconcileFocusedMessageQueries(h.client, "channel", "c1", "s1")
+ expect(load).toHaveBeenCalledTimes(2)
+ expect(h.ids()).toEqual(["m98", "m99", "m100", "m101", "m102", "m103", "m104"])
+ expect(h.read().pages[0].hasMoreNewer).toBe(false)
+ expect(h.read().pages[0].newerCursor).toBeUndefined()
+ } finally { h.unsubscribe() }
+ })
+
+ it("accepts the resource contract's zero-seq boundary without rereading its complete successor", async () => {
+ const h = await setup([0])
+ ingestMessages(h.registry, "c1", [row(1)])
+ load.mockResolvedValue(page([row(0)], 1))
+ try {
+ await reconcileFocusedMessageQueries(h.client, "channel", "c1", "s1")
+ expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages"])
+ expect(h.ids()).toEqual(["m0", "m1"])
+ } finally { h.unsubscribe() }
+ })
+
+ it("does not turn a repair target into coverage while another sequence is still missing", async () => {
+ const h = await setup()
+ ingestMessages(h.registry, "c1", [row(101), row(104)])
+ load.mockResolvedValueOnce(page([row(100)], 100)).mockResolvedValueOnce(page([row(102)], 102))
+ try {
+ await expect(reconcileWindow(h.client, { kind: "channel", scopeId: "c1", serverId: "s1" }, h.key, 104)).rejects.toThrow("Messages have not caught up yet")
+ expect(h.ids()).toEqual(["m98", "m99", "m100", "m101", "m102"])
+ expect(h.read().pages[0].latestSeq).toBe(102)
+ } finally { h.unsubscribe() }
+ })
+
+ it("starts before an actual loaded-window hole rather than using its maximum seq", async () => {
+ const h = await setup([98, 100])
+ ingestMessages(h.registry, "c1", [row(102)])
+ load.mockResolvedValueOnce(page([row(100)], 102)).mockResolvedValueOnce(page([row(99), row(100), row(101), row(102)], 102))
+ try {
+ await reconcileFocusedMessageQueries(h.client, "channel", "c1", "s1")
+ expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages", `/api/community/channels/c1/messages?${suffix(98)}`])
+ expect(h.ids()).toEqual(["m98", "m99", "m100", "m101", "m102"])
+ } finally { h.unsubscribe() }
+ })
+
+ it.each(["missing", "partial", "other-channel", "duplicate-seq", "cursor-order", "invalid-time", "cursor-separator"] as const)("does not let %s evidence or a maximum seq hide a missing resource", async kind => {
+ const h = await setup()
+ ingestMessages(h.registry, "c1", [row(103)])
+ if (kind === "partial") ingestMessages(h.registry, "c1", [{ id: "m101", seq: 101, createdAt: row(101).createdAt, content: "partial" }])
+ if (kind === "other-channel") ingestMessages(h.registry, "c2", [{ ...row(101), channelId: "c2" }])
+ if (kind === "duplicate-seq") ingestMessages(h.registry, "c1", [row(101), { ...row(101), id: "other101" }])
+ if (kind === "cursor-order") ingestMessages(h.registry, "c1", [{ ...row(101), createdAt: row(99).createdAt }])
+ if (kind === "invalid-time") ingestMessages(h.registry, "c1", [{ ...row(101), createdAt: "not-a-time" }])
+ if (kind === "cursor-separator") ingestMessages(h.registry, "c1", [{ ...row(101), id: "m|101" }])
+ load.mockResolvedValueOnce(page([row(100)], 103)).mockResolvedValueOnce(page([row(101), row(102), row(103)], 103))
+ try {
+ await reconcileFocusedMessageQueries(h.client, "channel", "c1", "s1")
+ expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages", `/api/community/channels/c1/messages?${suffix(100)}`])
+ expect(h.ids()).toEqual(["m98", "m99", "m100", "m101", "m102", "m103"])
+ } finally { h.unsubscribe() }
+ })
+
+ it("keeps tag-filtered seq gaps under the original transport contract", async () => {
+ const h = await setup([98, 100], "bug")
+ ingestMessages(h.registry, "c1", [row(101), row(102)])
+ load.mockResolvedValueOnce(page([row(100)], 102)).mockResolvedValueOnce(page([row(102)], 102))
+ try {
+ await reconcileFocusedMessageQueries(h.client, "channel", "c1", "s1")
+ expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages?tag=bug", `/api/community/channels/c1/messages?tag=bug&${suffix(100)}`])
+ expect(h.ids()).toEqual(["m98", "m100", "m102"])
+ } finally { h.unsubscribe() }
+ })
+
+ it("does not publish cached or returned additions into a replacement window", async () => {
+ const h = await setup()
+ ingestMessages(h.registry, "c1", [row(101)])
+ let release!: (value: MessagesPage) => void
+ load.mockImplementationOnce(() => new Promise<MessagesPage>(resolve => { release = resolve }))
+ const pending = reconcileFocusedMessageQueries(h.client, "channel", "c1", "s1").catch(error => error)
+ await vi.waitFor(() => expect(load).toHaveBeenCalledOnce())
+ h.client.removeQueries({ queryKey: h.key, exact: true })
+ const replacement = { pages: [messageWindowPage(page([row(500)], 500))], pageParams: [{ mode: "newest" as const }] }
+ h.client.setQueryData(h.key, replacement)
+ release(page([row(100)], 101))
+ await pending
+ expect(h.client.getQueryData(h.key)).toBe(replacement)
+ h.unsubscribe()
+ })
+})
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 a0007b4ae..d9894697d 100644
--- a/src/web/src/hooks/community/community-ws/reconnect-messages.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.ts
@@ -1,13 +1,14 @@
+import { CommunityMessageResourceSchema } from "@alook/shared"
import { CancelledError, hashKey, queryOptions, type InfiniteData, type Query, 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"
+import { assertCommunityLiveSnapshotTokenCurrent, captureCommunityLiveSnapshotToken, publishCommunityMessages, retireCommunityChannelReading, getCanonicalCommunityMessages } from "@/lib/community-db/sync"
import { ConversationReadTimeoutError, withConversationReadDeadline, isConversationAnchorMissingError } from "@/lib/community/conversation-read"
import { ApiError, isAbortError } from "@/lib/errors"
import { communityKeys } from "@/lib/query-keys"
import { getCommunityRuntime } from "@/stores/community/runtime"
import { messageScopeKey } from "@/stores/community/message-stream-store"
-import { messageWindowPage, type MessagesPage, type MessagesPageParam, type MessagesWindowPage } from "@/lib/community/models/message"
+import { messageWindowPage, type MessageInput, type MessagesPage, type MessagesPageParam, type MessagesWindowPage } from "@/lib/community/models/message"
import { buildMessagesUrl, messageWindowIdentity } from "@/lib/community/message-window"
type MessageCache = InfiniteData<MessagesWindowPage, MessagesPageParam>
@@ -32,6 +33,50 @@ function mergeWindow(cache: MessageCache, refreshed: MessagesPage, catchUp: Mess
return { ...cache, pages }
}
+function cachedCoverage(queryClient: QueryClient, scopeId: string, cache: MessageCache, refreshed: MessagesPage, target: number, tag: string | null) {
+ if (tag !== null || !Number.isSafeInteger(target)) return
+ const byId = new Map<string, MessageInput>(getCanonicalCommunityMessages(queryClient)
+ .filter(row => row.channelId === scopeId && row.resourceComplete === true).map(row => [row.id, row]))
+ for (const message of refreshed.messages) {
+ const parsed = CommunityMessageResourceSchema.strip().safeParse(message)
+ if (parsed.success && parsed.data.channelId === scopeId) byId.set(message.id, parsed.data)
+ }
+ const rows = [...byId.values()]
+ const combined = mergeWindow(cache, refreshed, [])
+ const loaded = [...new Map(combined.pages.flatMap(page => page.messages).map(row => [row.id, row])).values()]
+ if (!loaded.length) return
+ const references = loaded.map(reference => {
+ const row = byId.get(reference.id)
+ return row && Number.isSafeInteger(row.seq) && row.seq! >= 0
+ && (reference.seq === undefined || row.seq === reference.seq) ? row : undefined
+ })
+ if (references.some(row => !row)) return
+ const first = Math.min(...references.map(row => row!.seq!))
+ const required = Math.max(target, ...references.map(row => row!.seq!))
+ const bySeq = new Map<number, typeof rows[number] | null>()
+ for (const row of rows) {
+ if (row.seq === undefined || !Number.isSafeInteger(row.seq) || row.seq < first || row.seq > required) continue
+ bySeq.set(row.seq, bySeq.has(row.seq) ? null : row)
+ }
+ const present = new Set(loaded.map(row => row.id))
+ const messages: MessagesPage["messages"] = []
+ let nextCursor: string | null = null, covered = first - 1
+ for (let seq = first; seq <= required; seq++) {
+ const row = bySeq.get(seq)
+ if (!row?.createdAt || !Number.isFinite(Date.parse(row.createdAt)) || row.id.includes("|")) break
+ const currentCursor = `${row.createdAt}|${row.id}`
+ if (nextCursor !== null && currentCursor <= nextCursor) break
+ nextCursor = currentCursor
+ covered = seq
+ if (!present.has(row.id)) messages.push(row)
+ }
+ if (!nextCursor) return
+ return { cursor: nextCursor, covered, page: {
+ messages, latestSeq: Math.max(latest(cache), refreshed.latestSeq ?? 0, covered), hasMoreNewer: covered < required,
+ newerCursor: covered < required ? nextCursor : undefined,
+ } satisfies MessagesPage }
+}
+
type MessageRepairOwner = { query: Query; signal: AbortSignal }
type MessageRepairReceipt = {
token: ReturnType<typeof captureCommunityLiveSnapshotToken>
@@ -121,17 +166,39 @@ export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepa
return page
}
const target = () => queryClient.getQueryData<number>(targetKey(key)) ?? 0
+ let cached: MessagesPage | undefined
+ let cachedCovered = 0
+ const published = new Set<MessagesPage>()
const prefetch = async (current: MessageCache, refreshed: MessagesPage) => {
- if (prefetched || Math.max(refreshed.latestSeq ?? 0, target()) <= latest(current, false)) return
- const nextCursor = cursor(current)
+ if (prefetched) return
+ const required = Math.max(refreshed.latestSeq ?? 0, target())
+ const coverage = cachedCoverage(queryClient, scopeId, current, refreshed, required, tag)
+ cached = coverage?.page
+ cachedCovered = coverage?.covered ?? 0
+ if (coverage ? coverage.covered >= required : required <= latest(current, false)) return
+ if (cached?.messages.length) publish(refreshed)
+ const nextCursor = coverage?.cursor ?? cursor(current)
if (!nextCursor && (refreshed.latestSeq ?? 0) >= target()) return
const param: MessagesPageParam = nextCursor ? { mode: "since", since: nextCursor } : current.pageParams[0]
prefetched = { param, page: await load(param) }
+ const after = originalQuery?.state.data
+ if (isMessageCache(after)) {
+ const remaining = cachedCoverage(queryClient, scopeId, after, {
+ ...prefetched.page, messages: [...refreshed.messages, ...prefetched.page.messages],
+ }, Math.max(required, target(), prefetched.page.latestSeq ?? 0), tag)
+ if (remaining) { cached = remaining.page; cachedCovered = remaining.covered }
+ }
}
const publish = (refreshed: MessagesPage) => {
assert()
- const catchUp = prefetched ? [prefetched.page] : []
- publishCommunityMessages(queryClient, { channelId: scopeId, messages: [refreshed, ...catchUp].flatMap((page) => page.messages), proof: { token, signal } })
+ const fetchedEnd = Math.max(0, ...(prefetched?.page.messages.map(message => message.seq ?? 0) ?? []))
+ const catchUp = cached && prefetched && cachedCovered >= fetchedEnd
+ ? [prefetched.page, cached] : [...(cached ? [cached] : []), ...(prefetched ? [prefetched.page] : [])]
+ const pending = [refreshed, ...(prefetched ? [prefetched.page] : [])].filter(page => !published.has(page))
+ if (pending.length) {
+ publishCommunityMessages(queryClient, { channelId: scopeId, messages: pending.flatMap(page => page.messages), proof: { token, signal } })
+ for (const page of pending) published.add(page)
+ }
queryClient.setQueryData<MessageCache>(key, (cache) => isMessageCache(cache) ? mergeWindow(cache, refreshed, catchUp) : cache)
}
try {
@@ -155,7 +222,7 @@ export function messageReconcileOptions(queryClient: QueryClient, scope: GapRepa
publish(refreshed)
}
assert()
- const latestSeq = Math.max(refreshed.latestSeq ?? 0, prefetched?.page.latestSeq ?? 0)
+ const latestSeq = Math.max(refreshed.latestSeq ?? 0, prefetched?.page.latestSeq ?? 0, cachedCovered)
if (latestSeq < target() && !(prefetched?.page.hasMoreNewer && prefetched.page.newerCursor)) {
throw new Error("Messages have not caught up yet")
}
@@ -213,7 +280,9 @@ export function reconcileWindow(queryClient: QueryClient, scope: GapRepairScope,
export function reconcileConversationLanding(queryClient: QueryClient, scope: GapRepairScope, key: QueryKey, page: MessagesPage, param: MessagesPageParam, owner: MessageRepairOwner) {
const data = queryClient.getQueryData(key)
const highWater = page.latestSeq ?? 0
- if (!isMessageCache(data) || highWater <= latest(data)) return Promise.resolve()
+ if (!isMessageCache(data)) return Promise.resolve()
+ const ids = new Set(data.pages.flatMap(part => part.messages.map(message => message.id)))
+ if (highWater <= latest(data, false) && page.messages.every(message => ids.has(message.id))) return Promise.resolve()
return reconcileWindow(queryClient, scope, key, highWater, { page, param }, owner)
}
diff --git a/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx b/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx
index d9c3c6bb6..00da1f557 100644
--- a/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx
+++ b/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx
@@ -332,7 +332,8 @@ describe("conversation entry return during accepted reading", () => {
const props = { channel: "Channel", messages: feed.messages,
loading: feed.isLoading, initialLoadError: feed.initialLoadError,
newDividerBefore: projection.newDividerBefore, scrollToMessageId,
- initialScrollReady: !feed.readSnapshotFetching && (projection.anchorFound || feed.initialPositionKnown),
+ initialScrollReady: feed.initialPositionKnown,
+ positionDataState: feed.positionDataState, positionEntry: feed.positionEntry, messageWindow: feed.messageWindow,
hasMore: feed.hasMoreOlder, hasMoreNewer: feed.hasMoreNewer,
historyStartKnown: feed.historyStartKnown,
initialPositionMessageId: feed.initialPositionMessageId,
@@ -369,6 +370,62 @@ describe("conversation entry return during accepted reading", () => {
return { view, root, visible, get latest() { return latest } }
}
+ it.each([30, 42])("reveals cached reading at %s through a slow real entry without granting reads or following late NEW", async readSeq => {
+ const owner = await readingOwner()
+ const held = deferred<ReturnType<typeof fixture>>()
+ const fresh = fixture()
+ fresh.messages = Array.from({ length: 45 }, (_, index) => ({ ...fresh.messages[0],
+ id: `m${index + 1}`, seq: index + 1,
+ createdAt: new Date(Date.UTC(2026, 9, 1, 0, 0, index + 1)).toISOString(),
+ }))
+ const readState = { channelId: "c1", lastReadMessageId: `m${readSeq}`, lastReadSeq: readSeq, lastReadAt: fresh.messages[readSeq - 1].createdAt }
+ fresh.readState = readState
+ fresh.readStateRevision = 5
+ fresh.selection = { reason: "read_pointer", anchorMessageId: `m${readSeq}` }
+ fresh.page = { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 45 }
+ await act(async () => {
+ ingestReadStateSnapshot(owner.registry, { revision: 5, readStates: [readState] })
+ publishAccountAttentionSnapshot(owner.client, {
+ snapshot: { scopes: [{ scopeId: "c1", channelId: "c1", serverId: "s1",
+ ordinaryUnread: true, lastUnreadSeq: 45, lastAttentionSeq: null, attentionCount: 0 }], items: [], limit: 100, truncated: false,
+ included: { servers: [], channels: [], dms: [], profiles: [], messages: [] } },
+ proof: { token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined },
+ })
+ })
+ const oldLoad = load.getMockImplementation()!
+ load.mockImplementation((url: string, options: unknown) => url.includes("/messages") ? held.promise : oldLoad(url, options))
+ const view = mountReadingEntry(owner)
+ try {
+ await act(async () => vi.advanceTimersByTimeAsync(0))
+ resize()
+ expect(view.latest.feed.readSnapshotFetching).toBe(true)
+ expect(view.latest.feed.initialPositionKnown).toBe(true)
+ expect(view.latest.controller.initialPosition.contentVisible).toBe(true)
+ expect(view.latest.controller.readPositionReady).toBe(false)
+ expect(view.latest.controller.paginationEnabled).toBe(false)
+ const anchor = [...view.root.querySelectorAll<HTMLElement>("[data-msg-id]")]
+ .find(row => row.getBoundingClientRect().bottom > 0)!
+ const before = anchor.getBoundingClientRect().top
+ const id = anchor.dataset.msgId!
+ await act(async () => vi.advanceTimersByTimeAsync(6500))
+ resize()
+ expect(view.latest.controller.initialPosition.contentVisible).toBe(true)
+ expect(load.mock.calls.some(([url, options]) => url === "/api/community/channels/c1/read" && options?.method === "PUT")).toBe(false)
+ await act(async () => held.resolve(fresh))
+ await act(async () => vi.advanceTimersByTimeAsync(0))
+ resize()
+ expect(view.root.querySelector<HTMLElement>(`[data-msg-id="${id}"]`)!.getBoundingClientRect().top).toBeCloseTo(before, 0)
+ expect(view.latest.feed.readSnapshot?.lastReadSeq).toBe(readSeq)
+ expect(view.latest.newDividerBefore).toBe(`m${readSeq + 1}`)
+ expect(view.latest.controller.initialPosition.contentVisible).toBe(true)
+ } finally {
+ view.view.unmount()
+ held.resolve(fresh)
+ releaseReadSurface(owner.lease)
+ await owner.finish()
+ }
+ })
+
it.each(["before PUT confirmation", "after PUT before canonical publication", "after ACK and failed canonical readback"] as const)(
"keeps accepted local reading in the returned viewport %s without confirming the entry snapshot", async boundary => {
const owner = await readingOwner()
diff --git a/src/web/src/hooks/community/use-messages.return-window.dom.test.tsx b/src/web/src/hooks/community/use-messages.return-window.dom.test.tsx
index 546bafb88..1a087e778 100644
--- a/src/web/src/hooks/community/use-messages.return-window.dom.test.tsx
+++ b/src/web/src/hooks/community/use-messages.return-window.dom.test.tsx
@@ -62,6 +62,18 @@ async function holdSelectedWindowRepair() {
}
describe("returned entry and selected message window", () => {
+ it("qualifies complete cached rows for positioning while the selected window repair is pending", async () => {
+ const { hook, late, fresh } = await holdSelectedWindowRepair()
+ try {
+ expect(hook.result.current.readSnapshotFetching).toBe(true)
+ expect(hook.result.current.positionDataState).toBe("pending")
+ expect(hook.result.current.initialPositionKnown).toBe(true)
+ expect(hook.result.current.messages.map(message => message.id)).toEqual(["m1"])
+ await act(async () => late.resolve({ messages: fresh.messages, latestSeq: 2, hasMoreNewer: false }))
+ await waitFor(() => expect(hook.result.current.positionDataState).toBe("ready"))
+ } finally { hook.unmount() }
+ })
+
it.each(["different-key newest", "same-key anchor"] as const)("publishes the new entry into the actual feed after %s return", async kind => {
const { wrapper, client, registry } = await setup()
const old = fixture()
diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.ts
index c65dea06a..009619a3a 100644
--- a/src/web/src/hooks/community/use-messages.ts
+++ b/src/web/src/hooks/community/use-messages.ts
@@ -245,7 +245,7 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefi
anchorReconciled: !!selectedWindow,
navigationBlocked: !entry.canRead,
readSnapshot: entry.snapshot, readSnapshotFetching,
- initialPositionKnown: !!selectedWindow && entry.snapshot !== null && !loading && !readSnapshotFetching,
+ initialPositionKnown: windowAvailable && entry.snapshot !== null && !loading && !missingCanonical && !initialLoadError && !retrySelection.pending,
initialPositionMessageId: entry.initialPositionMessageId, positionEntry, positionDataState, messageWindow: query.data,
retryInitialLoad, retryingInitialLoad: entry.isFetching || query.isFetching,
entryCanRead: entry.canRead, entryDenied: entry.denied, entryAnchorMissing: entry.anchorMissing,
diff --git a/src/web/src/hooks/community/use-scroll-anchor.lifecycle.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.lifecycle.dom.test.ts
index 132fa867f..a3a47d327 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.lifecycle.dom.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.lifecycle.dom.test.ts
@@ -111,6 +111,120 @@ describe("qualified positioning lifecycle", () => {
expect(positioned).toHaveBeenCalledTimes(target === "target" ? 1 : 0)
})
+ it.each((["local", "unread", "tail"] as const).flatMap(target => [false, true].flatMap(strict =>
+ [320, 1280].map(width => [target, strict, width] as const))))("finishes cached %s positioning with StrictMode=%s at %spx while reads remain pending and retains it through late NEW", (target, strict, width) => {
+ scrollFixture.width = width
+ const settled = vi.fn()
+ const items = Array.from({ length: 14 }, (_, i) => ({ ...message(`m${i}`), newDivider: i === 5 }))
+ const h = mount({ items, positionDataState: "pending", initialScrollReady: true,
+ ...(target === "local" ? { initialPositionMessageId: "m4" } : target === "unread" ? { newDividerBefore: "m5" } : {}),
+ onInitialPositionSettled: settled,
+ }, strict)
+ expect(settled).toHaveBeenCalledOnce()
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ expect(scrollFixture.latest.paginationEnabled).toBe(false)
+ const targetId = target === "local" ? "m4" : target === "unread" ? "m5" : "m13"
+ expect(bodyTop(h.root, targetId)).toBeGreaterThan(0)
+ expect(bodyTop(h.root, targetId)).toBeLessThan(h.root.clientHeight)
+ const anchor = [...h.root.querySelectorAll<HTMLElement>("[data-msg-id]")]
+ .find(row => row.getBoundingClientRect().bottom > 0)!.dataset.msgId!
+ const before = bodyTop(h.root, anchor)
+ const native = scrollFixture.latest.virtualizer
+ const end = vi.spyOn(native, "scrollToEnd"), index = vi.spyOn(native, "scrollToIndex")
+ act(() => vi.advanceTimersByTime(6500))
+ h.update({ items: [...items.map(item => ({ ...item, newDivider: false })),
+ { ...message("m14"), newDivider: true }, message("m15")], newDividerBefore: "m14" })
+ expect(bodyTop(h.root, anchor)).toBeCloseTo(before, 0)
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ h.update({ positionDataState: "ready" })
+ expect(bodyTop(h.root, anchor)).toBeCloseTo(before, 0)
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ expect(scrollFixture.latest.paginationEnabled).toBe(true)
+ expect(end).not.toHaveBeenCalled()
+ expect(index).not.toHaveBeenCalled()
+ expect(settled).toHaveBeenCalledOnce()
+ })
+
+ it("withdraws reading during a new data wait without restarting settled cached positioning", () => {
+ const settled = vi.fn()
+ const h = mount({ initialPositionMessageId: "m5", onInitialPositionSettled: settled })
+ const before = bodyTop(h.root, "m5")
+ const index = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToIndex")
+ h.update({ positionDataState: "pending" })
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ expect(scrollFixture.latest.paginationEnabled).toBe(false)
+ act(() => vi.advanceTimersByTime(6500))
+ h.update({ positionDataState: "ready", newDividerBefore: "m10" })
+ expect(bodyTop(h.root, "m5")).toBeCloseTo(before, 0)
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ expect(index).not.toHaveBeenCalled()
+ expect(settled).toHaveBeenCalledOnce()
+ })
+
+ it("does not accept layout while local row qualification is withdrawn", () => {
+ scrollFixture.height = 0
+ const settled = vi.fn()
+ const h = mount({ initialPositionMessageId: "m5", onInitialPositionSettled: settled }, false, undefined, undefined, 0)
+ h.stage({ initialScrollReady: false, positionDataState: "pending" })
+ scrollFixture.height = 500
+ resize()
+ expect(settled).not.toHaveBeenCalled()
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ h.update({ initialScrollReady: true })
+ expect(settled).toHaveBeenCalledOnce()
+ expect(bodyTop(h.root, "m5")).toBeGreaterThan(0)
+ expect(bodyTop(h.root, "m5")).toBeLessThan(h.root.clientHeight)
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ h.update({ positionDataState: "ready" })
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ })
+
+ it("degrades a cached zero-size layout on the geometry deadline without claiming success or reviving", () => {
+ scrollFixture.height = 0
+ const settled = vi.fn()
+ const h = mount({ initialScrollReady: true, positionDataState: "pending", onInitialPositionSettled: settled }, false, undefined, undefined, 0)
+ runFrames(320)
+ expect(settled).toHaveBeenCalledOnce()
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")
+ scrollFixture.height = 500
+ h.update({ positionDataState: "ready" })
+ expect(end).not.toHaveBeenCalled()
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ expect(h.root.scrollTop).toBe(0)
+ })
+
+ it("keeps only the original remaining layout budget when read state becomes pending", () => {
+ scrollFixture.height = 0
+ const settled = vi.fn()
+ const h = mount({ onInitialPositionSettled: settled }, false, undefined, undefined, 0)
+ act(() => vi.advanceTimersByTime(4800))
+ h.stage({ positionDataState: "pending" })
+ scrollFixture.height = 500
+ resize(0)
+ vi.spyOn(h.root, "scrollTo").mockImplementation(() => {})
+ runFrames(1)
+ act(() => vi.advanceTimersByTime(184))
+ expect(settled).toHaveBeenCalledOnce()
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ h.update({ positionDataState: "ready" })
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ })
+
+ it("leaves the visible cached fallback when its initial local target is absent and the budget expires", () => {
+ const settled = vi.fn()
+ const h = mount({ initialPositionMessageId: "missing", positionDataState: "pending", onInitialPositionSettled: settled })
+ const before = bodyTop(h.root, "m0")
+ act(() => vi.advanceTimersByTime(5000))
+ expect(settled).toHaveBeenCalledOnce()
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ const index = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToIndex")
+ h.update({ positionDataState: "ready", items: [...h.input.items, message("missing")] })
+ expect(index).not.toHaveBeenCalled()
+ expect(bodyTop(h.root, "m0")).toBe(before)
+ expect(scrollFixture.latest.readPositionReady).toBe(false)
+ })
+
it("keeps precommit user takeover after data and route commit arrive", () => {
const settled = vi.fn()
const h = mount({ active: false, positioningActive: true, initialScrollReady: false,
diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.ts
index 034755b60..40f0b6fd5 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.ts
@@ -150,7 +150,7 @@ export function useScrollAnchor({
const visible = positioningActive && documentVisible
const entryActivationRef = useRef({ entry: positionEntry, seen: visible })
const dataState = positionDataState ?? (initialScrollReady ? items.some(item => item.kind === "message") ? "ready" : "empty" : "pending")
- const contextRef = useRef({ dataState, messageWindow, isFetchingOlder, isFetchingNewer, visible })
+ const contextRef = useRef({ dataState, initialScrollReady, messageWindow, isFetchingOlder, isFetchingNewer, visible })
const [requestRevision, setRequestRevision] = useState(0)
const [committedEntry, setCommittedEntry] = useState(positionEntry)
const entryChanged = committedEntry !== positionEntry
@@ -202,7 +202,7 @@ export function useScrollAnchor({
onTargetPositionedRef.current = onScrollTargetPositioned
onTargetCancelledRef.current = onScrollTargetCancelled
settleCallbackRef.current = onInitialPositionSettled
- contextRef.current = { dataState, messageWindow, isFetchingOlder, isFetchingNewer, visible }
+ contextRef.current = { dataState, initialScrollReady, messageWindow, isFetchingOlder, isFetchingNewer, visible }
}, [items, positionEntry, initialScrollReady, onScrollTargetPositioned, onScrollTargetCancelled, onInitialPositionSettled, dataState, messageWindow, isFetchingOlder, isFetchingNewer, visible])
const followSuspension = useCreateAtom(false)
const [followSuspended, setFollowSuspended] = useAtom(followSuspension)
@@ -281,7 +281,8 @@ export function useScrollAnchor({
scheduleGeometryRef.current()
}, [claimPosition, positionKind, readReady, retireInitialPosition, setReadPositionReady, settlePresentation])
const armBudget = useCallback(() => {
- if (!positionOwnerRef.current.active || !contextRef.current.visible || contextRef.current.dataState === "pending") return
+ if (!positionOwnerRef.current.active || !contextRef.current.visible
+ || (positionKind.get() === "initial" ? !contextRef.current.initialScrollReady : contextRef.current.dataState === "pending")) return
if (initialDeadlineRef.current?.handle) return
const epoch = positionOwnerRef.current.epoch
const at = initialDeadlineRef.current?.at ?? Date.now() + INITIAL_POSITION_TIMEOUT_MS
@@ -290,7 +291,7 @@ export function useScrollAnchor({
releasePosition()
}, Math.max(0, at - Date.now()))
initialDeadlineRef.current = { handle, at }
- }, [releasePosition])
+ }, [positionKind, releasePosition])
const readPageMessageGeometry = useCallback((key: string): { viewportOffset: number; bodyInset: number } | null => {
@@ -352,7 +353,7 @@ export function useScrollAnchor({
scrollPaddingStart: scrollPaddingStartRef.current,
anchorTo: !entryChanged && ownerKind === "idle" && !awaitingTarget && !pendingLocalSubmit
&& (paginationDirection !== null || (readPositionReady && (nativeOriginKey === null || nativeOriginKey !== items[0]?.key))) ? "end" : "start",
- followOnAppend: visible && !entryChanged && ownerKind === "idle" && readPositionReady && !awaitingTarget
+ followOnAppend: visible && !entryChanged && ownerKind === "idle" && readPositionReady && dataState === "ready" && !awaitingTarget
&& !pendingLocalSubmit && !followSuspended && !hasMoreNewer
&& !isFetchingOlder && !isFetchingNewer && paginationDirection === null
&& (nativeOriginKey === null || nativeOriginKey !== items[0]?.key) ? "auto" : false,
@@ -420,6 +421,7 @@ export function useScrollAnchor({
const root = scrollRef.current
const native = virtualizerRef.current
if (!intent || intent.epoch !== owner.epoch || !root || !native) return
+ if (positionKind.get() === "initial" && !contextRef.current.initialScrollReady) return
const pendingEnd = intent.pendingInitialEnd
if (pendingEnd) {
const deadline = initialDeadlineRef.current
@@ -490,6 +492,8 @@ export function useScrollAnchor({
}
}
if (landed) {
+ const initial = positionKind.get() === "initial"
+ if (initial && contextRef.current.dataState === "pending") setFollowSuspended(true)
const geometry = readGeometry()
if (!geometry) {
initialSettleFrameRef.current = window.requestAnimationFrame(settle)
@@ -497,7 +501,7 @@ export function useScrollAnchor({
}
if (intent.type !== "end" && root.scrollTop <= 1) holdNativeOrigin(currentItemsRef.current[0]?.key ?? null)
settlePresentation()
- if (contextRef.current.dataState === "pending") return
+ if (!initial && contextRef.current.dataState === "pending") return
acceptedGeometryRef.current = geometry
semanticIntentRef.current = null
setOwnerKind("idle")
@@ -515,7 +519,7 @@ export function useScrollAnchor({
initialSettleFrameRef.current = window.requestAnimationFrame(settle)
}
initialSettleFrameRef.current = window.requestAnimationFrame(settle)
- }, [clearBudget, holdNativeOrigin, readGeometry, releasePosition, retireInitialPosition, setOwnerKind, setReadPositionReady, settlePresentation])
+ }, [clearBudget, holdNativeOrigin, positionKind, readGeometry, releasePosition, retireInitialPosition, setFollowSuspended, setOwnerKind, setReadPositionReady, settlePresentation])
const onRowsLayoutCommit = useCallback((layout: VirtualRowsLayoutSnapshot | null) => {
committedRowsRef.current = layout ? { layout, native: virtualizer, entry: positionEntry, items } : null
@@ -530,7 +534,7 @@ export function useScrollAnchor({
: findMessageIndex(currentItemsRef.current, id) : null
semanticIntentRef.current = {
epoch: owner.epoch, type, id, index, behavior, notifyTarget, loadedTailPresent,
- awaitingData: contextRef.current.dataState === "pending",
+ awaitingData: positionKind.get() === "initial" ? !contextRef.current.initialScrollReady : contextRef.current.dataState === "pending",
viewport: { width: scrollRef.current?.clientWidth ?? 0, height: scrollRef.current?.clientHeight ?? 0 },
pendingInitialEnd: type === "end" && positionKind.get() === "initial" && !loadedTailPresent && !initialEndIssuedRef.current
? { root: scrollRef.current, scrollTop: scrollRef.current?.scrollTop ?? 0 } : null,
@@ -635,8 +639,10 @@ export function useScrollAnchor({
useLayoutEffect(() => {
const intent = semanticIntentRef.current
- if (visible && dataState === "ready" && intent?.awaitingData) startIntent(intent.type, intent.id, intent.behavior, intent.notifyTarget, intent.loadedTailPresent)
- }, [dataState, startIntent, visible])
+ if (visible && intent?.awaitingData && (positionKind.get() === "initial" ? initialScrollReady : dataState === "ready")) {
+ startIntent(intent.type, intent.id, intent.behavior, intent.notifyTarget, intent.loadedTailPresent)
+ }
+ }, [dataState, initialScrollReady, positionKind, startIntent, visible])
useLayoutEffect(() => {
if (!visible || dataState !== "ready") return
@@ -1087,14 +1093,14 @@ export function useScrollAnchor({
if (dataState === "empty") setReadPositionReady(true)
return
}
- if (dataState === "pending") return
+ if (dataState === "pending" && !initialScrollReady) return
if (positionKind.get() !== "initial" || initialRetiredRef.current || !hasMessages) return
armBudget()
if (!entryResolvedRef.current) {
entryResolvedRef.current = true
startIntent(initialPositionMessageId ? "target" : newDividerBefore ? "unread" : "end", initialPositionMessageId ?? newDividerBefore ?? null)
} else scheduleInitialPositionSettled()
- }, [armBudget, dataState, hasMessages, initialPositionMessageId, items, newDividerBefore, positionEntry, positionKind, releasePosition, scheduleInitialPositionSettled, setReadPositionReady, startIntent, virtualItems, visible])
+ }, [armBudget, dataState, hasMessages, initialPositionMessageId, initialScrollReady, items, newDividerBefore, positionEntry, positionKind, releasePosition, scheduleInitialPositionSettled, setReadPositionReady, startIntent, virtualItems, visible])
const scrollToBottom = useCallback(() => {
if (!positionOwnerRef.current.active || !contextRef.current.visible) return
@@ -1120,7 +1126,7 @@ export function useScrollAnchor({
const pageReceipt = paginationRef.current?.receipt
const paginationRequestPending = !!pageReceipt && (!pageReceipt.result || pageReceipt.result.status === "success" && messageWindow !== pageReceipt.result.window)
return {
- scrollRef, virtualizer, onRowsLayoutCommit, readPositionReady: active && visible && resumeValidated && !entryChanged && readPositionReady, paginationEnabled: active && visible && dataState !== "pending" && dataState !== "error" && !entryChanged && ownerKind === "idle" && !awaitingTarget, belowCount,
+ scrollRef, virtualizer, onRowsLayoutCommit, readPositionReady: active && visible && dataState !== "pending" && dataState !== "error" && resumeValidated && !entryChanged && readPositionReady, paginationEnabled: active && visible && dataState !== "pending" && dataState !== "error" && !entryChanged && ownerKind === "idle" && !awaitingTarget, belowCount,
paginationRequestPending,
scrollToBottom, requestPresentPosition, jumpTo,
captureOlderPageAnchor, captureNewerPageAnchor,
diff --git a/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts b/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts
index 01ba02a30..d85818747 100644
--- a/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts
+++ b/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts
@@ -1,6 +1,9 @@
import { test, expect } from "./_fixtures/case-fixture"
import { composerEditable, expectMessageVisible, gotoAfterUserWsAuth, sendMessage } from "./_fixtures/actions"
-import type { Frame, Request } from "@playwright/test"
+import type { Frame, Page, Request, Response as PlaywrightResponse } from "@playwright/test"
+import { COMMUNITY_CONTRACT_VERSION, CommunityMessageResourceSchema, requestedCommunityContract } from "@alook/shared"
+import { decodeCommunityReadResponse } from "@/lib/community/read-response"
+import type { MessagesPage } from "@/lib/community/models/message"
import {
communityFrameEvents,
@@ -17,6 +20,42 @@ function messageFrame(frame: CapturedCommunityFrame, channelId: string, content:
&& event.message?.content?.includes(content))
}
+function captureMessageRepairs(page: Page, channelId: string) {
+ const responses: PlaywrightResponse[] = []
+ page.on("response", (response) => {
+ const url = new URL(response.url())
+ if (response.request().method() === "GET" && url.pathname === `/api/community/channels/${channelId}/messages`
+ && !url.searchParams.has("entry")) responses.push(response)
+ })
+ return responses
+}
+
+async function decodedResponse(response: PlaywrightResponse) {
+ expect(response.status()).toBe(200)
+ const request = response.request()
+ const url = new URL(response.url())
+ return decodeCommunityReadResponse(`${url.pathname}${url.search}`, request.method(),
+ new Response(null, { headers: response.headers() }), await response.json(),
+ requestedCommunityContract(new Headers(request.headers())) ?? COMMUNITY_CONTRACT_VERSION)
+}
+
+async function expectRepairedMessage(responses: PlaywrightResponse[], channelId: string, content: string) {
+ expect(responses.some((response) => new URL(response.url()).search === "")).toBe(true)
+ const pages = await Promise.all(responses.map(async (response) => ({
+ url: new URL(response.url()), page: await decodedResponse(response) as MessagesPage,
+ })))
+ const supplied = pages.find(({ page }) => page.messages.some((message) => message.content?.includes(content)))
+ expect(supplied, "repair response must supply the missing full message").toBeDefined()
+ const message = CommunityMessageResourceSchema.strip().parse(supplied!.page.messages.find((row) => row.content?.includes(content)))
+ expect(message.channelId).toBe(channelId)
+ expect(message.seq).toBe(2)
+ expect(Number.isFinite(Date.parse(message.createdAt))).toBe(true)
+ expect(supplied!.page.latestSeq).toBeGreaterThanOrEqual(message.seq)
+ const since = supplied!.url.searchParams.get("since")
+ if (since) expect(`${message.createdAt}|${message.id}` > since).toBe(true)
+ return message
+}
+
test.describe("committed message delivery QA", () => {
test("Q4: a readable nonparticipant gets child content and parent projection without notifications", async ({ caseActors }) => {
const actors = await caseActors(["alice", "bob", "carol"])
@@ -88,18 +127,12 @@ test.describe("committed message delivery QA", () => {
}
return "forward"
} })
- const gapRequests: string[] = []
- bob.page.on("request", (request) => {
- const url = new URL(request.url())
- if (url.pathname === `/api/community/channels/${channelId}/messages` && url.searchParams.has("since")) {
- gapRequests.push(url.toString())
- }
- })
await gotoAfterUserWsAuth(bob.page, `/c/channels/${serverId}/${channelId}`)
await expect(composerEditable(bob.page)).toBeVisible()
const alice = await asUser("alice")
await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${channelId}`)
+ const repairResponses = captureMessageRepairs(bob.page, channelId)
armed = true
const editable = composerEditable(alice.page)
await editable.click()
@@ -112,12 +145,14 @@ test.describe("committed message delivery QA", () => {
await expectMessageVisible(bob.page, missing)
await expectMessageVisible(bob.page, later)
- expect(gapRequests.length).toBeGreaterThan(0)
+ const repaired = await expectRepairedMessage(repairResponses, channelId, missing)
expect(proxy.heldCount()).toBe(1)
const heldBatch = proxy.frames.find((frame) => messageFrame(frame, channelId, missing))
expect(heldBatch?.type).toBe("community:events.batch.v2")
expect(communityFrameEvents(heldBatch!).some((event) =>
event.type === "community:mention.create")).toBe(true)
+ expect(communityFrameEvents(heldBatch!).find((event) => event.type === "community:message.create")?.message)
+ .toMatchObject({ id: repaired.id, seq: repaired.seq })
expect(proxy.releaseHeld((frame) => messageFrame(frame, channelId, missing))).toBe(1)
await bob.page.evaluate(() => new Promise<void>((resolve) => {
requestAnimationFrame(() => requestAnimationFrame(() => resolve()))
@@ -151,7 +186,7 @@ test.describe("committed message delivery QA", () => {
let dropped = false
const missing = `missing dm ${Date.now()}`
const later = `later dm ${Date.now()}`
- await proxyCommunityWebSockets(bob.context, { decide: (frame) => {
+ const proxy = await proxyCommunityWebSockets(bob.context, { decide: (frame) => {
if (armed && !dropped && frame.type === "community:message.create" && frame.channelId === dmId) {
dropped = true
return "drop"
@@ -162,18 +197,17 @@ test.describe("committed message delivery QA", () => {
}
return "forward"
} })
- const gapRequests: string[] = []
- bob.page.on("request", (request) => {
- const url = new URL(request.url())
- if (url.pathname === `/api/community/channels/${dmId}/messages` && url.searchParams.has("since")) {
- gapRequests.push(url.toString())
- }
- })
await gotoAfterUserWsAuth(bob.page, `/c/me/${dmId}`)
await expect(composerEditable(bob.page)).toBeVisible()
const alice = await asUser("alice")
await gotoAfterUserWsAuth(alice.page, `/c/me/${dmId}`)
+ const repairResponses = captureMessageRepairs(bob.page, dmId)
+ const readResponses: PlaywrightResponse[] = []
+ bob.page.on("response", (response) => {
+ if (response.request().method() === "PUT" && response.status() === 200
+ && new URL(response.url()).pathname === `/api/community/channels/${dmId}/read`) readResponses.push(response)
+ })
armed = true
await sendMessage(alice.page, missing)
await expect.poll(() => dropped, { timeout: 20_000 }).toBe(true)
@@ -181,7 +215,19 @@ test.describe("committed message delivery QA", () => {
await expectMessageVisible(bob.page, missing)
await expectMessageVisible(bob.page, later)
- expect(gapRequests.length).toBeGreaterThan(0)
+ const repaired = await expectRepairedMessage(repairResponses, dmId, missing)
+ const missingFrame = proxy.frames.find((frame) => messageFrame(frame, dmId, missing))!
+ expect(communityFrameEvents(missingFrame).find((event) => event.type === "community:message.create")?.message)
+ .toMatchObject({ id: repaired.id, seq: repaired.seq })
+ await expect(bob.page.getByTestId(tid.message(repaired.id))).toHaveCount(1)
+ await expect(bob.page.getByText(later, { exact: false })).toHaveCount(1)
+ const tail = proxy.frames.flatMap(communityFrameEvents).find((event) => event.type === "community:message.create"
+ && event.channelId === dmId && event.message?.content?.includes(later))?.message
+ expect(tail?.seq).toBe(3)
+ await expect.poll(async () => {
+ const reads = await Promise.all(readResponses.map(async (response) => await decodedResponse(response) as { targetSeq: number }))
+ return reads.some((read) => read.targetSeq === tail!.seq)
+ }, { timeout: 20_000 }).toBe(true)
})
test("Q8: capable duplicate suppression ends safely at full reload", async ({ caseActors }) => {