Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): open conversations at latest and jump to New (#1187)

Generc0da9081848d
diff --git a/src/shared/src/business-schema-version.ts b/src/shared/src/business-schema-version.ts
index 427ba71c8..113fbf41f 100644
--- a/src/shared/src/business-schema-version.ts
+++ b/src/shared/src/business-schema-version.ts
@@ -1 +1 @@
-export const BUSINESS_SCHEMA_VERSION = 9 as const
+export const BUSINESS_SCHEMA_VERSION = 10 as const
diff --git a/src/shared/src/community-resources.ts b/src/shared/src/community-resources.ts
index 0dcd932ae..f63764021 100644
--- a/src/shared/src/community-resources.ts
+++ b/src/shared/src/community-resources.ts
@@ -119,6 +119,10 @@ export const CommunityMessageResourceSchema = z.strictObject({
botCreation: BotCreationPayloadSchema.optional(),
})
+const CommunityMessagePositionSchema = CommunityMessageResourceSchema.pick({
+ id: true, channelId: true, seq: true, authorId: true,
+})
+
export function communityMessageProfileIds(messages: readonly Pick<CommunityMessageResource, "authorId" | "replyTo">[]) {
return [...new Set(messages.flatMap(message => [message.authorId, ...(message.replyTo?.authorId && message.replyTo.deleted !== true ? [message.replyTo.authorId] : [])]))]
}
@@ -208,6 +212,10 @@ export const CommunityConversationEntryReadSchema = CommunityMessagesReadSchema.
access: CommunityAccessDecisionSchema.extend({ canRead: z.literal(true) }),
readState: CommunityReadStateResourceSchema,
readStateRevision: z.number().int().nonnegative(),
+ newBoundary: z.strictObject({
+ afterSeq: CommunityReadStateResourceSchema.shape.lastReadSeq,
+ target: CommunityMessagePositionSchema.nullable(),
+ }),
forumFeed: z.lazy(() => CommunityThreadsReadSchema).optional(),
opener: CommunityMessageResourceSchema.optional(),
parent: CommunityChannelResourceSchema.optional(),
@@ -216,6 +224,18 @@ export const CommunityConversationEntryReadSchema = CommunityMessagesReadSchema.
anchorMessageId: nullableId,
}),
}).superRefine((entry, ctx) => {
+ if (entry.newBoundary.afterSeq > Math.max(entry.readState.lastReadSeq, entry.page.latestSeq)) {
+ ctx.addIssue({ code: "custom", path: ["newBoundary"], message: "Conversation New snapshot mismatch" })
+ }
+ if (entry.newBoundary.target) {
+ const target = entry.newBoundary.target
+ const message = entry.messages.find(message => message.id === target.id)
+ if (entry.channel.type === "forum" || target.channelId !== entry.channelId || target.authorId === entry.viewerId
+ || target.seq <= entry.newBoundary.afterSeq || target.seq > entry.page.latestSeq
+ || message && (message.seq !== target.seq || message.authorId !== target.authorId)) {
+ ctx.addIssue({ code: "custom", path: ["newBoundary", "target"], message: "Conversation New target mismatch" })
+ }
+ }
for (const [path, channelId] of [
[["channel", "id"], entry.channel.id],
[["access", "channelId"], entry.access.channelId],
@@ -281,6 +301,7 @@ export type CommunityCategoryResource = z.infer<typeof CommunityCategoryResource
export type CommunityChannelResource = z.infer<typeof CommunityChannelResourceSchema>
export type CommunityChannelIdentity = z.infer<typeof CommunityChannelIdentitySchema>
export type CommunityMessageResource = z.infer<typeof CommunityMessageResourceSchema>
+export type CommunityMessagePosition = z.infer<typeof CommunityMessagePositionSchema>
export type CommunityMemberRelation = z.infer<typeof CommunityMemberRelationSchema>
export type CommunityReadStateResource = z.infer<typeof CommunityReadStateResourceSchema>
export type CommunityAccessDecision = z.infer<typeof CommunityAccessDecisionSchema>
diff --git a/src/shared/src/db/queries/community/message.ts b/src/shared/src/db/queries/community/message.ts
index 0d8cf12a0..09ad4e6cd 100644
--- a/src/shared/src/db/queries/community/message.ts
+++ b/src/shared/src/db/queries/community/message.ts
@@ -1,4 +1,4 @@
-import { eq, and, asc, desc, exists, gt, lt, or, sql, inArray, count, min, type SQL, type GetColumnData } from "drizzle-orm";
+import { eq, ne, and, asc, desc, exists, gt, lt, lte, or, sql, inArray, count, min, type SQL, type GetColumnData } from "drizzle-orm";
import {
communityMessage,
communityChannel,
@@ -14,6 +14,7 @@ import {
import { user } from "../../schema";
import { nanoid } from "nanoid";
import type { Database } from "../../index";
+import type { CommunityMessagePosition } from "../../../community-resources";
import { attachmentReadableSql } from "./attachment";
import { MAX_ATTACHMENTS_PER_MESSAGE } from "../../../constants/community";
import { createLogger } from "../../../logger";
@@ -1000,6 +1001,24 @@ export async function getMessageByChannelAndSeq(
return rows[0] ?? null;
}
+export async function getFirstPeerMessageAfterSeq(
+ db: Database,
+ target: { channelId: string; viewerId: string; afterSeq: number; throughSeq: number },
+): Promise<CommunityMessagePosition | null> {
+ const rows = await db
+ .select({ id: communityMessage.id, channelId: communityMessage.channelId, seq: communityMessage.seq, authorId: communityMessage.authorId })
+ .from(communityMessage)
+ .where(and(
+ eq(communityMessage.channelId, target.channelId),
+ ne(communityMessage.authorId, target.viewerId),
+ gt(communityMessage.seq, target.afterSeq),
+ lte(communityMessage.seq, target.throughSeq),
+ ))
+ .orderBy(asc(communityMessage.seq))
+ .limit(1);
+ return rows[0] ?? null;
+}
+
/**
* Channel-scoped identity lookup for operations that address a message but do
* not project it. In particular, blocked-DM mark cleanup must not hydrate
diff --git a/src/shared/test/community-resources.contract.test.ts b/src/shared/test/community-resources.contract.test.ts
index 53c8c4e18..7f79005bc 100644
--- a/src/shared/test/community-resources.contract.test.ts
+++ b/src/shared/test/community-resources.contract.test.ts
@@ -8,7 +8,7 @@ describe("current community resources", () => {
it("accepts only the exact current read contract", () => {
const body = { contractVersion: BUSINESS_SCHEMA_VERSION, channelId: "channel", changed: true, targetSeq: 7, revision: 9 }
expect(communityReadSchemas().readAdvance.parse(body)).toEqual(body)
- for (const version of [undefined, 1, 2, 3, BUSINESS_SCHEMA_VERSION + 1]) {
+ for (const version of [undefined, 1, 2, 3, BUSINESS_SCHEMA_VERSION - 1, BUSINESS_SCHEMA_VERSION + 1]) {
expect(() => communityReadSchemas(version === undefined ? 0 : version)).toThrow("protocol mismatch")
expect(communityReadSchemas().readAdvance.safeParse({ ...body, contractVersion: version }).success).toBe(false)
}
@@ -62,7 +62,7 @@ describe("conversation entry resource", () => {
messages: [], profiles: [],
page: { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 0 },
surfaceReceipt: { channelId: communityResourceChannelFixture.id, surfaceKind: "channel" },
- readStateRevision: 0, selection: { reason: "tail", anchorMessageId: null },
+ readStateRevision: 0, newBoundary: { afterSeq: 0, target: null }, selection: { reason: "tail", anchorMessageId: null },
})
@@ -109,6 +109,29 @@ describe("conversation entry resource", () => {
expect(communityReadSchemas().messages.safeParse(value).success).toBe(false)
})
+ it("qualifies the exact New boundary independently of a later read ACK", () => {
+ const target = { id: "unloaded", channelId: communityResourceChannelFixture.id, seq: 9, authorId: communityResourceMessageFixture.message.authorId }
+ const value = { ...entry(), readState: { ...entry().readState, lastReadSeq: 20 },
+ page: { ...entry().page, latestSeq: 30 }, newBoundary: { afterSeq: 5, target } }
+ expect(CommunityConversationEntryReadSchema.parse(value).newBoundary).toEqual(value.newBoundary)
+ expect(CommunityConversationEntryReadSchema.parse({ ...value, newBoundary: { afterSeq: 5, target: null } }).newBoundary.target).toBeNull()
+ for (const newBoundary of [undefined, { afterSeq: 31, target: null },
+ { afterSeq: 5, target: undefined },
+ ...[{ ...target, channelId: "foreign" }, { ...target, authorId: "viewer" },
+ { ...target, seq: 5 }, { ...target, seq: 31 }, { ...target, authorId: undefined }]
+ .map(target => ({ afterSeq: 5, target })),
+ ]) expect(CommunityConversationEntryReadSchema.safeParse({ ...value, newBoundary }).success).toBe(false)
+ const message = { ...communityResourceMessageFixture.message, id: target.id, channelId: value.channelId,
+ seq: target.seq, authorId: target.authorId }
+ const loaded = { ...value, messages: [message], profiles: communityResourceMessageFixture.profiles }
+ expect(CommunityConversationEntryReadSchema.parse(loaded).newBoundary).toEqual(value.newBoundary)
+ const mismatch = CommunityConversationEntryReadSchema.safeParse({ ...loaded, messages: [{ ...message, seq: 10 }] })
+ expect(mismatch.success).toBe(false)
+ if (!mismatch.success) expect(mismatch.error.issues.some(issue => issue.path[0] === "newBoundary")).toBe(true)
+ const forum = forumEntry()
+ expect(CommunityConversationEntryReadSchema.safeParse({ ...forum, page: value.page, newBoundary: { afterSeq: 0, target } }).success).toBe(false)
+ })
+
it.each(["channel", "access", "readState", "surfaceReceipt"] as const)("rejects a foreign %s in the entry", (field) => {
const value = entry()
const input = { ...value, [field]: { ...value[field], [field === "channel" ? "id" : "channelId"]: "foreign" } }
@@ -236,7 +259,7 @@ describe("complete message author dependency graphs", () => {
access: { channelId: channel.id, canRead: true, canSend: true, canCreateDiscussion: false },
readState: { channelId: channel.id, lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 },
messages: [], profiles: [author], page: { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 0 },
- surfaceReceipt: { channelId: channel.id, surfaceKind: "thread" }, readStateRevision: 0, selection: { reason: "tail", anchorMessageId: null } }
+ surfaceReceipt: { channelId: channel.id, surfaceKind: "thread" }, readStateRevision: 0, newBoundary: { afterSeq: 0, target: null }, selection: { reason: "tail", anchorMessageId: null } }
expect(CommunityConversationEntryReadSchema.parse(value)).toEqual(value)
const result = CommunityConversationEntryReadSchema.safeParse({ ...value, profiles: [] })
expect(result.success).toBe(false)
diff --git a/src/shared/test/queries/community-message-new-target-sqlite.test.ts b/src/shared/test/queries/community-message-new-target-sqlite.test.ts
new file mode 100644
index 000000000..ea5f07c74
--- /dev/null
+++ b/src/shared/test/queries/community-message-new-target-sqlite.test.ts
@@ -0,0 +1,26 @@
+import { afterEach, expect, it } from "vitest"
+import { communityWriteDb } from "../helpers/community-write-db"
+import { getFirstPeerMessageAfterSeq } from "../../src/db/queries/community/message"
+
+const stores: ReturnType<typeof communityWriteDb>[] = []
+afterEach(() => { for (const store of stores) store.sqlite.close(); stores.length = 0 })
+
+it("returns the first peer ID in the exact scoped sequence interval, with gaps and competing rows", async () => {
+ const store = communityWriteDb(); stores.push(store)
+ store.sqlite.exec("INSERT INTO community_channel (id,type,created_at) VALUES ('foreign','text','now'),('empty','text','now')")
+ const insert = store.sqlite.prepare("INSERT INTO community_message (id,author_id,content,type,channel_id,seq,created_at) VALUES (?,?,'body','default',?,?,'same-time')")
+ for (const [id, author, channel, seq] of [
+ ["later-peer", "peer", "channel", 15], ["legacy", "peer", "channel", 0],
+ ["already-read", "peer", "channel", 4], ["own", "author", "channel", 6],
+ ["foreign-peer", "peer", "foreign", 7], ["first-peer", "peer", "channel", 9],
+ ["later-own", "author", "channel", 12],
+ ] as const) insert.run(id, author, channel, seq)
+ const target = { channelId: "channel", viewerId: "author", afterSeq: 5, throughSeq: 20 }
+ await expect(getFirstPeerMessageAfterSeq(store.db, { ...target, afterSeq: 0, throughSeq: 5 })).resolves.toEqual({ id: "already-read", channelId: "channel", seq: 4, authorId: "peer" })
+ await expect(getFirstPeerMessageAfterSeq(store.db, target)).resolves.toEqual({ id: "first-peer", channelId: "channel", seq: 9, authorId: "peer" })
+ await expect(getFirstPeerMessageAfterSeq(store.db, { ...target, throughSeq: 8 })).resolves.toBeNull()
+ await expect(getFirstPeerMessageAfterSeq(store.db, { ...target, afterSeq: 9 })).resolves.toEqual({ id: "later-peer", channelId: "channel", seq: 15, authorId: "peer" })
+ await expect(getFirstPeerMessageAfterSeq(store.db, { ...target, channelId: "empty" })).resolves.toBeNull()
+ store.sqlite.prepare("DELETE FROM community_message WHERE id=?").run("first-peer")
+ await expect(getFirstPeerMessageAfterSeq(store.db, target)).resolves.toEqual({ id: "later-peer", channelId: "channel", seq: 15, authorId: "peer" })
+})
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
index ec6740fba..24a28b7dc 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/route.test.ts
@@ -29,6 +29,7 @@ const mockListMessages = vi.fn()
const mockListMessagesAround = vi.fn()
const mockListMessagesSince = vi.fn()
const mockGetLatestMessageSeq = vi.fn()
+const mockGetFirstPeerMessageAfterSeq = vi.fn<(...args: unknown[]) => Promise<null>>(async () => null)
const mockListByMessageIds = vi.fn()
const mockListReactionsByMessageIds = vi.fn()
const mockGetUserPublic = vi.fn()
@@ -109,6 +110,7 @@ vi.mock("@alook/shared", async () => {
listMessagesAround: (...a: unknown[]) => mockListMessagesAround(...a),
listMessagesSince: (...a: unknown[]) => mockListMessagesSince(...a),
getLatestMessageSeq: (...a: unknown[]) => mockGetLatestMessageSeq(...a),
+ getFirstPeerMessageAfterSeq: (...a: unknown[]) => mockGetFirstPeerMessageAfterSeq(...a),
getMessageByChannelAndSeq: (...a: unknown[]) => mockGetMessageByChannelAndSeq(...a),
hardDeleteMessage: (...a: unknown[]) => mockHardDeleteMessage(...a),
getMessageByAuthorAndNonce: (...a: unknown[]) => mockGetMessageByAuthorAndNonce(...a),
@@ -1584,6 +1586,7 @@ describe("GET explicit conversation entry", () => {
contractVersion: BUSINESS_SCHEMA_VERSION, readStateRevision: 0, viewerId: "u1", channelId: "c1", channel: { id: "c1", type: "text", archived: false },
access: { channelId: "c1", canRead: true, canSend: true, canCreateDiscussion: true },
readState: { channelId: "c1", lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 },
+ newBoundary: { afterSeq: 0, target: null },
selection: { reason: "tail", anchorMessageId: null }, messages: [],
page: { hasMoreOlder: false, hasMoreNewer: false, latestSeq: 0 },
})
diff --git a/src/web/src/app/api/community/channels/[id]/messages/route.ts b/src/web/src/app/api/community/channels/[id]/messages/route.ts
index f232a43a0..bd6445e78 100644
--- a/src/web/src/app/api/community/channels/[id]/messages/route.ts
+++ b/src/web/src/app/api/community/channels/[id]/messages/route.ts
@@ -104,8 +104,11 @@ export const GET = withAuth(communityActorPolicy(), async (req: NextRequest, ctx
if (tag && tag.length > MAX_FORUM_TAG_LENGTH) return writeError(`tag must be ≤ ${MAX_FORUM_TAG_LENGTH} characters`, 400)
if (params.get("entry") === "1") {
+ const boundary = params.get("newAfterSeq")
+ const newAfterSeq = boundary === null ? undefined : Number(boundary)
+ if (boundary !== null && (!/^(0|[1-9]\d*)$/.test(boundary) || !Number.isSafeInteger(newAfterSeq))) return writeError("invalid New snapshot", 400)
const result = await readCommunityConversationEntry(db, {
- viewerId: userId, target: resolved.value, window, tag, preferTail: params.get("window") === "tail",
+ viewerId: userId, target: resolved.value, window, tag, preferTail: params.get("window") === "tail", newAfterSeq,
})
if (!result.ok) return NextResponse.json({ error: result.error, ...(result.details ? { details: result.details } : {}) }, { status: result.status })
return writeCommunityConversationEntryRead(result.entry)
diff --git a/src/web/src/app/c/QueryProvider.late-block-restore.dom.test.tsx b/src/web/src/app/c/QueryProvider.late-block-restore.dom.test.tsx
index 58c81decd..2fabb153a 100644
--- a/src/web/src/app/c/QueryProvider.late-block-restore.dom.test.tsx
+++ b/src/web/src/app/c/QueryProvider.late-block-restore.dom.test.tsx
@@ -31,7 +31,9 @@ it.each([null, false, true].flatMap(blockMode => (["accepted", "incoming"] as co
const fresh = dmConversationEntryFixture()
fresh.messages = [{ ...fresh.messages[0], id: "m2", seq: 2, content: "Fresh authorized entry" }]
fresh.readState = { ...fresh.readState, lastReadMessageId: "m2", lastReadSeq: 2 }
- fresh.selection = { reason: "read_pointer", anchorMessageId: "m2" }
+ fresh.selection = { reason: "tail", anchorMessageId: null }
+ fresh.page = { ...fresh.page, latestSeq: 2 }
+ fresh.newBoundary = { afterSeq: 2, target: null }
const original = IDBObjectStore.prototype.get
let reads = 0, held = 0
let release: (() => void) | undefined
diff --git a/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.ts b/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.ts
index 1c2fa90d4..4b610d3d2 100644
--- a/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.ts
+++ b/src/web/src/app/c/me/[dmId]/page.dismissal.dom.test.ts
@@ -120,9 +120,6 @@ vi.mock("@/hooks/community/use-messages", () => ({
}),
}))
-vi.mock("@/lib/community/message-read-projection", () => ({
- resolveMessageReadProjection: () => ({ newDividerBefore: undefined, anchorFound: false }),
-}))
vi.mock("@/hooks/community/use-dm-watermark", () => ({ useDmWatermark: vi.fn() }))
vi.mock("@/hooks/community/use-channel-ref-directory", () => ({
useChannelRefDirectory: () => ({
diff --git a/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.ts b/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.ts
index 5c54c689b..4f108d153 100644
--- a/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.ts
+++ b/src/web/src/components/community/channels/dm-view.send-lifecycle.dom.test.ts
@@ -63,6 +63,7 @@ async function createDmOwner() {
value.messages = []
value.selection = { reason: "tail", anchorMessageId: null }
value.readState = { ...value.readState, lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 }
+ value.newBoundary = { afterSeq: 0, target: null }
value.page = { ...value.page, olderCursor: null, hasMoreOlder: false, latestSeq: 0 }
await seedConversationEntry(owner.client, value)
}
diff --git a/src/web/src/components/community/channels/dm-view.tsx b/src/web/src/components/community/channels/dm-view.tsx
index 19421c64a..31ca3038a 100644
--- a/src/web/src/components/community/channels/dm-view.tsx
+++ b/src/web/src/components/community/channels/dm-view.tsx
@@ -34,7 +34,6 @@ import { makeUserNameResolver } from "@/lib/community/display-name"
import { useDms } from "@/hooks/community/use-dms"
import { useFriends } from "@/hooks/community/use-friends"
import { useDmMessages } from "@/hooks/community/use-messages"
-import { resolveMessageReadProjection } from "@/lib/community/message-read-projection"
import { useMessageUnreadCount } from "@/hooks/community/use-message-unread-count"
import { useDmWatermark } from "@/hooks/community/use-dm-watermark"
import { useChannelRefDirectory } from "@/hooks/community/use-channel-ref-directory"
@@ -154,15 +153,14 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom
fetchOlder: fetchOlderMessages,
fetchNewer: fetchNewerMessages,
jumpToPresent,
- presentVersion, presentRequest,
+ presentVersion, presentRequest, newBoundary, retiredNewTargetId, loadNewTarget, readNewBoundary,
latestSeq,
isPending: messagesPending,
isError: messagesError,
isFetching: messagesFetching,
refetch: refetchMessages,
navigationBlocked,
- anchorReconciled,
- readSnapshot, readSnapshotFetching, initialDisplayReady, preserveInitialPresentation, onUserTakeover,
+ readSnapshot, readSnapshotFetching, initialScrollReady, preserveInitialPresentation, onUserTakeover,
initialLoadError, targetLoadError, retryInitialLoad, retryingInitialLoad, observation, positionEntry, positionScope, positionDataState, targetPositionDataState, messageWindow,
} = useDmMessages(dmId, {
enabled: !dmBlocked && !metadata.revoked && !metadata.denied,
@@ -216,26 +214,7 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom
}
if (channelRefDirectoryError) void refetchChannelRefDirectory()
}, [channelRefDirectoryEnabled, channelRefDirectoryError, refetchChannelRefDirectory, setChannelRefDirectoryEnabled])
- // Anchor of the "New" divider: the first non-self message after
- // `lastReadMessageId` inside the currently-loaded window. Mirrors the
- // channel-view logic exactly — see channel page for why we skip past
- // runs of viewer-authored messages (the server advances the sender's
- // own watermark on POST, so anchoring above the viewer's own row would
- // never be "unread" from the sender's perspective).
- // `anchorFound` and `newDividerBefore` MUST be computed inside the same
- // memo — mirrors the channel page's identical fix exactly (see its doc
- // 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 } = useMemo(() => {
- if (!readSnapshot) return { newDividerBefore: undefined, anchorFound: false }
- return resolveMessageReadProjection({
- messages,
- lastReadMessageId: readSnapshot.lastReadMessageId,
- viewerUserId: currentUser.id,
- anchorReconciled,
- })
- }, [anchorReconciled, messages, readSnapshot, currentUser.id])
+ const newDividerBefore = newBoundary?.target?.id
// Scroll root of the message list — needed so `useDmWatermark`'s
// IntersectionObserver measures against the correct viewport rather
@@ -474,6 +453,11 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom
retryingInitialLoad={retryingInitialLoad || messagesFetching}
onRetryInitialLoad={retryInitialLoad}
newDividerBefore={newDividerBefore}
+ newBoundary={newBoundary}
+ latestSeq={latestSeq}
+ retiredNewTargetId={retiredNewTargetId}
+ onLoadNewTarget={loadNewTarget}
+ onReadNewBoundary={readNewBoundary}
onOpenThread={() => { }}
onToggleReaction={dmBlocked ? undefined : messageActions.onToggleReaction}
onReact={dmBlocked ? undefined : messageActions.onReact}
@@ -488,7 +472,7 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom
resolveUserName={resolveUserName}
onScrollRoot={setScrollRootEl}
viewerUserId={currentUser.id}
- initialScrollReady={initialDisplayReady}
+ initialScrollReady={initialScrollReady}
preserveInitialPresentation={preserveInitialPresentation}
onUserTakeover={onUserTakeover}
hasMore={hasMoreMessages}
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 080cdf1fd..e5de44936 100644
--- a/src/web/src/components/community/channels/text-channel-surface.tsx
+++ b/src/web/src/components/community/channels/text-channel-surface.tsx
@@ -154,6 +154,11 @@ export function TextChannelSurface({
onRetryInitialLoad={feed.retryInitialLoad}
pinnedIds={controller.pinnedIds}
newDividerBefore={feed.newDividerBefore}
+ newBoundary={feed.newBoundary}
+ latestSeq={feed.latestSeq}
+ retiredNewTargetId={feed.retiredNewTargetId}
+ onLoadNewTarget={feed.loadNewTarget}
+ onReadNewBoundary={feed.readNewBoundary}
onOpenThread={onOpenThread}
{...controller.messageActions}
onPin={canManagePins ? controller.messageActions.onPin : undefined}
@@ -164,7 +169,7 @@ export function TextChannelSurface({
scrollToMessageId={controller.scrollTargetId}
onScrollRoot={feed.setScrollRootEl}
viewerUserId={viewer.id}
- initialScrollReady={feed.initialDisplayReady}
+ initialScrollReady={feed.initialScrollReady}
preserveInitialPresentation={feed.preserveInitialPresentation}
onUserTakeover={feed.onUserTakeover}
onScrollTargetConsumed={controller.consumeScrollTarget}
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 b689c38f3..ac8cdabb4 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
@@ -159,6 +159,7 @@ function feed(overrides: Record<string, unknown> = {}) {
anchorInCache: true,
initialPositionKnown: true,
initialDisplayReady: true,
+ initialScrollReady: 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 c969a1cbe..e708fb78f 100644
--- a/src/web/src/components/community/channels/thread-channel-surface.tsx
+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx
@@ -251,6 +251,11 @@ export function ThreadChannelSurface({
onRetryInitialLoad={controller.feed.retryInitialLoad}
pinnedIds={controller.pinnedIds}
newDividerBefore={controller.feed.newDividerBefore}
+ newBoundary={controller.feed.newBoundary}
+ latestSeq={controller.feed.latestSeq}
+ retiredNewTargetId={controller.feed.retiredNewTargetId}
+ onLoadNewTarget={controller.feed.loadNewTarget}
+ onReadNewBoundary={controller.feed.readNewBoundary}
onOpenThread={ignoreNestedThread}
{...controller.threadActions}
onPin={canManagePins ? controller.threadActions.onPin : undefined}
@@ -262,7 +267,7 @@ export function ThreadChannelSurface({
hero={opener}
onScrollRoot={controller.feed.setScrollRootEl}
viewerUserId={viewer.id}
- initialScrollReady={controller.feed.initialDisplayReady}
+ initialScrollReady={controller.feed.initialScrollReady}
preserveInitialPresentation={controller.feed.preserveInitialPresentation}
onUserTakeover={controller.feed.onUserTakeover}
onScrollTargetConsumed={controller.consumeScrollTarget}
diff --git a/src/web/src/components/community/messages/composer-accessory-rail-layout.ts b/src/web/src/components/community/messages/composer-accessory-rail-layout.ts
index 71a259001..e9dcdb4ec 100644
--- a/src/web/src/components/community/messages/composer-accessory-rail-layout.ts
+++ b/src/web/src/components/community/messages/composer-accessory-rail-layout.ts
@@ -2,6 +2,7 @@ export type ComposerAccessoryRailOccupancy = {
mode: "normal"
left: boolean
center: boolean
+ right?: boolean
}
export type ComposerAccessoryRailLayout =
@@ -12,7 +13,7 @@ export type ComposerAccessoryRailLayout =
export function allocateComposerAccessoryRail(
occupancy: ComposerAccessoryRailOccupancy,
): ComposerAccessoryRailLayout {
- if (occupancy.center) return "centered"
+ if (occupancy.center || occupancy.right) return "centered"
if (occupancy.left) return "left-only"
return "empty"
}
diff --git a/src/web/src/components/community/messages/composer-accessory-rail.dom.test.tsx b/src/web/src/components/community/messages/composer-accessory-rail.dom.test.tsx
index a68eb334f..05e8e05ef 100644
--- a/src/web/src/components/community/messages/composer-accessory-rail.dom.test.tsx
+++ b/src/web/src/components/community/messages/composer-accessory-rail.dom.test.tsx
@@ -1,7 +1,7 @@
import React from "react"
import { createPortal } from "react-dom"
import { describe, expect, it, vi } from "vitest"
-import { render } from "@/test/react-dom-harness"
+import { fireEvent, render } from "@/test/react-dom-harness"
import { tid } from "@/lib/community/testids"
import { ComposerAccessoryRail } from "./composer-accessory-rail"
import { ConversationFooterShell, ConversationFooterSlotProvider, useConversationFooterSlot } from "./conversation-footer-shell"
@@ -11,6 +11,23 @@ vi.mock("@/components/ui/number-ticker", () => ({
}))
describe("ComposerAccessoryRail geometry", () => {
+ it("shows New by itself, keeps the present action independent and hides an accepted pending jump", () => {
+ const onNew = vi.fn(), onScroll = vi.fn()
+ const view = (pending: boolean, count = 0) => <ComposerAccessoryRail typingNames={[]} scrollCount={count} scrollMode="scroll"
+ onScroll={onScroll} newVisible newPending={pending} onNew={onNew} />
+ const renderer = render(view(false))
+ expect(renderer.getByTestId(tid.composerAccessoryRail)).toBeDefined()
+ expect(renderer.queryByTestId(tid.scrollToPresent)).toBeNull()
+ fireEvent.click(renderer.getByRole("button", { name: "Jump to New" }))
+ expect(onNew).toHaveBeenCalledOnce()
+ expect(onScroll).not.toHaveBeenCalled()
+ renderer.rerender(view(false, 8))
+ expect(renderer.getByTestId(tid.scrollToNew)).toBeDefined()
+ expect(renderer.getByTestId(tid.scrollToPresent)).toBeDefined()
+ renderer.rerender(view(true, 8))
+ expect(renderer.queryByTestId(tid.scrollToNew)).toBeNull()
+ expect(renderer.getByTestId(tid.scrollToPresent)).toBeDefined()
+ })
it("shares the composer's logical safe-area-aware inline edges", () => {
function Accessory() {
const target = useConversationFooterSlot()?.accessoryTarget
diff --git a/src/web/src/components/community/messages/composer-accessory-rail.tsx b/src/web/src/components/community/messages/composer-accessory-rail.tsx
index 5470da9bf..2b228378f 100644
--- a/src/web/src/components/community/messages/composer-accessory-rail.tsx
+++ b/src/web/src/components/community/messages/composer-accessory-rail.tsx
@@ -1,6 +1,6 @@
"use client"
-import { ArrowDown, ImageIcon, X } from "lucide-react"
+import { ArrowDown, ArrowUp, ImageIcon, X } from "lucide-react"
import { Button } from "@/components/ui/button"
import { NumberTicker } from "@/components/ui/number-ticker"
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
@@ -15,18 +15,26 @@ export function ComposerAccessoryRail({
scrollCount,
scrollMode,
onScroll,
+ newVisible = false,
+ newPending = false,
+ onNew,
}: {
typingNames: string[]
scrollCount: number | undefined
scrollMode: "scroll" | "jump"
onScroll: () => void
+ newVisible?: boolean
+ newPending?: boolean
+ onNew?: () => void
}) {
const hasTyping = typingNames.length > 0
const hasScroll = scrollMode === "jump" || (scrollCount ?? 0) > 0
+ const hasNew = newVisible && !newPending && !!onNew
const layout = allocateComposerAccessoryRail({
mode: "normal",
left: hasTyping,
center: hasScroll,
+ right: hasNew,
})
if (layout === "empty") return null
@@ -55,6 +63,18 @@ export function ComposerAccessoryRail({
<ScrollControl count={scrollCount} mode={scrollMode} onClick={onScroll} />
</div>
)}
+ {hasNew && (
+ <button
+ type="button"
+ data-testid={tid.scrollToNew}
+ aria-label="Jump to New"
+ onClick={onNew}
+ className="pointer-events-auto col-start-3 flex h-full min-w-11 max-w-full items-center justify-center gap-1.5 justify-self-end rounded-full border border-destructive bg-background/90 px-2 text-xs font-medium text-destructive shadow-(--e1) backdrop-blur-sm transition-colors hover:bg-accent focus-visible:outline-none focus-visible:ring-3 focus-visible:ring-ring/50"
+ >
+ <ArrowUp className="size-3.5 shrink-0" />
+ <span>New</span>
+ </button>
+ )}
</div>
</div>
)
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 eb373f262..c5d9a7bac 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
@@ -20,6 +20,9 @@ const readWebSource = (path: string) => {
const mocks = vi.hoisted(() => ({
readPositionReady: false,
paginationEnabled: false,
+ followingTail: false,
+ requestNewPosition: vi.fn(),
+ newDividerVisibility: "offscreen" as "offscreen" | "visible" | "pending",
scrollInputs: [] as unknown[],
paginationInputs: [] as unknown[],
scrollRef: { current: null as HTMLDivElement | null },
@@ -57,6 +60,9 @@ vi.mock("@/hooks/community/use-scroll-anchor", () => ({
positionOutcome,
readPositionReady: mocks.readPositionReady,
paginationEnabled: mocks.paginationEnabled,
+ followingTail: mocks.followingTail,
+ requestNewPosition: mocks.requestNewPosition,
+ newDividerVisibility: mocks.newDividerVisibility,
captureOlderPageAnchor: mocks.captureOlderPageAnchor,
captureNewerPageAnchor: mocks.captureNewerPageAnchor,
}
@@ -128,9 +134,9 @@ describe("useMessageListController", () => {
isConnected: true,
querySelectorAll: () => visibleMessageIds.map((id) => ({
dataset: { msgId: id },
- getBoundingClientRect: () => ({ top: 10, bottom: 20 }),
+ getBoundingClientRect: () => ({ top: 10, bottom: 20, left: 0, right: 100, width: 100, height: 10 }),
})),
- getBoundingClientRect: () => ({ top: 0, bottom: 100 }),
+ getBoundingClientRect: () => ({ top: 0, bottom: 100, left: 0, right: 100, width: 100, height: 100 }),
}
beforeEach(() => {
@@ -139,6 +145,9 @@ describe("useMessageListController", () => {
disconnect.mockClear()
mocks.readPositionReady = false
mocks.paginationEnabled = false
+ mocks.followingTail = false
+ mocks.newDividerVisibility = "offscreen"
+ mocks.requestNewPosition.mockReset().mockReturnValue({ accepted: false })
mocks.captureOlderPageAnchor.mockClear()
mocks.captureNewerPageAnchor.mockClear()
mocks.scrollInputs.length = 0
@@ -185,6 +194,153 @@ describe("useMessageListController", () => {
return entry[0]
}
+ const boundary = (seq: number | null, afterSeq = 0) => ({ afterSeq,
+ target: seq === null ? null : { id: `m${seq}`, seq, channelId: "c1", authorId: "peer" } })
+ const peer = (seq: number) => ({ ...baseMessage, id: `m${seq}`, seq, authorId: "peer" })
+
+ it("keeps one New target across ACK and consumes only a completed successful position", async () => {
+ let finish!: (value: "success" | "error") => void
+ mocks.requestNewPosition.mockImplementation(() => ({ accepted: true, completed: new Promise(resolve => { finish = resolve }) }))
+ const value = props({ messages: [peer(1), peer(2)], newBoundary: boundary(1), viewerUserId: "viewer" })
+ const view = rtlRender(React.createElement(Probe, { value }))
+ expect(latest.newJumpVisible).toBe(true)
+ view.rerender(React.createElement(Probe, { value: { ...value, newBoundary: boundary(null, 2) } }))
+ expect(latest.items.some(item => item.kind === "divider" && item.messageId === "m1" && item.newDivider)).toBe(true)
+ act(() => latest.jumpToNew())
+ expect(mocks.requestNewPosition).toHaveBeenCalledWith("m1", undefined)
+ expect(latest.newJumpPending).toBe(true)
+ await act(async () => finish("error"))
+ expect(latest.newLoadError).toBeInstanceOf(Error)
+ expect(latest.newJumpVisible).toBe(true)
+ act(() => latest.retryNew())
+ await act(async () => finish("success"))
+ expect(latest.newJumpVisible).toBe(false)
+ view.rerender(React.createElement(Probe, { value: { ...value, latestSeq: 2 } }))
+ expect(latest.newJumpVisible).toBe(false)
+ view.unmount()
+ })
+
+ it("keeps cancellation retryable and ignores completion after a new entry", async () => {
+ let finish!: (value: "success" | "cancelled") => void
+ mocks.requestNewPosition.mockImplementation(() => ({ accepted: true, completed: new Promise(resolve => { finish = resolve }) }))
+ const value = props({ messages: [peer(1)], newBoundary: boundary(1), positionEntry: {} })
+ const view = rtlRender(React.createElement(Probe, { value }))
+ act(() => latest.jumpToNew())
+ await act(async () => finish("cancelled"))
+ expect(latest.newJumpVisible).toBe(true)
+ act(() => latest.jumpToNew())
+ view.rerender(React.createElement(Probe, { value: { ...value, newBoundary: boundary(2), positionEntry: {} } }))
+ await act(async () => finish("success"))
+ expect(latest.items.some(item => item.kind === "divider" && item.messageId === "m1" && item.newDivider)).toBe(false)
+ expect(latest.newJumpPending).toBe(false)
+ view.unmount()
+ })
+
+ it("retires an exact deleted target and hides any partly visible divider", () => {
+ const value = props({ messages: [peer(1)], newBoundary: boundary(1) })
+ const view = rtlRender(React.createElement(Probe, { value }))
+ expect(latest.newJumpVisible).toBe(true)
+ mocks.newDividerVisibility = "visible"
+ view.rerender(React.createElement(Probe, { value: { ...value } }))
+ expect(latest.newJumpVisible).toBe(false)
+ mocks.newDividerVisibility = "offscreen"
+ view.rerender(React.createElement(Probe, { value: { ...value, retiredNewTargetId: "m1" } }))
+ expect(latest.newJumpVisible).toBe(false)
+ expect(latest.items.some(item => item.kind === "divider" && item.newDivider)).toBe(false)
+ view.unmount()
+ })
+
+ it("does not read or rearm a batch for own or normally visible arrivals", () => {
+ mocks.readPositionReady = true
+ const read = vi.fn()
+ const value = props({ messages: [peer(1)], newBoundary: boundary(null, 1), viewerUserId: "viewer", onReadNewBoundary: read })
+ const view = rtlRender(React.createElement(Probe, { value }))
+ visibleMessageIds = ["m2"]
+ view.rerender(React.createElement(Probe, { value: { ...value, messages: [peer(1), { ...peer(2), authorId: "viewer" }] } }))
+ expect(read).not.toHaveBeenCalled()
+ view.rerender(React.createElement(Probe, { value: { ...value, messages: [peer(1), peer(2)] } }))
+ expect(read).not.toHaveBeenCalled()
+ expect(latest.newJumpVisible).toBe(false)
+ mocks.followingTail = true
+ visibleMessageIds = []
+ view.rerender(React.createElement(Probe, { value: { ...value, messages: [peer(1), peer(2), peer(3)] } }))
+ expect(read).not.toHaveBeenCalled()
+ view.unmount()
+ })
+
+ it("does not skip an unseen peer when the first peer becomes visible during the boundary read", async () => {
+ mocks.readPositionReady = true
+ visibleMessageIds = []
+ let finish!: (value: { boundary: ReturnType<typeof boundary>; latestSeq: number }) => void
+ const read = vi.fn().mockImplementationOnce(() => new Promise(resolve => { finish = resolve }))
+ .mockResolvedValueOnce({ boundary: boundary(3, 2), latestSeq: 3 })
+ const value = props({ messages: [peer(1)], newBoundary: boundary(null, 1), viewerUserId: "viewer", onReadNewBoundary: read })
+ const view = rtlRender(React.createElement(Probe, { value }))
+ const arrived = { ...value, messages: [peer(1), peer(2), peer(3)] }
+ view.rerender(React.createElement(Probe, { value: arrived }))
+ expect(read).toHaveBeenCalledExactlyOnceWith(1)
+ visibleMessageIds = ["m2"]
+ await act(async () => finish({ boundary: boundary(2, 1), latestSeq: 3 }))
+ expect(read.mock.calls).toEqual([[1], [2]])
+ expect(latest.newJumpVisible).toBe(true)
+ expect(latest.items.some(item => item.kind === "divider" && item.messageId === "m3" && item.newDivider)).toBe(true)
+ view.unmount()
+ })
+
+ it.each(["before the read", "during the read"] as const)("keeps a consumed visible New divider when the next batch arrives %s", async timing => {
+ mocks.readPositionReady = true
+ visibleMessageIds = []
+ mocks.requestNewPosition.mockReturnValue({ accepted: true, completed: Promise.resolve("success") })
+ const next = { boundary: boundary(3, 2), latestSeq: 3 }
+ let finish!: (value: typeof next) => void
+ const read = timing === "during the read"
+ ? vi.fn().mockImplementationOnce(() => new Promise(resolve => { finish = resolve })).mockResolvedValue(next)
+ : vi.fn().mockResolvedValue(next)
+ const value = props({ messages: [peer(1), peer(2)], newBoundary: boundary(1), viewerUserId: "viewer", onReadNewBoundary: read })
+ const view = rtlRender(React.createElement(Probe, { value }))
+ try {
+ await act(async () => latest.jumpToNew())
+ if (timing === "before the read") mocks.newDividerVisibility = "visible"
+ const arrived = { ...value, messages: [peer(1), peer(2), peer(3)] }
+ view.rerender(React.createElement(Probe, { value: arrived }))
+ if (timing === "during the read") {
+ expect(read).toHaveBeenCalledExactlyOnceWith(2)
+ mocks.newDividerVisibility = "visible"
+ view.rerender(React.createElement(Probe, { value: arrived }))
+ await act(async () => finish(next))
+ } else {
+ await act(async () => {})
+ expect(read).not.toHaveBeenCalled()
+ }
+ expect(latest.items.some(item => item.kind === "divider" && item.messageId === "m1" && item.newDivider)).toBe(true)
+ expect(latest.newJumpVisible).toBe(false)
+ mocks.newDividerVisibility = "offscreen"
+ view.rerender(React.createElement(Probe, { value: arrived }))
+ await act(async () => {})
+ expect(read).toHaveBeenCalledTimes(timing === "during the read" ? 2 : 1)
+ expect(latest.items.some(item => item.kind === "divider" && item.messageId === "m3" && item.newDivider)).toBe(true)
+ expect(latest.newJumpVisible).toBe(true)
+ } finally { view.unmount() }
+ })
+
+ it("retries a failed later metadata read and creates a new batch after the prior successful use", async () => {
+ mocks.readPositionReady = true
+ visibleMessageIds = []
+ mocks.requestNewPosition.mockReturnValue({ accepted: true, completed: Promise.resolve("success") })
+ const read = vi.fn().mockRejectedValueOnce(new Error("offline")).mockResolvedValueOnce({ boundary: boundary(3, 2), latestSeq: 3 })
+ const value = props({ messages: [peer(1), peer(2)], newBoundary: boundary(1), viewerUserId: "viewer", onReadNewBoundary: read })
+ const view = rtlRender(React.createElement(Probe, { value }))
+ await act(async () => latest.jumpToNew())
+ view.rerender(React.createElement(Probe, { value: { ...value, messages: [peer(1), peer(2), peer(3)] } }))
+ await act(async () => {})
+ expect(latest.newLoadError?.message).toBe("offline")
+ expect(read).toHaveBeenCalledExactlyOnceWith(2)
+ await act(async () => latest.retryNew())
+ expect(read.mock.calls).toEqual([[2], [2]])
+ expect(latest.newJumpVisible).toBe(true)
+ view.unmount()
+ })
+
it("requires a new positioning settlement for a fresh entry on the retained list", () => {
const value = props({ positionEntry: {} })
const view = rtlRender(React.createElement(Probe, { value }))
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 3257f3d11..de9ce9c3b 100644
--- a/src/web/src/components/community/messages/message-list-controller.ts
+++ b/src/web/src/components/community/messages/message-list-controller.ts
@@ -1,20 +1,29 @@
"use client"
import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useCallback, useEffect, useMemo, useRef } from "react"
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"
import type { RenderMsg } from "@/lib/community/models/message"
import { flattenMessageItems } from "@/lib/community/message-list-items"
import { useScrollAnchor } from "@/hooks/community/use-scroll-anchor"
import { useVirtualCursorPagination } from "@/hooks/community/use-virtual-cursor-pagination"
import { useInitialPositionTransition } from "./initial-position-transition"
import type { ResolvedMessageListProps } from "./message-list-types"
+import { conversationListScopeKey } from "@/lib/community/conversation-qualification"
+import { hashKey } from "@tanstack/react-query"
+import { READ_VISIBILITY_THRESHOLD } from "@/hooks/community/use-read-observer"
export function useMessageListController({
messages,
+ viewerUserId,
onOpenContextId,
loading,
initialLoadError,
newDividerBefore,
+ newBoundary,
+ latestSeq,
+ retiredNewTargetId,
+ onLoadNewTarget,
+ onReadNewBoundary,
scrollToMessageId,
initialPositionMessageId,
positionEntry,
@@ -44,10 +53,20 @@ export function useMessageListController({
}: ResolvedMessageListProps) {
const [jumpRevision, setJumpRevision] = useAtom(useCreateAtom(0))
const [jumped, setJumped] = useAtom(useCreateAtom<string | null>(null))
+ const scopeKey = positionScope ? hashKey(conversationListScopeKey(positionScope)) : null
+ const observedSeq = Math.max(latestSeq ?? 0, ...messages.map(message => message.seq ?? 0))
+ const createLookback = () => ({ owner: {}, scopeKey, entry: positionEntry,
+ initialized: newBoundary !== undefined || newDividerBefore !== undefined,
+ target: newBoundary !== undefined ? newBoundary.target?.id ?? null : newDividerBefore ?? null,
+ used: false, pending: false, checking: false, throughSeq: observedSeq, checkedThrough: -1, error: null as Error | null })
+ const [lookback, setLookback] = useState(createLookback)
+ if (lookback.scopeKey !== scopeKey || lookback.entry !== positionEntry) setLookback(createLookback())
+ const dividerTarget = lookback.initialized ? lookback.target ?? undefined
+ : newBoundary !== undefined ? newBoundary.target?.id : newDividerBefore
const items = useMemo(
- () => flattenMessageItems(messages, newDividerBefore, !!hasMore, !!hasMoreNewer),
- [messages, newDividerBefore, hasMore, hasMoreNewer],
+ () => flattenMessageItems(messages, dividerTarget, !!hasMore, !!hasMoreNewer),
+ [messages, dividerTarget, hasMore, hasMoreNewer],
)
const [selectMode, setSelectMode] = useAtom(useCreateAtom(false))
@@ -107,9 +126,12 @@ export function useMessageListController({
captureOlderPageAnchor,
captureNewerPageAnchor,
positionOutcome,
+ requestNewPosition,
+ newDividerVisibility,
+ followingTail,
} = useScrollAnchor({
items,
- newDividerBefore,
+ newDividerBefore: dividerTarget,
initialScrollReady,
...(preserveInitialPresentation ? { preserveInitialPresentation } : {}),
...(onUserTakeover ? { onUserTakeover } : {}),
@@ -137,6 +159,90 @@ export function useMessageListController({
authoritativeEmpty,
positionSettled: positionOutcome !== "pending",
})
+ const readVisiblePeerSeq = useCallback(() => {
+ const root = scrollRef.current
+ if (!root || active === false || !readPositionReady) return 0
+ const viewport = root.getBoundingClientRect()
+ const peers = new Map(messages.filter(message => message.authorId && message.authorId !== viewerUserId)
+ .map(message => [message.id, message.seq ?? 0]))
+ let through = 0
+ for (const body of root.querySelectorAll<HTMLElement>("[data-msg-id]")) {
+ const seq = peers.get(body.dataset.msgId ?? "")
+ if (!seq || seq <= through) continue
+ const rect = body.getBoundingClientRect()
+ const visibleArea = Math.max(0, Math.min(rect.bottom, viewport.bottom) - Math.max(rect.top, viewport.top))
+ * Math.max(0, Math.min(rect.right, viewport.right) - Math.max(rect.left, viewport.left))
+ if (rect.width > 0 && rect.height > 0 && visibleArea / (rect.width * rect.height) >= READ_VISIBILITY_THRESHOLD) through = seq
+ }
+ return through
+ }, [active, messages, readPositionReady, scrollRef, viewerUserId])
+ const lookbackView = useRef<{ owner: object; throughSeq: number; followingTail: boolean; readable: boolean; dividerVisibility: typeof newDividerVisibility; visiblePeerSeq: () => number } | null>(null)
+ useLayoutEffect(() => {
+ lookbackView.current = { owner: lookback.owner, throughSeq: observedSeq, followingTail,
+ readable: active !== false && readPositionReady, dividerVisibility: newDividerVisibility, visiblePeerSeq: readVisiblePeerSeq }
+ return () => { if (lookbackView.current?.owner === lookback.owner) lookbackView.current = null }
+ }, [active, followingTail, lookback.owner, observedSeq, readPositionReady, newDividerVisibility, readVisiblePeerSeq])
+ useLayoutEffect(() => {
+ if (!lookback.initialized && newBoundary !== undefined) {
+ setLookback(current => current.owner === lookback.owner ? { ...current, initialized: true, target: newBoundary.target?.id ?? null,
+ throughSeq: observedSeq } : current)
+ } else if (lookback.target && lookback.target === retiredNewTargetId) {
+ setLookback(current => current.owner === lookback.owner ? { ...current, target: null, used: true, pending: false } : current)
+ } else if (lookback.target && !lookback.used && observedSeq > lookback.throughSeq) {
+ setLookback(current => current.owner === lookback.owner ? { ...current, throughSeq: observedSeq } : current)
+ }
+ }, [lookback, newBoundary, observedSeq, retiredNewTargetId])
+ useEffect(() => {
+ if (!lookback.initialized || lookback.target && !lookback.used || observedSeq <= lookback.throughSeq) return
+ if (active === false || !readPositionReady || lookback.pending || lookback.checking) return
+ const visibleThrough = followingTail ? observedSeq : readVisiblePeerSeq()
+ if (visibleThrough > lookback.throughSeq) {
+ setLookback(current => current.owner === lookback.owner ? { ...current, throughSeq: visibleThrough, error: null } : current)
+ return
+ }
+ if (lookback.target && lookback.used && newDividerVisibility !== "offscreen") return
+ if (lookback.checkedThrough >= observedSeq || !onReadNewBoundary
+ || !messages.some(message => message.authorId && message.authorId !== viewerUserId && (message.seq ?? 0) > lookback.throughSeq)) return
+ const owner = lookback.owner
+ setLookback(current => current.owner === owner ? { ...current, checking: true, checkedThrough: observedSeq, error: null } : current)
+ void onReadNewBoundary(lookback.throughSeq).then(result => {
+ const view = lookbackView.current
+ if (!view || view.owner !== owner) return
+ const visibleThrough = view.visiblePeerSeq()
+ setLookback(current => {
+ if (current.owner !== owner) return current
+ if (!result) return { ...current, checking: false, error: new Error("Could not load New") }
+ if (view.readable && view.followingTail) return { ...current, checking: false, throughSeq: Math.max(current.throughSeq, result.latestSeq, view.throughSeq) }
+ if (!result.boundary.target) return { ...current, checking: false, throughSeq: Math.max(current.throughSeq, result.latestSeq) }
+ if (result.boundary.target.seq <= visibleThrough) return { ...current, checking: false,
+ throughSeq: Math.max(current.throughSeq, visibleThrough), checkedThrough: -1 }
+ if (current.target && current.used && view.dividerVisibility !== "offscreen") return { ...current, checking: false, checkedThrough: -1 }
+ return { ...current, checking: false, target: result.boundary.target.id, used: false,
+ throughSeq: Math.max(current.throughSeq, result.latestSeq) }
+ })
+ }, error => {
+ if (lookbackView.current?.owner === owner) setLookback(current => current.owner === owner
+ ? { ...current, checking: false, error: error instanceof Error ? error : new Error("Could not load New") } : current)
+ })
+ }, [active, followingTail, lookback, messages, newDividerVisibility, observedSeq, onReadNewBoundary, readPositionReady, readVisiblePeerSeq, viewerUserId])
+ const jumpToNew = useCallback(() => {
+ const id = lookback.target, owner = lookback.owner
+ if (!id || lookback.used || lookback.pending || lookbackView.current?.owner !== owner) return
+ const request = requestNewPosition(id, onLoadNewTarget ? () => onLoadNewTarget(id) : undefined)
+ if (!request.accepted) return
+ setLookback(current => current.owner === owner ? { ...current, pending: true, error: null } : current)
+ void request.completed.then(result => {
+ if (lookbackView.current?.owner !== owner) return
+ setLookback(current => current.owner !== owner || current.target !== id ? current : { ...current, pending: false,
+ used: result === "success" || result === "missing" || current.used,
+ target: result === "missing" ? null : current.target,
+ error: result === "error" ? new Error("Could not jump to New") : null })
+ })
+ }, [lookback, onLoadNewTarget, requestNewPosition])
+ const retryNew = useCallback(() => {
+ if (lookback.target && !lookback.used) jumpToNew()
+ else setLookback(current => ({ ...current, checkedThrough: -1, error: null }))
+ }, [jumpToNew, lookback.target, lookback.used])
useEffect(() => {
if (!onScrollRoot) return
@@ -262,6 +368,12 @@ export function useMessageListController({
pillCount,
pillMode: jumpMode ? "jump" as const : "scroll" as const,
pillOnClick,
+ newJumpVisible: !!dividerTarget && !lookback.used && newDividerVisibility === "offscreen"
+ && (!!onLoadNewTarget || messages.some(message => message.id === dividerTarget)),
+ newJumpPending: lookback.pending,
+ jumpToNew,
+ newLoadError: lookback.error,
+ retryNew,
}
}
diff --git a/src/web/src/components/community/messages/message-list-types.ts b/src/web/src/components/community/messages/message-list-types.ts
index 80d8875e4..7ed81e705 100644
--- a/src/web/src/components/community/messages/message-list-types.ts
+++ b/src/web/src/components/community/messages/message-list-types.ts
@@ -3,6 +3,7 @@ import type { FileAttachment, ImagePreview, Msg } from "@/lib/community/models/m
import type { OpenProfile } from "@/components/community/social/profile-types"
import type { MessagePositionState, MessageRequest } from "@/lib/community/message-position"
import type { ConversationListScope } from "@/lib/community/conversation-qualification"
+import type { CommunityConversationEntryRead } from "@alook/shared"
export type MessageListProps = {
observation?: import("@/lib/observability/regions").ResourceObservation
@@ -15,6 +16,11 @@ export type MessageListProps = {
onRetryInitialLoad?: () => void
pinnedIds?: Set<string>
newDividerBefore?: string
+ newBoundary?: CommunityConversationEntryRead["newBoundary"]
+ latestSeq?: number
+ retiredNewTargetId?: string
+ onLoadNewTarget?: (id: string) => MessageRequest
+ onReadNewBoundary?: (afterSeq: number) => Promise<{ boundary: CommunityConversationEntryRead["newBoundary"]; latestSeq: number } | undefined>
typingUsers?: string[]
onOpenThread: (id: string) => void
onOpenProfile?: OpenProfile
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 8b32c70e2..6bf3582b9 100644
--- a/src/web/src/components/community/messages/message-list-view.tsx
+++ b/src/web/src/components/community/messages/message-list-view.tsx
@@ -39,6 +39,9 @@ export function renderMessageListView(
scrollCount={controller.pillCount}
scrollMode={controller.pillMode}
onScroll={controller.pillOnClick}
+ newVisible={controller.newJumpVisible}
+ newPending={controller.newJumpPending}
+ onNew={controller.jumpToNew}
/>,
accessoryFooterSlot,
)}
@@ -49,9 +52,9 @@ export function renderMessageListView(
onClose={controller.closeShare}
/>
)}
- {props.targetLoadError && controller.initialPosition.contentVisible && <div role="alert" className="flex items-center justify-between gap-2 px-4 py-2 text-sm">
- <span>Couldn’t load the requested messages</span>
- <Button variant="ghost" className="h-11 sm:h-9" disabled={props.retryingInitialLoad} onClick={props.onRetryInitialLoad}>
+ {(props.targetLoadError || controller.newLoadError) && controller.initialPosition.contentVisible && <div role="alert" className="flex items-center justify-between gap-2 px-4 py-2 text-sm">
+ <span>{controller.newLoadError ? "Couldn’t load New" : "Couldn’t load the requested messages"}</span>
+ <Button variant="ghost" className="h-11 sm:h-9" disabled={props.retryingInitialLoad || controller.newJumpPending} onClick={controller.newLoadError ? controller.retryNew : props.onRetryInitialLoad}>
{props.retryingInitialLoad ? "Retrying…" : "Retry"}
</Button>
</div>}
diff --git a/src/web/src/components/community/messages/message-list.tsx b/src/web/src/components/community/messages/message-list.tsx
index d840eaad4..e582f8d87 100644
--- a/src/web/src/components/community/messages/message-list.tsx
+++ b/src/web/src/components/community/messages/message-list.tsx
@@ -25,7 +25,8 @@ function MessageListEntry({
...props
}: MessageListProps) {
const [admitted, setAdmitted] = useState(false)
- const ready = initialScrollReady && (props.messages.length > 0 || !props.loading && !props.initialLoadError)
+ const ready = props.messages.length > 0 && !!(props.initialLoadError || props.targetLoadError)
+ || initialScrollReady && (props.messages.length > 0 || !props.loading && !props.initialLoadError)
|| !!props.scrollToMessageId && (props.targetPositionDataState ?? props.positionDataState) === "ready" && props.messages.length > 0
if (ready && !admitted) setAdmitted(true)
if (props.positionScope && !admitted && !ready && !props.initialLoadError) return <MessageListSkeleton variant={variant} />
diff --git a/src/web/src/components/community/shell/cached-conversation-route.dom.test.tsx b/src/web/src/components/community/shell/cached-conversation-route.dom.test.tsx
index 661b2a04c..4ffcb7c7e 100644
--- a/src/web/src/components/community/shell/cached-conversation-route.dom.test.tsx
+++ b/src/web/src/components/community/shell/cached-conversation-route.dom.test.tsx
@@ -105,6 +105,7 @@ describe("cached target through the real route, entry and message consumers", ()
createdAt: new Date(Date.UTC(2026, 9, 1, 0, 0, index + 1)).toISOString() }))
entry.readState = { channelId: "c1", lastReadMessageId: "m42", lastReadSeq: 42, lastReadAt: entry.messages[41].createdAt }
entry.selection = { reason: "tail", anchorMessageId: null }
+ entry.newBoundary = { afterSeq: 42, target: null }
entry.page = { ...entry.page, hasMoreOlder: false, hasMoreNewer: false, olderCursor: null, newerCursor: null, latestSeq: 42 }
await seedConversationEntry(owner.client, entry)
scrollFixture.width = 905
@@ -148,12 +149,12 @@ describe("cached target through the real route, entry and message consumers", ()
expect(previous.isConnected).toBe(false)
await act(async () => vi.advanceTimersByTimeAsync(6000))
const previousLoad = mocks.load.getMockImplementation()!
- mocks.load.mockImplementation((url: string) => url === "/api/community/channels/c1/messages?entry=1"
+ mocks.load.mockImplementation((url: string) => url === "/api/community/channels/c1/messages?entry=1&window=tail"
? new Promise(() => {}) : previousLoad(url))
const serverTarget = resolveCommunityLandingHref({ serverId: "s1", channelIds: ["c1"], last: "c1", breakpoint: "desktop" })
await go(serverTarget)
expect(serverTarget).toBe(href)
- expect(mocks.load.mock.calls.some(([url]) => url === "/api/community/channels/c1/messages?entry=1")).toBe(true)
+ expect(mocks.load.mock.calls.some(([url]) => url === "/api/community/channels/c1/messages?entry=1&window=tail")).toBe(true)
expect(root().scrollTop).not.toBe(offset)
expect(root().scrollHeight - root().clientHeight - root().scrollTop).toBeLessThanOrEqual(1)
expect(root().querySelector('[data-message-list-content]')).toHaveAttribute("aria-hidden", "false")
diff --git a/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsx b/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsx
index 32b33c5aa..ddf82d8cc 100644
--- a/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsx
+++ b/src/web/src/components/community/shell/server-sidebar-slot.identity.dom.test.tsx
@@ -150,6 +150,6 @@ it.each([false, true])("keeps real same-server list, row and category nodes thro
fireEvent.contextMenu(scroll, { button: 2 })
expect(await view.findByRole("menuitem", { name: "Create category" })).toBeVisible()
await user.keyboard("{Escape}")
- expect(mocks.load.mock.calls.map(([path]) => path)).toEqual(["/api/community/channels/channel/messages?entry=1"])
+ expect(mocks.load.mock.calls.map(([path]) => path)).toEqual(["/api/community/channels/channel/messages?entry=1&window=tail"])
expect(mocks.load.mock.calls.every(([, options]) => !options?.method || options.method === "GET")).toBe(true)
})
diff --git a/src/web/src/hooks/community/channel-metadata.test.ts b/src/web/src/hooks/community/channel-metadata.test.ts
index 3feb48818..99702d8bd 100644
--- a/src/web/src/hooks/community/channel-metadata.test.ts
+++ b/src/web/src/hooks/community/channel-metadata.test.ts
@@ -23,7 +23,7 @@ describe("channel resource options use the common entry", () => {
const metadata = channelMetadataOptions(client, serverId, "c1")
expect(metadata.queryKey).toEqual(conversationEntryOptions(client, { channelId: "c1", serverId }).queryKey)
await client.query({ ...metadata, select: undefined })
- expect(load.mock.calls.map(([path]) => path)).toEqual(["/api/community/channels/c1/messages?entry=1"])
+ expect(load.mock.calls.map(([path]) => path)).toEqual(["/api/community/channels/c1/messages?entry=1&window=tail"])
expect(registry.collections.channels.get("c1")).toMatchObject(packet.channel)
})
diff --git a/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts b/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts
index 5c5759567..a52cfd8b2 100644
--- a/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/membership-events.dom.test.ts
@@ -635,7 +635,7 @@ describe("membership metadata and access lifetime", () => {
else expect(capturedQueryClient.getQueryData(key)).toEqual(content)
await vi.waitFor(() => expect(capturedQueryClient.getQueryData(entryKey("server", "child"))).toMatchObject({ channelId: "child", proof: expect.any(Object) }))
expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child", "server")).toBe(false)
- expect(api).toHaveBeenCalledWith("/api/community/channels/child/messages?entry=1", expect.anything())
+ expect(api).toHaveBeenCalledWith("/api/community/channels/child/messages?entry=1&window=tail", expect.anything())
})
it("retires a DM access denial including only its subscription and content", async () => {
@@ -670,10 +670,10 @@ describe("membership metadata and access lifetime", () => {
const api = getCommunityApiFetchMock()
const fallback = api.getMockImplementation()!
const error = new ApiError("metadata lookup failed", status)
- api.mockImplementation((...args) => args[0] === "/api/community/channels/child/messages?entry=1" ? Promise.reject(error) : fallback(...args))
+ api.mockImplementation((...args) => args[0] === "/api/community/channels/child/messages?entry=1&window=tail" ? Promise.reject(error) : fallback(...args))
const query = vi.spyOn(capturedQueryClient, "query")
capturedOnMessage!(currentCommunityEventFixture({ type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me", relation: "access", present: true }))
- await vi.waitFor(() => expect(api).toHaveBeenCalledWith("/api/community/channels/child/messages?entry=1", expect.anything()))
+ await vi.waitFor(() => expect(api).toHaveBeenCalledWith("/api/community/channels/child/messages?entry=1&window=tail", expect.anything()))
await expect(query.mock.results[0]!.value).rejects.toBe(error)
expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child", "server")).toBe(status !== 500)
expect(getCapturedRuntime().ws.get().accessEpoch).toBe(before)
@@ -688,13 +688,13 @@ describe("membership metadata and access lifetime", () => {
const api = getCommunityApiFetchMock()
const fallback = api.getMockImplementation()!
const archived = new ApiError("archived", 403)
- api.mockImplementation((...args) => args[0] === "/api/community/channels/child/messages?entry=1" ? Promise.reject(archived) : fallback(...args))
+ api.mockImplementation((...args) => args[0] === "/api/community/channels/child/messages?entry=1&window=tail" ? Promise.reject(archived) : fallback(...args))
const key = communityKeys.channelMessages("child")
capturedQueryClient.setQueryData(key, { pages: [{ messages: [{ id: "private" }] }] })
expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child", "server")).toBe(false)
const query = vi.spyOn(capturedQueryClient, "query")
capturedOnMessage!(currentCommunityEventFixture({ type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me", relation: "access", present: true }))
- await vi.waitFor(() => expect(api).toHaveBeenCalledWith("/api/community/channels/child/messages?entry=1", expect.anything()))
+ await vi.waitFor(() => expect(api).toHaveBeenCalledWith("/api/community/channels/child/messages?entry=1&window=tail", expect.anything()))
await expect(query.mock.results[0]!.value).rejects.toBe(archived)
await vi.waitFor(() => expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child", "server")).toBe(true))
expect(capturedQueryClient.getQueryData(key)).toBeUndefined()
@@ -801,7 +801,7 @@ describe("membership metadata and access lifetime", () => {
await vi.waitFor(() => expect(canonicalMessage(currentBody.id)?.content).toBe("Current body"))
const reads: Array<{ signal: AbortSignal; resolve: (value: unknown) => void; reject: (error: unknown) => void }> = []
api.mockImplementation(async (...args: unknown[]) => {
- if (args[0] !== "/api/community/channels/child/messages?entry=1") return payload
+ if (args[0] !== "/api/community/channels/child/messages?entry=1&window=tail") return payload
return await new Promise((resolve, reject) => {
reads.push({ signal: (args[1] as { signal: AbortSignal }).signal, resolve, reject })
})
@@ -851,7 +851,7 @@ describe("membership metadata and access lifetime", () => {
api.mockResolvedValue(payload)
const metadata = await mountCanonicalHook(() => useChannelMetadata("server", "child"))
await vi.waitFor(() => expect(metadata.result.current.isVerified).toBe(true))
- const before = api.mock.calls.filter(([path]) => path === "/api/community/channels/child/messages?entry=1").length
+ const before = api.mock.calls.filter(([path]) => path === "/api/community/channels/child/messages?entry=1&window=tail").length
const events = [
{ relation: "access", present: true, type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me" },
{ relation: "access", present: true, type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me" },
@@ -865,7 +865,7 @@ describe("membership metadata and access lifetime", () => {
})
if (!encoded.ok) throw new Error("Participant events must encode")
await act(async () => capturedOnMessage!(encoded.batch))
- await vi.waitFor(() => expect(api.mock.calls.filter(([path]) => path === "/api/community/channels/child/messages?entry=1")).toHaveLength(before + 1))
+ await vi.waitFor(() => expect(api.mock.calls.filter(([path]) => path === "/api/community/channels/child/messages?entry=1&window=tail")).toHaveLength(before + 1))
await vi.waitFor(() => expect(metadata.result.current.isVerified).toBe(true))
expect(isChannelMetadataTokenCurrent(metadata.result.current.data!.identityProof!)).toBe(true)
expect(hasCanonicalChannelNotify("child", "u_me")).toBe(false)
@@ -884,17 +884,17 @@ describe("membership metadata and access lifetime", () => {
capturedQueryClient.setQueryDefaults(communityKeys.conversationEntries("child"), { retryDelay: 0 })
const metadata = await mountCanonicalHook(() => useChannelMetadata("server", "child"))
await vi.waitFor(() => expect(metadata.result.current.isVerified).toBe(true))
- const before = api.mock.calls.filter(([path]) => path === "/api/community/channels/child/messages?entry=1").length
+ const before = api.mock.calls.filter(([path]) => path === "/api/community/channels/child/messages?entry=1&window=tail").length
api.mockRejectedValue(new ApiError("temporary", 503))
capturedOnMessage!(currentCommunityEventFixture({ relation: "access", present: true, type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me" }))
await vi.waitFor(() => expect(metadata.result.current).toMatchObject({ isError: true, fetchStatus: "idle", isVerified: false }))
- expect(api.mock.calls.filter(([path]) => path === "/api/community/channels/child/messages?entry=1")).toHaveLength(before + 2)
+ expect(api.mock.calls.filter(([path]) => path === "/api/community/channels/child/messages?entry=1&window=tail")).toHaveLength(before + 2)
await act(async () => { await new Promise<void>((resolve) => setTimeout(resolve, 20)) })
- expect(api.mock.calls.filter(([path]) => path === "/api/community/channels/child/messages?entry=1")).toHaveLength(before + 2)
+ expect(api.mock.calls.filter(([path]) => path === "/api/community/channels/child/messages?entry=1&window=tail")).toHaveLength(before + 2)
api.mockResolvedValue(payload)
await act(async () => { await metadata.result.current.refetch({ cancelRefetch: false }) })
await vi.waitFor(() => expect(metadata.result.current.isVerified).toBe(true))
- expect(api.mock.calls.filter(([path]) => path === "/api/community/channels/child/messages?entry=1")).toHaveLength(before + 3)
+ expect(api.mock.calls.filter(([path]) => path === "/api/community/channels/child/messages?entry=1&window=tail")).toHaveLength(before + 3)
})
it.each(["parent", "server", "account", "unmount"] as const)("does not restart participation metadata after %s retirement before handoff", async (race) => {
@@ -918,7 +918,7 @@ describe("membership metadata and access lifetime", () => {
const gate = new Promise<void>((resolve) => { release = resolve })
const cancel = capturedQueryClient.cancelQueries.bind(capturedQueryClient)
vi.spyOn(capturedQueryClient, "cancelQueries").mockImplementation(async (...args) => { await cancel(...args); await gate })
- const before = api.mock.calls.filter(([path]) => path === "/api/community/channels/child/messages?entry=1").length
+ const before = api.mock.calls.filter(([path]) => path === "/api/community/channels/child/messages?entry=1&window=tail").length
await act(async () => {
capturedOnMessage!(currentCommunityEventFixture({ relation: "notify", present: false, type: "community:channel.membership.change", channelId: "child", serverId: "server", userId: "u_me" }))
if (race === "parent") capturedOnMessage!(currentCommunityEventFixture({ relation: "access", present: false, type: "community:channel.membership.change", channelId: "parent", serverId: "server", userId: "u_me" }))
@@ -927,7 +927,7 @@ describe("membership metadata and access lifetime", () => {
else metadata.unmount()
})
await act(async () => { release(); await Promise.resolve(); await Promise.resolve() })
- expect(api.mock.calls.filter(([path]) => path === "/api/community/channels/child/messages?entry=1")).toHaveLength(before)
+ expect(api.mock.calls.filter(([path]) => path === "/api/community/channels/child/messages?entry=1&window=tail")).toHaveLength(before)
if (race === "parent" || race === "server") {
const current = capturedQueryClient.getQueryCache().find({ queryKey: metaKey, exact: true })
expect(current).not.toBe(original)
@@ -1005,7 +1005,7 @@ describe("membership metadata and access lifetime", () => {
const key = communityKeys.channelMessages("child")
capturedQueryClient.setQueryData(key, { pages: [] })
capturedOnMessage!(currentCommunityEventFixture({ type: "community:channel.membership.change", relation: "access", present, channelId: "child", serverId: "server", userId: "u_me" }))
- await vi.waitFor(() => expect(getCommunityApiFetchMock()).toHaveBeenCalledWith("/api/community/channels/child/messages?entry=1", expect.anything()))
+ await vi.waitFor(() => expect(getCommunityApiFetchMock()).toHaveBeenCalledWith("/api/community/channels/child/messages?entry=1&window=tail", expect.anything()))
await vi.waitFor(() => expect(capturedQueryClient.getQueryState(entryKey("server", "child"))?.fetchStatus ?? "idle").toBe("idle"))
expect(getCapturedRuntime().ws.actions.isChannelAccessRevoked("child")).toBe(!present || status !== 500)
expect(capturedQueryClient.getQueryData(key) === undefined).toBe(!present || status !== 500)
diff --git a/src/web/src/hooks/community/community-ws/message-events.dom.test.ts b/src/web/src/hooks/community/community-ws/message-events.dom.test.ts
index 85c48c781..fe1a9891f 100644
--- a/src/web/src/hooks/community/community-ws/message-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/message-events.dom.test.ts
@@ -164,7 +164,7 @@ describe("useCommunityWs — message.create", () => {
await seedCanonicalForumSidebar("srv_1")
expect(hasCanonicalChannel("post_live")).toBe(false)
getCommunityApiFetchMock().mockImplementation(async (url: string) => {
- if (url === "/api/community/channels/post_live/messages?entry=1") {
+ if (url === "/api/community/channels/post_live/messages?entry=1&window=tail") {
return conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0,
id: "post_live",
serverId: "srv_1",
@@ -195,7 +195,7 @@ describe("useCommunityWs — message.create", () => {
.find((channel) => channel.id === "post_live")?.lastMessageAt)
.toBe("2026-07-03T00:00:00.000Z")
expect(getCommunityApiFetchMock()).toHaveBeenCalledWith(
- "/api/community/channels/post_live/messages?entry=1",
+ "/api/community/channels/post_live/messages?entry=1&window=tail",
expect.objectContaining({ signal: expect.any(AbortSignal), assertActive: expect.any(Function), authenticationAccount: "u_me" }),
)
@@ -206,7 +206,7 @@ describe("useCommunityWs — message.create", () => {
parentChannelId: "forum_1",
} satisfies CommunityMessageCreate))
await vi.waitFor(() => expect(getCommunityApiFetchMock()).toHaveBeenCalledWith(
- "/api/community/channels/post_unavailable/messages?entry=1",
+ "/api/community/channels/post_unavailable/messages?entry=1&window=tail",
expect.objectContaining({ signal: expect.any(AbortSignal), assertActive: expect.any(Function), authenticationAccount: "u_me" }),
))
expect(hasCanonicalChannel("post_unavailable")).toBe(false)
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
index d10fccfd7..7a7a3728d 100644
--- 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
@@ -35,6 +35,7 @@ async function setup(sequences = [98, 99, 100], tag: string | null = null) {
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 },
+ newBoundary: { afterSeq: last.seq, target: null },
page: { ...fixture().page, latestSeq: last.seq, hasMoreOlder: true, hasMoreNewer: false },
}
const options = conversationEntryOptions(owner.client, target)
diff --git a/src/web/src/hooks/community/community-ws/social-events.dom.test.ts b/src/web/src/hooks/community/community-ws/social-events.dom.test.ts
index 81d3169b6..5011e347b 100644
--- a/src/web/src/hooks/community/community-ws/social-events.dom.test.ts
+++ b/src/web/src/hooks/community/community-ws/social-events.dom.test.ts
@@ -238,7 +238,7 @@ describe("useCommunityWs — friend + mention → invalidate", () => {
const metadata = { ...baseMetadata, peer: { ...baseMetadata.peer!, id: "u_a" } }
const api = getCommunityApiFetchMock()
const original = api.getMockImplementation()!
- api.mockImplementation((...args: unknown[]) => args[0] === "/api/community/channels/dm_u_a/messages?entry=1" ? Promise.resolve(metadata) : original(...args))
+ api.mockImplementation((...args: unknown[]) => args[0] === "/api/community/channels/dm_u_a/messages?entry=1&window=tail" ? Promise.resolve(metadata) : original(...args))
await capturedQueryClient.query(channelMetadataOptions(capturedQueryClient, null, "dm_u_a"))
const proof = captureCommunityLiveSnapshotToken(capturedQueryClient)
const oldMetadata = captureChannelMetadataToken(capturedQueryClient, "dm_u_a")
@@ -246,9 +246,9 @@ describe("useCommunityWs — friend + mention → invalidate", () => {
expect(canonicalMessage("private")?.content).toBe("private body")
let release!: (value: typeof metadata) => void
const held = new Promise<typeof metadata>((resolve) => { release = resolve })
- api.mockImplementation((...args: unknown[]) => args[0] === "/api/community/channels/dm_u_a/messages?entry=1" ? held : original(...args))
+ api.mockImplementation((...args: unknown[]) => args[0] === "/api/community/channels/dm_u_a/messages?entry=1&window=tail" ? held : original(...args))
const pending = capturedQueryClient.query({ ...channelMetadataOptions(capturedQueryClient, null, "dm_u_a"), staleTime: 0 }).catch((error: unknown) => error)
- await vi.waitFor(() => expect(api.mock.calls.filter(([path]) => path === "/api/community/channels/dm_u_a/messages?entry=1")).toHaveLength(2))
+ await vi.waitFor(() => expect(api.mock.calls.filter(([path]) => path === "/api/community/channels/dm_u_a/messages?entry=1&window=tail")).toHaveLength(2))
act(() => {
getCapturedRuntime().ui.actions.setCurrentChannelId("dm_u_a")
getCapturedRuntime().ui.setState((state) => ({ ...state, subscription: { dmConversationId: "dm_u_a" } }))
diff --git a/src/web/src/hooks/community/conversation-cache-reveal.dom.test.tsx b/src/web/src/hooks/community/conversation-cache-reveal.dom.test.tsx
index 66c04cf03..210498859 100644
--- a/src/web/src/hooks/community/conversation-cache-reveal.dom.test.tsx
+++ b/src/web/src/hooks/community/conversation-cache-reveal.dom.test.tsx
@@ -6,8 +6,8 @@ import { conversationEntryFixture, dmConversationEntryFixture, seedConversationE
import { ingestReadStateSnapshot } from "@/lib/community-db/sync"
import { communityKeys } from "@/lib/query-keys"
import { MessageList } from "@/components/community/messages/message-list"
+import { ConversationFooterShell, ConversationFooterSlotProvider } from "@/components/community/messages/conversation-footer-shell"
import { CommunityRouteContext } from "@/contexts/community/route-frame"
-import { resolveMessageReadProjection } from "@/lib/community/message-read-projection"
import { useDmMessages, useMessages } from "./use-messages"
import { installMessageScrollFixture, restoreMessageScrollFixture, resize, runFrames, scrollFixture } from "@/test/message-scroll-fixture"
@@ -43,7 +43,7 @@ beforeEach(() => { installMessageScrollFixture(); load.mockReset(); preCommand.l
afterEach(restoreMessageScrollFixture)
const kinds = ["text", "text-thread", "forum-post", "dm"] as const
-it.each(["text", "dm"] as const)("keeps ordinary $0 cached entry at the qualified tail after refresh", async kind => {
+it.each(["text", "dm"] as const)("waits for the latest ordinary $0 entry when only a history window is cached", async kind => {
scrollFixture.width = 390
const owner = await createCommunityQueryOwner("viewer", { defaultOptions: { queries: { retry: false, staleTime: Infinity } } })
const packet = kind === "dm" ? dmConversationEntryFixture() : conversationEntryFixture()
@@ -52,8 +52,9 @@ it.each(["text", "dm"] as const)("keeps ordinary $0 cached entry at the qualifie
packet.messages = rows.slice(0, 35)
packet.readState = { ...packet.readState, lastReadMessageId: "m35", lastReadSeq: 35, lastReadAt: rows[34].createdAt }
packet.selection = { reason: "read_pointer", anchorMessageId: "m35" }
+ packet.newBoundary = { afterSeq: 35, target: { id: "m36", channelId: "c1", seq: 36, authorId: "peer" } }
packet.page = { olderCursor: null, newerCursor: `${rows[34].createdAt}|m35`, hasMoreOlder: false, hasMoreNewer: true, latestSeq: 80 }
- await seedConversationEntry(owner.client, packet)
+ await seedConversationEntry(owner.client, packet, { channelId: "c1", serverId: packet.channel.serverId, preferTail: false })
const read = { ...packet.readState, lastReadMessageId: "m80", lastReadSeq: 80, lastReadAt: rows[79].createdAt }
ingestReadStateSnapshot(owner.registry, { revision: 5, readStates: [read] })
owner.client.removeQueries({ queryKey: communityKeys.conversationEntries("c1") })
@@ -64,33 +65,33 @@ it.each(["text", "dm"] as const)("keeps ordinary $0 cached entry at the qualifie
const channel = useMessages(kind === "dm" ? null : "c1", { serverId: "s1" })
const dm = useDmMessages(kind === "dm" ? "c1" : null)
feed = kind === "dm" ? dm : channel
- const projection = resolveMessageReadProjection({ messages: feed.messages, lastReadMessageId: feed.readSnapshot?.lastReadMessageId ?? null,
- viewerUserId: "viewer", anchorReconciled: feed.anchorReconciled })
+ const newBoundary = feed.newBoundary
return <MessageList channel="Channel" variant={kind === "dm" ? "dm" : "channel"} messages={feed.messages}
loading={feed.isLoading} initialLoadError={feed.initialLoadError} targetLoadError={feed.targetLoadError}
- initialScrollReady={feed.initialDisplayReady} preserveInitialPresentation={feed.preserveInitialPresentation} positionScope={feed.positionScope} positionEntry={feed.positionEntry}
+ initialScrollReady={feed.initialScrollReady} preserveInitialPresentation={feed.preserveInitialPresentation} positionScope={feed.positionScope} positionEntry={feed.positionEntry}
positionDataState={feed.positionDataState} targetPositionDataState={feed.targetPositionDataState} messageWindow={feed.messageWindow}
- newDividerBefore={projection.newDividerBefore} hasMore={feed.hasMoreOlder} hasMoreNewer={feed.hasMoreNewer}
+ newBoundary={newBoundary} latestSeq={feed.latestSeq} retiredNewTargetId={feed.retiredNewTargetId}
+ onLoadNewTarget={feed.loadNewTarget} onReadNewBoundary={feed.readNewBoundary} hasMore={feed.hasMoreOlder} hasMoreNewer={feed.hasMoreNewer}
onUserTakeover={feed.onUserTakeover} onRetryInitialLoad={feed.retryInitialLoad} retryingInitialLoad={feed.retryingInitialLoad} onOpenThread={() => {}} />
}
const view = render(<CommunityTestProvider {...owner}><Probe /></CommunityTestProvider>)
const phases: unknown[] = []
try {
resize()
- const root = view.getByTestId("community-message-scroller")
+ let root = view.getByTestId("community-message-scroller")
const capture = (phase: string) => phases.push({ phase, scrollTop: root.scrollTop, scrollHeight: root.scrollHeight, clientHeight: root.clientHeight,
distanceToEnd: root.scrollHeight - root.clientHeight - root.scrollTop, first: feed.messages[0]?.id, last: feed.messages.at(-1)?.id,
hasMoreNewer: feed.hasMoreNewer, positionDataState: feed.positionDataState, busy: root.getAttribute("aria-busy") })
- capture("cached-display")
- expect(root).toHaveAttribute("aria-busy", "false")
- expect(root.scrollHeight - root.clientHeight - root.scrollTop).toBeLessThanOrEqual(1)
+ capture("waiting-for-latest")
+ expect(root.closest("[aria-busy]")).toHaveAttribute("aria-busy", "true")
+ expect(feed.messages).toEqual([])
const fresh = { ...packet, messages: rows.slice(34), readState: read, readStateRevision: 5,
- selection: { reason: "read_pointer" as const, anchorMessageId: "m80" },
+ selection: { reason: "tail" as const, anchorMessageId: null }, newBoundary: { afterSeq: 80, target: null },
page: { olderCursor: `${rows[34].createdAt}|m35`, newerCursor: null, hasMoreOlder: true, hasMoreNewer: false, latestSeq: 80 } }
await act(async () => { release(fresh); await vi.advanceTimersByTimeAsync(0) })
resize()
capture("entry-refresh")
- expect(view.getByTestId("community-message-scroller")).toBe(root)
+ root = view.getByTestId("community-message-scroller")
expect(feed.messages.at(-1)?.id).toBe("m80")
expect(root.querySelector("[data-new-divider]")).toBeNull()
expect(root.scrollHeight - root.clientHeight - root.scrollTop).toBeLessThanOrEqual(1)
@@ -118,8 +119,10 @@ it.each(kinds.flatMap(kind => [
createdAt: new Date(Date.UTC(2026, 9, 1, 0, 0, index + 1)).toISOString() }))
packet.messages = rows.slice(0, 35)
packet.readState = { ...packet.readState, lastReadMessageId: "m10", lastReadSeq: 10 }
- packet.selection = { reason: "read_pointer", anchorMessageId: "m10" }
- packet.page = { olderCursor: null, newerCursor: `${rows[34].createdAt}|m35`, hasMoreOlder: false, hasMoreNewer: true, latestSeq: 80 }
+ packet.selection = { reason: "tail", anchorMessageId: null }
+ packet.newBoundary = { afterSeq: 10, target: { id: "m11", channelId: "c1", seq: 11, authorId: "peer" } }
+ packet.channel.messageCount = 35
+ packet.page = { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 35 }
await seedConversationEntry(owner.client, packet)
const read = { ...packet.readState, lastReadMessageId: "m60", lastReadSeq: 60, lastReadAt: rows[59].createdAt }
ingestReadStateSnapshot(owner.registry, { revision: 5, readStates: [read] })
@@ -131,48 +134,53 @@ it.each(kinds.flatMap(kind => [
const channel = useMessages(kind === "dm" ? null : "c1", { serverId: "s1" })
const dm = useDmMessages(kind === "dm" ? "c1" : null)
feed = kind === "dm" ? dm : channel
- const projection = resolveMessageReadProjection({ messages: feed.messages, lastReadMessageId: feed.readSnapshot?.lastReadMessageId ?? null,
- viewerUserId: "viewer", anchorReconciled: feed.anchorReconciled })
- return <MessageList channel="Channel" variant={kind === "dm" ? "dm" : "channel"} messages={feed.messages}
+ const newBoundary = feed.newBoundary
+ return <ConversationFooterSlotProvider><div data-slot="community-conversation-surface"><MessageList channel="Channel" variant={kind === "dm" ? "dm" : "channel"} messages={feed.messages}
loading={feed.isLoading} initialLoadError={feed.initialLoadError} targetLoadError={feed.targetLoadError}
- initialScrollReady={feed.initialDisplayReady} preserveInitialPresentation={feed.preserveInitialPresentation} positionScope={feed.positionScope} positionEntry={feed.positionEntry}
+ initialScrollReady={feed.initialScrollReady} preserveInitialPresentation={feed.preserveInitialPresentation} positionScope={feed.positionScope} positionEntry={feed.positionEntry}
positionDataState={feed.positionDataState} targetPositionDataState={feed.targetPositionDataState} messageWindow={feed.messageWindow}
- newDividerBefore={projection.newDividerBefore} hasMore={feed.hasMoreOlder} hasMoreNewer={feed.hasMoreNewer}
+ newBoundary={newBoundary} latestSeq={feed.latestSeq} retiredNewTargetId={feed.retiredNewTargetId}
+ onLoadNewTarget={feed.loadNewTarget} onReadNewBoundary={feed.readNewBoundary} hasMore={feed.hasMoreOlder} hasMoreNewer={feed.hasMoreNewer}
onUserTakeover={feed.onUserTakeover} onRetryInitialLoad={feed.retryInitialLoad} retryingInitialLoad={feed.retryingInitialLoad} onOpenThread={() => {}} />
+ <ConversationFooterShell><div>composer</div></ConversationFooterShell>
+ </div></ConversationFooterSlotProvider>
}
const view = render(<CommunityTestProvider {...owner}><Probe /></CommunityTestProvider>)
try {
resize()
- const root = view.getByTestId("community-message-scroller")
- expect(root).toHaveAttribute("aria-busy", "false")
- expect(root.querySelector("[data-read-position-ready]")).toHaveAttribute("data-read-position-ready", "false")
+ let root = view.getByTestId("community-message-scroller")
+ expect(root.closest("[aria-busy]")).toHaveAttribute("aria-busy", "true")
+ expect(root.querySelector('[data-read-position-ready="true"]')).toBeNull()
expect(root).toHaveAttribute("data-pagination-enabled", "false")
await act(async () => { reject(new Error("held entry failed")); await vi.advanceTimersByTimeAsync(2000) })
resize()
+ root = view.getByTestId("community-message-scroller")
+ expect(root.querySelector('[data-msg-id="m10"]')).not.toBeNull()
let release!: (value: typeof packet) => void
const retry = new Promise<typeof packet>(resolve => { release = resolve })
- const repairPage = { ...packet.page, profiles: packet.profiles, messages: packet.messages }
+ const repairPage = { ...packet.page, latestSeq: 80, profiles: packet.profiles, messages: rows.slice(35) }
let failRepair = repairFailure
load.mockImplementation((url: string) => url.includes("entry=1") ? retry
: failRepair ? Promise.reject(new Error("owned window repair failed")) : Promise.resolve(repairPage))
fireEvent.click(view.getByRole("button", { name: "Retry" }))
await act(async () => { await vi.advanceTimersByTimeAsync(0) })
resize()
- expect(root).toHaveAttribute("aria-busy", "false")
+ expect(root).toHaveAttribute("aria-busy", "true")
expect(root).toHaveAttribute("data-pagination-enabled", "false")
if (takeover) {
- fireEvent.wheel(root, { deltaY: -300 })
- act(() => root.scrollTo({ top: root.scrollTop - 300 }))
+ fireEvent.wheel(root, { deltaY: 1000 })
+ act(() => root.scrollTo({ top: 1000 }))
resize()
}
+ expect(root).toHaveAttribute("aria-busy", takeover ? "false" : "true")
const viewport = root.getBoundingClientRect()
const reader = Array.from(root.querySelectorAll<HTMLElement>("[data-msg-id]")).find(row => row.getBoundingClientRect().bottom > viewport.top + 1)!
const readerId = reader.dataset.msgId!
const offset = reader.getBoundingClientRect().top - viewport.top
expect(Number(readerId.slice(1))).toBeLessThan(35)
- const fresh = { ...packet, messages: rows.slice(34), readState: read, readStateRevision: 5,
- selection: { reason: "read_pointer" as const, anchorMessageId: "m60" },
- page: { olderCursor: `${rows[34].createdAt}|m35`, newerCursor: null, hasMoreOlder: true, hasMoreNewer: false, latestSeq: 80 } }
+ const fresh = { ...packet, channel: { ...packet.channel, messageCount: 80 }, messages: rows.slice(59), readState: read, readStateRevision: 5,
+ selection: { reason: "tail" as const, anchorMessageId: null }, newBoundary: { afterSeq: 60, target: { id: "m61", channelId: "c1", seq: 61, authorId: "peer" } },
+ page: { olderCursor: `${rows[59].createdAt}|m60`, newerCursor: null, hasMoreOlder: true, hasMoreNewer: false, latestSeq: 80 } }
await act(async () => { release(fresh); await vi.advanceTimersByTimeAsync(0) })
resize()
expect(view.getByTestId("community-message-scroller")).toBe(root)
@@ -184,10 +192,10 @@ it.each(kinds.flatMap(kind => [
expect(root.querySelector(`[data-msg-id="${readerId}"]`)).toBe(reader)
expect(Math.abs(reader.getBoundingClientRect().top - root.getBoundingClientRect().top - offset)).toBeLessThanOrEqual(1)
} else {
- expect(feed.messages.map(row => row.id)).toEqual(rows.slice(34).map(row => row.id))
- const divider = root.querySelector<HTMLElement>("[data-new-divider]")!.getBoundingClientRect()
- expect(divider.bottom).toBeGreaterThan(viewport.top)
- expect(divider.top).toBeLessThan(viewport.bottom)
+ expect(feed.messages.map(row => row.id)).toEqual(rows.map(row => row.id))
+ expect(root.scrollHeight - root.clientHeight - root.scrollTop).toBeLessThanOrEqual(1)
+ expect(feed.newBoundary?.target?.id).toBe("m61")
+ expect(view.getByRole("button", { name: "Jump to New" })).toBeVisible()
}
if (repairFailure) {
expect(root).toHaveAttribute("data-pagination-enabled", "false")
@@ -227,24 +235,25 @@ it.each(kinds.flatMap(kind => (["success", "offline", "timeout"] as const).map(r
}
packet.messages = Array.from({ length: 42 }, (_, index) => ({ ...packet.messages[0], id: `m${index + 1}`, seq: index + 1 }))
packet.readState = { ...packet.readState, lastReadMessageId: "m30", lastReadSeq: 30 }
- packet.selection = { reason: "read_pointer", anchorMessageId: "m30" }
- packet.page = { olderCursor: null, newerCursor: "newer", hasMoreOlder: false, hasMoreNewer: true, latestSeq: 80 }
+ packet.selection = { reason: "tail", anchorMessageId: null }
+ packet.newBoundary = { afterSeq: 30, target: { id: "m31", channelId: "c1", seq: 31, authorId: "peer" } }
+ packet.page = { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 42 }
await seedConversationEntry(owner.client, packet)
- if (kind === "dm") ingestReadStateSnapshot(owner.registry, { revision: 5, readStates: [{ ...packet.readState, lastReadMessageId: "m60", lastReadSeq: 60, lastReadAt: packet.messages[0].createdAt }] })
owner.client.removeQueries({ queryKey: communityKeys.conversationEntries("c1") })
let resolve!: (value: typeof packet) => void, reject!: (error: Error) => void
load.mockReturnValue(new Promise<typeof packet>((yes, no) => { resolve = yes; reject = no }))
let feed!: ReturnType<typeof useMessages>
function Probe() {
const channel = useMessages(kind === "dm" ? null : "c1", { serverId: "s1", anchorMessageId: "m60" })
- const dm = useDmMessages(kind === "dm" ? "c1" : null)
+ const dm = useDmMessages(kind === "dm" ? "c1" : null, { anchorMessageId: "m60" })
feed = kind === "dm" ? dm : channel
- const projection = resolveMessageReadProjection({ messages: feed.messages, lastReadMessageId: feed.readSnapshot?.lastReadMessageId ?? null, viewerUserId: "viewer", anchorReconciled: feed.anchorReconciled })
+ const newBoundary = feed.newBoundary
return <MessageList channel="Channel" variant={kind === "dm" ? "dm" : "channel"} messages={feed.messages}
loading={feed.isLoading} initialLoadError={feed.initialLoadError} targetLoadError={feed.targetLoadError}
- initialScrollReady={feed.initialDisplayReady} preserveInitialPresentation={feed.preserveInitialPresentation} positionScope={feed.positionScope} positionEntry={feed.positionEntry}
+ initialScrollReady={feed.initialScrollReady} preserveInitialPresentation={feed.preserveInitialPresentation} positionScope={feed.positionScope} positionEntry={feed.positionEntry}
positionDataState={feed.positionDataState} targetPositionDataState={feed.targetPositionDataState} messageWindow={feed.messageWindow}
- newDividerBefore={projection.newDividerBefore} scrollToMessageId={kind === "dm" ? undefined : "m60"} hasMoreNewer={feed.hasMoreNewer}
+ newBoundary={newBoundary} latestSeq={feed.latestSeq} retiredNewTargetId={feed.retiredNewTargetId}
+ onLoadNewTarget={feed.loadNewTarget} onReadNewBoundary={feed.readNewBoundary} scrollToMessageId="m60" hasMoreNewer={feed.hasMoreNewer}
onRetryInitialLoad={feed.retryInitialLoad} retryingInitialLoad={feed.retryingInitialLoad} onOpenThread={() => {}} />
}
const view = render(<CommunityTestProvider {...owner}><Probe /></CommunityTestProvider>)
@@ -254,19 +263,18 @@ it.each(kinds.flatMap(kind => (["success", "offline", "timeout"] as const).map(r
expect(feed.initialDisplayReady).toBe(true)
expect(feed.initialPositionKnown).toBe(false)
expect(feed.readSnapshotFetching).toBe(true)
- expect(feed.targetPositionDataState).toBe(kind === "dm" ? "ready" : "pending")
+ expect(feed.targetPositionDataState).toBe("pending")
expect(feed.positionDataState).toBe("pending")
expect(root).toHaveAttribute("aria-busy", "false")
expect(root.querySelector("[data-message-list-content]")).toHaveAttribute("aria-hidden", "false")
expect(root.querySelector("[data-read-position-ready]")).toHaveAttribute("data-read-position-ready", "false")
expect(root).toHaveAttribute("data-pagination-enabled", "false")
expect(root.querySelectorAll("[data-msg-id]").length).toBeGreaterThan(0)
- expect(load.mock.calls.some(([path]) => path.endsWith(kind === "dm" ? "entry=1" : "entry=1&anchor=m60"))).toBe(true)
+ expect(load.mock.calls.some(([path]) => new URL(path, "https://test.invalid").searchParams.get("anchor") === "m60")).toBe(true)
expect(load.mock.calls.some(([path]) => path.endsWith("/read"))).toBe(false)
- const fresh = { ...packet, selection: { reason: kind === "dm" ? "read_pointer" as const : "explicit_anchor" as const, anchorMessageId: "m60" },
- ...(kind === "dm" ? { readState: { ...packet.readState, lastReadMessageId: "m60", lastReadSeq: 60 }, readStateRevision: 5 } : {}),
+ const fresh = { ...packet, selection: { reason: "explicit_anchor" as const, anchorMessageId: "m60" },
messages: Array.from({ length: 22 }, (_, index) => ({ ...packet.messages[0], id: `m${index + 59}`, seq: index + 59 })),
- page: { ...packet.page, hasMoreOlder: true, hasMoreNewer: false, newerCursor: null } }
+ page: { ...packet.page, latestSeq: 80, hasMoreOlder: true, hasMoreNewer: false, newerCursor: null } }
await act(async () => {
if (result === "success") resolve(fresh)
else if (result === "offline") reject(new Error("offline"))
@@ -346,7 +354,8 @@ it.each([
packet.messages = rows
packet.channel.messageCount = 60
packet.readState = { ...packet.readState, lastReadMessageId: "ro60", lastReadSeq: 60, lastReadAt: rows[59].createdAt }
- packet.selection = { reason: "read_pointer", anchorMessageId: "ro60" }
+ packet.selection = { reason: "tail", anchorMessageId: null }
+ packet.newBoundary = { afterSeq: 60, target: null }
packet.page = { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 60 }
await seedConversationEntry(owner.client, packet)
load.mockResolvedValue(packet)
@@ -358,12 +367,11 @@ it.each([
const handovers = vi.fn(() => feed.onUserTakeover())
function Probe() {
feed = useDmMessages("c1")
- const projection = resolveMessageReadProjection({ messages: feed.messages, lastReadMessageId: feed.readSnapshot?.lastReadMessageId ?? null,
- viewerUserId: "viewer", anchorReconciled: feed.anchorReconciled })
- newDivider = projection.newDividerBefore
+ const newBoundary = feed.newBoundary
+ newDivider = newBoundary?.target?.id
return <MessageList channel="DM" variant="dm" messages={feed.messages} loading={feed.isLoading}
initialLoadError={feed.initialLoadError} targetLoadError={feed.targetLoadError}
- initialScrollReady={feed.initialDisplayReady} preserveInitialPresentation={feed.preserveInitialPresentation}
+ initialScrollReady={feed.initialScrollReady} preserveInitialPresentation={feed.preserveInitialPresentation}
positionScope={feed.positionScope} positionEntry={feed.positionEntry}
positionDataState={feed.positionDataState} targetPositionDataState={feed.targetPositionDataState} messageWindow={feed.messageWindow}
initialPositionMessageId={feed.initialPositionMessageId} newDividerBefore={newDivider}
diff --git a/src/web/src/hooks/community/conversation-entry.request-scope.dom.test.tsx b/src/web/src/hooks/community/conversation-entry.request-scope.dom.test.tsx
index 8da7ebaa3..be89f513c 100644
--- a/src/web/src/hooks/community/conversation-entry.request-scope.dom.test.tsx
+++ b/src/web/src/hooks/community/conversation-entry.request-scope.dom.test.tsx
@@ -46,7 +46,7 @@ it("retains hidden message and panel caches without starting requests, then load
hook.rerender()
await waitFor(() => expect(load.mock.calls.map(([url]) => String(url))).toHaveLength(3))
expect(load.mock.calls.map(([url]) => String(url))).toEqual(expect.arrayContaining([
- "/api/community/channels/c1/messages?entry=1", "/api/community/channels/c1/pins",
+ "/api/community/channels/c1/messages?entry=1&window=tail&newAfterSeq=1", "/api/community/channels/c1/pins",
"/api/community/channels/c1/threads?include=parentMessage,firstMessage,tags,participants&archived=false",
]))
expect(hook.result.current.feed.messages.map(message => message.id)).toEqual(["m1"])
diff --git a/src/web/src/hooks/community/message-window.reentry.dom.test.tsx b/src/web/src/hooks/community/message-window.reentry.dom.test.tsx
index ca51afc7b..138a1545a 100644
--- a/src/web/src/hooks/community/message-window.reentry.dom.test.tsx
+++ b/src/web/src/hooks/community/message-window.reentry.dom.test.tsx
@@ -23,7 +23,7 @@ async function wireOwner() {
const read = { ...base.readState, lastReadMessageId: "m240", lastReadSeq: 240, lastReadAt: messages[239].createdAt }
const entry = { ...base, channel: { ...base.channel, messageCount: 240, lastMessageAt: messages[239].createdAt },
messages: messages.slice(214, 240), readState: read, readStateRevision: 121,
- selection: { reason: "read_pointer" as const, anchorMessageId: "m240" },
+ selection: { reason: "tail" as const, anchorMessageId: null }, newBoundary: { afterSeq: 240, target: null },
page: { olderCursor: `${messages[214].createdAt}|m215`, newerCursor: null, hasMoreOlder: true, hasMoreNewer: false, latestSeq: 240 },
}
const requests: Array<{ query: string; version: string | null }> = []
@@ -66,7 +66,7 @@ async function wireOwner() {
const app = (active = true) => <Providers>{active ? <Probe /> : <div data-testid="away" />}</Providers>
const view = render(app())
await waitFor(() => expect(latest.messages).toHaveLength(26))
- const key = communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "m240" })
+ const key = communityKeys.channelMessagesWindow("c1", { mode: "newest" })
return { ...owner, view, key, requests, get latest() { return latest }, app,
enableCatchUp: () => { catchUp = true }, forceLegacyPages: () => { legacyPages = true },
}
diff --git a/src/web/src/hooks/community/use-channel-message-feed.dom.test.ts b/src/web/src/hooks/community/use-channel-message-feed.dom.test.ts
index 04bd1ab23..aa6696436 100644
--- a/src/web/src/hooks/community/use-channel-message-feed.dom.test.ts
+++ b/src/web/src/hooks/community/use-channel-message-feed.dom.test.ts
@@ -9,6 +9,7 @@ import { ConversationActivityContext } from "@/contexts/community/conversation-a
const mocks = vi.hoisted(() => ({
messages: { messages: [{ id: "read", authorId: "viewer", seq: 1 }, { id: "peer", authorId: "peer", seq: 2 }],
readSnapshot: { channelId: "c1", lastReadMessageId: "read", lastReadSeq: 1, lastReadAt: null } as { channelId: string; lastReadMessageId: string | null; lastReadSeq: number; lastReadAt: null } | null,
+ newBoundary: { afterSeq: 1, target: { id: "peer", channelId: "c1", seq: 2, authorId: "peer" } } as { afterSeq: number; target: { id: string; channelId: string; seq: number; authorId: string } } | undefined,
readSnapshotFetching: false, anchorReconciled: true, initialPositionKnown: true,
entryDenied: false, initialLoadError: null as Error | null, isPending: false, isError: false, hasMoreNewer: false,
latestSeq: 2, retryInitialLoad: vi.fn(), refetch: vi.fn(),
@@ -25,7 +26,7 @@ beforeEach(async () => {
owner = await createCommunityQueryOwner("viewer")
mocks.useMessages.mockClear(); mocks.watermark.mockClear(); mocks.messages.retryInitialLoad.mockClear()
Object.assign(mocks.messages, { readSnapshot: { channelId: "c1", lastReadMessageId: "read", lastReadSeq: 1, lastReadAt: null }, readSnapshotFetching: false,
- entryDenied: false, initialLoadError: null, isPending: false, isError: false, anchorReconciled: true, initialPositionKnown: true })
+ newBoundary: { afterSeq: 1, target: { id: "peer", channelId: "c1", seq: 2, authorId: "peer" } }, entryDenied: false, initialLoadError: null, isPending: false, isError: false, anchorReconciled: true, initialPositionKnown: true })
})
describe("message feed consumes the entry snapshot", () => {
@@ -42,14 +43,13 @@ describe("message feed consumes the entry snapshot", () => {
const hook = renderHook(() => useChannelMessageFeed(target), { wrapper: Owner })
expect(hook.result.current.newDividerBefore).toBe("peer")
expect(hook.result.current.unreadCount).toBe(1)
- expect(hook.result.current.anchorInCache).toBe(true)
expect(hook.result.current.threadsLoading).toBe(true)
expect(mocks.watermark).toHaveBeenLastCalledWith(expect.objectContaining({ snapshotStatus: "ready", confirmedSeq: 1, feedStatus: "ready" }))
hook.unmount()
})
it("keeps an unresolved entry pointer pending without a second leaf-read gate", () => {
- mocks.messages.readSnapshot = null; mocks.messages.readSnapshotFetching = true; mocks.messages.initialPositionKnown = false
+ mocks.messages.newBoundary = undefined; mocks.messages.readSnapshot = null; mocks.messages.readSnapshotFetching = true; mocks.messages.initialPositionKnown = false
const hook = renderHook(() => useChannelMessageFeed({ ...target, anchorMessageId: "deep" }), { wrapper: Owner })
expect(hook.result.current.newDividerBefore).toBeUndefined()
expect(mocks.watermark).toHaveBeenLastCalledWith(expect.objectContaining({ snapshotStatus: "pending" }))
diff --git a/src/web/src/hooks/community/use-channel-message-feed.ts b/src/web/src/hooks/community/use-channel-message-feed.ts
index d7cd88ecb..f26e89ca6 100644
--- a/src/web/src/hooks/community/use-channel-message-feed.ts
+++ b/src/web/src/hooks/community/use-channel-message-feed.ts
@@ -2,13 +2,11 @@
import { useConversationActivity } from "@/contexts/community/conversation-activity"
import { useAtom, useCreateAtom } from "@tanstack/react-store";
-import { useMemo } from "react"
import { isConversationAccessError } from "@/lib/community/conversation-read"
import { useMessageUnreadCount } from "./use-message-unread-count"
import { useChannelWatermark } from "./use-channel-watermark"
import { useMessages } from "./use-messages"
import { usePins, useThreads } from "./use-channel-panels"
-import { resolveMessageReadProjection } from "@/lib/community/message-read-projection"
export function useChannelMessageFeed({
channelId,
@@ -32,15 +30,7 @@ export function useChannelMessageFeed({
viewerUserId,
})
const readSnapshot = messagesQuery.readSnapshot
- const { newDividerBefore, anchorFound } = useMemo(() => {
- if (!readSnapshot) return { newDividerBefore: undefined, anchorFound: false }
- return resolveMessageReadProjection({
- messages: messagesQuery.messages,
- lastReadMessageId: readSnapshot.lastReadMessageId,
- viewerUserId,
- anchorReconciled: messagesQuery.anchorReconciled,
- })
- }, [messagesQuery.anchorReconciled, messagesQuery.messages, readSnapshot, viewerUserId])
+ const newDividerBefore = messagesQuery.newBoundary?.target?.id
const [scrollRootEl, setScrollRootEl] = useAtom(useCreateAtom<HTMLDivElement | null>(null))
/* istanbul ignore next -- retained Chromium covers the mounted observer integration */
useChannelWatermark({
@@ -74,7 +64,6 @@ export function useChannelMessageFeed({
...messagesQuery,
readSnapshot,
newDividerBefore,
- anchorInCache: anchorFound || messagesQuery.initialPositionKnown,
unreadCount,
scrollRootEl,
setScrollRootEl,
diff --git a/src/web/src/hooks/community/use-channel-metadata.dom.test.tsx b/src/web/src/hooks/community/use-channel-metadata.dom.test.tsx
index 77c6150fa..b8948187e 100644
--- a/src/web/src/hooks/community/use-channel-metadata.dom.test.tsx
+++ b/src/web/src/hooks/community/use-channel-metadata.dom.test.tsx
@@ -137,7 +137,7 @@ describe("qualified canonical channel identity", () => {
const hook = renderHook(() => useChannelMetadata("s1", "c1", { anchorMessageId: "gone" }), { wrapper })
await waitFor(() => expect(hook.result.current.canRead).toBe(true))
expect(hook.result.current.denied).toBe(false)
- expect(load.mock.calls.map(([path]) => path)).toEqual(["/api/community/channels/c1/messages?entry=1&anchor=gone", "/api/community/channels/c1/messages?entry=1"])
+ expect(load.mock.calls.map(([path]) => path)).toEqual(["/api/community/channels/c1/messages?entry=1&anchor=gone", "/api/community/channels/c1/messages?entry=1&window=tail"])
hook.unmount()
})
diff --git a/src/web/src/hooks/community/use-channel-metadata.ts b/src/web/src/hooks/community/use-channel-metadata.ts
index 3ff1096b6..44ed225c1 100644
--- a/src/web/src/hooks/community/use-channel-metadata.ts
+++ b/src/web/src/hooks/community/use-channel-metadata.ts
@@ -18,7 +18,7 @@ export function useChannelMetadata(serverId: string | null, channelId: string |
const storedTag = useStoredForumTag(forumSelection ? channelId ?? null : null)
const selectedTag = forumSelection ? forumTagFromUrl(intent?.tag) ?? storedTag : intent?.tag ?? "All"
const tag = selectedTag === "All" ? null : selectedTag
- const entry = useConversationResource(channelId ? { channelId, serverId, ...intent, tag } : null, null, false, "metadata", selectedTag !== null)
+ const entry = useConversationResource(channelId ? { channelId, serverId, ...intent, tag } : null, null, "metadata", selectedTag !== null)
const { query, canonical, scope, canRead, windowReady, revoked, denied } = entry
const runtime = useCommunityRuntime()
const denialCode = useSelector(runtime.ws, state => {
diff --git a/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts b/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts
index 6c463e0a0..638dbc209 100644
--- a/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts
+++ b/src/web/src/hooks/community/use-channel-route-model.retry.dom.test.ts
@@ -194,7 +194,7 @@ describe("unresolved metadata terminal error and retry", () => {
await until(() => current.routeLifecycle === "ready")
expect(current.metadataError).toBe(false)
expect(current.currentChannelMeta?.id).toBe("post-1")
- expect(mocks.apiFetch.mock.calls.every(([url]) => url === "/api/community/channels/post-1/messages?entry=1")).toBe(true)
+ expect(mocks.apiFetch.mock.calls.every(([url]) => url === "/api/community/channels/post-1/messages?entry=1&window=tail")).toBe(true)
expect(client.getQueryCache().findAll({ queryKey: channelMetadataOptions(client, "server-1", "post-1").queryKey, exact: true })).toHaveLength(1)
expect(mocks.replace).not.toHaveBeenCalled()
})
@@ -266,7 +266,7 @@ describe("unresolved metadata terminal error and retry", () => {
})
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)) })
expect(client.getQueryState(channelMetadataOptions(client, "server-1", "post-1").queryKey)?.status).toBe("error")
- expect(mocks.apiFetch).toHaveBeenCalledWith("/api/community/channels/post-1/messages?entry=1", expect.anything())
+ expect(mocks.apiFetch).toHaveBeenCalledWith("/api/community/channels/post-1/messages?entry=1&window=tail", expect.anything())
expect(current.routeLifecycle).toBe("ready")
expect(current.currentChannelMeta?.id).toBe("post-1")
expect(current.metadataError).toBe(false)
@@ -338,7 +338,7 @@ describe("unresolved metadata terminal error and retry", () => {
})
it("requires fresh metadata after reauthorization and can exit again on a later denial", async () => {
- const metadataPath = "/api/community/channels/post-1/messages?entry=1"
+ const metadataPath = "/api/community/channels/post-1/messages?entry=1&window=tail"
const metadataCalls = () => mocks.apiFetch.mock.calls.filter(([path]) => path === metadataPath).length
let readMetadata: () => Promise<unknown> = async () => payload()
mocks.apiFetch.mockImplementation((path: string) => path === metadataPath ? readMetadata() : Promise.resolve({ id: "viewer-1", name: "Viewer", discriminator: "0001", avatar: "V", avatarVersion: 0 }))
diff --git a/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts b/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts
index 30b9e1bcd..b92b1a421 100644
--- a/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts
+++ b/src/web/src/hooks/community/use-channel-route-model.subscription.dom.test.ts
@@ -594,15 +594,20 @@ it.each(["older", "newer", "jump"] as const)("rejects %s admission from a retain
value.channel = { ...value.channel, id: "post-1", serverId: "server-1" }
value.messages = value.messages.map(message => ({ ...message, channelId: "post-1" }))
value.access.channelId = value.readState.channelId = value.surfaceReceipt.channelId = "post-1"
+ const latest = { ...value.messages[0], id: "m2", seq: 2 }
+ await seedConversationEntry(queryClient, { ...value, messages: [latest], page: { ...value.page, latestSeq: 2 },
+ newBoundary: { afterSeq: 1, target: { id: "m2", channelId: "post-1", seq: 2, authorId: latest.authorId } } })
+ value.page.latestSeq = 2
+ value.selection = { reason: "explicit_anchor", anchorMessageId: "m1" }
value.page.newerCursor = "newer"
value.page.hasMoreNewer = true
- await seedConversationEntry(queryClient, value)
+ await seedConversationEntry(queryClient, value, { channelId: "post-1", serverId: "server-1", anchorMessageId: "m1" })
mocks.useRealMetadata = true
mocks.load.mockResolvedValue({ messages: value.messages, profiles: value.profiles, ...value.page })
const registry = getCommunityDbRegistry(queryClient)!
let feed!: ReturnType<typeof useMessages>
function Surface() {
- const current = useMessages("post-1", { serverId: "server-1" })
+ const current = useMessages("post-1", { serverId: "server-1", anchorMessageId: "m1" })
React.useLayoutEffect(() => { feed = current }, [current])
return React.createElement("span", { "data-testid": "retained-action-window" }, current.positionDataState)
}
diff --git a/src/web/src/hooks/community/use-child-channel-meta.dom.test.ts b/src/web/src/hooks/community/use-child-channel-meta.dom.test.ts
index 75fb5debf..1a8068966 100644
--- a/src/web/src/hooks/community/use-child-channel-meta.dom.test.ts
+++ b/src/web/src/hooks/community/use-child-channel-meta.dom.test.ts
@@ -114,7 +114,7 @@ describe("child channel metadata stale rendering", () => {
await waitFor(() => expect(apiFetchMock).toHaveBeenCalledOnce())
expect(apiFetchMock).toHaveBeenCalledWith(
- "/api/community/channels/post-1/messages?entry=1",
+ "/api/community/channels/post-1/messages?entry=1&window=tail",
expect.objectContaining({ authenticationAccount: "viewer", signal: expect.any(AbortSignal) }),
)
expect(queryClient.getQueryData(
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 241215a71..846a0320d 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
@@ -1,7 +1,7 @@
import { resourceBundleFixture, fullResourceBundleFixture, serverResourceFixture, profileResourceFixture } from "@/test/community-resource-fixtures"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { createElement, type PropsWithChildren } from "react"
-import { QueryClientProvider, QueryObserver } from "@tanstack/react-query"
+import { IsRestoringProvider, QueryClientProvider, QueryObserver } from "@tanstack/react-query"
import { act, render, renderHook, waitFor } from "@/test/react-dom-harness"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { conversationEntryFixture as fixture, dmConversationEntryFixture, forumConversationEntryFixture, conversationEntryTarget as target } from "@/test/conversation-entry-fixtures"
@@ -18,7 +18,6 @@ import { useConversationEntry } from "./use-conversation-entry"
import { useChannelMetadata } from "./use-channel-metadata"
import { useDmMessages, useMessages } from "./use-messages"
import { useForumFeed } from "./use-forum-feed"
-import { resolveMessageReadProjection } from "@/lib/community/message-read-projection"
import { useMessageListController } from "@/components/community/messages/message-list-controller"
import { VirtualRows } from "@/components/community/messages/virtual-cursor-list"
import { installMessageScrollFixture, restoreMessageScrollFixture, resize } from "@/test/message-scroll-fixture"
@@ -51,6 +50,51 @@ async function setup() {
}
describe("conversation entry selection", () => {
+ it("waits for a refreshing warm null boundary and preserves the captured cutoff across ACK", async () => {
+ const owner = await setup()
+ const old = fixture()
+ const resource = await owner.publish(old)
+ owner.client.setQueryData(conversationEntryOptions(owner.client, target).queryKey, resource, { updatedAt: Date.now() - 6000 })
+ const held = deferred<typeof old>()
+ load.mockReturnValue(held.promise)
+ const hook = renderHook(() => useMessages("c1", { serverId: "s1" }), { wrapper: owner.wrapper })
+ await waitFor(() => expect(load).toHaveBeenCalledOnce())
+ expect(hook.result.current.messages.map(message => message.id)).toEqual(["m1"])
+ expect(hook.result.current.newBoundary).toBeUndefined()
+ expect(new URL(load.mock.calls[0][0], "https://test.invalid").searchParams.get("newAfterSeq")).toBe("1")
+ const fresh = fixture()
+ fresh.messages = [...fresh.messages, { ...fresh.messages[0], id: "m2", seq: 2 }]
+ fresh.page = { ...fresh.page, latestSeq: 2 }
+ fresh.readState = { ...fresh.readState, lastReadMessageId: "m2", lastReadSeq: 2 }
+ fresh.readStateRevision = 5
+ fresh.newBoundary = { afterSeq: 1, target: { id: "m2", seq: 2, channelId: "c1", authorId: "peer" } }
+ await act(async () => held.resolve(fresh))
+ await waitFor(() => expect(hook.result.current.newBoundary?.target?.id).toBe("m2"))
+ await act(async () => ingestReadStateSnapshot(owner.registry, { revision: 6, readStates: [{ ...fresh.readState, lastReadSeq: 3, lastReadMessageId: "m3", lastReadAt: "2026-10-01T00:00:03.000Z" }] }))
+ expect(hook.result.current.newBoundary).toEqual(fresh.newBoundary)
+ expect(load.mock.calls.filter(([url]) => String(url).includes("entry=1"))).toHaveLength(1)
+ hook.unmount()
+ owner.client.clear()
+ })
+
+ it("offers entry Retry after warm New metadata fails while leaving the current messages readable", async () => {
+ const owner = await setup()
+ const packet = fixture()
+ const resource = await owner.publish(packet)
+ owner.client.setQueryData(conversationEntryOptions(owner.client, target).queryKey, resource, { updatedAt: Date.now() - 6000 })
+ load.mockRejectedValueOnce(new ConversationReadTimeoutError()).mockResolvedValue(packet)
+ const hook = renderHook(() => useMessages("c1", { serverId: "s1" }), { wrapper: owner.wrapper })
+ await waitFor(() => expect(hook.result.current.targetLoadError).toBeInstanceOf(ConversationReadTimeoutError))
+ expect(hook.result.current.initialDisplayReady).toBe(true)
+ expect(hook.result.current.newBoundary).toBeUndefined()
+ act(() => hook.result.current.retryInitialLoad())
+ await waitFor(() => expect(hook.result.current.newBoundary).toEqual({ afterSeq: 1, target: null }))
+ expect(hook.result.current.targetLoadError).toBeNull()
+ expect(load.mock.calls.filter(([url]) => String(url).includes("entry=1"))).toHaveLength(2)
+ hook.unmount()
+ owner.client.clear()
+ })
+
it("keeps takeover on its original entry and retires that selection on a fresh navigation", async () => {
const { client, wrapper: Owner, publish, registry } = await setup()
const old = fixture()
@@ -59,7 +103,9 @@ describe("conversation entry selection", () => {
fresh.messages = [{ ...fresh.messages[0], id: "m2", seq: 2, createdAt: "2026-10-01T00:00:02.000Z" }]
fresh.readState = { ...fresh.readState, lastReadMessageId: "m2", lastReadSeq: 2, lastReadAt: fresh.messages[0].createdAt }
fresh.readStateRevision = 5
- fresh.selection = { reason: "read_pointer", anchorMessageId: "m2" }
+ fresh.selection = { reason: "tail", anchorMessageId: null }
+ fresh.newBoundary = { afterSeq: 2, target: null }
+ fresh.page.latestSeq = 2
ingestReadStateSnapshot(registry, { revision: 5, readStates: [{ ...fresh.readState, lastReadAt: fresh.messages[0].createdAt }] })
client.removeQueries({ queryKey: communityKeys.conversationEntries("c1") })
const held = deferred<typeof fresh>()
@@ -79,9 +125,9 @@ describe("conversation entry selection", () => {
expect(hook.result.current.window?.key).toEqual(original.windowKey)
navigation.entryIntent = { href: "/c/channels/s1/c1" }
hook.rerender()
- expect(hook.result.current.window?.initial).toEqual({ mode: "anchor", anchor: "m2" })
+ expect(hook.result.current.window?.initial).toEqual({ mode: "newest" })
act(oldTakeover)
- expect(hook.result.current.window?.initial).toEqual({ mode: "anchor", anchor: "m2" })
+ expect(hook.result.current.window?.initial).toEqual({ mode: "newest" })
await act(async () => registry.runtime.ws.actions.revokeChannelAccess("s1", "c1"))
act(() => hook.result.current.retainWindow())
expect(hook.result.current.window).toBeNull()
@@ -256,7 +302,7 @@ describe("conversation entry selection", () => {
const surface = useSurface()
return { metadata, surface }
}, { wrapper })
- await waitFor(() => expect(load.mock.calls.some(([url]) => url === "/api/community/channels/c1/messages?entry=1")).toBe(true))
+ await waitFor(() => expect(load.mock.calls.some(([url]) => String(url).startsWith("/api/community/channels/c1/messages?entry=1&"))).toBe(true))
expect(hook.result.current.metadata.canRead).toBe(true)
expect(hook.result.current.metadata.windowReady).toBe(true)
expect(hook.result.current.metadata.data?.id).toBe("c1")
@@ -274,6 +320,7 @@ describe("conversation entry selection", () => {
const { client, wrapper, publish } = await setup()
const value = fixture()
value.messages = []
+ value.newBoundary = { afterSeq: 0, target: null }
value.readState = { ...value.readState, lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 }
value.selection = { reason: "tail", anchorMessageId: null }
value.page = { ...value.page, olderCursor: null, hasMoreOlder: false, latestSeq: 0 }
@@ -312,6 +359,7 @@ describe("conversation entry selection", () => {
const value = fixture()
value.messages.push({ ...value.messages[0], id: "m2", seq: 2, content: "Second" })
value.page.latestSeq = 2
+ value.newBoundary = { afterSeq: 1, target: { id: "m2", channelId: "c1", seq: 2, authorId: "peer" } }
await publish(value)
let active = true
const navigation = { entryIntent: { href: "/c/channels/s1/c1" } as { href: string; resume?: boolean } }
@@ -335,10 +383,12 @@ describe("conversation entry selection", () => {
hook.rerender()
expect(hook.result.current.window).toBe(original)
expect(hook.result.current.snapshot?.lastReadMessageId).toBe("m1")
+ load.mockResolvedValue({ ...value, readState: { ...value.readState, lastReadMessageId: "m2", lastReadSeq: 2 }, readStateRevision: 5,
+ newBoundary: { afterSeq: 2, target: null } })
navigation.entryIntent = { href: "/c/channels/s1/c1" }
hook.rerender()
expect(hook.result.current.snapshot?.lastReadMessageId).toBe("m2")
- expect(load).not.toHaveBeenCalled()
+ expect(load).toHaveBeenCalledOnce()
})
it("shares one returned-DM read between metadata and the subsequently mounted body", async () => {
@@ -351,7 +401,9 @@ describe("conversation entry selection", () => {
const next = dmConversationEntryFixture()
next.readState = { ...next.readState, lastReadMessageId: "m2", lastReadSeq: 2 }
next.readStateRevision = 6
- next.selection = { reason: "read_pointer", anchorMessageId: "m2" }
+ next.selection = { reason: "tail", anchorMessageId: null }
+ next.newBoundary = { afterSeq: 2, target: null }
+ next.page.latestSeq = 2
next.messages = [{ ...next.messages[0], id: "m2", seq: 2 }]
load.mockResolvedValue(next)
const navigation = { entryIntent: { href: "/c/me/c1" } }
@@ -367,6 +419,155 @@ describe("conversation entry selection", () => {
view.unmount()
})
+ it("joins the held cold child entry when sidebar scope publishes before the body", async () => {
+ const owner = await setup()
+ const value = fixture()
+ value.channel = { ...value.channel, type: "thread", parentChannelId: "parent", parentMessageId: "opener" }
+ value.parent = { ...fixture().channel, id: "parent", type: "forum" }
+ value.surfaceReceipt = { channelId: "c1", surfaceKind: "thread" }
+ const held = deferred<typeof value>()
+ load.mockReturnValue(held.promise)
+ let body: ReturnType<typeof useMessages> | undefined
+ function Body() { body = useMessages("c1", { serverId: "s1" }); return null }
+ function Route() {
+ const metadata = useChannelMetadata("s1", "c1")
+ return metadata.canRead ? createElement(Body) : null
+ }
+ const view = render(createElement(Route), { wrapper: owner.wrapper })
+ try {
+ await waitFor(() => expect(load).toHaveBeenCalledOnce())
+ expect(body).toBeUndefined()
+ await act(async () => publishCommunityResourceBundle(owner.client,
+ fullResourceBundleFixture("viewer", [serverResourceFixture({ id: "s1", ownerId: "viewer" })], [value.parent!, value.channel]),
+ { token: captureCommunityLiveSnapshotToken(owner.client) }))
+ await waitFor(() => expect(body?.entryCanRead).toBe(true))
+ expect(body?.navigationBlocked).toBe(true)
+ expect(body?.messages).toEqual([])
+ expect(load).toHaveBeenCalledOnce()
+ await act(async () => held.resolve(value))
+ await waitFor(() => expect(body?.messages.map(message => message.id)).toEqual(["m1"]))
+ expect(body?.navigationBlocked).toBe(false)
+ expect(load).toHaveBeenCalledOnce()
+ } finally { view.unmount(); owner.client.clear() }
+ })
+
+ it("captures a fresh DM cutoff after confirmed reading while metadata stays mounted", async () => {
+ const owner = await setup()
+ const old = dmConversationEntryFixture()
+ old.messages.push({ ...old.messages[0], id: "m2", seq: 2 })
+ old.page.latestSeq = 2
+ old.newBoundary = { afterSeq: 1, target: { id: "m2", channelId: "c1", seq: 2, authorId: "peer" } }
+ load.mockResolvedValue(old)
+ let showBody = true
+ let body: ReturnType<typeof useDmMessages> | undefined
+ const navigation = { entryIntent: { href: "/c/me/c1" } }
+ function Body() { body = useDmMessages("c1"); return null }
+ function Route() { useChannelMetadata(null, "c1"); return showBody ? createElement(Body) : null }
+ const tree = () => createElement(CommunityRouteContext, { value: { navigation } as never }, createElement(Route))
+ const view = render(tree(), { wrapper: owner.wrapper })
+ try {
+ await waitFor(() => expect(body?.newBoundary?.target?.id).toBe("m2"))
+ showBody = false
+ navigation.entryIntent = { href: "/c/me" }
+ view.rerender(tree())
+ const readState = { ...old.readState, lastReadMessageId: "m2", lastReadSeq: 2, lastReadAt: old.messages[1].createdAt }
+ await act(async () => ingestReadStateSnapshot(owner.registry, { revision: 5, readStates: [readState] }))
+ const fresh = { ...old, readState, readStateRevision: 5, newBoundary: { afterSeq: 2, target: null } }
+ load.mockResolvedValue(fresh)
+ showBody = true
+ navigation.entryIntent = { href: "/c/me/c1" }
+ view.rerender(tree())
+ await waitFor(() => expect(body?.newBoundary).toEqual(fresh.newBoundary))
+ expect(body?.readSnapshot?.lastReadSeq).toBe(2)
+ expect(load.mock.calls.filter(([url]) => String(url).includes("entry=1"))).toHaveLength(2)
+ } finally { view.unmount(); owner.client.clear() }
+ })
+
+ it("shares the restored cutoff when metadata initializes before restored scope", async () => {
+ const owner = await setup()
+ let restoring = true
+ const held = deferred<ReturnType<typeof fixture>>()
+ load.mockReturnValue(held.promise)
+ let body: ReturnType<typeof useMessages> | undefined
+ function Body() { body = useMessages("c1", { serverId: "s1" }); return null }
+ function Route() {
+ const metadata = useChannelMetadata("s1", "c1")
+ return metadata.canRead ? createElement(Body) : null
+ }
+ const tree = () => createElement(IsRestoringProvider, { value: restoring }, createElement(Route))
+ const view = render(tree(), { wrapper: owner.wrapper })
+ try {
+ expect(load).not.toHaveBeenCalled()
+ const value = fixture()
+ const restored = await owner.publish(value)
+ owner.client.setQueryData(conversationEntryOptions(owner.client, target).queryKey, restored, { updatedAt: Date.now() - 6000 })
+ view.rerender(tree())
+ await waitFor(() => expect(body?.entryCanRead).toBe(true))
+ expect(load).not.toHaveBeenCalled()
+ restoring = false
+ view.rerender(tree())
+ await waitFor(() => expect(load, JSON.stringify(load.mock.calls.map(([url]) => url))).toHaveBeenCalledOnce())
+ await act(async () => held.resolve(value))
+ await waitFor(() => expect(body?.isFetching).toBe(false))
+ expect(load).toHaveBeenCalledOnce()
+ expect(body?.newBoundary).toEqual(value.newBoundary)
+ } finally { view.unmount(); owner.client.clear() }
+ })
+
+ it("does not freeze a previous New target into a fresh DM while its metadata refresh is held", async () => {
+ const owner = await setup()
+ const old = dmConversationEntryFixture()
+ old.messages.push({ ...old.messages[0], id: "m2", seq: 2 })
+ old.page.latestSeq = 2
+ old.newBoundary = { afterSeq: 1, target: { id: "m2", channelId: "c1", seq: 2, authorId: "peer" } }
+ load.mockResolvedValue(old)
+ let showBody = true
+ let body: ReturnType<typeof useDmMessages> | undefined
+ const navigation = { entryIntent: { href: "/c/me/c1" } }
+ function Body() { body = useDmMessages("c1"); return null }
+ function Route() { useChannelMetadata(null, "c1"); return showBody ? createElement(Body) : null }
+ const tree = () => createElement(CommunityRouteContext, { value: { navigation } as never }, createElement(Route))
+ const view = render(tree(), { wrapper: owner.wrapper })
+ try {
+ await waitFor(() => expect(body?.newBoundary?.target?.id).toBe("m2"))
+ showBody = false
+ navigation.entryIntent = { href: "/c/me" }
+ view.rerender(tree())
+ const fresh = { ...old, readState: { ...old.readState, lastReadMessageId: "m2", lastReadSeq: 2 },
+ readStateRevision: 5, newBoundary: { afterSeq: 2, target: null } }
+ const held = deferred<typeof fresh>()
+ load.mockReturnValue(held.promise)
+ let refresh!: Promise<void>
+ act(() => { refresh = owner.client.invalidateQueries({ queryKey: communityKeys.conversationEntries("c1") }) })
+ await waitFor(() => expect(load).toHaveBeenCalledTimes(2))
+ showBody = true
+ navigation.entryIntent = { href: "/c/me/c1" }
+ view.rerender(tree())
+ expect(body?.messages.map(message => message.id)).toEqual(["m1", "m2"])
+ await act(async () => { held.resolve(fresh); await refresh })
+ await waitFor(() => expect(body?.isFetching).toBe(false))
+ expect(body?.newBoundary).toEqual(fresh.newBoundary)
+ expect(load.mock.calls.filter(([url]) => String(url).includes("entry=1"))).toHaveLength(2)
+ } finally { view.unmount(); owner.client.clear() }
+ })
+
+ it("shares one cold entry when metadata mounts the body after its real publication", async () => {
+ const owner = await setup()
+ load.mockResolvedValue(fixture())
+ let body: ReturnType<typeof useMessages> | undefined
+ function Body() { body = useMessages("c1", { serverId: "s1" }); return null }
+ function Route() {
+ const metadata = useChannelMetadata("s1", "c1")
+ return metadata.canRead ? createElement(Body) : null
+ }
+ const view = render(createElement(Route), { wrapper: owner.wrapper })
+ await waitFor(() => expect(body?.messages.map(message => message.id)).toEqual(["m1"]))
+ expect(load).toHaveBeenCalledOnce()
+ expect(body?.newBoundary).toEqual({ afterSeq: 1, target: null })
+ view.unmount()
+ owner.client.clear()
+ })
+
it("resolves a cold main window and freezes NEW from the single entry GET", async () => {
const { wrapper } = await setup()
const transport = deferred<ReturnType<typeof fixture>>()
@@ -379,7 +580,7 @@ describe("conversation entry selection", () => {
await waitFor(() => expect(hook.result.current.window).not.toBeNull())
expect(hook.result.current.snapshot?.lastReadMessageId).toBe("m1")
expect(hook.result.current.canRead).toBe(true)
- expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages?entry=1"])
+ expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages?entry=1&window=tail"])
hook.unmount()
})
@@ -388,6 +589,7 @@ describe("conversation entry selection", () => {
const value = fixture()
value.messages.push({ ...value.messages[0], id: "m2", seq: 2, content: "Second" })
value.page.latestSeq = 2
+ value.newBoundary = { afterSeq: 2, target: null }
await publish(value)
ingestReadStateSnapshot(registry, { revision: 5, readStates: [{ channelId: "c1", lastReadMessageId: "m2", lastReadAt: "at", lastReadSeq: 2 }] })
const hook = renderHook(() => useConversationEntry(target), { wrapper })
@@ -445,11 +647,13 @@ describe("conversation entry selection", () => {
const next = fixture()
next.readState = { channelId: "c1", lastReadMessageId: "m2", lastReadAt: "second", lastReadSeq: 2 }
next.readStateRevision = 5
- next.selection = { reason: "read_pointer", anchorMessageId: "m2" }
+ next.selection = { reason: "tail", anchorMessageId: null }
+ next.newBoundary = { afterSeq: 2, target: null }
+ next.page.latestSeq = 2
next.messages = [{ ...next.messages[0], id: "m2", seq: 2, content: "Second" }]
await act(async () => transport.resolve(next))
await waitFor(() => expect(hook.result.current.snapshot?.lastReadMessageId).toBe("m2"))
- expect(hook.result.current.window?.initial).toEqual({ mode: "anchor", anchor: "m2" })
+ expect(hook.result.current.window?.initial).toEqual({ mode: "newest" })
expect(load).toHaveBeenCalledOnce()
hook.unmount()
})
@@ -466,10 +670,12 @@ describe("conversation entry selection", () => {
expect(hook.result.current.snapshot?.lastReadMessageId).toBe("m1")
await act(async () => { ingestReadStateSnapshot(registry, { revision: 5, readStates: [{ channelId: "c1", lastReadMessageId: "m2", lastReadAt: "later", lastReadSeq: 2 }] }) })
expect(hook.result.current.snapshot?.lastReadMessageId).toBe("m1")
+ load.mockResolvedValue({ ...packet, readState: { ...packet.readState, lastReadMessageId: "m2", lastReadSeq: 2 }, readStateRevision: 5,
+ newBoundary: { afterSeq: 2, target: null } })
navigation.entryIntent = { href: "/c/channels/s1/c1" }
hook.rerender()
expect(hook.result.current.snapshot?.lastReadMessageId).toBe("m2")
- expect(load).not.toHaveBeenCalled()
+ expect(load).toHaveBeenCalledOnce()
hook.unmount()
})
@@ -521,7 +727,7 @@ describe("conversation entry selection", () => {
hook.rerender()
})
await waitFor(() => expect(load).toHaveBeenCalledOnce())
- expect(invalidate).toHaveBeenCalledWith({ queryKey: conversationEntryOptions(client, target).queryKey, exact: true })
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: conversationEntryOptions(client, { ...target, newAfterSeq: 1 }).queryKey, exact: true })
expect(hook.result.current.canRead).toBe(true)
expect(hook.result.current.scope?.proof.ownerGeneration).toBeGreaterThan(original.proof.ownerGeneration)
expect(hook.result.current.resource).toBeUndefined()
@@ -550,9 +756,15 @@ describe("conversation entry return during accepted reading", () => {
value.channel.messageCount = 42
value.channel.lastMessageAt = value.messages[41].createdAt
value.readState = { channelId: "c1", lastReadMessageId: "m30", lastReadSeq: 30, lastReadAt: value.messages[29].createdAt }
- value.selection = { reason: "read_pointer", anchorMessageId: "m30" }
+ value.selection = { reason: "tail", anchorMessageId: null }
+ value.newBoundary = { afterSeq: 30, target: { id: "m31", channelId: "c1", seq: 31, authorId: "peer" } }
value.page = { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 42 }
await owner.publish(value)
+ const historyTarget = { ...target, anchorMessageId: "m30" }
+ const history = await publishConversationEntry(owner.client, historyTarget,
+ { ...value, selection: { reason: "explicit_anchor", anchorMessageId: "m30" } },
+ { token: captureCommunityLiveSnapshotToken(owner.client, "c1") })
+ owner.client.setQueryData(conversationEntryOptions(owner.client, historyTarget).queryKey, history)
const put = deferred<{ changed: boolean; revision: number; targetSeq: number }>()
const canonical = deferred<{ revision: number; readStates: typeof value.readState[] }>()
load.mockImplementation((url: string) => {
@@ -585,14 +797,13 @@ describe("conversation entry return during accepted reading", () => {
}
function EntryList() {
const feed = useMessages("c1", { serverId: "s1", viewerUserId: "viewer" })
- const projection = resolveMessageReadProjection({ messages: feed.messages,
- lastReadMessageId: feed.readSnapshot?.lastReadMessageId ?? null,
- viewerUserId: "viewer", anchorReconciled: feed.anchorReconciled,
- })
+ const newDividerBefore = feed.newBoundary?.target?.id
const props = { channel: "Channel", messages: feed.messages,
loading: feed.isLoading, initialLoadError: feed.initialLoadError,
- newDividerBefore: projection.newDividerBefore, scrollToMessageId,
- initialScrollReady: feed.initialDisplayReady,
+ newBoundary: feed.newBoundary, latestSeq: feed.latestSeq, retiredNewTargetId: feed.retiredNewTargetId,
+ onLoadNewTarget: feed.loadNewTarget, onReadNewBoundary: feed.readNewBoundary, scrollToMessageId,
+ initialScrollReady: feed.initialScrollReady,
+ onUserTakeover: feed.onUserTakeover,
positionDataState: feed.positionDataState, positionEntry: feed.positionEntry, messageWindow: feed.messageWindow,
hasMore: feed.hasMoreOlder, hasMoreNewer: feed.hasMoreNewer,
historyStartKnown: feed.historyStartKnown,
@@ -602,7 +813,7 @@ describe("conversation entry return during accepted reading", () => {
onOpenThread: () => undefined,
}
const controller = useMessageListController(props)
- latest = { feed, controller, newDividerBefore: projection.newDividerBefore }
+ latest = { feed, controller, newDividerBefore }
return createElement("div", { "data-slot": "community-conversation-surface" },
createElement("div", { ref: controller.scrollRef, "data-testid": "community-message-scroller" },
createElement("div", { "data-message-list-content": "", "data-read-position-ready": String(controller.readPositionReady) },
@@ -630,7 +841,7 @@ 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 early reads and consumes a first late NEW once", async readSeq => {
+ it.each([30, 42])("preserves an admitted reader through canonical read %s and slow refresh without granting early reads or replacing its New cutoff", async readSeq => {
const owner = await readingOwner()
const held = deferred<ReturnType<typeof fixture>>()
const fresh = fixture()
@@ -641,8 +852,16 @@ describe("conversation entry return during accepted reading", () => {
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.selection = { reason: "tail", anchorMessageId: null }
+ fresh.newBoundary = { afterSeq: 30, target: { id: "m31", channelId: "c1", seq: 31, authorId: "peer" } }
fresh.page = { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 45 }
+ const oldLoad = load.getMockImplementation()!
+ load.mockImplementation((url: string, options: unknown) => url.includes("/messages") ? held.promise : oldLoad(url, options))
+ const view = mountReadingEntry(owner)
+ try {
+ expect(view.latest.controller.initialPosition.contentVisible).toBe(true)
+ act(() => { view.root.dispatchEvent(new WheelEvent("wheel", { deltaY: -1000 })); view.root.scrollTo({ top: 1800 }) })
+ resize()
await act(async () => {
ingestReadStateSnapshot(owner.registry, { revision: 5, readStates: [readState] })
await publishAccountAttentionSnapshot(owner.client, {
@@ -652,10 +871,7 @@ describe("conversation entry return during accepted reading", () => {
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 () => { void owner.client.invalidateQueries({ queryKey: communityKeys.conversationEntries("c1") }); await vi.advanceTimersByTimeAsync(0) })
await act(async () => vi.advanceTimersByTimeAsync(0))
resize()
expect(view.latest.feed.readSnapshotFetching).toBe(true)
@@ -674,14 +890,9 @@ describe("conversation entry return during accepted reading", () => {
await act(async () => held.resolve(fresh))
await act(async () => vi.advanceTimersByTimeAsync(0))
resize()
- if (readSeq === 30) expect(view.root.querySelector<HTMLElement>(`[data-msg-id="${id}"]`)!.getBoundingClientRect().top).toBeCloseTo(before, 0)
- else {
- const index = view.latest.controller.items.findIndex(item => item.kind === "divider" && item.newDivider && item.messageId === `m${readSeq + 1}`)
- expect(index).toBeGreaterThanOrEqual(0)
- expect(view.root.scrollTop).toBeCloseTo(view.latest.controller.virtualizer.getOffsetForIndex(index, "center")![0], 0)
- }
- expect(view.latest.feed.readSnapshot?.lastReadSeq).toBe(readSeq)
- expect(view.latest.newDividerBefore).toBe(`m${readSeq + 1}`)
+ expect(view.root.querySelector<HTMLElement>(`[data-msg-id="${id}"]`)!.getBoundingClientRect().top).toBeCloseTo(before, 0)
+ expect(view.latest.feed.readSnapshot?.lastReadSeq).toBe(30)
+ expect(view.latest.newDividerBefore).toBe("m31")
expect(view.latest.controller.initialPosition.contentVisible).toBe(true)
} finally {
view.view.unmount()
@@ -760,25 +971,27 @@ describe("conversation entry return during accepted reading", () => {
owner.client.setQueryData(originalKey, { ...originalWindow, pages: originalWindow.pages.map(page => ({ ...page,
messages: page.messages.filter(message => message.id !== "m42"), hasMoreNewer: true,
})) })
+ owner.client.removeQueries({ queryKey: communityKeys.channelMessagesWindow("c1", { mode: "newest" }), exact: true })
const retainedWindow = owner.client.getQueryData(originalKey)
expect(owner.registry.collections.messages.get("m42")?.seq).toBe(42)
load.mockImplementation((url: string, options: unknown) => url.includes("/messages?entry=1") ? entryRead.promise : originalLoad(url, options))
view = mountReadingEntry(owner)
expect(view.latest.feed.initialPositionKnown).toBe(false)
expect(view.latest.feed.initialPositionMessageId).toBeNull()
- expect(load.mock.calls.some(([url]) => url === "/api/community/channels/c1/messages?entry=1&anchor=m42")).toBe(true)
+ expect(load.mock.calls.some(([url]) => url === "/api/community/channels/c1/messages?entry=1&window=tail&newAfterSeq=30")).toBe(true)
const fresh = fixture()
fresh.messages = Array.from({ length: 23 }, (_, index) => ({ ...fresh.messages[0], id: `m${index + 20}`, seq: index + 20,
createdAt: new Date(Date.UTC(2026, 9, 1, 0, 0, index + 20)).toISOString(),
}))
fresh.readState = { channelId: "c1", lastReadMessageId: "m30", lastReadSeq: 30, lastReadAt: fresh.messages.find(message => message.id === "m30")!.createdAt }
- fresh.selection = { reason: "explicit_anchor", anchorMessageId: "m42" }
+ fresh.selection = { reason: "tail", anchorMessageId: null }
+ fresh.newBoundary = { afterSeq: 30, target: { id: "m31", channelId: "c1", seq: 31, authorId: "peer" } }
fresh.page = { ...fresh.page, hasMoreOlder: true, hasMoreNewer: false, latestSeq: 42 }
await act(async () => entryRead.resolve(fresh))
expect(view.latest.feed.error).toBeNull()
resize()
expect(view.latest.feed.initialPositionKnown).toBe(true)
- expect(view.latest.feed.initialPositionMessageId).toBe("m42")
+ expect(view.latest.feed.initialPositionMessageId).toBeNull()
expect(view.visible("m42")).toBe(true)
expect(view.latest.feed.readSnapshot?.lastReadSeq).toBe(30)
expect(owner.client.getQueryData(originalKey)).toBe(retainedWindow)
@@ -802,7 +1015,7 @@ describe("conversation entry return during accepted reading", () => {
expect(retainedWindow).toBeDefined()
const ordinaryKey = conversationEntryOptions(owner.client, target).queryKey
owner.client.removeQueries({ queryKey: ordinaryKey, exact: true })
- owner.client.removeQueries({ queryKey: communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "m30" }), exact: true })
+ owner.client.removeQueries({ queryKey: communityKeys.channelMessagesWindow("c1", { mode: "newest" }), exact: true })
return { alternate, alternateResource, alternateKey, retainedWindow, ordinaryKey }
}
@@ -813,17 +1026,11 @@ describe("conversation entry return during accepted reading", () => {
expect(owner.client.getQueryData(ordinaryKey)).toBeUndefined()
expect(owner.client.getQueryData(alternateKey)).toBe(qualified ? alternateResource : undefined)
expect(owner.registry.collections.messages.get("m42")?.seq).toBe(42)
- const response = qualified ? fixture() : alternate
- if (qualified) {
- response.messages = [{ ...response.messages[0], id: "m30", seq: 30, createdAt: alternate.readState.lastReadAt! }]
- response.channel.messageCount = 42
- response.readState = alternate.readState
- response.selection = { reason: "read_pointer", anchorMessageId: "m30" }
- response.page = { ...response.page, hasMoreOlder: true, hasMoreNewer: true, latestSeq: 42 }
- }
+ const response = { ...alternate, selection: { reason: "tail" as const, anchorMessageId: null },
+ newBoundary: { afterSeq: 30, target: { id: "m31", channelId: "c1", seq: 31, authorId: "peer" } } }
const entryRead = deferred<ReturnType<typeof fixture>>()
const originalLoad = load.getMockImplementation()!
- const expectedRequest = "/api/community/channels/c1/messages?entry=1"
+ const expectedRequest = "/api/community/channels/c1/messages?entry=1&window=tail&newAfterSeq=30"
load.mockImplementation((url: string, options: unknown) => {
if (!url.includes("/messages?entry=1")) return originalLoad(url, options)
if (url !== expectedRequest) throw new Error(`Unexpected entry coverage request ${url}`)
@@ -833,21 +1040,16 @@ describe("conversation entry return during accepted reading", () => {
try {
expect(submitReadIntentGeneration(owner.lease, { kind: "timeline", channelId: "c1", messageId: "m42", seq: 42 })).not.toBeNull()
view = mountReadingEntry(owner)
- expect(view.latest.feed.initialPositionKnown).toBe(true)
- if (qualified) {
- expect(view.latest.feed.initialPositionMessageId).toBe("m42")
- expect(view.latest.feed.readSnapshot?.lastReadSeq).toBe(30)
- expect(view.latest.controller.readPositionReady).toBe(true)
- expect(view.visible("m42")).toBe(true)
- expect(view.latest.feed.readSnapshotFetching).toBe(false)
- }
- const capturedSnapshot = view.latest.feed.readSnapshot, capturedOffset = view.root.scrollTop
+ expect(view.latest.feed.initialPositionKnown).toBe(false)
+ expect(view.latest.feed.initialPositionMessageId).toBeNull()
+ expect(view.latest.controller.readPositionReady).toBe(false)
+ const retainedAnchor = owner.client.getQueryData(alternateResource.windowKey)
expect(load.mock.calls.filter(([url]) => url.includes("/messages?entry=1")).map(([url]) => url)).toEqual([expectedRequest])
await act(async () => entryRead.resolve(response))
resize()
expect(view.latest.feed.error).toBeNull()
expect(view.latest.feed.initialPositionKnown).toBe(true)
- expect(view.latest.feed.initialPositionMessageId).toBe("m42")
+ expect(view.latest.feed.initialPositionMessageId).toBeNull()
expect(view.latest.feed.messages.map(message => message.id)).toEqual(["m42"])
expect(view.visible("m42")).toBe(true)
expect(view.latest.feed.readSnapshot?.lastReadSeq).toBe(30)
@@ -855,9 +1057,9 @@ describe("conversation entry return during accepted reading", () => {
expect(owner.client.getQueryData(alternateResource.windowKey)).toBe(retainedWindow)
expect(view.latest.feed.historyStartKnown).toBe(false)
expect(load.mock.calls.filter(([url]) => url.includes("/messages?entry=1")).map(([url]) => url)).toEqual([expectedRequest])
+ expect(owner.client.getQueryData(alternateResource.windowKey)).toBe(retainedAnchor)
if (qualified) {
- expect(view.latest.feed.readSnapshot).toBe(capturedSnapshot)
- expect(view.root.scrollTop).toBe(capturedOffset)
+ const capturedSnapshot = view.latest.feed.readSnapshot, capturedOffset = view.root.scrollTop
await act(async () => ingestReadStateSnapshot(owner.registry, { revision: 5, readStates: [owner.read42] }))
resize()
expect(view.latest.feed.readSnapshot).toBe(capturedSnapshot)
@@ -878,12 +1080,12 @@ describe("conversation entry return during accepted reading", () => {
const read = { channelId: "c1", lastReadMessageId: `m${seq}`, lastReadSeq: seq,
lastReadAt: seq === 42 ? owner.read42.lastReadAt : "2026-10-01T00:01:40.000Z" }
const response = { ...alternate, readState: read, readStateRevision: 5,
- selection: { reason: "read_pointer" as const, anchorMessageId: read.lastReadMessageId },
+ selection: { reason: "tail" as const, anchorMessageId: null }, newBoundary: { afterSeq: seq, target: null },
messages: [{ ...alternate.messages[0], id: read.lastReadMessageId, seq, createdAt: read.lastReadAt! }],
page: { ...alternate.page, latestSeq: seq } }
const entryRead = deferred<ReturnType<typeof fixture>>()
const originalLoad = load.getMockImplementation()!
- const expectedRequest = "/api/community/channels/c1/messages?entry=1"
+ const expectedRequest = `/api/community/channels/c1/messages?entry=1&window=tail&newAfterSeq=${seq}`
load.mockImplementation((url: string, options: unknown) => {
if (!url.includes("/messages?entry=1")) return originalLoad(url, options)
if (url !== expectedRequest) throw new Error(`Unexpected canonical entry request ${url}`)
@@ -894,16 +1096,10 @@ describe("conversation entry return during accepted reading", () => {
expect(submitReadIntentGeneration(owner.lease, { kind: "timeline", channelId: "c1", messageId: "m42", seq: 42 })).not.toBeNull()
await act(async () => ingestReadStateSnapshot(owner.registry, { revision: 5, readStates: [read] }))
view = mountReadingEntry(owner)
- expect(view.latest.feed.initialPositionKnown).toBe(seq === 42)
+ expect(view.latest.feed.initialPositionKnown).toBe(false)
expect(view.latest.feed.initialPositionMessageId).toBeNull()
- if (seq === 42) {
- expect(view.latest.feed.readSnapshot?.lastReadSeq).toBe(42)
- expect(view.visible("m42")).toBe(true)
- expect(view.latest.controller.readPositionReady).toBe(true)
- } else {
- expect(view.latest.feed.readSnapshot?.lastReadSeq).toBe(100)
- expect(view.latest.controller.readPositionReady).toBe(false)
- }
+ expect(view.latest.controller.readPositionReady).toBe(false)
+ expect(currentConversationReadState(owner.client, "c1")?.lastReadSeq).toBe(seq)
expect(load.mock.calls.filter(([url]) => url.includes("/messages?entry=1")).map(([url]) => url)).toEqual([expectedRequest])
await act(async () => entryRead.resolve(response))
resize()
@@ -936,8 +1132,8 @@ describe("conversation entry return during accepted reading", () => {
returned = mountReadingEntry(owner)
expect(returned.latest.feed.readSnapshot?.lastReadSeq).toBe(30)
expect(returned.latest.newDividerBefore).toBe("m31")
- expect(returned.visible("m31")).toBe(true)
- expect(returned.visible("m42")).toBe(false)
+ expect(returned.visible("m31")).toBe(false)
+ expect(returned.visible("m42")).toBe(true)
expect(load).not.toHaveBeenCalled()
const captured = returned.latest.feed.readSnapshot, offset = returned.root.scrollTop
await act(async () => ingestReadStateSnapshot(owner.registry, { revision: 5, readStates: [owner.read42] }))
@@ -953,47 +1149,38 @@ describe("conversation entry return during accepted reading", () => {
}
})
- it.each(["covering response", "canonical publication before the covering response"] as const)("takes higher progress from %s through its own qualified window", async boundary => {
+ it.each(["covering response", "canonical publication before the covering response"] as const)("takes higher progress from %s through its own qualified latest window", async boundary => {
const owner = await readingOwner()
const previousKey = communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "m30" })
- const previous = owner.client.getQueryData<import("@/lib/community/message-window").MessageWindowData>(previousKey)!
- const localRead = deferred<ReturnType<typeof fixture>>(), canonicalRead = deferred<ReturnType<typeof fixture>>()
+ const previous = owner.client.getQueryData(previousKey)
+ const pending = deferred<ReturnType<typeof fixture>>()
let view: ReturnType<typeof mountReadingEntry> | undefined
try {
expect(submitReadIntentGeneration(owner.lease, { kind: "timeline", channelId: "c1", messageId: "m42", seq: 42 })).not.toBeNull()
- owner.client.setQueryData(previousKey, { ...previous, pages: previous.pages.map(page => ({ ...page, messages: page.messages.filter(message => message.id !== "m42"), hasMoreNewer: true })) })
- const oldLoad = load.getMockImplementation()!
- load.mockImplementation((url: string, options: unknown) => url === "/api/community/channels/c1/messages?entry=1&anchor=m42" ? localRead.promise
- : url === "/api/community/channels/c1/messages?entry=1" ? canonicalRead.promise : oldLoad(url, options))
+ owner.client.removeQueries({ queryKey: communityKeys.channelMessagesWindow("c1", { mode: "newest" }), exact: true })
+ load.mockReturnValue(pending.promise)
view = mountReadingEntry(owner)
const higher = { channelId: "c1", lastReadMessageId: "m100", lastReadSeq: 100, lastReadAt: "2026-10-01T00:01:40.000Z" }
- const aroundLocal = fixture()
- aroundLocal.messages = [{ ...aroundLocal.messages[0], id: "m42", seq: 42 }]
- aroundLocal.readState = boundary === "covering response" ? higher : { ...aroundLocal.readState, lastReadMessageId: "m30", lastReadSeq: 30 }
- aroundLocal.readStateRevision = boundary === "covering response" ? 5 : 4
- aroundLocal.selection = { reason: "explicit_anchor", anchorMessageId: "m42" }
- aroundLocal.page = { ...aroundLocal.page, hasMoreOlder: true, hasMoreNewer: true, latestSeq: 100 }
+ const response = fixture()
+ response.messages = [{ ...response.messages[0], id: "m100", seq: 100, createdAt: higher.lastReadAt }]
+ response.readState = boundary === "covering response" ? higher : { ...response.readState, lastReadMessageId: "m30", lastReadSeq: 30 }
+ response.readStateRevision = boundary === "covering response" ? 5 : 4
+ response.newBoundary = { afterSeq: 30, target: { id: "m31", channelId: "c1", seq: 31, authorId: "peer" } }
+ response.page = { ...response.page, hasMoreOlder: true, hasMoreNewer: false, latestSeq: 100 }
+ expect(view.latest.feed.initialPositionKnown).toBe(false)
+ expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages?entry=1&window=tail&newAfterSeq=30"])
await act(async () => {
if (boundary !== "covering response") ingestReadStateSnapshot(owner.registry, { revision: 5, readStates: [higher] })
- localRead.resolve(aroundLocal)
+ pending.resolve(response)
})
resize()
- await act(async () => vi.advanceTimersByTimeAsync(0))
- expect(view.latest.feed.initialPositionKnown).toBe(false)
- expect(view.latest.feed.initialPositionMessageId).toBeNull()
- expect(load.mock.calls.some(([url]) => url === "/api/community/channels/c1/messages?entry=1")).toBe(true)
- const aroundCanonical = fixture()
- aroundCanonical.messages = [{ ...aroundCanonical.messages[0], id: "m100", seq: 100, createdAt: higher.lastReadAt }]
- aroundCanonical.readState = higher
- aroundCanonical.readStateRevision = 5
- aroundCanonical.selection = { reason: "read_pointer", anchorMessageId: "m100" }
- aroundCanonical.page = { ...aroundCanonical.page, hasMoreOlder: true, hasMoreNewer: false, latestSeq: 100 }
- await act(async () => canonicalRead.resolve(aroundCanonical))
- resize()
expect(view.latest.feed.initialPositionKnown).toBe(true)
expect(view.latest.feed.readSnapshot?.lastReadSeq).toBe(100)
+ expect(currentConversationReadState(owner.client, "c1")?.lastReadSeq).toBe(100)
expect(view.latest.feed.initialPositionMessageId).toBeNull()
expect(view.visible("m100")).toBe(true)
+ expect(view.latest.newDividerBefore).toBe("m31")
+ expect(owner.client.getQueryData(previousKey)).toBe(previous)
} finally { view?.view.unmount(); releaseReadSurface(owner.lease); await owner.finish() }
})
@@ -1025,12 +1212,21 @@ describe("conversation entry return during accepted reading", () => {
try {
expect(submitReadIntentGeneration(owner.lease, { kind: "timeline", channelId: "c1", messageId: "m31", seq: 31 })).not.toBeNull()
await act(async () => ingestReadStateSnapshot(owner.registry, { revision: 5, readStates: [owner.read42] }))
+ const current = fixture()
+ current.messages = [{ ...current.messages[0], id: "m42", seq: 42 }]
+ current.readState = owner.read42
+ current.readStateRevision = 5
+ current.page.latestSeq = 42
+ current.newBoundary = { afterSeq: 42, target: null }
+ load.mockResolvedValue(current)
view = mountReadingEntry(owner)
expect(view.latest.feed.initialPositionMessageId).toBeNull()
expect(view.latest.feed.readSnapshot?.lastReadSeq).toBe(42)
+ await act(async () => {})
+ resize()
expect(view.latest.newDividerBefore).toBeUndefined()
expect(view.visible("m42")).toBe(true)
- expect(load).not.toHaveBeenCalled()
+ expect(load).toHaveBeenCalledOnce()
} finally { view?.view.unmount(); releaseReadSurface(owner.lease); await owner.finish() }
})
@@ -1052,7 +1248,7 @@ describe("conversation entry return during accepted reading", () => {
} finally { view.unmount(); releaseReadSurface(owner.lease); await owner.finish() }
})
- it("reveals the actual cached history boundary while an uncovered newer target is pending", async () => {
+ it("preserves the actual cached reader and history boundary while a newer tail reconciles", async () => {
const owner = await readingOwner()
const entryRead = deferred<ReturnType<typeof fixture>>()
const previousKey = communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "m30" })
@@ -1066,7 +1262,8 @@ describe("conversation entry return during accepted reading", () => {
const read60 = { channelId: "c1", lastReadMessageId: "m60", lastReadSeq: 60, lastReadAt: fresh.messages[1].createdAt }
fresh.readState = read60
fresh.readStateRevision = 5
- fresh.selection = { reason: "read_pointer", anchorMessageId: "m60" }
+ fresh.selection = { reason: "tail", anchorMessageId: null }
+ fresh.newBoundary = { afterSeq: 60, target: { id: "m61", channelId: "c1", seq: 61, authorId: "peer" } }
fresh.channel.messageCount = 80
fresh.channel.lastMessageAt = fresh.messages.at(-1)!.createdAt
fresh.page = { olderCursor: "older", newerCursor: null, hasMoreOlder: true, hasMoreNewer: false, latestSeq: 80 }
@@ -1078,11 +1275,21 @@ describe("conversation entry return during accepted reading", () => {
})
})
load.mockImplementation((url: string) => {
- if (url === "/api/community/channels/c1/messages?entry=1") return entryRead.promise
+ if (url.includes("/messages?entry=1")) return entryRead.promise
+ if (url.includes("/messages?since=")) return Promise.resolve({ ...fresh.page, hasMoreOlder: false, olderCursor: null,
+ messages: Array.from({ length: 38 }, (_, index) => ({ ...fresh.messages[0], id: `m${index + 43}`, seq: index + 43 })), profiles: fresh.profiles })
throw new Error(`Unexpected history transport ${url}`)
})
const view = mountReadingEntry(owner)
try {
+ act(() => {
+ view.root.dispatchEvent(new WheelEvent("wheel", { deltaY: 1000, bubbles: true }))
+ view.root.scrollTo({ top: 1000 })
+ })
+ resize()
+ const viewport = view.root.getBoundingClientRect()
+ const reader = [...view.root.querySelectorAll<HTMLElement>("[data-msg-id]")].find(row => row.getBoundingClientRect().bottom > viewport.top + 1)!
+ const readerOffset = reader.getBoundingClientRect().top - viewport.top
expect(view.latest.feed.messages.map(message => message.id)).toEqual([...Array.from({ length: 42 }, (_, index) => `m${index + 1}`), "m80"])
expect(view.latest.feed.initialPositionKnown).toBe(false)
expect(owner.client.getQueryData(previousKey)).toBe(previousWindow)
@@ -1098,10 +1305,11 @@ describe("conversation entry return during accepted reading", () => {
await act(async () => entryRead.resolve(fresh))
resize()
expect(view.latest.feed.initialPositionKnown).toBe(true)
- expect(view.latest.feed.hasMoreOlder).toBe(true)
+ expect(view.latest.feed.hasMoreOlder).toBe(false)
+ expect(view.latest.feed.historyStartKnown).toBe(true)
expect(owner.client.getQueryData(previousKey)).toBe(previousWindow)
- expect(view.latest.feed.messages.map(message => message.id)).toEqual(fresh.messages.map(message => message.id))
- expect(view.root.textContent).not.toContain("Beginning of the channel")
+ expect(view.latest.feed.messages.map(message => message.id)).toEqual(Array.from({ length: 80 }, (_, index) => `m${index + 1}`))
+ expect(Math.abs(reader.getBoundingClientRect().top - view.root.getBoundingClientRect().top - readerOffset)).toBeLessThanOrEqual(1)
} finally {
view.view.unmount()
entryRead.resolve(fresh)
@@ -1141,9 +1349,10 @@ describe("native entry freshness with authoritative newer attention", () => {
expect(load).not.toHaveBeenCalled()
} else {
await waitFor(() => expect(load).toHaveBeenCalledOnce())
- expect(load.mock.calls[0][0]).toBe("/api/community/channels/c1/messages?entry=1")
+ expect(load.mock.calls[0][0]).toBe("/api/community/channels/c1/messages?entry=1&window=tail&newAfterSeq=1")
expect(hook.result.current.window).toBe(selected)
- const fresh = { ...packet, channel: { ...packet.channel, messageCount: 2 }, messages: [...packet.messages, { ...packet.messages[0], id: "m2", seq: 2, content: "New message" }], page: { ...packet.page, latestSeq: 2 } }
+ const fresh = { ...packet, channel: { ...packet.channel, messageCount: 2 }, messages: [...packet.messages, { ...packet.messages[0], id: "m2", seq: 2, content: "New message" }], page: { ...packet.page, latestSeq: 2 },
+ newBoundary: { afterSeq: 1, target: { id: "m2", channelId: "c1", seq: 2, authorId: "peer" } } }
await act(async () => { held.resolve(fresh) })
await waitFor(() => expect(client.getQueryData<{ pages: Array<{ messages: Array<{ id: string }> }> }>(original.windowKey)?.pages.flatMap(page => page.messages.map(row => row.id))).toContain("m2"))
expect(hook.result.current.window).toBe(selected)
diff --git a/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx b/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx
index f56db6e84..18981dd78 100644
--- a/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx
+++ b/src/web/src/hooks/community/use-conversation-entry.position.dom.test.tsx
@@ -63,8 +63,11 @@ function Conversation({ channelId, kind, anchorMessageId }: { channelId: string;
})
const props = { channel: "Conversation", messages: feed.messages,
loading: feed.isLoading, initialLoadError: feed.initialLoadError,
+ newBoundary: feed.newBoundary, latestSeq: feed.latestSeq, retiredNewTargetId: feed.retiredNewTargetId,
+ onLoadNewTarget: feed.loadNewTarget, onReadNewBoundary: feed.readNewBoundary,
newDividerBefore: feed.newDividerBefore, initialPositionMessageId: feed.initialPositionMessageId,
- initialScrollReady: feed.initialPositionKnown,
+ initialScrollReady: feed.initialScrollReady,
+ preserveInitialPresentation: feed.preserveInitialPresentation,
positionEntry: feed.positionEntry, positionScope: feed.positionScope,
positionDataState: feed.positionDataState, messageWindow: feed.messageWindow, presentRequest: feed.presentRequest,
scrollToMessageId: channel.scrollTargetId, onScrollTargetConsumed: channel.consumeScrollTarget,
@@ -94,7 +97,8 @@ function entry(kind: Kind, channelId = "c1", ownTail = false) {
}))
value.profiles = messageProfilesFixture(value.messages)
value.readState = { channelId, lastReadMessageId: `${prefix}30`, lastReadSeq: 30, lastReadAt: value.messages[29].createdAt }
- value.selection = { reason: "read_pointer", anchorMessageId: `${prefix}30` }
+ value.selection = { reason: "tail", anchorMessageId: null }
+ value.newBoundary = { afterSeq: 30, target: { id: `${prefix}31`, channelId, seq: 31, authorId: "peer" } }
value.surfaceReceipt = { channelId, surfaceKind: kind === "channel" ? "channel" : "thread" }
value.page = { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 42 }
return value
@@ -125,13 +129,29 @@ async function setup(kind: Kind, ownTail = false, strict = false, options: {
const canonicalTransport = new Promise(resolve => { finishCanonical = resolve })
releaseTransport = () => { finishPut({ changed: true, revision: 6, targetSeq: 42 }); finishCanonical({ revision: 6, readStates: [] }) }
load.mockImplementation((url: string) => {
- if (url === "/api/community/channels/c1/messages?entry=1" && options.refresh) return options.refresh
+ if (url.startsWith("/api/community/channels/c1/messages?") && new URL(url, "https://test.invalid").searchParams.has("entry") && options.refresh) return options.refresh
if (url === "/api/community/channels/c1/messages" && options.refreshWindow) return options.refreshWindow.then(value => ({
...value.page, profiles: value.profiles, messages: value.messages,
}))
if (url.startsWith("/api/community/channels/c1/messages?since=") && options.refresh) return options.refresh.then(value => ({
...value.page, profiles: value.profiles, messages: value.messages.filter(message => message.seq > 1),
}))
+ if (url.includes("/messages?") && new URL(url, "https://test.invalid").searchParams.has("entry")) {
+ const requested = new URL(url, "https://test.invalid")
+ const id = requested.pathname.split("/").at(-2)!
+ const packet = entry(id === "c1" ? kind : "channel", id, ownTail && id === "c1")
+ const current = currentConversationReadState(owner.client, id)
+ if (current) {
+ packet.readState = { channelId: id, lastReadMessageId: current.lastReadMessageId, lastReadSeq: current.lastReadSeq, lastReadAt: current.lastReadAt }
+ packet.readStateRevision = current.observedRevision ?? packet.readStateRevision
+ }
+ const afterSeq = Number(requested.searchParams.get("newAfterSeq") ?? packet.readState.lastReadSeq)
+ const first = packet.messages.find(message => message.seq > afterSeq && message.authorId !== viewer.id)
+ packet.newBoundary = { afterSeq, target: first ? { id: first.id, channelId: id, seq: first.seq, authorId: first.authorId } : null }
+ const anchor = requested.searchParams.get("anchor")
+ if (anchor) packet.selection = { reason: "explicit_anchor", anchorMessageId: anchor }
+ return Promise.resolve(packet)
+ }
if (url.endsWith("/read")) return put
if (url === "/api/community/users/me/read-state") return canonicalTransport
if (url === "/api/community/users/me/attention") return Promise.resolve({ scopes: [], items: [], limit: 100, truncated: false })
@@ -236,6 +256,7 @@ describe("conversation entry positioning through real reading owners", () => {
cached.channel.messageCount = 1
cached.page.latestSeq = 1
cached.readState = { channelId: "c1", lastReadMessageId: null, lastReadSeq: 0, lastReadAt: null }
+ cached.newBoundary = { afterSeq: 0, target: { id: "m1", channelId: "c1", seq: 1, authorId: "peer" } }
cached.selection = { reason: "tail", anchorMessageId: null }
const view = await setup("channel", false, false, { cached, initialActive: mode !== "inactive" })
expect(view.root().querySelector('[data-read-position-ready]')).toHaveAttribute("data-read-position-ready", "false")
@@ -263,27 +284,29 @@ describe("conversation entry positioning through real reading owners", () => {
expect(load.mock.calls.some(([, options]) => options?.method === "PUT")).toBe(false)
await view.setActivity(true)
expect(latest.feed.positionEntry).toBe(entry)
- expect(view.visible("m31")).toBe(true)
+ expect(view.visible("m42")).toBe(true)
expect(view.root().querySelector('[data-read-position-ready]')).toHaveAttribute("data-read-position-ready", "true")
- const row = view.root().querySelector('[data-msg-id="m31"]')!
+ const row = view.root().querySelector('[data-msg-id="m42"]')!
const observer = boundObserver(row)
act(() => observer.callback([intersection(row)], {} as IntersectionObserver))
- expect(getReadCoordinator(owner.client, viewer.id).state.get().scopes.get("timeline:c1")?.accepted?.intent.seq).toBe(31)
+ expect(getReadCoordinator(owner.client, viewer.id).state.get().scopes.get("timeline:c1")?.accepted?.intent.seq).toBe(42)
})
- it.each([{ delayCanonical: false, previousTail: false }, { delayCanonical: true, previousTail: false }, { delayCanonical: false, previousTail: true }])("keeps a cached read tail visible until native data is complete, delayed canonical=$delayCanonical, previous tail=$previousTail", async ({ delayCanonical, previousTail }) => {
+ it.each([{ delayCanonical: false, previousTail: false }, { delayCanonical: true, previousTail: false }, { delayCanonical: false, previousTail: true }])("waits for the latest ordinary native window before revealing, delayed canonical=$delayCanonical, previous tail=$previousTail", async ({ delayCanonical, previousTail }) => {
const fresh = entry("channel")
fresh.messages = fresh.messages.slice(0, 13)
fresh.channel.messageCount = 13
const readPointer = { channelId: "c1", lastReadMessageId: "m1", lastReadSeq: 1, lastReadAt: fresh.messages[0].createdAt }
fresh.readState = readPointer
- fresh.selection = { reason: "read_pointer", anchorMessageId: "m1" }
+ fresh.selection = { reason: "tail", anchorMessageId: null }
+ fresh.newBoundary = { afterSeq: 1, target: { id: "m2", channelId: "c1", seq: 2, authorId: "peer" } }
fresh.readStateRevision = 2
fresh.page.latestSeq = 13
- const cached = { ...fresh, channel: { ...fresh.channel, messageCount: 1 }, messages: fresh.messages.slice(0, 1), page: { ...fresh.page, latestSeq: 1 } }
+ const cached = { ...fresh, channel: { ...fresh.channel, messageCount: 1 }, messages: fresh.messages.slice(0, 1), page: { ...fresh.page, latestSeq: 1 }, newBoundary: { afterSeq: 1, target: null } as typeof fresh.newBoundary }
if (previousTail) {
cached.readState = { channelId: "c1", lastReadMessageId: null, lastReadSeq: 0, lastReadAt: null }
cached.readStateRevision = 1
+ cached.newBoundary = { afterSeq: 0, target: { id: "m1", channelId: "c1", seq: 1, authorId: "peer" } }
cached.selection = { reason: "tail", anchorMessageId: null }
}
let finishRefresh!: (value: typeof fresh) => void
@@ -304,9 +327,10 @@ describe("conversation entry positioning through real reading owners", () => {
}
try {
expect(latest.feed.messages.map(message => message.id)).toEqual(["m1"])
- expect(view.visible("m1")).toBe(true)
+ expect(view.visible("m1")).toBe(false)
+ expect(view.root().closest("[aria-busy]")).toHaveAttribute("aria-busy", "true")
expect(latest.feed.isFetching).toBe(true)
- const initialReadReady = view.root().querySelector("[data-message-list-content]")!.getAttribute("data-read-position-ready")
+ const initialReadReady = view.root().querySelector("[data-message-list-content]")!.getAttribute("data-read-position-ready") ?? "false"
await act(async () => { finishRefresh(fresh); await vi.advanceTimersByTimeAsync(0) })
resize()
if (delayCanonical) {
@@ -314,26 +338,18 @@ describe("conversation entry positioning through real reading owners", () => {
resize()
expect({ latestSeq: latest.feed.latestSeq, messages: latest.feed.messages.map(message => message.id),
fetching: latest.feed.isFetching, readSnapshotFetching: latest.feed.readSnapshotFetching,
- readReady: view.root().querySelector("[data-message-list-content]")!.getAttribute("data-read-position-ready"),
- }).toEqual({ latestSeq: previousTail ? 13 : 1, messages: ["m1"], fetching: !previousTail, readSnapshotFetching: true, readReady: "false" })
+ readReady: view.root().querySelector("[data-message-list-content]")!.getAttribute("data-read-position-ready") ?? "false",
+ }).toEqual({ latestSeq: 1, messages: ["m1"], fetching: true, readSnapshotFetching: true, readReady: "false" })
await act(async () => { await publish(); await vi.advanceTimersByTimeAsync(0) })
resize()
}
- if (previousTail) {
- expect({ latestSeq: latest.feed.latestSeq, messages: latest.feed.messages.map(message => message.id),
- fetching: latest.feed.isFetching, readSnapshotFetching: latest.feed.readSnapshotFetching,
- readReady: view.root().querySelector("[data-message-list-content]")!.getAttribute("data-read-position-ready"),
- }).toEqual({ latestSeq: 1, messages: ["m1"], fetching: false, readSnapshotFetching: true, readReady: "false" })
- await act(async () => { finishWindow(fresh); await vi.advanceTimersByTimeAsync(0) })
- resize()
- }
expect(latest.feed.error).toBeNull()
expect(latest.feed.messages).toHaveLength(13)
const marker = view.root().querySelector("[data-new-divider]")!.getBoundingClientRect()
const viewport = view.root().getBoundingClientRect()
expect({ initialReadReady, newInViewport: marker.bottom > viewport.top && marker.top < viewport.bottom,
lastInViewport: view.visible("m13"), readReadyAfter: view.root().querySelector("[data-message-list-content]")!.getAttribute("data-read-position-ready"),
- }).toEqual({ initialReadReady: "false", newInViewport: true, lastInViewport: false, readReadyAfter: "true" })
+ }).toEqual({ initialReadReady: "false", newInViewport: false, lastInViewport: true, readReadyAfter: "true" })
expect(latest.feed.readSnapshot?.lastReadSeq).toBe(1)
expect(load.mock.calls.some(([, options]) => options?.method === "PUT")).toBe(false)
} finally {
@@ -341,7 +357,7 @@ describe("conversation entry positioning through real reading owners", () => {
}
})
- it("uses the normal unread entry after a stale cached message-owner remount", async () => {
+ it("uses normal bottom entry after a stale cached message-owner remount", async () => {
const view = await setup("channel", true)
await view.tail()
const oldRoot = view.root()
@@ -354,11 +370,11 @@ describe("conversation entry positioning through real reading owners", () => {
expect(oldRoot.isConnected).toBe(false)
await act(async () => vi.advanceTimersByTimeAsync(6000))
const previousLoad = load.getMockImplementation()!
- load.mockImplementation((url: string, options: unknown) => url === "/api/community/channels/c1/messages?entry=1" ? new Promise(() => {}) : previousLoad(url, options))
+ load.mockImplementation((url: string, options: unknown) => url.includes("/messages?entry=1") ? new Promise(() => {}) : previousLoad(url, options))
await view.navigate("/c/channels/s1/c1")
- expect(load.mock.calls.some(([url]) => url === "/api/community/channels/c1/messages?entry=1")).toBe(true)
+ expect(load.mock.calls.some(([url]) => url.includes("/messages?entry=1"))).toBe(true)
expect(view.root().scrollTop).not.toBeCloseTo(offset, 0)
- expect(view.visible("m31")).toBe(true)
+ expect(view.visible("m42")).toBe(true)
expect(latest.feed.newDividerBefore).toBe("m31")
expect(currentConversationReadState(owner.client, "c1")?.lastReadSeq).toBe(30)
expect(load.mock.calls.some(([, options]) => options?.method === "PUT")).toBe(false)
@@ -370,7 +386,7 @@ describe("conversation entry positioning through real reading owners", () => {
] as const)("positions a fresh retained $kind entry once while semantic resume keeps its viewport (StrictMode=$strict)", async ({ kind, strict }) => {
const view = await setup(kind, false, strict)
const originalRoot = view.root(), originalWindow = latest.feed.readSnapshot
- expect(view.visible("m31")).toBe(true)
+ expect(view.visible("m42")).toBe(true)
act(() => latest.channel.jumpToSeq(10))
resize()
expect(view.visible("m10")).toBe(true)
@@ -384,12 +400,13 @@ describe("conversation entry positioning through real reading owners", () => {
await view.navigate("/c/channels/s1/c1")
expect(latest.feed.readSnapshot?.lastReadSeq).toBe(40)
expect(view.root()).toBe(originalRoot)
- expect(view.visible("m41")).toBe(true)
+ expect(view.visible("m42")).toBe(true)
const landed = view.root().scrollTop
await view.canonical(42)
expect(latest.feed.readSnapshot?.lastReadSeq).toBe(40)
expect(view.root().scrollTop).toBe(landed)
- expect(messageOrReadRequests()).toEqual([])
+ expect(messageOrReadRequests().filter(([, options]) => options?.method === "PUT")).toEqual([])
+ expect(messageOrReadRequests().filter(([url]) => String(url).includes("entry=1"))).toHaveLength(1)
})
it("adopts a new same-pane msg after target consumption, including a repeated target and an independent seq", async () => {
@@ -421,7 +438,7 @@ describe("conversation entry positioning through real reading owners", () => {
it.each([false, true])("cancels a target lost by the current ready query window without granting its old observer a read (StrictMode=%s)", async strict => {
const view = await setup("channel", false, strict), root = view.root()
- const previousRow = root.querySelector('[data-msg-id="m31"]')!
+ const previousRow = root.querySelector('[data-msg-id="m42"]')!
const previousObserver = boundObserver(previousRow)
const explicit = entry("channel")
explicit.selection = { reason: "explicit_anchor", anchorMessageId: "m5" }
@@ -490,8 +507,8 @@ describe("conversation entry positioning through real reading owners", () => {
act(() => observer.callback([record], {} as IntersectionObserver))
expect(getLocalReadingPosition(owner.client, "c1")).toBeNull()
await view.navigate("/c/channels/s1/c1")
- expect(view.visible("m42")).toBe(false)
- expect(view.visible("m31")).toBe(true)
+ expect(view.visible("m31")).toBe(false)
+ expect(view.visible("m42")).toBe(true)
expect(getLocalReadingPosition(owner.client, "c1")).toBeNull()
const offset = view.root().scrollTop
await view.canonical(42)
@@ -511,8 +528,8 @@ describe("conversation entry positioning through real reading owners", () => {
visibility = "visible"
await view.navigate("/c/channels/s1/c2")
await view.navigate("/c/channels/s1/c1")
- expect(view.visible("m42")).toBe(false)
- expect(view.visible("m31")).toBe(true)
+ expect(view.visible("m31")).toBe(false)
+ expect(view.visible("m42")).toBe(true)
expect(getLocalReadingPosition(owner.client, "c1")).toBeNull()
expect(currentConversationReadState(owner.client, "c1")?.lastReadSeq).toBe(30)
expect(messageOrReadRequests()).toEqual([])
diff --git a/src/web/src/hooks/community/use-conversation-entry.ts b/src/web/src/hooks/community/use-conversation-entry.ts
index 6b9496990..f025d308c 100644
--- a/src/web/src/hooks/community/use-conversation-entry.ts
+++ b/src/web/src/hooks/community/use-conversation-entry.ts
@@ -11,7 +11,7 @@ import { useCanonicalMessagesById, useCanonicalProfilesProjection, useChannelRea
import { canonicalMessageResource } from "@/lib/community-db/resources"
import { getCommunityDbRegistry } from "@/lib/community-db/collections"
import { useCommunityRuntime } from "@/stores/community/runtime"
-import { isChannelMetadataTokenCurrent } from "@/lib/community/conversation-qualification"
+import { conversationListScopeKey, isChannelMetadataTokenCurrent } from "@/lib/community/conversation-qualification"
import { actionAttributes, currentPageObservation, navigationForHref } from "@/lib/observability/context"
import { emitTelemetry, telemetryGeneration } from "@/lib/observability/telemetry"
import {
@@ -22,11 +22,10 @@ import { messageWindowIdentity, type MessageWindowData } from "@/lib/community/m
import { communityKeys } from "@/lib/query-keys"
import { reconcileWindow } from "./community-ws/reconnect-messages"
import { isConversationAccessError, isConversationAnchorMissingError } from "@/lib/community/conversation-read"
-import { getLocalReadingPosition } from "./read-coordinator"
type EntryWindow = NonNullable<ReturnType<typeof findConversationEntryWindow>>
-export function useConversationResource(target: ConversationEntryTarget | null, intent?: { href: string; resume?: boolean } | null, useLocalPosition = false, consumer: "metadata" | "messages" | "forum" = "metadata", networkEnabled = true) {
+export function useConversationResource(target: ConversationEntryTarget | null, intent?: { href: string; resume?: boolean } | null, consumer: "metadata" | "messages" | "forum" = "metadata", networkEnabled = true) {
const client = useQueryClient()
const restoring = useIsRestoring()
const active = useConversationActivity()
@@ -49,9 +48,30 @@ export function useConversationResource(target: ConversationEntryTarget | null,
const serverId = target?.serverId ?? null
const anchorMessageId = target?.anchorMessageId ?? null
const tag = target?.tag ?? null
- const preferTail = target?.preferTail === true
- const enabled = target !== null && networkEnabled
- const baseInput = useMemo(() => ({ channelId, serverId, anchorMessageId, tag, preferTail }), [channelId, serverId, anchorMessageId, tag, preferTail])
+ const preferTail = target?.preferTail !== false
+ const cutoffScope = hashKey([channelId, serverId, anchorMessageId, tag, preferTail, accountEpoch, accessEpoch, generation, parentGeneration, lifetime])
+ const providedCutoff = target?.newAfterSeq ?? null
+ const qualifiedPointer = target && getQualifiedConversationScope(client, target) ? currentConversationReadState(client, channelId) : undefined
+ const captureCutoff = () => {
+ if (providedCutoff !== null) return providedCutoff
+ const qualification = { accountEpoch, accessEpoch, channelGeneration: generation }
+ const pending = client.getQueryCache().findAll({ queryKey: communityKeys.conversationEntries(channelId) }).find(query => {
+ if (query.state.fetchStatus !== "fetching") return false
+ const candidate = query.queryKey[communityKeys.conversationEntries(channelId).length] as Parameters<typeof communityKeys.conversationEntry>[1] | undefined
+ return candidate && hashKey(communityKeys.conversationEntry(channelId, { serverId, anchorMessageId, tag, preferTail, newAfterSeq: candidate.newAfterSeq }, qualification)) === query.queryHash
+ })
+ if (pending) return (pending.queryKey[communityKeys.conversationEntries(channelId).length] as NonNullable<Parameters<typeof communityKeys.conversationEntry>[1]>).newAfterSeq ?? null
+ return qualifiedPointer?.lastReadSeq ?? null
+ }
+ const [entryCutoff, setEntryCutoff] = useState(() => ({ client, cutoffScope, intent, providedCutoff, restoring, afterSeq: captureCutoff() }))
+ let currentCutoff = entryCutoff
+ if (entryCutoff.client !== client || entryCutoff.cutoffScope !== cutoffScope || entryCutoff.intent !== intent || entryCutoff.providedCutoff !== providedCutoff || entryCutoff.restoring !== restoring) {
+ currentCutoff = { client, cutoffScope, intent, providedCutoff, restoring, afterSeq: captureCutoff() }
+ setEntryCutoff(currentCutoff)
+ }
+ const newAfterSeq = currentCutoff.afterSeq
+ const enabled = target !== null && networkEnabled && !restoring
+ const baseInput = useMemo(() => ({ channelId, serverId, anchorMessageId, tag, preferTail, newAfterSeq }), [channelId, serverId, anchorMessageId, tag, preferTail, newAfterSeq])
const qualification = useMemo(() => ({ accountEpoch, accessEpoch, generation, parentGeneration, lifetime, parentId: canonical?.parentChannelId }),
[accountEpoch, accessEpoch, generation, parentGeneration, lifetime, canonical?.parentChannelId])
const assessment = assessConversationScope(client, baseInput)
@@ -63,19 +83,9 @@ export function useConversationResource(target: ConversationEntryTarget | null,
return { qualification, intent, scope, resource: cached && isChannelMetadataTokenCurrent(cached.proof) ? cached : getQualifiedConversationEntry(client, channelId) }
}, [client, baseInput, channelId, qualification, intent, scope])
const cachedResource = cachedSelection.resource
- const landing = useMemo(() => {
- const search = new URLSearchParams(intent?.href.split("?")[1] ?? "")
- const position = useLocalPosition && enabled && !anchorMessageId && !tag && !preferTail && !intent?.resume && !search.has("msg") && !search.has("seq")
- ? getLocalReadingPosition(client, channelId) : null
- const pointer = currentConversationReadState(client, channelId)
- if (!position || !pointer || pointer.lastReadSeq >= position.seq) return { qualification: cachedSelection.qualification, input: baseInput, requestInput: baseInput, position: null }
- const input = { ...baseInput, anchorMessageId: position.messageId }
- const cachedScope = cachedSelection.resource ?? cachedSelection.scope
- const covered = cachedScope && findConversationEntryWindow(client, input, cachedScope, pointer)
- return { qualification: cachedSelection.qualification, input, requestInput: covered ? baseInput : input, position }
- }, [client, baseInput, cachedSelection, intent, useLocalPosition, enabled, anchorMessageId, channelId, tag, preferTail])
- const input = landing.input
- const options = useMemo(() => conversationEntryOptions(client, landing.requestInput), [client, landing])
+ const input = baseInput
+ const request = useMemo(() => ({ qualification, options: conversationEntryOptions(client, input) }), [client, input, qualification])
+ const options = request.options
const entryHash = hashKey(options.queryKey)
const restoreSubscriptionEnabled = restoring && target !== null
const subscribeRestoredEntry = useCallback((notify: () => void) => restoreSubscriptionEnabled
@@ -108,20 +118,20 @@ export function useConversationResource(target: ConversationEntryTarget | null,
const refetch = query.refetch
useEffect(() => { if (presented && enabled && verification.needed) void refetch({ cancelRefetch: false }) }, [refetch, verification, enabled, presented])
useEffect(() => {
- if (!presented || !target || revoked || !query.data || isChannelMetadataTokenCurrent(query.data.proof) || query.isFetching || query.isError) return
+ if (!presented || restoring || !target || revoked || !query.data || isChannelMetadataTokenCurrent(query.data.proof) || query.isFetching || query.isError) return
void client.invalidateQueries({ queryKey: options.queryKey, exact: true })
- }, [client, parentGeneration, options.queryKey, query.data, query.isFetching, query.isError, revoked, target, presented])
+ }, [client, parentGeneration, options.queryKey, query.data, query.isFetching, query.isError, revoked, target, presented, restoring])
const fallbackRefetch = fallback.refetch
const retryVerification = useCallback(() => (anchorMissing ? fallbackRefetch : refetch)({ cancelRefetch: false }), [anchorMissing, fallbackRefetch, refetch])
useEffect(() => {
- if (!presented || !target || !intent || revoked || !query.data || query.isFetching || query.isError) return
+ if (!presented || restoring || !target || !intent || revoked || !query.data || query.isFetching || query.isError) return
if (client.getQueryData(options.queryKey) !== query.data) return
const pointer = currentConversationReadState(client, channelId)
const received = client.getQueryData<MessageWindowData>(query.data.windowKey)
const anchor = input.anchorMessageId ?? pointer?.lastReadMessageId
if (received?.pages?.some(page => Array.isArray(page.messages) && (anchor ? page.messages.some(message => message.id === anchor) : page.hasMoreNewer === false))) return
if (pointer && !findConversationEntryWindow(client, input, query.data, pointer)) void client.query({ ...options, select: undefined }).catch(() => undefined)
- }, [client, channelId, intent, input, options, query.data, query.isFetching, query.isError, revoked, target, presented])
+ }, [client, channelId, intent, input, options, query.data, query.isFetching, query.isError, revoked, target, presented, restoring])
const currentPointer = read.readState ?? (read.hasSnapshot ? currentConversationReadState(client, channelId) : undefined)
const retainedIds = client.getQueryCache().findAll({ queryKey: communityKeys.channelMessages(channelId) }).flatMap(query => {
const identity = messageWindowIdentity(query.queryKey)
@@ -187,8 +197,7 @@ export function useConversationResource(target: ConversationEntryTarget | null,
emitTelemetry("conversation.cache", { ...actionAttributes(action), cache_consumer: consumer, cache_reason: assessment.reason,
cache_window: cacheWindow, entry_status: entryStatus, target_coverage: targetCoverage, eligibility: scopeAvailable ? "eligible" : "rejected" })
}, [active, assessment.reason, cacheWindow, channelId, consumer, enabled, entryStatus, intent, scopeAvailable, serverId, targetCoverage, telemetryOwner])
- return { client, cachedResource, scope: readableScope, currentPointer, windowReady, displayWindow: cachedWindow, input: anchorMissing && landing.position ? baseInput : input, options, query, canonical, resource: qualified ? resource : undefined, canRead: qualified, revoked,
- localPosition: anchorMissing ? null : landing.position,
+ return { client, cachedResource, scope: readableScope, currentPointer, windowReady, displayWindow: cachedWindow, input, options, query, canonical, resource: qualified ? resource : undefined, canRead: qualified, revoked,
denied: serverRevoked || revoked && (!verification.needed || generation !== verification.generation) || isConversationAccessError(query.error) && Number((query.error as { status?: unknown } | null)?.status) !== 401, anchorMissing,
verificationError: (!qualified && anchorMissing ? fallback.error : query.error)?.name === "AbortError" ? null : !qualified && anchorMissing ? fallback.error : query.error,
verificationPending: !qualified && (anchorMissing ? fallback.isPending : query.isPending),
@@ -211,42 +220,47 @@ export function useConversationEntry(target: ConversationEntryTarget | null) {
? current : { path: expectedPath, intent: incomingIntent })
}, [active, expectedPath, incomingIntent, resuming])
const intent = (active && !resuming) || retainedIntent.path !== expectedPath ? incomingIntent : retainedIntent.intent
- const { client, cachedResource, scope, currentPointer, input, options: entryOptions, query, canonical, resource, canRead, windowReady, revoked, denied, anchorMissing, localPosition } = useConversationResource(target, intent, true, "messages")
- const canonicalInput = useMemo(() => localPosition ? { ...input, anchorMessageId: null } : input, [input, localPosition])
- const entry = useMemo(() => {
+ const baseTarget = useMemo(() => target ? { ...target, preferTail: true } : null,
+ [target?.channelId, target?.serverId, target?.anchorMessageId, target?.tag])
+ const { client, cachedResource, scope, currentPointer, input, options: entryOptions, query, canonical, resource, canRead, windowReady, revoked, denied, anchorMissing } = useConversationResource(baseTarget, intent, "messages")
+ const entryIdentity = hashKey([input, scope ? conversationListScopeKey({ proof: scope.proof, tag: input.tag }) : null])
+ const createEntry = () => {
const pointer = scope ? currentConversationReadState(client, input.channelId) : undefined
const cachedScope = cachedResource ?? scope
- const covered = cachedScope ? findConversationEntryWindow(client,
- localPosition && pointer && pointer.lastReadSeq >= localPosition.seq ? canonicalInput : input, cachedScope, pointer) : undefined
+ const covered = cachedScope ? findConversationEntryWindow(client, input, cachedScope, pointer) : undefined
const window = covered ?? (cachedScope ? findConversationDisplayWindow(client, input, cachedScope) : undefined)
- return { intent, knownRevision: pointer?.observedRevision ?? -1, state: createStore<{ snapshot: CommunityReadStateResource | null; window: EntryWindow | null; covered: boolean; retained: boolean }>({
+ const boundary = cachedResource && (query.isSuccess && !query.isFetching && query.data === cachedResource
+ || input.newAfterSeq !== null && cachedResource.newBoundaryAtEntry.target !== null) && (input.newAfterSeq !== null
+ ? cachedResource.newBoundaryAtEntry.afterSeq === input.newAfterSeq
+ : cachedResource.readStateRevision >= (pointer?.observedRevision ?? -1)) ? cachedResource.newBoundaryAtEntry : undefined
+ return { client, identity: entryIdentity, intent, knownRevision: pointer?.observedRevision ?? -1, state: createStore<{ snapshot: CommunityReadStateResource | null; window: EntryWindow | null; covered: boolean; retained: boolean; newBoundary: ConversationEntryResource["newBoundaryAtEntry"] | undefined }>({
snapshot: pointer ?? null,
- window: window ?? null, covered: !!covered, retained: false,
+ window: window ?? null, covered: !!covered, retained: false, newBoundary: boundary,
}) }
- }, [client, cachedResource, scope, input, canonicalInput, localPosition, intent])
+ }
+ const [entry, setEntry] = useState(createEntry)
+ if (entry.client !== client || entry.identity !== entryIdentity || entry.intent !== intent) setEntry(createEntry())
const selected = useSelector(entry.state, (state) => state)
const currentRevision = currentPointer?.observedRevision ?? -1
- const needsCanonicalWindow = !!localPosition && !!resource && (resource.readStateRevision < currentRevision && !findConversationEntryWindow(client, canonicalInput, resource, currentPointer)
- || resource.readStateAtEntry.lastReadSeq >= localPosition.seq && !findConversationEntryWindow(client, canonicalInput, resource, resource.readStateAtEntry))
- const canonicalQuery = useQuery({ ...conversationEntryOptions(client, canonicalInput), enabled: presented && canRead && needsCanonicalWindow,
- subscribed: needsCanonicalWindow, staleTime: 0, refetchOnReconnect: false, refetchOnWindowFocus: false })
- const candidateResource = needsCanonicalWindow && canonicalQuery.data && isChannelMetadataTokenCurrent(canonicalQuery.data.proof)
- && canonicalQuery.data.readStateRevision >= Math.max(entry.knownRevision, currentRevision) ? canonicalQuery.data : resource
+ const candidateResource = resource
const candidatePointer = candidateResource && candidateResource.readStateRevision >= Math.max(entry.knownRevision, currentRevision)
? candidateResource.readStateAtEntry : scope ? currentConversationReadState(client, input.channelId) : undefined
- const candidateTarget = localPosition && candidatePointer && candidatePointer.lastReadSeq >= localPosition.seq
- ? canonicalInput : input
const candidateScope = candidateResource ?? scope
- const candidate = (!selected.covered || needsCanonicalWindow) && candidateScope
- ? findConversationEntryWindow(client, candidateTarget, candidateScope, candidatePointer) : undefined
+ const candidate = !selected.covered && candidateScope
+ ? findConversationEntryWindow(client, input, candidateScope, candidatePointer) : undefined
const display = !selected.window && candidateScope ? findConversationDisplayWindow(client, input, candidateScope) : undefined
const window = canRead ? (selected.retained ? selected.window : candidate) ?? selected.window ?? candidate ?? display ?? null : null
- const snapshot = window ? (needsCanonicalWindow || !selected.covered ? candidatePointer ?? selected.snapshot : selected.snapshot) ?? null : null
- const targetCovered = canRead && (needsCanonicalWindow ? !!candidate : selected.covered || !!candidate)
+ const snapshot = window ? (!selected.covered ? candidatePointer ?? selected.snapshot : selected.snapshot) ?? null : null
+ const targetCovered = canRead && (selected.covered || !!candidate)
+ const newBoundary = selected.newBoundary ?? (candidateResource
+ && (query.isSuccess && !query.isFetching && query.data === candidateResource
+ || input.newAfterSeq !== null && candidateResource.newBoundaryAtEntry.target !== null)
+ && (input.newAfterSeq === null || candidateResource.newBoundaryAtEntry.afterSeq === input.newAfterSeq)
+ ? candidateResource.newBoundaryAtEntry : undefined)
useLayoutEffect(() => {
- if (!window || !snapshot || selected.window === window && selected.snapshot === snapshot && selected.covered === targetCovered) return
- entry.state.setState(current => ({ ...current, window, snapshot, covered: targetCovered }))
- }, [window, snapshot, targetCovered, entry, selected])
+ if (!window || !snapshot || selected.window === window && selected.snapshot === snapshot && selected.covered === targetCovered && selected.newBoundary === newBoundary) return
+ entry.state.setState(current => ({ ...current, window, snapshot, covered: targetCovered, newBoundary }))
+ }, [window, snapshot, targetCovered, newBoundary, entry, selected])
const retainWindow = useCallback(() => {
if (!canRead || !window) return
entry.state.setState(current => current.retained ? current : { ...current, window, retained: true })
@@ -265,14 +279,18 @@ export function useConversationEntry(target: ConversationEntryTarget | null) {
}, window.key, target, undefined, owner ? { query: owner, signal: controller.signal } : undefined).catch(() => undefined)
return () => controller.abort()
}, [canRead, client, entryOptions.queryKey, input.channelId, input.serverId, resource, window, presented, selected.covered, entry.state, query.isFetching])
- const activeQuery = needsCanonicalWindow ? canonicalQuery : query
+ const activeQuery = query
const refetch = activeQuery.refetch
const retry = useCallback(() => refetch({ cancelRefetch: false }), [refetch])
- return { ...activeQuery, intent, resource, scope, canonical, canRead, windowReady, window, snapshot, targetCovered, revoked, denied, anchorMissing,
+ const refreshedBoundary = query.isSuccess && !query.isFetching && query.data && isChannelMetadataTokenCurrent(query.data.proof)
+ ? query.data.newBoundaryAtEntry : undefined
+ const retiredNewTargetId = newBoundary?.target && refreshedBoundary?.afterSeq === newBoundary.afterSeq
+ && refreshedBoundary.target?.id !== newBoundary.target.id ? newBoundary.target.id : undefined
+ return { ...activeQuery, intent, resource, scope, canonical, canRead, windowReady, window, snapshot, newBoundary: canRead ? newBoundary : undefined, retiredNewTargetId, targetCovered, revoked, denied, anchorMissing,
initialPositionPending: !targetCovered,
- initialPositionMessageId: targetCovered && localPosition && snapshot && snapshot.lastReadSeq < localPosition.seq ? localPosition.messageId : null,
+ initialPositionMessageId: null,
isPending: !!target && !window && !denied && !anchorMissing && !activeQuery.isError && activeQuery.errorUpdatedAt === 0,
failed: !window && activeQuery.errorUpdatedAt > 0,
- retry, retrying: activeQuery.isFetching, retainWindow,
+ retry, retrying: activeQuery.isFetching, retainWindow, retainedWindow: selected.retained,
}
}
diff --git a/src/web/src/hooks/community/use-dm-route-verification.dom.test.ts b/src/web/src/hooks/community/use-dm-route-verification.dom.test.ts
index 371fca708..53cb8845b 100644
--- a/src/web/src/hooks/community/use-dm-route-verification.dom.test.ts
+++ b/src/web/src/hooks/community/use-dm-route-verification.dom.test.ts
@@ -54,7 +54,7 @@ describe("DM route uses the shared Channel metadata owner", () => {
await expect(first).resolves.toBe("present")
await expect(second).resolves.toBe("present")
await waitFor(() => expect(route.result.current.status).toBe("readable"))
- expect(apiFetch).toHaveBeenCalledWith(`/api/community/channels/${dm.id}/messages?entry=1`, expect.objectContaining({ signal: expect.any(AbortSignal), authenticationAccount: "viewer" }))
+ expect(apiFetch).toHaveBeenCalledWith(`/api/community/channels/${dm.id}/messages?entry=1&window=tail`, expect.objectContaining({ signal: expect.any(AbortSignal), authenticationAccount: "viewer" }))
expect(client.getQueryData(channelMetadataOptions(client, null, dm.id).queryKey)).toMatchObject({ channelId: metadata.channelId })
expect(client.getQueryData(communityKeys.dms())).toEqual({ conversations: [] })
expect(registry.runtime.ws.get().channelAccessScopes.get(dm.id)).toMatchObject({ serverId: null, generation: 0, revoked: false })
diff --git a/src/web/src/hooks/community/use-forum-entry-selection.dom.test.tsx b/src/web/src/hooks/community/use-forum-entry-selection.dom.test.tsx
index 85782e93a..7cb35b460 100644
--- a/src/web/src/hooks/community/use-forum-entry-selection.dom.test.tsx
+++ b/src/web/src/hooks/community/use-forum-entry-selection.dom.test.tsx
@@ -31,7 +31,7 @@ it.each(["URL", "saved"] as const)("shares one cold %s-tag entry between route m
feed: useForumFeed("s1", "c1", source === "URL" ? { routeTag: "beta" } : undefined),
}), { wrapper: ({ children }) => <QueryClientProvider client={owner.client}><CommunityDbProvider registry={owner.registry}>{children}</CommunityDbProvider></QueryClientProvider> })
await waitFor(() => expect(release).toBeTypeOf("function"))
- expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages?entry=1&tag=beta"])
+ expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages?entry=1&window=tail&tag=beta"])
await act(async () => release())
await waitFor(() => expect(hook.result.current.feed.posts.map(post => post.id)).toEqual(["t1"]))
expect(hook.result.current.route.routeLifecycle).toBe("ready")
@@ -53,7 +53,7 @@ it("updates metadata and body from the same-window saved selection without an ex
await waitFor(() => expect(hook.result.current.feed.data).toBeDefined())
await act(async () => hook.result.current.feed.selectTag("gamma"))
await waitFor(() => expect(hook.result.current.feed.tag).toBe("gamma"))
- expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages?entry=1&tag=beta", "/api/community/channels/c1/messages?entry=1&tag=gamma"])
+ expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages?entry=1&window=tail&tag=beta", "/api/community/channels/c1/messages?entry=1&window=tail&newAfterSeq=1&tag=gamma"])
hook.unmount()
})
diff --git a/src/web/src/hooks/community/use-forum-feed.entry.dom.test.tsx b/src/web/src/hooks/community/use-forum-feed.entry.dom.test.tsx
index f55a3625c..63152f996 100644
--- a/src/web/src/hooks/community/use-forum-feed.entry.dom.test.tsx
+++ b/src/web/src/hooks/community/use-forum-feed.entry.dom.test.tsx
@@ -23,7 +23,7 @@ describe("forum common entry", () => {
await waitFor(() => expect(view.result.current.entry.snapshot?.lastReadMessageId).toBe("m1"))
expect(view.result.current.feed.posts.map(post => post.name)).toEqual(empty ? [] : ["Body"])
expect(view.result.current.feed.isLoading).toBe(false)
- expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages?entry=1"])
+ expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages?entry=1&window=tail"])
view.rerender()
expect(load).toHaveBeenCalledOnce()
view.unmount()
diff --git a/src/web/src/hooks/community/use-forum-feed.ts b/src/web/src/hooks/community/use-forum-feed.ts
index 67305e111..0112b9940 100644
--- a/src/web/src/hooks/community/use-forum-feed.ts
+++ b/src/web/src/hooks/community/use-forum-feed.ts
@@ -129,7 +129,7 @@ export function useForumFeed(serverId: string, channelId: string, options?: { ro
} })
useEffect(() => { if (selectionReady && !pendingTagCommands && tagsQuery.isSuccess && tag !== "All" && validateForumTagSelection(tag, tagsQuery.data.tags) === "All") selectTag("All") }, [selectionReady, pendingTagCommands, tag, tagsQuery.isSuccess, tagsQuery.data, selectTag])
const selectedTag = tag === "All" ? null : tag
- const entry = useConversationResource(selectionReady ? { channelId, serverId, tag: selectedTag } : null, null, false, "forum")
+ const entry = useConversationResource(selectionReady ? { channelId, serverId, tag: selectedTag } : null, null, "forum")
const queryKey = communityKeys.forumFeed(entry.canRead ? channelId : "__none__", selectedTag)
const query = useInfiniteQuery({ queryKey, queryFn: forumFeedPageQueryFn(channelId, selectedTag, queryClient), initialPageParam: null as string | null, getNextPageParam: (lastPage) => lastPage.hasMore ? lastPage.nextCursor : undefined,
enabled: presented && selectionReady && entry.canRead && !entry.verificationFetching && (!entry.verificationFailed || entry.displayWindow !== undefined), subscribed: selectionReady && entry.canRead, staleTime: 5_000,
diff --git a/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.ts b/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.ts
index 6509ef13e..1c33f6a8d 100644
--- a/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.ts
+++ b/src/web/src/hooks/community/use-forum-sidebar-threads.dom.test.ts
@@ -445,7 +445,7 @@ describe("forum sidebar canonical projection", () => {
await waitFor(() => expect(sidebar.result.current.isSuccess).toBe(true))
expect(queryClient.getQueryData(communityKeys.forumSidebarThreads("server-1"))).toMatchObject({ window: { retained: { id: "post-1", disposition: "opener-archived" } } })
let resolveMetadata!: (value: ReturnType<typeof conversationEntryFromChannel>) => void
- apiFetchMock.mockImplementation((path: string) => path.includes("/messages?entry=1")
+ apiFetchMock.mockImplementation((path: string) => path.includes("/messages?entry=1&window=tail")
? new Promise(resolve => { resolveMetadata = resolve })
: refresh === "failed" ? Promise.reject(new Error("Sidebar unavailable")) : new Promise(() => {}))
const { dispatchCommunityWsEvent } = await import("./community-ws/registry")
@@ -570,7 +570,7 @@ describe("forum sidebar canonical projection", () => {
await waitFor(() => expect(sidebar.result.current.threads[0]?.title).toBe("Canonical title"))
let releaseRetained!: (value: SidebarThreadEnvelope) => void
const retained = new Promise<SidebarThreadEnvelope>((resolve) => { releaseRetained = resolve })
- apiFetchMock.mockImplementation((url) => url === "/api/community/channels/post-1/messages?entry=1" ? Promise.resolve(conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0, parentChannelId: "forum-1", parentMessageId: "opener-1", creatorId: null, lastMessageAt: null, id: "post-1", serverId: "server-1", type: "thread", name: "Canonical title", archived: false, createdAt: new Date().toISOString() })) : retained)
+ apiFetchMock.mockImplementation((url) => url === "/api/community/channels/post-1/messages?entry=1&window=tail" ? Promise.resolve(conversationEntryFromChannel({ categoryId: null, topic: "", position: 0, messageCount: 0, parentChannelId: "forum-1", parentMessageId: "opener-1", creatorId: null, lastMessageAt: null, id: "post-1", serverId: "server-1", type: "thread", name: "Canonical title", archived: false, createdAt: new Date().toISOString() })) : retained)
retainId = "post-1"
sidebar.rerender()
const route = renderHook(() => {
@@ -584,7 +584,7 @@ describe("forum sidebar canonical projection", () => {
await waitFor(() => expect(route.result.current.metadata.canRead).toBe(true))
expect(route.result.current.opener.data?.content).toBe("Canonical title")
await waitFor(() => expect(apiFetchMock.mock.calls.some(([url]) => new URL(url, "http://localhost").searchParams.get("retainId") === "post-1")).toBe(true))
- expect(apiFetchMock.mock.calls.filter(([url]) => url === "/api/community/channels/post-1/messages?entry=1")).toHaveLength(1)
+ expect(apiFetchMock.mock.calls.filter(([url]) => url === "/api/community/channels/post-1/messages?entry=1&window=tail")).toHaveLength(1)
await waitFor(() => expect(queryClient.getQueryData(conversationEntryOptions(queryClient, { serverId: "server-1", channelId: "post-1" }).queryKey)).toBeDefined())
expect(isChannelMetadataTokenCurrent(queryClient.getQueryData(conversationEntryOptions(queryClient, { serverId: "server-1", channelId: "post-1" }).queryKey)!.proof)).toBe(true)
} finally {
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 835d1fd04..81f594497 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
@@ -51,10 +51,10 @@ describe("entry-owned message activation", () => {
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 key = communityKeys.channelMessagesWindow("c1", { mode: "newest" })
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" }] }))
+ await act(async () => client.setQueryData(key, { pages, pageParams: [{ mode: "newest" }, { mode: "older", cursor: "old-1" }, { mode: "older", cursor: "old-2" }] }))
first.unmount()
const clock = vi.spyOn(Date, "now").mockReturnValue(Date.now() + 6000)
try {
@@ -89,7 +89,7 @@ describe("entry-owned message activation", () => {
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)
+ expect(client.getQueryData<MessageWindowData>(communityKeys.channelMessagesWindow("c1", { mode: "newest" }))?.pages).toHaveLength(1)
returned.unmount()
} finally { clock.mockRestore() }
})
diff --git a/src/web/src/hooks/community/use-messages.anchor-retry.dom.test.ts b/src/web/src/hooks/community/use-messages.anchor-retry.dom.test.ts
index bc5584fbd..78c840a09 100644
--- a/src/web/src/hooks/community/use-messages.anchor-retry.dom.test.ts
+++ b/src/web/src/hooks/community/use-messages.anchor-retry.dom.test.ts
@@ -100,7 +100,7 @@ describe("entry failure and explicit recovery", () => {
expect(hook.result.current.messages.map(message => message.id)).toEqual(["m1"])
expect(hook.result.current.readSnapshotFetching).toBe(true)
expect(registry.collections.channels.has("c1")).toBe(true)
- expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages?entry=1&anchor=gone", "/api/community/channels/c1/messages?entry=1"])
+ expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages?entry=1&anchor=gone", "/api/community/channels/c1/messages?entry=1&window=tail"])
hook.unmount()
})
})
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 7385e6207..f490fab2d 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
@@ -37,6 +37,7 @@ async function holdSelectedWindowRepair() {
old.selection = { reason: "tail", anchorMessageId: null }
old.readState = { channelId: "c1", lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 }
old.readStateRevision = 0
+ old.newBoundary = { afterSeq: 0, target: { id: "m1", channelId: "c1", seq: 1, authorId: "peer" } }
load.mockResolvedValueOnce(old)
const useSurface = () => useMessages("c1", { serverId: "s1", viewerUserId: "viewer" })
const first = renderHook(useSurface, { wrapper: owner.wrapper })
@@ -47,51 +48,102 @@ async function holdSelectedWindowRepair() {
}] }))
const fresh = fixture()
fresh.readStateRevision = 1
- fresh.messages.push({ ...fresh.messages[0], id: "m2", seq: 2, createdAt: "2026-10-01T00:00:02.000Z" })
- fresh.page.latestSeq = 2
+ const missing = { ...fresh.messages[0], id: "m2", seq: 2, createdAt: "2026-10-01T00:00:02.000Z" }
+ fresh.messages = [{ ...missing, id: "m3", seq: 3, createdAt: "2026-10-01T00:00:03.000Z" }]
+ fresh.page.latestSeq = 3
+ fresh.newBoundary = { afterSeq: 1, target: { id: "m2", channelId: "c1", seq: 2, authorId: "peer" } }
const late = deferred<{ messages: typeof fresh.messages; latestSeq: number; hasMoreNewer: boolean }>()
load.mockImplementation((url: string) => new URL(url, "https://example.test").searchParams.has("entry")
? Promise.resolve(fresh) : late.promise)
vi.spyOn(Date, "now").mockReturnValue(Date.now() + 6000)
const hook = renderHook(useSurface, { wrapper: owner.wrapper })
- await waitFor(() => expect(load.mock.calls.some(([url]) => url === "/api/community/channels/c1/messages")).toBe(true))
- const call = load.mock.calls.find(([url]) => url === "/api/community/channels/c1/messages")!
+ await waitFor(() => expect(load.mock.calls.some(([url]) => new URL(url, "https://example.test").searchParams.has("since"))).toBe(true))
+ const call = load.mock.calls.find(([url]) => new URL(url, "https://example.test").searchParams.has("since"))!
expect(hook.result.current.messages.map(message => message.id)).toEqual(["m1"])
expect(hook.result.current.readSnapshot?.lastReadSeq).toBe(1)
return { ...owner, hook, late, signal: call[1].signal as AbortSignal,
- key: communityKeys.channelMessagesWindow("c1", { mode: "newest" }), fresh }
+ key: communityKeys.channelMessagesWindow("c1", { mode: "newest" }), fresh: { ...fresh, messages: [missing, ...fresh.messages] } }
}
describe("returned entry and selected message window", () => {
- it("qualifies complete cached rows for positioning while the selected window repair is pending", async () => {
+ it.each(["query replacement", "access withdrawal", "unmount", "new Present attempt"] as const)("binds updated Present data to its query owner until %s", async retirement => {
+ const { wrapper, client, registry } = await setup()
+ const entry = fixture()
+ entry.selection = { reason: "explicit_anchor", anchorMessageId: "m1" }
+ entry.page.hasMoreNewer = true
+ load.mockResolvedValueOnce(entry)
+ const hook = renderHook(() => useMessages("c1", { serverId: "s1", anchorMessageId: "m1" }), { wrapper })
+ let unmounted = false
+ try {
+ await waitFor(() => expect(hook.result.current.initialPositionKnown).toBe(true))
+ const held = deferred<ReturnType<typeof messageReadPageFixture>>()
+ load.mockReturnValue(held.promise)
+ let request!: ReturnType<typeof hook.result.current.jumpToPresent>
+ act(() => { request = hook.result.current.jumpToPresent() })
+ if (!request.accepted) throw new Error("Expected the current Present request to be accepted")
+ const historyKey = communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "m1" })
+ await act(async () => { client.setQueryData<MessageWindowData>(historyKey, data => data && ({ ...data,
+ pages: data.pages.map(page => ({ ...page, latestSeq: 2 })) })) })
+ await act(async () => held.resolve(messageReadPageFixture({ messages: [{ ...entry.messages[0], id: "m2", seq: 2 }],
+ latestSeq: 2, hasMoreOlder: false, hasMoreNewer: false })))
+ const completed = await request.completed
+ if (completed.status !== "success" || !completed.windowState) throw new Error("Expected a successful Present selection proof")
+ const windowState = completed.windowState
+ await waitFor(() => expect(hook.result.current.messages.map(message => message.id)).toEqual(["m2"]))
+ expect(windowState(hook.result.current.messageWindow)).toBe("ready")
+ const tailKey = communityKeys.channelMessagesWindow("c1", { mode: "newest" })
+ await act(async () => { client.setQueryData<MessageWindowData>(tailKey, data => data && ({ ...data,
+ pages: data.pages.map(page => ({ ...page, latestSeq: 3 })) })) })
+ expect(client.getQueryData(tailKey)).not.toBe(completed.window)
+ await waitFor(() => expect(hook.result.current.latestSeq).toBe(3))
+ const updated = hook.result.current.messageWindow
+ expect(updated).not.toBe(completed.window)
+ expect(windowState(updated)).toBe("ready")
+ expect(windowState(completed.window)).toBe("pending")
+ if (retirement === "query replacement") {
+ await act(async () => {
+ client.removeQueries({ queryKey: tailKey, exact: true })
+ client.setQueryData(tailKey, updated)
+ })
+ } else if (retirement === "access withdrawal") {
+ await act(async () => registry.runtime.ws.actions.revokeChannelAccess("s1", "c1"))
+ } else if (retirement === "new Present attempt") {
+ act(() => { expect(hook.result.current.jumpToPresent().accepted).toBe(true) })
+ } else {
+ hook.unmount()
+ unmounted = true
+ }
+ expect(windowState(updated)).toBe("retired")
+ } finally { if (!unmounted) hook.unmount(); client.clear() }
+ })
+
+ it("retains complete cached rows but waits for latest 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.initialScrollReady).toBe(false)
expect(hook.result.current.messages.map(message => message.id)).toEqual(["m1"])
- await act(async () => late.resolve(messageReadPageFixture({ messages: fresh.messages, latestSeq: 2, hasMoreNewer: false })))
+ await act(async () => late.resolve(messageReadPageFixture({ messages: fresh.messages, latestSeq: 3, 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 => {
+ it.each(["different-key history", "same-key newest"] as const)("publishes the new entry into the actual feed after %s return", async kind => {
const { wrapper, client, registry } = await setup()
const old = fixture()
old.readStateRevision = 1
old.page.hasMoreOlder = false
old.page.olderCursor = null
- if (kind === "different-key newest") {
- old.readState = { channelId: "c1", lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 }
- old.readStateRevision = 0
- old.selection = { reason: "tail", anchorMessageId: null }
- }
+ let anchorMessageId: string | undefined = kind === "different-key history" ? "m1" : undefined
+ if (anchorMessageId) old.selection = { reason: "explicit_anchor", anchorMessageId }
load.mockResolvedValueOnce(old)
- const useSurface = () => useMessages("c1", { serverId: "s1", viewerUserId: "viewer" })
+ const useSurface = () => useMessages("c1", { serverId: "s1", viewerUserId: "viewer", anchorMessageId })
const first = renderHook(useSurface, { wrapper })
await waitFor(() => expect(first.result.current.initialPositionKnown).toBe(true))
expect(first.result.current.messages.map(message => message.id)).toEqual(["m1"])
first.unmount()
+ anchorMessageId = undefined
await act(async () => ingestReadStateSnapshot(registry, { revision: 1, readStates: [{
channelId: "c1", lastReadMessageId: "m1", lastReadAt: old.messages[0].createdAt, lastReadSeq: 1,
}] }))
@@ -102,6 +154,7 @@ describe("returned entry and selected message window", () => {
...fresh.messages[0], id: `m${index + 1}`, seq: index + 1,
content: `Mention ${index + 1}`, createdAt: new Date(Date.UTC(2026, 9, 1, 0, 0, index + 1)).toISOString(),
}))
+ fresh.newBoundary = { afterSeq: 1, target: { id: "m2", channelId: "c1", seq: 2, authorId: "peer" } }
fresh.channel.messageCount = 13
fresh.channel.lastMessageAt = fresh.messages.at(-1)!.createdAt
fresh.page = { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 13 }
@@ -119,23 +172,24 @@ describe("returned entry and selected message window", () => {
const returned = renderHook(useSurface, { wrapper })
try {
await waitFor(() => expect(load).toHaveBeenCalledTimes(2))
- const oldParam = kind === "different-key newest" ? { mode: "newest" } : { mode: "anchor", anchor: "m1" }
- expect(returned.result.current.data?.pageParams[0]).toEqual(oldParam)
- expect(returned.result.current.messages.map(message => message.id)).toEqual(["m1"])
- expect(returned.result.current.readSnapshot?.lastReadSeq).toBe(1)
+ const oldParam = { mode: "newest" }
+ expect(returned.result.current.data?.pageParams[0]).toEqual(kind === "same-key newest" ? oldParam : undefined)
+ expect(returned.result.current.messages.map(message => message.id)).toEqual(kind === "same-key newest" ? ["m1"] : [])
+ expect(returned.result.current.readSnapshot?.lastReadSeq).toBe(kind === "same-key newest" ? 1 : undefined)
await act(async () => response.resolve(fresh))
await waitFor(() => expect(returned.result.current.isFetching).toBe(false))
const expectedIds = fresh.messages.map(message => message.id)
- const anchorKey = communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "m1" })
- expect(client.getQueryData<MessageWindowData>(anchorKey)?.pages.flatMap(page => page.messages.map(message => message.id))).toEqual(expectedIds)
+ const latestKey = communityKeys.channelMessagesWindow("c1", { mode: "newest" })
+ expect(client.getQueryData<MessageWindowData>(latestKey)?.pages.flatMap(page => page.messages.map(message => message.id))).toEqual(expectedIds)
expect(expectedIds.every(id => registry.collections.messages.has(id))).toBe(true)
+ if (kind === "different-key history") expect(client.getQueryData<MessageWindowData>(communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "m1" }))?.pages[0].messages.map(message => message.id)).toEqual(["m1"])
expect(returned.result.current.readSnapshot?.lastReadMessageId).toBe("m1")
expect(returned.result.current.readSnapshot?.lastReadSeq).toBe(1)
expect(returned.result.current.initialPositionKnown).toBe(true)
await waitFor(() => expect(returned.result.current.messages.map(message => message.id)).toEqual(expectedIds))
expect(returned.result.current.latestSeq).toBe(13)
expect(returned.result.current.data?.pageParams[0]).toEqual(oldParam)
- expect(load.mock.calls.filter(([url]) => url === "/api/community/channels/c1/messages")).toHaveLength(kind === "different-key newest" ? 1 : 0)
+ expect(load.mock.calls.filter(([url]) => url === "/api/community/channels/c1/messages")).toHaveLength(0)
const capturedSnapshot = returned.result.current.readSnapshot
await act(async () => ingestReadStateSnapshot(registry, { revision: 2, readStates: [{
channelId: "c1", lastReadMessageId: "m13", lastReadAt: fresh.messages.at(-1)!.createdAt, lastReadSeq: 13,
@@ -153,6 +207,7 @@ describe("returned entry and selected message window", () => {
old.selection = { reason: "tail", anchorMessageId: null }
old.readState = { channelId: "c1", lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 }
old.readStateRevision = 0
+ old.newBoundary = { afterSeq: 0, target: { id: "m1", channelId: "c1", seq: 1, authorId: "peer" } }
load.mockResolvedValueOnce(old)
const useSurface = () => useMessages("c1", { serverId: "s1", viewerUserId: "viewer" })
const first = renderHook(useSurface, { wrapper })
@@ -192,8 +247,9 @@ describe("returned entry and selected message window", () => {
await waitFor(() => expect(load.mock.calls.filter(([url]) => url === "/api/community/channels/c1/messages")).toHaveLength(1))
await act(async () => entry.resolve(fresh))
await waitFor(() => expect(returned.result.current.isFetching).toBe(false))
- const anchorKey = communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "m1" })
- expect(client.getQueryData<MessageWindowData>(anchorKey)?.pages[0].messages).toHaveLength(13)
+ const latestKey = communityKeys.channelMessagesWindow("c1", { mode: "newest" })
+ expect(client.getQueryData<MessageWindowData>(latestKey)?.pages[0].messages.map(message => message.id)).toEqual(["m1"])
+ expect(fresh.messages.every(message => registry.collections.messages.has(message.id))).toBe(true)
await act(async () => {
oldWindow.resolve(messageReadPageFixture({ messages: old.messages, latestSeq: 1, hasMoreNewer: false }))
await olderRepair
@@ -217,10 +273,10 @@ describe("returned entry and selected message window", () => {
else hook.unmount()
})
expect(signal.aborted).toBe(true)
- const lateMessage = { ...fresh.messages[0], id: "late_m3", seq: 3 }
- await act(async () => late.resolve(messageReadPageFixture({ messages: [...fresh.messages, lateMessage], latestSeq: 3, hasMoreNewer: false })))
- expect(registry.collections.messages.get("late_m3")).toBeUndefined()
- expect(client.getQueryData<MessageWindowData>(key)?.pages.flatMap(page => page.messages.map(message => message.id)) ?? []).not.toContain("late_m3")
+ const lateMessage = { ...fresh.messages[0], id: "late_m4", seq: 4 }
+ await act(async () => late.resolve(messageReadPageFixture({ messages: [...fresh.messages, lateMessage], latestSeq: 4, hasMoreNewer: false })))
+ expect(registry.collections.messages.get("late_m4")).toBeUndefined()
+ expect(client.getQueryData<MessageWindowData>(key)?.pages.flatMap(page => page.messages.map(message => message.id)) ?? []).not.toContain("late_m4")
if (kind !== "unmount") hook.unmount()
})
@@ -236,7 +292,7 @@ describe("returned entry and selected message window", () => {
expect(hook.result.current.readSnapshot?.lastReadSeq).toBe(1)
expect(hook.result.current.initialPositionKnown).toBe(true)
expect(hook.result.current.initialLoadError).toBeNull()
- expect(load.mock.calls.filter(([url]) => url === "/api/community/channels/c1/messages")).toHaveLength(3)
+ expect(load.mock.calls.filter(([url]) => new URL(url, "https://example.test").searchParams.has("since"))).toHaveLength(3)
hook.unmount()
})
})
diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.ts
index 1342c0638..3d7736b05 100644
--- a/src/web/src/hooks/community/use-messages.ts
+++ b/src/web/src/hooks/community/use-messages.ts
@@ -15,7 +15,7 @@ import { getCommunityRuntime } from "@/stores/community/runtime"
import { useMessageOverlayIds } from "@/stores/community/message-stream"
import { materializeMessageStream, type MessageScope } from "@/lib/community/message-stream"
import { messageWindowOptions, type InitialMessageWindow, type MessageWindowData } from "@/lib/community/message-window"
-import { knownConversationLatestSeq, type findConversationEntryWindow } from "@/lib/community/conversation-entry"
+import { conversationEntryOptions, knownConversationLatestSeq, type findConversationEntryWindow } from "@/lib/community/conversation-entry"
import type { Msg } from "@/lib/community/models/message"
import type { MessagePositionState, MessageRequest, MessageRequestResult } from "@/lib/community/message-position"
import { ConversationReadTimeoutError, withConversationReadDeadline } from "@/lib/community/conversation-read"
@@ -128,8 +128,8 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefi
const originalQuery = client.getQueryCache().find({ queryKey, exact: true })
const owner = useMemo(() => ({ present, retries, query: originalQuery, enabled: enabled && presented }), [present, retries, originalQuery, enabled, presented])
const committed = useRef<typeof owner | null>(null)
- const committedWindowReady = useRef(entry.windowReady)
- useLayoutEffect(() => { committedWindowReady.current = entry.windowReady }, [entry.windowReady])
+ const committedWindowReady = useRef(false)
+ const committedNewReady = useRef(false)
useLayoutEffect(() => {
committed.current = owner
return () => { if (committed.current === owner) committed.current = null }
@@ -145,6 +145,8 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefi
const presentationResources = useMemo(() => new Map([...projection.relatedMessages.map(message => [message.id, message] as const), ...canonicalById]), [canonicalById, projection.relatedMessages])
const missingCanonical = ids.some(id => !canonicalById.has(id))
const projectionFailed = projection.status === "error"
+ const selectedWindowReady = entry.windowReady && !!query.data && projection.canonicalMessages !== undefined && !missingCanonical && !projectionFailed
+ useLayoutEffect(() => { committedWindowReady.current = selectedWindowReady }, [selectedWindowReady])
const [projectionFailure, setProjectionFailure] = useState<{ window: object; attempt: object | null; viewKey: string } | null>(null)
useEffect(() => {
if (!entry.canRead || !query.data || !missingCanonical || projectionFailed) return
@@ -212,7 +214,14 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefi
if (!isCurrent()) return { status: "retired" }
present.setState((state) => ({ ...state, pending: false, version: attempt,
window: { key: tail.queryKey, initial: { mode: "newest" }, tag } }))
- return { status: "success", window: data }
+ return { status: "success", window: data, windowState: window => {
+ const current = committed.current
+ if (!current?.enabled || current.present !== present || present.get().attempt !== attempt || !isChannelMetadataTokenCurrent(token)
+ || client.getQueryCache().get(captured.queryHash) !== captured) return "retired"
+ if (current.query === captured) return window === captured.state.data ? "ready" : "pending"
+ return current.query === original.query && !!original.query
+ && client.getQueryCache().get(original.query.queryHash) === original.query ? "pending" : "retired"
+ } }
}, (error: unknown) => {
if (!isCurrent()) return { status: "retired" } as const
present.setState((state) => ({ ...state, pending: false, error: error instanceof Error ? error : new Error("Could not load recent messages") }))
@@ -222,6 +231,45 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefi
present.setState(state => ({ ...state, request }))
return request
}, [channelId, client, observation, owner, present, tag])
+ const loadNewTarget = useCallback((id: string): MessageRequest => {
+ const original = committed.current
+ if (!channelId || !original?.enabled || original !== owner || !committedNewReady.current || present.get().pending) return { accepted: false }
+ if (references.some(message => message.id === id) && query.data) return { accepted: true, completed: Promise.resolve({ status: "success", window: query.data }) }
+ const token = captureChannelMetadataToken(client, channelId)
+ const initial = { mode: "anchor" as const, anchor: id }
+ const anchored = messageWindowOptions(client, channelId, initial, tag, { observation })
+ const captured = client.getQueryCache().build<unknown, Error, unknown>(client, { queryKey: anchored.queryKey })
+ present.setState(state => ({ ...state, attempt: state.attempt + 1, pending: true, error: null }))
+ const attempt = present.get().attempt
+ let cancelled = false
+ const isCurrent = () => !cancelled && present.get().attempt === attempt && committed.current === original && isChannelMetadataTokenCurrent(token)
+ && client.getQueryCache().get(captured.queryHash) === captured
+ const completed = client.infiniteQuery({ ...anchored, staleTime: 0, select: undefined }).then((data): MessageRequestResult => {
+ if (!isCurrent()) return { status: "retired" }
+ if (!data.pages.some(page => page.messages.some(message => message.id === id))) {
+ present.setState(state => ({ ...state, pending: false }))
+ return { status: "missing" }
+ }
+ present.setState(state => ({ ...state, pending: false, window: { key: anchored.queryKey, initial, tag } }))
+ return { status: "success", window: data }
+ }, (error: unknown): MessageRequestResult => {
+ if (!isCurrent()) return { status: "retired" }
+ present.setState(state => ({ ...state, pending: false }))
+ return { status: typeof error === "object" && error !== null && "status" in error && (error.status === 403 || error.status === 404) ? "missing" : "error" }
+ })
+ return { accepted: true, completed, cancel: () => {
+ cancelled = true
+ if (committed.current === original && present.get().attempt === attempt) present.setState(state => ({ ...state, pending: false }))
+ } }
+ }, [channelId, client, observation, owner, present, query.data, references, tag])
+ const readNewBoundary = useCallback(async (afterSeq: number) => {
+ const original = committed.current
+ if (!channelId || !original?.enabled || original !== owner || !committedNewReady.current) return
+ const token = captureChannelMetadataToken(client, channelId)
+ const resource = await client.query({ ...conversationEntryOptions(client, { channelId, serverId, tag, preferTail: true, newAfterSeq: afterSeq }, observation()), staleTime: 0 })
+ if (committed.current !== original || !isChannelMetadataTokenCurrent(token)) return
+ return { boundary: resource.newBoundaryAtEntry, latestSeq: resource.latestSeqAtEntry }
+ }, [channelId, client, observation, owner, serverId, tag])
const error = query.error ?? entry.error
const windowAvailable = !!selectedWindow && query.data !== undefined
const projectionError = projectionFailed || missingCanonical && !!projectionFailure && projectionFailure.window === query.data
@@ -229,7 +277,7 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefi
const initialLoadError = windowAvailable ? projectionError : retrySelection.error ?? error ?? (entry.failed ? INITIAL_ENTRY_ERROR : null)
const repairError = repairQuery && isFailedMessageRepair(client, repairQuery) ? repair.error : null
const targetLoadError = windowAvailable && !selection.window && !entry.isFetching && entry.error?.name !== "AbortError"
- ? (!entry.targetCovered ? entry.error : null) ?? repairError : null
+ ? (!entry.targetCovered || entry.newBoundary === undefined ? entry.error : null) ?? repairError : null
const loading = !!channelId && (windowAvailable ? projection.canonicalMessages === undefined : !initialLoadError && !entry.denied && !entry.anchorMissing)
const entryWindow = entry.window, retryEntry = entry.retry, refetchWindow = query.refetch
const retryInitialLoad = useCallback(() => {
@@ -241,19 +289,23 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefi
const request = repairError ? reconcileWindow(client, {
kind: serverId === null ? "dm" : "channel", scopeId: channelId, serverId: serverId ?? undefined,
}, queryKey).then(() => ({ error: null }), error => ({ error: error instanceof Error ? error : new Error("Could not repair this message window") }))
- : entryWindow && entry.targetCovered ? refetchWindow({ cancelRefetch: false }) : retryEntry()
+ : entryWindow && entry.targetCovered && entry.newBoundary !== undefined ? refetchWindow({ cancelRefetch: false }) : retryEntry()
void request.then(result => {
if (!current()) return
retries.setState(() => ({ attempt, pending: false, error: result.error }))
})
- }, [channelId, client, entryWindow, entry.targetCovered, queryKey, repairError, retryEntry, refetchWindow, retries, serverId])
+ }, [channelId, client, entryWindow, entry.targetCovered, entry.newBoundary, queryKey, repairError, retryEntry, refetchWindow, retries, serverId])
const targetPositionDataState: MessagePositionState = retrySelection.pending ? "pending"
: initialLoadError || targetLoadError || retrySelection.error || entry.denied || !windowAvailable && entry.anchorMissing && !entry.isFetching ? "error"
: !windowAvailable || loading || missingCanonical || !!anchorMessageId && !entry.targetCovered && !selection.window && !entry.anchorMissing ? "pending"
: messages.length ? "ready" : "empty"
- const positionDataState: MessagePositionState = targetPositionDataState === "error" && !targetLoadError ? "error"
+ const positionDataState: MessagePositionState = targetPositionDataState === "error"
+ && (!targetLoadError || !anchorMessageId && !entry.targetCovered && !entry.retainedWindow && !selection.window) ? "error"
: !windowAvailable || !entry.snapshot || loading || readSnapshotFetching || retrySelection.pending ? "pending"
: messages.length ? "ready" : "empty"
+ useLayoutEffect(() => { committedNewReady.current = entry.canRead && windowAvailable && !loading && !missingCanonical
+ && !initialLoadError && !targetLoadError && positionDataState === "ready" },
+ [entry.canRead, windowAvailable, loading, missingCanonical, initialLoadError, targetLoadError, positionDataState])
return {
...query, observation: { snapshot_source: entry.resource?.source ?? "unknown" as const, target_coverage: entry.targetCovered || selection.window ? "covered" as const : "uncovered" as const,
wait_reason: !entry.canRead ? "entry" as const : !windowAvailable ? "window" as const : loading ? "projection" as const : "none" as const },
@@ -263,12 +315,13 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefi
error, initialLoadError, targetLoadError, isFetching: entry.isFetching || query.isFetching,
isFetchingOlder: query.isFetchingNextPage,
isFetchingNewer: query.isFetchingPreviousPage || selection.pending,
- fetchOlder, fetchNewer, jumpToPresent, presentVersion: selection.version, presentRequest: selection.request,
+ fetchOlder, fetchNewer, jumpToPresent, loadNewTarget, readNewBoundary, newBoundary: entry.newBoundary, retiredNewTargetId: entry.retiredNewTargetId, presentVersion: selection.version, presentRequest: selection.request,
anchorReconciled: entry.targetCovered || !!selection.window,
- navigationBlocked: !entry.windowReady,
+ navigationBlocked: !selectedWindowReady,
readSnapshot: entry.snapshot, readSnapshotFetching,
initialDisplayReady: windowAvailable && !loading && !missingCanonical && !initialLoadError,
- preserveInitialPresentation: !!retrySelection.attempt && windowAvailable,
+ initialScrollReady: windowAvailable && !loading && !missingCanonical && !initialLoadError && (!!anchorMessageId || !readSnapshotFetching),
+ preserveInitialPresentation: !!retrySelection.attempt && windowAvailable && (!!anchorMessageId || entry.targetCovered || entry.retainedWindow),
initialPositionKnown: windowAvailable && entry.snapshot !== null && !loading && !missingCanonical && !initialLoadError && !retrySelection.pending && !entry.initialPositionPending,
initialPositionMessageId: entry.initialPositionMessageId, positionEntry, positionScope, positionDataState, targetPositionDataState, messageWindow: query.data,
onUserTakeover: entry.retainWindow,
diff --git a/src/web/src/hooks/community/use-messages.window.dom.test.tsx b/src/web/src/hooks/community/use-messages.window.dom.test.tsx
index b3350c90f..c6dc4c799 100644
--- a/src/web/src/hooks/community/use-messages.window.dom.test.tsx
+++ b/src/web/src/hooks/community/use-messages.window.dom.test.tsx
@@ -56,8 +56,8 @@ describe("native conversation windows", () => {
await waitFor(() => expect(hook.result.current.messages.map((message) => message.content)).toEqual(["Body"]))
expect(hook.result.current.isLoading).toBe(false)
expect(hook.result.current.readSnapshot?.lastReadMessageId).toBe("m1")
- expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages?entry=1"])
- const key = communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "m1" })
+ expect(load.mock.calls.map(([url]) => url)).toEqual(["/api/community/channels/c1/messages?entry=1&window=tail"])
+ const key = communityKeys.channelMessagesWindow("c1", { mode: "newest" })
expect(JSON.stringify(client.getQueryData(key))).not.toContain("Body")
hook.unmount()
})
@@ -68,7 +68,7 @@ describe("native conversation windows", () => {
load.mockImplementation((url: string) => {
const search = new URL(url, "https://example.test").searchParams
if (search.has("entry")) return Promise.resolve(fixture())
- if (search.has("anchor")) return refresh.promise
+ if (search.size === 0) return refresh.promise
if (search.get("cursor") === "older") return Promise.resolve(page("m0", 0))
throw new Error("Unexpected message window")
})
@@ -80,7 +80,7 @@ describe("native conversation windows", () => {
expect(load.mock.calls.some(([url]) => new URL(url, "https://example.test").searchParams.has("cursor"))).toBe(false)
await act(async () => { refresh.resolve(page("m1", 1, true)); await refetch })
await waitFor(() => expect(hook.result.current.messages.map((message) => message.id)).toEqual(["m0", "m1"]))
- expect(hook.result.current.data?.pageParams).toEqual([{ mode: "anchor", anchor: "m1" }, { mode: "older", cursor: "older" }])
+ expect(hook.result.current.data?.pageParams).toEqual([{ mode: "newest" }, { mode: "older", cursor: "older" }])
hook.unmount()
})
@@ -109,10 +109,11 @@ describe("native conversation windows", () => {
it.each(["success", "error"] as const)("returns a real newer cursor request's %s receipt", async status => {
const { wrapper } = await setup()
const packet = fixture()
+ packet.selection = { reason: "explicit_anchor", anchorMessageId: "m1" }
packet.page.hasMoreNewer = true
packet.page.newerCursor = "newer"
load.mockResolvedValue(packet)
- const hook = renderHook(() => useMessages("c1", options), { wrapper })
+ const hook = renderHook(() => useMessages("c1", { ...options, anchorMessageId: "m1" }), { wrapper })
await waitFor(() => expect(hook.result.current.positionDataState).toBe("ready"))
const original = hook.result.current.data
load.mockImplementation(() => status === "success" ? Promise.resolve(page("m2", 2)) : Promise.reject(new ConversationReadTimeoutError()))
@@ -138,13 +139,16 @@ describe("native conversation windows", () => {
const { wrapper, client } = await setup()
const first = deferred<MessagesPage>()
const second = deferred<MessagesPage>()
+ const packet = fixture()
+ packet.selection = { reason: "explicit_anchor", anchorMessageId: "m1" }
let attempts = 0
load.mockImplementation((url: string) => new URL(url, "https://example.test").searchParams.has("entry")
- ? Promise.resolve(fixture()) : ++attempts === 1 ? first.promise : second.promise)
- const hook = renderHook(() => useMessages("c1", options), { wrapper })
+ ? Promise.resolve(packet) : ++attempts === 1 ? first.promise : second.promise)
+ const hook = renderHook(() => useMessages("c1", { ...options, anchorMessageId: "m1" }), { wrapper })
await waitFor(() => expect(hook.result.current.messages).toHaveLength(1))
const anchorKey = communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "m1" })
const original = client.getQueryData(anchorKey)
+ expect(original).toBeDefined()
await act(async () => hook.result.current.jumpToPresent())
expect(hook.result.current.isFetchingNewer).toBe(true)
expect(hook.result.current.messages[0].id).toBe("m1")
diff --git a/src/web/src/hooks/community/use-read-observer.ts b/src/web/src/hooks/community/use-read-observer.ts
index 01ced73c3..786084f6b 100644
--- a/src/web/src/hooks/community/use-read-observer.ts
+++ b/src/web/src/hooks/community/use-read-observer.ts
@@ -22,7 +22,7 @@ import {
type InboxReadReservationLease,
} from "./inbox-read-reservation"
-const READ_VISIBILITY_THRESHOLD = 0.2
+export const READ_VISIBILITY_THRESHOLD = 0.2
const MESSAGE_LIST_CONTENT_SELECTOR = "[data-message-list-content]"
function readPresentationReadable(scrollRootEl: HTMLElement) {
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 4954a3548..004167646 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
@@ -90,7 +90,7 @@ describe("qualified positioning lifecycle", () => {
const native = scrollFixture.latest.virtualizer
const end = vi.spyOn(native, "scrollToEnd")
const index = vi.spyOn(native, "scrollToIndex")
- if (target === "end") expect(native.isAtEnd(1)).toBe(true)
+ if (target === "end" || target === "unread") expect(native.isAtEnd(1)).toBe(true)
else {
expect(bodyTop(h.root, "m5")).toBeGreaterThan(0)
expect(bodyTop(h.root, "m5")).toBeLessThan(h.root.clientHeight)
@@ -112,7 +112,7 @@ describe("qualified positioning lifecycle", () => {
})
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 consumes late NEW at most once", (target, strict, width) => {
+ [320, 1280].map(width => [target, strict, width] as const))))("finishes cached %s positioning with StrictMode=%s at %spx while reads remain pending without late NEW taking ownership", (target, strict, width) => {
scrollFixture.width = width
const settled = vi.fn()
const items = Array.from({ length: 14 }, (_, i) => ({ ...message(`m${i}`), newDivider: i === 5 }))
@@ -123,7 +123,7 @@ describe("qualified positioning lifecycle", () => {
expect(settled).toHaveBeenCalledOnce()
expect(scrollFixture.latest.readPositionReady).toBe(false)
expect(scrollFixture.latest.paginationEnabled).toBe(false)
- const targetId = target === "local" ? "m4" : target === "unread" ? "m5" : "m13"
+ const targetId = target === "local" ? "m4" : "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]")]
@@ -134,14 +134,8 @@ describe("qualified positioning lifecycle", () => {
act(() => vi.advanceTimersByTime(6500))
h.update({ items: [...items.map(item => ({ ...item, newDivider: false })),
{ ...message("m14"), newDivider: true }, message("m15")], newDividerBefore: "m14" })
- if (target === "unread") {
- expect(bodyTop(h.root, anchor)).toBeCloseTo(before, 0)
- expect(index).not.toHaveBeenCalled()
- } else {
- const targetIndex = native.getVirtualItems().find(row => row.key === "divider:msg:m14")!.index
- expect(h.root.scrollTop).toBeCloseTo(native.getOffsetForIndex(targetIndex, "center")![0], 0)
- expect(index).toHaveBeenCalledOnce()
- }
+ expect(bodyTop(h.root, anchor)).toBeCloseTo(before, 0)
+ expect(index).not.toHaveBeenCalled()
expect(scrollFixture.latest.readPositionReady).toBe(false)
const landed = h.root.scrollTop
const commands = index.mock.calls.length
@@ -154,20 +148,20 @@ describe("qualified positioning lifecycle", () => {
expect(settled).toHaveBeenCalledOnce()
})
- it("withdraws reading during a data wait and admits its first late NEW without repeating initial reveal", () => {
+ it("withdraws reading during a data wait and preserves the reader when late NEW arrives", () => {
const settled = vi.fn()
const h = mount({ initialPositionMessageId: "m5", onInitialPositionSettled: settled })
const native = scrollFixture.latest.virtualizer
const index = vi.spyOn(native, "scrollToIndex")
+ const before = h.root.scrollTop
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" })
- const targetIndex = native.getVirtualItems().find(row => row.key === "msg:m10")!.index
- expect(h.root.scrollTop).toBeCloseTo(native.getOffsetForIndex(targetIndex, "center")![0], 0)
+ expect(h.root.scrollTop).toBe(before)
expect(scrollFixture.latest.readPositionReady).toBe(true)
- expect(index).toHaveBeenCalledOnce()
+ expect(index).not.toHaveBeenCalled()
expect(settled).toHaveBeenCalledOnce()
})
@@ -280,8 +274,8 @@ describe("qualified positioning lifecycle", () => {
...(target === "local" ? { initialPositionMessageId: "m5" } : target === "unread" ? { newDividerBefore: "m5" } : {}),
})
expect(scrollFixture.latest.readPositionReady).toBe(true)
- expect(end).toHaveBeenCalledTimes(target === "end" ? 1 : 0)
- if (target !== "end") expect(bodyTop(h.root, "m5")).toBeGreaterThan(0)
+ expect(end).toHaveBeenCalledTimes(target === "local" ? 0 : 1)
+ if (target === "local") expect(bodyTop(h.root, "m5")).toBeGreaterThan(0)
})
it("does not revive initial positioning when data resolves after user takeover", () => {
@@ -477,6 +471,26 @@ describe("qualified positioning lifecycle", () => {
expect(scrollFixture.latest.readPositionReady).toBe(status === "success")
})
+ it.each(["source", "target"] as const)("keeps Present ownership through a same-query %s data update", async changed => {
+ const previous = {}, expected = {}, updated = {}
+ const h = mount({ messageWindow: previous, hasMoreNewer: true, presentRequest: null })
+ try {
+ h.move(300)
+ const pending = request()
+ h.update({ localSubmitVersion: 1, presentRequest: pending.value })
+ if (changed === "source") h.update({ messageWindow: updated })
+ const result = { status: "success" as const, window: expected,
+ windowState: (window: object | undefined): "pending" | "ready" | "retired" => window === previous ? "pending"
+ : window === updated ? changed === "source" ? "pending" : "ready" : window === expected ? "ready" : "retired" }
+ await act(async () => pending.finish(result))
+ expect(scrollFixture.latest.paginationEnabled).toBe(false)
+ h.update({ messageWindow: changed === "source" ? expected : updated, hasMoreNewer: false })
+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ expect(scrollFixture.latest.paginationEnabled).toBe(true)
+ } finally { h.view.unmount() }
+ })
+
it("finishes a Present request that commits an authorized empty window without scrolling", async () => {
const previous = {}, next = {}
const h = mount({ messageWindow: previous, hasMoreNewer: true })
diff --git a/src/web/src/hooks/community/use-scroll-anchor.new-lookback.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.new-lookback.dom.test.ts
new file mode 100644
index 000000000..02ebf8cf9
--- /dev/null
+++ b/src/web/src/hooks/community/use-scroll-anchor.new-lookback.dom.test.ts
@@ -0,0 +1,170 @@
+import { afterEach, beforeEach, expect, it, vi } from "vitest"
+import { act } from "@/test/react-dom-harness"
+import { installMessageScrollFixture, restoreMessageScrollFixture, message, mount, resize, scrollFixture } from "@/test/message-scroll-fixture"
+import type { MessageRequest, MessageRequestResult, NewPositionRequest, NewPositionResult } from "@/lib/community/message-position"
+import { CONVERSATION_READ_TIMEOUT_MS } from "@/lib/community/conversation-read"
+
+beforeEach(installMessageScrollFixture)
+afterEach(restoreMessageScrollFixture)
+
+function start(id: string, load?: () => MessageRequest) {
+ let request!: NewPositionRequest
+ act(() => { request = scrollFixture.latest.requestNewPosition(id, load) })
+ if (!request.accepted) throw new Error("New positioning was not accepted")
+ return request
+}
+const items = () => Array.from({ length: 50 }, (_, index) => ({ ...message(`m${index}`), newDivider: index === 5 }))
+
+it("enters at the real bottom and keeps late New metadata from taking scroll ownership", () => {
+ const h = mount({ items: items(), newDividerBefore: "m5" })
+ try {
+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)
+ expect(scrollFixture.latest.newDividerVisibility).toBe("offscreen")
+ h.update({ newDividerBefore: undefined })
+ h.update({ newDividerBefore: "m5" })
+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ } finally { h.view.unmount() }
+})
+
+it.each([5, 49])("finishes only with actual New divider-start geometry, target index=%s", async target => {
+ const id = `m${target}`
+ const rows = items().map((item, index) => ({ ...item, newDivider: index === target }))
+ const h = mount({ items: rows, newDividerBefore: id })
+ try {
+ h.move(100)
+ let outcome: NewPositionResult | undefined
+ const request = start(id)
+ void request.completed.then(result => { outcome = result })
+ resize()
+ await act(async () => {})
+ expect(outcome).toBe("success")
+ const divider = h.root.querySelector<HTMLElement>(`[data-message-divider-for="${id}"] [data-new-divider]`)!
+ expect(Math.abs(divider.getBoundingClientRect().top - h.root.getBoundingClientRect().top)).toBeLessThanOrEqual(1)
+ expect(scrollFixture.latest.newDividerVisibility).toBe("visible")
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ expect(scrollFixture.latest.followingTail).toBe(false)
+ h.update({ items: [...rows, message("arrived-after-New")] })
+ expect(Math.abs(divider.getBoundingClientRect().top - h.root.getBoundingClientRect().top)).toBeLessThanOrEqual(1)
+ expect(scrollFixture.latest.followingTail).toBe(false)
+ } finally { h.view.unmount() }
+})
+
+it("waits for the exact main window and committed target rows after accepting a load", async () => {
+ const h = mount({ items: Array.from({ length: 50 }, (_, index) => message(`tail${index}`)), newDividerBefore: "m5" })
+ let complete!: (result: MessageRequestResult) => void
+ const loaded = new Promise<MessageRequestResult>(resolve => { complete = resolve })
+ try {
+ let outcome: NewPositionResult | undefined
+ const request = start("m5", () => ({ accepted: true, completed: loaded }))
+ void request.completed.then(result => { outcome = result })
+ resize()
+ expect(outcome).toBeUndefined()
+ const window = {}
+ await act(async () => { complete({ status: "success", window }) })
+ resize()
+ expect(outcome).toBeUndefined()
+ h.update({ items: items(), messageWindow: window })
+ await act(async () => {})
+ expect(outcome).toBe("success")
+ const divider = h.root.querySelector<HTMLElement>('[data-message-divider-for="m5"] [data-new-divider]')!
+ expect(Math.abs(divider.getBoundingClientRect().top - h.root.getBoundingClientRect().top)).toBeLessThanOrEqual(1)
+ } finally { h.view.unmount() }
+})
+
+it("cancels the data selection and ignores late completion after the user takes over", async () => {
+ const h = mount({ items: Array.from({ length: 50 }, (_, index) => message(`tail${index}`)), newDividerBefore: "m5" })
+ let complete!: (result: MessageRequestResult) => void
+ const loaded = new Promise<MessageRequestResult>(resolve => { complete = resolve }), cancel = vi.fn()
+ try {
+ const request = start("m5", () => ({ accepted: true, completed: loaded, cancel }))
+ h.move(h.root.scrollTop - 80)
+ expect(await request.completed).toBe("cancelled")
+ expect(cancel).toHaveBeenCalledOnce()
+ const reader = h.root.scrollTop
+ await act(async () => { complete({ status: "success", window: {} }) })
+ resize()
+ expect(h.root.scrollTop).toBe(reader)
+ } finally { h.view.unmount() }
+})
+
+it("keeps data and layout failures retryable instead of consuming an issued scroll", async () => {
+ const h = mount({ items: items(), newDividerBefore: "m5" })
+ try {
+ const failed = start("m5", () => ({ accepted: true, completed: Promise.resolve({ status: "error" }) }))
+ await act(async () => {})
+ expect(await failed.completed).toBe("error")
+ resize()
+ scrollFixture.height = 0
+ h.update({})
+ const unpositioned = start("m5")
+ resize()
+ await act(async () => { await vi.advanceTimersByTimeAsync(CONVERSATION_READ_TIMEOUT_MS) })
+ expect(await unpositioned.completed).toBe("error")
+ scrollFixture.height = 500
+ resize()
+ let outcome: NewPositionResult | undefined
+ const retry = start("m5")
+ void retry.completed.then(result => { outcome = result })
+ resize()
+ await act(async () => {})
+ expect(outcome).toBe("success")
+ } finally { h.view.unmount() }
+})
+
+it("keeps short-suffix New reading at its viewport origin through viewport size changes", async () => {
+ const rows = items().map((item, index) => ({ ...item, newDivider: index === 49 }))
+ const h = mount({ items: rows, newDividerBefore: "m49" })
+ try {
+ const request = start("m49")
+ resize()
+ await act(async () => {})
+ expect(await request.completed).toBe("success")
+ for (const height of [680, 320, 500]) {
+ scrollFixture.height = height
+ resize()
+ const divider = h.root.querySelector<HTMLElement>('[data-message-divider-for="m49"] [data-new-divider]')!
+ expect(Math.abs(divider.getBoundingClientRect().top - h.root.getBoundingClientRect().top)).toBeLessThanOrEqual(1)
+ expect(scrollFixture.latest.followingTail).toBe(false)
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ }
+ } finally { h.view.unmount() }
+})
+
+it("restores an owned New suffix reserve after append exhausts it and the viewport grows", async () => {
+ const rows = items().map((item, index) => ({ ...item, newDivider: index === 49 }))
+ const h = mount({ items: rows, newDividerBefore: "m49" })
+ try {
+ const naturalHeight = h.root.scrollHeight
+ const request = start("m49")
+ resize()
+ await act(async () => {})
+ expect(await request.completed).toBe("success")
+ h.update({ items: [...rows, ...Array.from({ length: 4 }, (_, index) => message(`later${index}`))] })
+ expect(h.root.scrollHeight).toBe(naturalHeight + 400)
+ scrollFixture.height = 680
+ resize()
+ const divider = h.root.querySelector<HTMLElement>('[data-message-divider-for="m49"] [data-new-divider]')!
+ expect(Math.abs(divider.getBoundingClientRect().top - h.root.getBoundingClientRect().top)).toBeLessThanOrEqual(1)
+ expect(scrollFixture.latest.followingTail).toBe(false)
+ expect(scrollFixture.latest.readPositionReady).toBe(true)
+ } finally { h.view.unmount() }
+})
+
+it.each(["explicit", "present"] as const)("releases measured lookback end space when %s takes position ownership", async action => {
+ const rows = items().map((item, index) => ({ ...item, newDivider: index === 49 }))
+ const h = mount({ items: rows, newDividerBefore: "m49" })
+ try {
+ const naturalHeight = h.root.scrollHeight
+ const request = start("m49")
+ resize()
+ await act(async () => {})
+ expect(await request.completed).toBe("success")
+ expect(h.root.scrollHeight).toBeGreaterThan(naturalHeight)
+ if (action === "explicit") h.update({ scrollToMessageId: "m49" })
+ else act(() => scrollFixture.latest.scrollToBottom())
+ resize()
+ expect(h.root.scrollHeight).toBe(naturalHeight)
+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)
+ } finally { h.view.unmount() }
+})
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 5723145be..75c50b59e 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
@@ -115,12 +115,14 @@ describe("native pagination and original semantic epoch", () => {
runFrames()
expect(h.root.scrollTop).toBe(settled)
})
- it("restores initial New intent and bounded settling after StrictMode effect replay", () => {
+ it("positions manual New and settles once after StrictMode effect replay", () => {
const shown = vi.fn()
const items = Array.from({ length: 14 }, (_, i) => ({ ...message(`m${i}`), newDivider: i === 4 }))
const h = mount({ items, newDividerBefore: "m4", onInitialPositionSettled: shown }, true)
+ act(() => scrollFixture.latest.requestNewPosition("m4"))
+ resize()
const marker = h.root.querySelector('[data-new-divider]')!.getBoundingClientRect()
- expect((marker.top + marker.bottom) / 2).toBeCloseTo(scrollFixture.height / 2, 0)
+ expect(marker.top).toBeCloseTo(0, 0)
expect(scrollFixture.latest.readPositionReady).toBe(true)
expect(shown).toHaveBeenCalledOnce()
})
@@ -176,14 +178,15 @@ describe("native pagination and original semantic epoch", () => {
expect(h.root.querySelector('[data-msg-id="m5"]')).toBeNull()
expect(end).not.toHaveBeenCalled()
})
- it("keeps the original initial New intent while an older page moves its numeric index", () => {
+ it("keeps a requested New intent while an older page moves its numeric index", () => {
const items = Array.from({ length: 14 }, (_, i) => ({ ...message(`m${i}`), newDivider: i === 4 }))
const h = mount({ items, newDividerBefore: "m4", initialScrollReady: false, hasMoreNewer: true })
+ act(() => scrollFixture.latest.requestNewPosition("m4"))
act(() => scrollFixture.latest.captureOlderPageAnchor())
h.update({ isFetchingOlder: true })
h.update({ items: [message("older"), ...h.input.items], isFetchingOlder: false, initialScrollReady: true })
const marker = h.root.querySelector('[data-new-divider]')!.getBoundingClientRect()
- expect((marker.top + marker.bottom) / 2).toBeCloseTo(scrollFixture.height / 2, 0)
+ expect(marker.top).toBeCloseTo(0, 0)
expect(scrollFixture.latest.readPositionReady).toBe(true)
})
it("retires the old native index once on replacement and rejects its canceled frame", () => {
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 de8858bd4..fec21d982 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
@@ -629,19 +629,20 @@ describe("locked native adapter and existing message scroll owner", () => {
onScrollTargetPositioned: positioned,
})
h.stage(intent === "target" ? { scrollToMessageId: "m0" } : { initialScrollReady: true })
- runFrames(2)
+ if (intent === "unread") act(() => scrollFixture.latest.requestNewPosition("m0"))
+ resize()
expect(scrollFixture.latest.readPositionReady).toBe(true)
if (intent === "target") expect(positioned).toHaveBeenCalledWith("m0")
- expect(h.root.scrollTop).toBe(0)
+ expect(h.root.scrollTop).toBe(intent === "unread" ? scrollFixture.firstPrefix : 0)
scrollFixture.width = 639
resize(0)
- expect(h.root.scrollTop).toBe(0)
+ expect(h.root.scrollTop).toBe(intent === "unread" ? scrollFixture.firstPrefix : 0)
scrollFixture.width = 265
scrollFixture.height = 727
scrollFixture.bodyHeights.set("m2", 900)
resize()
expect(h.root.scrollHeight).toBeGreaterThan(h.root.clientHeight)
- expect(h.root.scrollTop).toBe(0)
+ expect(h.root.scrollTop).toBe(intent === "unread" ? scrollFixture.firstPrefix : 0)
expect(bodyTop(h.root, "m0")).toBeGreaterThanOrEqual(0)
expect(bodyTop(h.root, "m0")).toBeLessThan(h.root.clientHeight)
})
@@ -654,23 +655,27 @@ describe("locked native adapter and existing message scroll owner", () => {
h.update({ tailPaddingEnd: 40 })
expect(h.root.scrollHeight).toBe(scrollFixture.latest.virtualizer.getTotalSize())
})
- it("centers the independent New row beside a long message with the native index command", () => {
+ it("positions the independent New row at the top beside a long message", () => {
scrollFixture.bodyHeights.set("m4", 1800)
const items = Array.from({ length: 12 }, (_, i) => ({ ...message(`m${i}`), ...(i === 4 ? { newDivider: true } : {}) }))
const h = mount({ items, newDividerBefore: "m4", hasMoreNewer: true })
+ act(() => scrollFixture.latest.requestNewPosition("m4"))
+ resize()
const marker = h.root.querySelector('[data-new-divider]')!.getBoundingClientRect()
- expect((marker.top + marker.bottom) / 2).toBeCloseTo(scrollFixture.height / 2, 0)
+ expect(marker.top).toBeCloseTo(0, 0)
expect(bodyTop(h.root, "m4")).toBeLessThan(scrollFixture.height)
expect(scrollFixture.latest.readPositionReady).toBe(true)
})
- it("clamps a first-row merged date/New boundary to the actual content origin", () => {
+ it("positions a first-row merged date/New boundary above the long message", () => {
scrollFixture.firstPrefix = 152
scrollFixture.bodyHeights.set("first", 1800)
const item = { ...message("first"), dateLabel: "Today", newDivider: true }
const h = mount({ items: [item], hasMoreOlder: false, newDividerBefore: "first" })
+ act(() => scrollFixture.latest.requestNewPosition("first"))
+ resize()
const marker = h.root.querySelector('[data-new-divider]')!.getBoundingClientRect()
- expect(h.root.scrollTop).toBe(0)
- expect(marker.top).toBeGreaterThanOrEqual(0)
+ expect(h.root.scrollTop).toBe(scrollFixture.firstPrefix)
+ expect(marker.top).toBeCloseTo(0, 0)
expect(marker.bottom).toBeLessThan(scrollFixture.height)
expect(bodyTop(h.root, "first")).toBeLessThan(scrollFixture.height)
expect(scrollFixture.latest.readPositionReady).toBe(true)
@@ -1606,13 +1611,12 @@ describe("locked native adapter and existing message scroll owner", () => {
expect(end).toHaveBeenCalledOnce()
expect(scrollFixture.latest.virtualizer.getVirtualItems().at(-1)?.key).toBe("client:send-1")
})
- it("keeps a warm position unchanged until the original unread boundary is qualified", () => {
+ it("keeps warm entry pending and then lands at the bottom despite its unread boundary", () => {
const h = mount({ initialScrollReady: false })
expect(scrollFixture.latest.readPositionReady).toBe(false)
expect(h.root.scrollTop).toBe(0)
h.update({ initialScrollReady: true, newDividerBefore: "m4", items: h.input.items.map(item => ({ ...item, newDivider: item.m.id === "m4" })) })
- const marker = h.root.querySelector('[data-new-divider]')!.getBoundingClientRect()
- expect((marker.top + marker.bottom) / 2).toBeCloseTo(scrollFixture.height / 2, 0)
+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)
expect(scrollFixture.latest.readPositionReady).toBe(true)
})
it("combines current prefix growth with the existing footer reading-offset policy once", () => {
@@ -1645,8 +1649,7 @@ describe("current composer intent and native passive ownership", () => {
it("does not reinterpret an old composer version on a new list mount", () => {
const items = Array.from({ length: 14 }, (_, i) => ({ ...message(`m${i}`), newDivider: i === 4 }))
const h = mount({ items, newDividerBefore: "m4", localSubmitVersion: 8 })
- const marker = h.root.querySelector('[data-new-divider]')!.getBoundingClientRect()
- expect((marker.top + marker.bottom) / 2).toBeCloseTo(scrollFixture.height / 2, 0)
+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)
h.move(300)
const end = vi.spyOn(scrollFixture.latest.virtualizer, "scrollToEnd")
h.update({ items: [...h.input.items, message("remote-self", "me")] })
diff --git a/src/web/src/hooks/community/use-scroll-anchor.restoration.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.restoration.dom.test.ts
index a10c03682..41f5c96e9 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.restoration.dom.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.restoration.dom.test.ts
@@ -26,7 +26,7 @@ describe("ordinary reconstruction and one-shot late unread ownership", () => {
}, strict)
const native = scrollFixture.latest.virtualizer
expect(returned.root.scrollTop).not.toBe(offset)
- if (source === "tail") expect(returned.root.scrollHeight - returned.root.clientHeight - returned.root.scrollTop).toBeLessThanOrEqual(1)
+ if (source === "tail" || source === "new") expect(returned.root.scrollHeight - returned.root.clientHeight - returned.root.scrollTop).toBeLessThanOrEqual(1)
else {
const id = source === "read" ? "m120" : source === "new" ? "m100" : "m80"
const index = native.getVirtualItems().find(row => row.key === `msg:${id}`)!.index
@@ -96,6 +96,10 @@ describe("ordinary reconstruction and one-shot late unread ownership", () => {
...(source === "target" ? { scrollToMessageId: id } : {}),
...(source === "new" || source === "new-fallback" ? { newDividerBefore: id } : {}),
})
+ if (source === "new" || source === "new-fallback") {
+ act(() => scrollFixture.latest.requestNewPosition(id))
+ resize()
+ }
const body = h.root.querySelector<HTMLElement>(`[data-msg-id="${id}"]`)!
const rect = body.getBoundingClientRect()
expect(h.root.clientHeight).toBe(500)
@@ -108,7 +112,7 @@ describe("ordinary reconstruction and one-shot late unread ownership", () => {
else {
const key = source === "new" ? "divider:msg:m120" : `msg:${id}`
const index = native.getVirtualItems().find(item => item.key === key)!.index
- expect(h.root.scrollTop).toBeCloseTo(native.getOffsetForIndex(index, "center")![0], 0)
+ expect(h.root.scrollTop).toBeCloseTo(native.getOffsetForIndex(index, source === "new" || source === "new-fallback" ? "start" : "center")![0], 0)
}
expect(rect.top).toBeLessThan(500)
expect(rect.top + body.scrollHeight).toBeGreaterThan(0)
@@ -153,23 +157,23 @@ describe("ordinary reconstruction and one-shot late unread ownership", () => {
expect(scrollFixture.latest.readPositionReady).toBe(true)
})
- it("centers the first late NEW once while data is pending and never restarts it for later boundaries", () => {
+ it("preserves its local target when late NEW changes while data is pending", () => {
const h = mount({ initialPositionMessageId: "m4", positionDataState: "pending" })
const native = scrollFixture.latest.virtualizer
const index = vi.spyOn(native, "scrollToIndex")
h.update({ newDividerBefore: "m8" })
- expect(index).toHaveBeenCalledOnce()
+ expect(index).not.toHaveBeenCalled()
expect(scrollFixture.latest.readPositionReady).toBe(false)
const before = h.root.scrollTop
h.update({ newDividerBefore: "m10" })
- expect(index).toHaveBeenCalledOnce()
+ expect(index).not.toHaveBeenCalled()
expect(h.root.scrollTop).toBe(before)
h.update({ positionDataState: "ready" })
expect(h.root.scrollTop).toBe(before)
expect(scrollFixture.latest.readPositionReady).toBe(true)
})
- it("keeps the first late NEW eligible beyond five seconds and waits for a real viewport without polling", () => {
+ it("keeps bottom entry pending beyond five seconds despite late NEW and waits for a real viewport without polling", () => {
scrollFixture.height = 0
const shown = vi.fn()
const h = mount({ onInitialPositionSettled: shown }, false, undefined, undefined, 0)
@@ -184,9 +188,8 @@ describe("ordinary reconstruction and one-shot late unread ownership", () => {
expect(scrollFixture.latest.readPositionReady).toBe(false)
scrollFixture.height = 500
resize()
- expect(index).toHaveBeenCalledOnce()
- const marker = h.root.querySelector("[data-new-divider]")!.getBoundingClientRect()
- expect((marker.top + marker.bottom) / 2).toBeCloseTo(250, 0)
+ expect(index).not.toHaveBeenCalled()
+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)
expect(shown).toHaveBeenCalledOnce()
expect(scrollFixture.latest.readPositionReady).toBe(true)
})
@@ -216,16 +219,16 @@ describe("ordinary reconstruction and one-shot late unread ownership", () => {
expect(h.root.scrollTop).toBe(before)
})
- it("gives a late NEW priority over native append following before issuing either command", () => {
+ it("keeps normal native append following when late NEW metadata arrives", () => {
const h = mount()
const native = scrollFixture.latest.virtualizer
const end = vi.spyOn(native, "scrollToEnd"), index = vi.spyOn(native, "scrollToIndex")
h.stage({ items: [...h.input.items, { ...message("m14"), newDivider: true }, message("m15")], newDividerBefore: "m14" })
- expect(native.options.followOnAppend).toBe(false)
- expect(end).not.toHaveBeenCalled()
+ expect(native.options.followOnAppend).toBe("auto")
+ expect(end).toHaveBeenCalledOnce()
resize()
- expect(index).toHaveBeenCalledOnce()
- expect(end).not.toHaveBeenCalled()
+ expect(index).not.toHaveBeenCalled()
+ expect(h.root.scrollHeight - h.root.clientHeight - h.root.scrollTop).toBeLessThanOrEqual(1)
expect(scrollFixture.latest.readPositionReady).toBe(true)
})
})
diff --git a/src/web/src/hooks/community/use-scroll-anchor.telemetry.dom.test.ts b/src/web/src/hooks/community/use-scroll-anchor.telemetry.dom.test.ts
index abdd69e81..053ccde3c 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.telemetry.dom.test.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.telemetry.dom.test.ts
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, expect, it, vi } from "vitest"
import { act, fireEvent } from "@/test/react-dom-harness"
import { configureTelemetry, installTelemetrySink, retireTelemetry } from "@/lib/observability/telemetry"
-import { installMessageScrollFixture, restoreMessageScrollFixture, mount, message, runFrames, scrollFixture } from "@/test/message-scroll-fixture"
+import { installMessageScrollFixture, restoreMessageScrollFixture, mount, message, resize, runFrames, scrollFixture } from "@/test/message-scroll-fixture"
import { createCommunityQueryOwner } from "@/test/community-query-owner"
import { captureChannelMetadataToken } from "@/lib/community/conversation-qualification"
@@ -71,8 +71,13 @@ it.each(["manual", "hidden", "entry", "unmount"] as const)("records %s retiremen
it.each(["read_anchor", "new_divider", "tail"] as const)("records the actual %s selection instead of inferring it from initial/settled", source => {
mount({ ...(source === "read_anchor" ? { initialPositionMessageId: "m4" } : {}),
- ...(source === "new_divider" ? { newDividerBefore: "m4" } : {}) })
- expect(terminals()).toEqual([expect.objectContaining({ position_source: source, position_reason: "settled" })])
+ ...(source === "new_divider" ? { newDividerBefore: "m4", items: Array.from({ length: 14 }, (_, i) => ({ ...message(`m${i}`), newDivider: i === 4 })) } : {}) })
+ if (source === "new_divider") {
+ act(() => scrollFixture.latest.requestNewPosition("m4"))
+ resize()
+ }
+ expect(terminals().at(-1)).toEqual(expect.objectContaining({ position_source: source, position_reason: "settled" }))
+ expect(terminals()).toHaveLength(source === "new_divider" ? 2 : 1)
})
it("attributes a reconstructed list to its normal entry rule without physical snapshot fields", async () => {
diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.ts
index 2119e2b76..d567e159f 100644
--- a/src/web/src/hooks/community/use-scroll-anchor.ts
+++ b/src/web/src/hooks/community/use-scroll-anchor.ts
@@ -5,8 +5,9 @@ import { defaultRangeExtractor, elementScroll, measureElement, useVirtualizer, t
import { COMMUNITY_VIRTUALIZER_REACT_OPTIONS, type VirtualRowsLayoutSnapshot } from "./virtualizer-react-options"
import { estimateRowHeight, computeBelowCount, type FlatItem } from "@/lib/community/message-list-items"
import { MESSAGE_RAIL_TAIL_PADDING_END_PX } from "@/lib/community/conversation-layout"
-import type { MessagePositionState, MessageRequest, MessageRequestResult } from "@/lib/community/message-position"
+import type { MessagePositionState, MessageRequest, MessageRequestResult, NewPositionRequest, NewPositionResult } from "@/lib/community/message-position"
import type { ConversationListScope } from "@/lib/community/conversation-qualification"
+import { withConversationReadDeadline } from "@/lib/community/conversation-read"
export const MESSAGE_LIST_DISPLAY_END_THRESHOLD_PX = 100
const VIEWPORT_RESIZE_TAIL_DISTANCE_PX = 100
@@ -135,7 +136,7 @@ export function useScrollAnchor({
onInitialPositionSettled?: (outcome: PositionOutcome) => void
onUserTakeover?: () => void
}) {
- type Kind = "initial" | "late-new" | "target" | "present" | "idle"
+ type Kind = "initial" | "target" | "present" | "idle"
type Intent = {
epoch: number
type: "unread" | "target" | "end"
@@ -162,6 +163,10 @@ export function useScrollAnchor({
pinEligible: boolean
isScrolling: boolean
}
+ type NewOperation = {
+ epoch: number; id: string; priorTarget: string | null; loaded: boolean; window?: object
+ cancel?: () => void; restoreFollow?: () => void; finish: (result: NewPositionResult) => void
+ }
const scrollRef = useRef<HTMLDivElement>(null)
const positionScopeRef = useRef(positionScope)
const virtualizerRef = useRef<ReactVirtualizer<HTMLDivElement, Element> | null>(null)
@@ -174,6 +179,18 @@ export function useScrollAnchor({
const targetDataState = targetPositionDataState ?? dataState
const contextRef = useRef({ dataState, targetDataState, initialScrollReady, messageWindow, isFetchingOlder, isFetchingNewer, visible, newDividerBefore })
const [requestRevision, setRequestRevision] = useState(0)
+ const [newEndSpace, setNewEndSpace] = useState(0)
+ const newEndAnchorRef = useRef<{ id: string; inset: number } | null>(null)
+ const [newDividerVisibility, setNewDividerVisibility] = useState<"visible" | "offscreen" | "pending">("pending")
+ const dividerVisibilityRef = useRef(newDividerVisibility)
+ const newOperationRef = useRef<NewOperation | null>(null)
+ const finishNewOperation = useCallback((result: NewPositionResult) => {
+ const operation = newOperationRef.current
+ if (!operation) return
+ newOperationRef.current = null
+ if (result !== "success") { operation.cancel?.(); operation.restoreFollow?.() }
+ operation.finish(result)
+ }, [])
const [committedEntry, setCommittedEntry] = useState(positionEntry)
const entryChanged = committedEntry !== positionEntry
const positionKind = useCreateAtom<Kind>("initial")
@@ -199,8 +216,6 @@ export function useScrollAnchor({
const measurementAnchorRef = useRef<{ key: string; epoch: number } | null>(null)
const entryResolvedRef = useRef(false)
const initialRetiredRef = useRef(false)
- const lateNewRef = useRef({ allowed: true, consumed: false })
- const localTargetRef = useRef<string | null>(null)
const initialSettleFrameRef = useRef<number | null>(null)
const semanticIntentRef = useRef<Intent | null>(null)
const committedRowsRef = useRef<{
@@ -302,7 +317,8 @@ export function useScrollAnchor({
observation?.finish(reason, observation.decision)
}, [])
const claimPosition = useCallback((kind: Kind, preservePage = false) => {
- if (kind === "target" || kind === "present") lateNewRef.current.allowed = false
+ finishNewOperation("cancelled")
+ if (kind !== "idle") { newEndAnchorRef.current = null; setNewEndSpace(0) }
const owner = positionOwnerRef.current
virtualizerRef.current?.cancelScroll()
clearMeasurementAnchor()
@@ -323,13 +339,14 @@ export function useScrollAnchor({
presentIntentRef.current = null
setReadPositionReady(false)
return owner.epoch
- }, [beginPosition, cancelFrame, clearMeasurementAnchor, finishPosition, holdNativeOrigin, observePageBody, setOwnerKind, setPaginationDirection, setReadPositionReady])
+ }, [beginPosition, cancelFrame, clearMeasurementAnchor, finishNewOperation, finishPosition, holdNativeOrigin, observePageBody, setOwnerKind, setPaginationDirection, setReadPositionReady])
const retireInitialPosition = useCallback(() => {
initialRetiredRef.current = true
entryResolvedRef.current = true
}, [])
const releasePosition = useCallback((userHandover = false, outcome: PositionOutcome = userHandover ? "user-cancelled" : "cancelled", reason: PositionReason = userHandover ? "manual_takeover" : outcome === "empty" ? "empty" : outcome === "error" ? "data_error" : "cancelled") => {
- lateNewRef.current.allowed = false
+ if (newOperationRef.current) userInputRef.current.handover = true
+ finishNewOperation(outcome === "error" ? "error" : "cancelled")
const cancelledTarget = (positionKind.get() === "target" || userHandover) && positionedTargetRef.current !== targetIntentRef.current
? targetIntentRef.current : null
const wasReadable = positionKind.get() === "idle" && readReady.get()
@@ -359,7 +376,7 @@ export function useScrollAnchor({
}
settlePresentation(outcome)
scheduleGeometryRef.current()
- }, [claimPosition, finishPosition, positionKind, readReady, retireInitialPosition, setReadPositionReady, settlePresentation])
+ }, [claimPosition, finishNewOperation, finishPosition, positionKind, readReady, retireInitialPosition, setReadPositionReady, settlePresentation])
const readPageMessageGeometry = useCallback((key: string): { viewportOffset: number; bodyInset: number } | null => {
const root = scrollRef.current
const native = virtualizerRef.current
@@ -417,8 +434,7 @@ export function useScrollAnchor({
if (offset !== null) Object.assign(anchor, offset)
}, [observePageBody, positionKind, readFirstPageAnchor, readPageMessageGeometry])
const awaitingTarget = !!scrollToMessageId && positionedTargetRef.current !== scrollToMessageId
- const pendingLateNew = visible && initialScrollReady && !!newDividerBefore && entryResolvedRef.current
- && lateNewRef.current.allowed && !lateNewRef.current.consumed && (ownerKind === "idle" || ownerKind === "initial")
+
const getItemKey = useCallback((index: number) => items[index].key, [items])
const estimateSize = useCallback((index: number) => estimateRowHeight(items[index], !!hasMoreOlder), [items, hasMoreOlder])
const scrollToFn = useCallback<ReactVirtualizer<HTMLDivElement, Element>["options"]["scrollToFn"]>((offset, options, native) => {
@@ -461,16 +477,16 @@ export function useScrollAnchor({
return index < 0 || indexes.includes(index) ? indexes : [...indexes, index].sort((a, b) => a - b)
},
scrollPaddingStart: scrollPaddingStartRef.current,
- anchorTo: !entryChanged && ownerKind === "idle" && !awaitingTarget && !pendingLocalSubmit && !pendingLateNew
+ anchorTo: !entryChanged && ownerKind === "idle" && !awaitingTarget && !pendingLocalSubmit
&& (paginationDirection !== null || (readPositionReady && (nativeOriginKey === null || nativeOriginKey !== items[0]?.key))) ? "end" : "start",
followOnAppend: visible && !entryChanged && ownerKind === "idle" && readPositionReady && dataState === "ready" && !awaitingTarget
- && !pendingLocalSubmit && !pendingLateNew && !followSuspended && !hasMoreNewer
+ && !pendingLocalSubmit && !followSuspended && !hasMoreNewer
&& !isFetchingOlder && !isFetchingNewer && paginationDirection === null
&& (nativeOriginKey === null || nativeOriginKey !== items[0]?.key) ? "auto" : false,
scrollEndThreshold: followSuspended ? -1 : 1,
scrollMargin: 0,
paddingStart: shortGap,
- paddingEnd: tailPaddingEnd,
+ paddingEnd: tailPaddingEnd + newEndSpace,
overscan: 8,
onChange: () => { refreshPendingPageAnchor(); reconcileViewportRef.current(); scheduleGeometryRef.current() },
})
@@ -541,6 +557,27 @@ export function useScrollAnchor({
&& row.end === current.end && row.lane === current.lane
})
}, [])
+ const updateNewDividerVisibility = useCallback(() => {
+ const root = scrollRef.current
+ const id = contextRef.current.newDividerBefore
+ let next: typeof newDividerVisibility = "pending"
+ if (root && id && contextRef.current.visible && contextRef.current.dataState !== "pending"
+ && contextRef.current.dataState !== "error" && hasCommittedRows()) {
+ const index = findMountScrollTargetIndex(currentItemsRef.current, id)
+ const divider = Array.from(root.querySelectorAll<HTMLElement>("[data-message-divider-for]"))
+ .find(element => element.dataset.messageDividerFor === id)?.querySelector<HTMLElement>("[data-new-divider]")
+ if (divider) {
+ const rect = divider.getBoundingClientRect(), viewport = root.getBoundingClientRect()
+ if (rect.height > 0 && rect.width > 0 && viewport.height > 0 && viewport.width > 0) next = rect.bottom > viewport.top && rect.top < viewport.bottom
+ && rect.right > viewport.left && rect.left < viewport.right ? "visible" : "offscreen"
+ } else if (index === null || !virtualizerRef.current?.getVirtualItems().some(item => item.index === index)) next = "offscreen"
+ }
+ if (dividerVisibilityRef.current !== next) {
+ dividerVisibilityRef.current = next
+ setNewDividerVisibility(next)
+ }
+ }, [hasCommittedRows])
+ useLayoutEffect(updateNewDividerVisibility)
const scheduleInitialPositionSettled = useCallback(() => {
if (initialSettleFrameRef.current !== null) return
const epoch = positionOwnerRef.current.epoch
@@ -563,7 +600,8 @@ export function useScrollAnchor({
if (intent.type !== "end" && (positionKind.get() === "target" ? contextRef.current.targetDataState : contextRef.current.dataState) === "ready") releasePosition(false, "cancelled", "target_missing")
return
}
- if ((positionKind.get() === "initial" || positionKind.get() === "late-new") && !contextRef.current.initialScrollReady) return
+ if (!hasCommittedRows()) return
+ if ((positionKind.get() === "initial") && !contextRef.current.initialScrollReady) return
if (!intent.issued) {
if (intent.origin && (intent.origin.root !== root || Math.abs(root.scrollTop - intent.origin.offset) > 1)) {
releasePosition(true, "user-cancelled", "origin_changed")
@@ -573,7 +611,7 @@ export function useScrollAnchor({
if (intent.type === "end") native.scrollToEnd({ behavior: intent.behavior })
else {
intent.index = index
- native.scrollToIndex(index, { align: "center", behavior: intent.behavior })
+ native.scrollToIndex(index, { align: intent.type === "unread" ? "start" : "center", behavior: intent.behavior })
}
intent.issued = true
intent.origin = null
@@ -594,7 +632,7 @@ export function useScrollAnchor({
} else if (intent.id) {
if (index !== intent.index) {
intent.index = index
- native.scrollToIndex(index, { align: "center", behavior: intent.behavior })
+ native.scrollToIndex(index, { align: intent.type === "unread" ? "start" : "center", behavior: intent.behavior })
}
const row = Array.from(root.querySelectorAll<HTMLElement>("[data-msg-id]"))
.find((element) => element.dataset.msgId === intent.id)
@@ -606,14 +644,26 @@ export function useScrollAnchor({
const rect = boundary === row ? body : boundary?.getBoundingClientRect()
const wrapper = row?.closest("[data-index]")?.getBoundingClientRect()
if (rect && body && wrapper && wrapper.height > 0 && rect.height > 0 && body.height > 0) {
- const targetOffset = native.getOffsetForIndex(index, "center")?.[0]
+ let targetOffset = native.getOffsetForIndex(index, intent.type === "unread" ? "start" : "center")?.[0]
+ if (intent.type === "unread") {
+ const boundaryWrapper = boundary?.closest("[data-index]")?.getBoundingClientRect()
+ const needed = Math.max(0, root.scrollTop + rect.top - viewport.top + root.clientHeight - root.scrollHeight)
+ if (needed > 1 && boundaryWrapper) {
+ newEndAnchorRef.current = { id: intent.id, inset: rect.top - boundaryWrapper.top }
+ setNewEndSpace(value => value + needed)
+ return
+ }
+ if (targetOffset !== undefined && boundaryWrapper) targetOffset = Math.min(Math.max(0, root.scrollHeight - root.clientHeight), targetOffset + rect.top - boundaryWrapper.top)
+ if (targetOffset !== undefined && Math.abs(root.scrollTop - targetOffset) > 1) native.scrollToOffset(targetOffset, { behavior: intent.behavior })
+ }
landed = targetOffset !== undefined && Math.abs(root.scrollTop - targetOffset) <= 1
+ && (intent.type !== "unread" || Math.abs(rect.top - viewport.top) <= 1)
&& rect.bottom > viewport.top + 1 && rect.top < viewport.bottom - 1
&& body.bottom > viewport.top + 1 && body.top < viewport.bottom - 1
}
}
if (landed) {
- const initial = positionKind.get() === "initial" || positionKind.get() === "late-new"
+ const initial = positionKind.get() === "initial"
if (initial && contextRef.current.dataState === "pending") setFollowSuspended(true)
const geometry = readGeometry()
if (!geometry) return
@@ -631,19 +681,21 @@ export function useScrollAnchor({
positionedTargetRef.current = intent.id
onTargetPositionedRef.current?.(intent.id)
}
+ if (intent.type === "unread" && newOperationRef.current?.id === intent.id) finishNewOperation("success")
scheduleGeometryRef.current()
return
}
}
initialSettleFrameRef.current = window.requestAnimationFrame(settle)
- }, [finishPosition, hasCommittedRows, holdNativeOrigin, positionKind, readGeometry, releasePosition, retireInitialPosition, setFollowSuspended, setOwnerKind, setReadPositionReady, settlePresentation])
+ }, [finishNewOperation, finishPosition, hasCommittedRows, 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
observePageBody()
+ updateNewDividerVisibility()
if (layout && positionOwnerRef.current.active && semanticIntentRef.current) scheduleInitialPositionSettled()
if (layout && paginationRef.current) scheduleGeometryRef.current()
- }, [items, observePageBody, positionEntry, scheduleInitialPositionSettled, virtualizer])
+ }, [items, observePageBody, positionEntry, scheduleInitialPositionSettled, updateNewDividerVisibility, virtualizer])
const startIntent = useCallback((type: Intent["type"], id: string | null, behavior: ScrollBehavior = "auto", notifyTarget = false, loadedTailPresent = false) => {
const owner = positionOwnerRef.current
@@ -658,7 +710,7 @@ export function useScrollAnchor({
: findMessageIndex(currentItemsRef.current, id) : null
semanticIntentRef.current = {
epoch: owner.epoch, type, id, index, behavior, notifyTarget, loadedTailPresent,
- awaitingData: positionKind.get() === "initial" || positionKind.get() === "late-new" ? !contextRef.current.initialScrollReady : (positionKind.get() === "target" ? contextRef.current.targetDataState : contextRef.current.dataState) === "pending",
+ awaitingData: positionKind.get() === "initial" ? !contextRef.current.initialScrollReady : (positionKind.get() === "target" ? contextRef.current.targetDataState : contextRef.current.dataState) === "pending",
viewport: { width: scrollRef.current?.clientWidth ?? 0, height: scrollRef.current?.clientHeight ?? 0 },
issued: false,
origin: positionKind.get() === "initial" ? { root: scrollRef.current, offset: scrollRef.current?.scrollTop ?? 0 } : null,
@@ -684,6 +736,7 @@ export function useScrollAnchor({
}
if (acceptedGeometryRef.current) acceptedGeometryRef.current.epoch = owner.epoch
return () => {
+ finishNewOperation("retired")
finishPosition("retired")
owner.active = false
owner.epoch += 1
@@ -695,7 +748,7 @@ export function useScrollAnchor({
if (geometryFrameRef.current !== null) window.cancelAnimationFrame(geometryFrameRef.current)
geometryFrameRef.current = null
}
- }, [beginPosition, cancelFrame, clearMeasurementAnchor, finishPosition, observePageBody, positionKind, scheduleInitialPositionSettled, startIntent])
+ }, [beginPosition, cancelFrame, clearMeasurementAnchor, finishNewOperation, finishPosition, observePageBody, positionKind, scheduleInitialPositionSettled, startIntent])
useLayoutEffect(() => {
const update = () => setDocumentVisible(document.visibilityState !== "hidden")
@@ -706,7 +759,6 @@ export function useScrollAnchor({
useLayoutEffect(() => {
if (!visible) {
- if (entryActivationRef.current.seen) lateNewRef.current.allowed = false
setResumeValidated(false)
if (entryActivationRef.current.seen && positionKind.get() !== "idle") releasePosition(false, "cancelled", "hidden")
positionOwnerRef.current.active = false
@@ -734,8 +786,8 @@ export function useScrollAnchor({
entryResolvedRef.current = preserve
initialRetiredRef.current = preserve
if (!preserve) setPositionOutcome("pending")
- lateNewRef.current = { allowed: true, consumed: false }
- localTargetRef.current = null
+ setNewEndSpace(0)
+ newEndAnchorRef.current = null
targetIntentRef.current = null
positionedTargetRef.current = null
consumedPresentVersionRef.current = presentVersion ?? 0
@@ -746,6 +798,7 @@ export function useScrollAnchor({
useLayoutEffect(() => {
const target = scrollToMessageId ?? null
+ if (newOperationRef.current && newOperationRef.current.priorTarget === target) return
if (!visible && target) return
const changed = targetIntentRef.current !== target
if (!changed && (!target || positionedTargetRef.current === target || positionKind.get() === "target")) return
@@ -755,7 +808,6 @@ export function useScrollAnchor({
positionedTargetRef.current = null
return
}
- lateNewRef.current.allowed = false
if (changed) positionedTargetRef.current = null
if (targetDataState === "pending") {
if (changed && (entryResolvedRef.current || positionKind.get() !== "initial" || semanticIntentRef.current)) {
@@ -777,7 +829,7 @@ export function useScrollAnchor({
useLayoutEffect(() => {
const intent = semanticIntentRef.current
- if (visible && intent?.awaitingData && (positionKind.get() === "initial" || positionKind.get() === "late-new" ? initialScrollReady : (positionKind.get() === "target" ? targetDataState : dataState) === "ready")) {
+ if (visible && intent?.awaitingData && (positionKind.get() === "initial" ? initialScrollReady : (positionKind.get() === "target" ? targetDataState : dataState) === "ready")) {
startIntent(intent.type, intent.id, intent.behavior, intent.notifyTarget, intent.loadedTailPresent)
}
}, [dataState, targetDataState, initialScrollReady, positionKind, startIntent, visible])
@@ -785,7 +837,7 @@ export function useScrollAnchor({
useLayoutEffect(() => {
if (!visible || targetDataState !== "ready") return
if (positionKind.get() === "target") {
- if (!semanticIntentRef.current && targetIntentRef.current) startIntent("target", targetIntentRef.current, "auto", true)
+ if (!newOperationRef.current && !semanticIntentRef.current && targetIntentRef.current) startIntent("target", targetIntentRef.current, "auto", true)
else scheduleInitialPositionSettled()
}
}, [targetDataState, items, positionKind, scheduleInitialPositionSettled, startIntent, visible])
@@ -891,6 +943,15 @@ export function useScrollAnchor({
if (!owner.active || !root || !native) return false
const page = reconcilePage()
if (page !== null) return page
+ const endAnchor = newEndAnchorRef.current
+ if (endAnchor && positionKind.get() === "idle" && hasCommittedRows()) {
+ const index = findMountScrollTargetIndex(currentItemsRef.current, endAnchor.id)
+ const anchor = index === null ? undefined : native.measurementsCache[index]
+ if (anchor) {
+ const needed = Math.max(0, anchor.start + endAnchor.inset + root.clientHeight - (native.getTotalSize() - newEndSpace))
+ if (Math.abs(needed - newEndSpace) > 1) { setNewEndSpace(needed); return true }
+ }
+ }
if (viewportOnly && (positionKind.get() !== "idle"
|| acceptedGeometryRef.current?.epoch !== owner.epoch
|| (acceptedGeometryRef.current.clientHeight === root.clientHeight
@@ -913,6 +974,9 @@ export function useScrollAnchor({
if (!viewportResized && !input.handover) {
if (!next) return false
observeGeometry(next)
+ if (!readReady.get() && preserveInitialPresentation
+ && contextRef.current.dataState === "ready" && contextRef.current.targetDataState === "ready"
+ && hasCommittedRows() && !next.isScrolling) setReadPositionReady(true)
} else {
const clampedByResize = viewportResized && !previous.isScrolling && previous.scrollTop > max
&& Math.abs(root.scrollTop - max) <= 1
@@ -949,7 +1013,7 @@ export function useScrollAnchor({
nextScrollHeight: next.scrollHeight,
previousScrollTop: adjustedPreviousOffset,
})
- offset = resized.scrollTop
+ offset = endAnchor ? adjustedPreviousOffset : resized.scrollTop
}
}
}
@@ -967,7 +1031,7 @@ export function useScrollAnchor({
else if (readReady.get()) setResumeValidated(true)
}
return false
- }, [claimPosition, holdNativeOrigin, observeGeometry, positionKind, readGeometry, readReady, reconcilePage, retireInitialPosition, setReadPositionReady, setShortGap, startIntent])
+ }, [claimPosition, hasCommittedRows, holdNativeOrigin, newEndSpace, observeGeometry, positionKind, preserveInitialPresentation, readGeometry, readReady, reconcilePage, retireInitialPosition, setReadPositionReady, setShortGap, startIntent])
const reconcileViewport = useCallback(() => {
const intent = semanticIntentRef.current
const root = scrollRef.current
@@ -992,11 +1056,12 @@ export function useScrollAnchor({
const accept = () => {
geometryFrameRef.current = null
if (reconcileGeometryRef.current()) geometryFrameRef.current = window.requestAnimationFrame(accept)
+ updateNewDividerVisibility()
}
geometryFrameRef.current = window.requestAnimationFrame(accept)
- }, [])
+ }, [updateNewDividerVisibility])
useLayoutEffect(() => { scheduleGeometryRef.current = scheduleGeometry }, [scheduleGeometry])
- useLayoutEffect(() => { scheduleGeometry() }, [items, ownerKind, readPositionReady, scheduleGeometry, shortGap, tailPaddingEnd])
+ useLayoutEffect(() => { scheduleGeometry() }, [dataState, targetDataState, items, newEndSpace, ownerKind, preserveInitialPresentation, readPositionReady, scheduleGeometry, shortGap, tailPaddingEnd])
useLayoutEffect(() => {
const root = scrollRef.current
@@ -1028,7 +1093,7 @@ export function useScrollAnchor({
if (next && native?.isAtEnd(1) && Math.abs(Math.max(0, next.scrollHeight - next.clientHeight) - next.scrollTop) <= 1
&& !userInputRef.current.touch && userInputRef.current.pointers.size === 0
&& positionKind.get() === "idle" && readReady.get()
- && nativeOrigin.get() !== currentItemsRef.current[0]?.key) setFollowSuspended(false)
+ && nativeOrigin.get() !== currentItemsRef.current[0]?.key && newEndSpace === 0) setFollowSuspended(false)
if (next) observeGeometry(next, true)
else if (positionKind.get() === "idle" && readReady.get()
&& previous?.epoch === positionOwnerRef.current.epoch && previous.scrollTop !== root.scrollTop
@@ -1118,7 +1183,7 @@ export function useScrollAnchor({
inputOwner.touch = false
inputOwner.pointers.clear()
}
- }, [holdNativeOrigin, nativeOrigin, observeGeometry, observePageBody, positionKind, readGeometry, readReady, reconcileGeometry, releasePosition, scheduleGeometry, scheduleInitialPositionSettled, setFollowSuspended])
+ }, [holdNativeOrigin, nativeOrigin, newEndSpace, observeGeometry, observePageBody, positionKind, readGeometry, readReady, reconcileGeometry, releasePosition, scheduleGeometry, scheduleInitialPositionSettled, setFollowSuspended])
const capturePageAnchor = useCallback((direction: "older" | "newer") => {
clearMeasurementAnchor()
@@ -1157,6 +1222,7 @@ export function useScrollAnchor({
const requestPresentPosition = useCallback((request?: MessageRequest | void) => {
if (!positionOwnerRef.current.active || !contextRef.current.visible) return
if (request && !request.accepted) return
+ setNewEndSpace(0)
const intent: NonNullable<typeof presentIntentRef.current> = { epoch: claimPosition("present"), allowAttachedTail: false, fetching: false }
presentIntentRef.current = intent
retireInitialPosition()
@@ -1178,6 +1244,7 @@ export function useScrollAnchor({
const accepted = version > consumedLocalSubmitVersionRef.current
consumedLocalSubmitVersionRef.current = version
if (!accepted || !visible) return
+ setNewEndSpace(0)
if ((hasMoreNewer || isFetchingNewer) && presentRequest !== undefined) {
if (presentRequest) requestPresentPosition(presentRequest)
else releasePosition()
@@ -1204,8 +1271,10 @@ export function useScrollAnchor({
const result = intent.receipt.result
if (!result) return
if (result.status !== "success" || dataState === "error") { releasePosition(false, "error"); return }
- if (messageWindow !== result.window && messageWindow !== intent.receipt.before) { releasePosition(); return }
- if (messageWindow !== result.window || dataState === "pending") return
+ const windowState = result.windowState?.(messageWindow)
+ ?? (messageWindow === result.window ? "ready" : messageWindow === intent.receipt.before ? "pending" : "retired")
+ if (windowState === "retired") { releasePosition(); return }
+ if (windowState === "pending" || dataState === "pending") return
presentIntentRef.current = null
if (dataState === "empty") {
releasePosition(false, "empty")
@@ -1234,31 +1303,10 @@ export function useScrollAnchor({
}, [dataState, hasMessages, hasMoreNewer, isFetchingNewer, messageWindow, positionKind, presentVersion, releasePosition, requestRevision, retireInitialPosition, setFollowSuspended, setReadPositionReady, startIntent])
const virtualItems = virtualizer.getVirtualItems()
- useLayoutEffect(() => {
- if (!initialPositionMessageId || localTargetRef.current || !lateNewRef.current.allowed || !entryResolvedRef.current
- || !visible || !initialScrollReady || !hasMessages
- || positionKind.get() !== "idle" && positionKind.get() !== "initial"
- || findMessageIndex(items, initialPositionMessageId) === null) return
- localTargetRef.current = initialPositionMessageId
- if (newDividerBefore) lateNewRef.current.consumed = true
- claimPosition("initial")
- startIntent("target", initialPositionMessageId)
- }, [claimPosition, hasMessages, initialPositionMessageId, initialScrollReady, items, newDividerBefore, positionEntry, positionKind, startIntent, visible])
- useLayoutEffect(() => {
- const late = lateNewRef.current
- if (!late.allowed || late.consumed || !newDividerBefore || !entryResolvedRef.current
- || !visible || !initialScrollReady || !hasMessages
- || positionKind.get() !== "idle" && positionKind.get() !== "initial"
- || findMountScrollTargetIndex(items, newDividerBefore) === null) return
- late.consumed = true
- claimPosition("late-new")
- startIntent("unread", newDividerBefore)
- }, [claimPosition, hasMessages, initialScrollReady, items, newDividerBefore, positionEntry, positionKind, startIntent, visible])
useLayoutEffect(() => {
if (!visible) return
const state = positionKind.get() === "target" ? targetDataState : dataState
if (state === "error" || state === "empty") {
- lateNewRef.current.allowed = false
if (positionKind.get() === "idle") return
releasePosition(false, state)
if (state === "empty") setReadPositionReady(true)
@@ -1269,14 +1317,13 @@ export function useScrollAnchor({
if (positionKind.get() !== "initial" || initialRetiredRef.current || !hasMessages) return
if (!entryResolvedRef.current) {
entryResolvedRef.current = true
- localTargetRef.current = initialPositionMessageId ?? null
- if (newDividerBefore) lateNewRef.current.consumed = true
- startIntent(initialPositionMessageId ? "target" : newDividerBefore ? "unread" : "end", initialPositionMessageId ?? newDividerBefore ?? null)
+ startIntent(initialPositionMessageId ? "target" : "end", initialPositionMessageId ?? null)
} else scheduleInitialPositionSettled()
}, [dataState, targetDataState, hasMessages, initialPositionMessageId, initialScrollReady, items, newDividerBefore, positionEntry, positionKind, releasePosition, scheduleInitialPositionSettled, setReadPositionReady, startIntent, virtualItems, visible])
const scrollToBottom = useCallback(() => {
if (!positionOwnerRef.current.active || !contextRef.current.visible) return
+ setNewEndSpace(0)
claimPosition("present")
retireInitialPosition()
setFollowSuspended(false)
@@ -1289,6 +1336,55 @@ export function useScrollAnchor({
retireInitialPosition()
startIntent("target", messageId, behavior)
}, [claimPosition, retireInitialPosition, startIntent])
+ const requestNewPosition = useCallback((id: string, load?: () => MessageRequest): NewPositionRequest => {
+ if (!positionOwnerRef.current.active || !contextRef.current.visible || contextRef.current.newDividerBefore !== id
+ || newOperationRef.current || !load && findMessageIndex(currentItemsRef.current, id) === null) return { accepted: false }
+ const priorEndAnchor = newEndAnchorRef.current
+ const epoch = claimPosition("target")
+ if (epoch === undefined) return { accepted: false }
+ retireInitialPosition()
+ const wasSuspended = followSuspension.get()
+ setFollowSuspended(true)
+ const timeout = new AbortController()
+ let finish!: (result: NewPositionResult) => void
+ const completed = new Promise<NewPositionResult>(resolve => { finish = result => { resolve(result); timeout.abort() } })
+ const operation: NewOperation = { epoch, id, priorTarget: targetIntentRef.current, loaded: !load, finish,
+ restoreFollow: () => { setFollowSuspended(wasSuspended); newEndAnchorRef.current = priorEndAnchor; setNewEndSpace(newEndSpace) } }
+ newOperationRef.current = operation
+ void withConversationReadDeadline(timeout.signal, () => completed).catch(() => {
+ if (newOperationRef.current === operation) releasePosition(false, "error")
+ })
+ try {
+ const request = load?.()
+ if (request && !request.accepted) { releasePosition(); return { accepted: false } }
+ if (request?.accepted) {
+ operation.cancel = request.cancel
+ const complete = (result: MessageRequestResult) => {
+ if (newOperationRef.current !== operation || positionOwnerRef.current.epoch !== epoch) return
+ if (result.status === "success") {
+ operation.loaded = true
+ operation.window = result.window
+ setRequestRevision(value => value + 1)
+ } else {
+ userInputRef.current.handover = true
+ finishNewOperation(result.status)
+ releasePosition(false, result.status === "error" ? "error" : "cancelled")
+ }
+ }
+ void request.completed.then(complete, () => complete({ status: "error" }))
+ } else setRequestRevision(value => value + 1)
+ } catch { releasePosition(false, "error") }
+ return { accepted: true, completed }
+ }, [claimPosition, finishNewOperation, followSuspension, newEndSpace, releasePosition, retireInitialPosition, setFollowSuspended])
+ useLayoutEffect(() => {
+ const operation = newOperationRef.current
+ if (!operation || !operation.loaded || positionKind.get() !== "target" || targetDataState !== "ready") return
+ if (operation.id !== newDividerBefore) { finishNewOperation("missing"); releasePosition(); return }
+ if (findMessageIndex(items, operation.id) !== null) {
+ if (!semanticIntentRef.current) startIntent("unread", operation.id)
+ else scheduleInitialPositionSettled()
+ } else if (messageWindow === operation.window) { finishNewOperation("missing"); releasePosition() }
+ }, [finishNewOperation, items, messageWindow, newDividerBefore, positionKind, releasePosition, requestRevision, scheduleInitialPositionSettled, startIntent, targetDataState])
const visibleItems = virtualizer.getVirtualItems()
const root = scrollRef.current
const lastVisibleIndex = root
@@ -1301,7 +1397,8 @@ export function useScrollAnchor({
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,
positionOutcome,
- scrollToBottom, requestPresentPosition, jumpTo,
+ scrollToBottom, requestPresentPosition, requestNewPosition, jumpTo, newDividerVisibility,
+ followingTail: !hasMoreNewer && !followSuspended && acceptedGeometryRef.current?.pinEligible === true,
captureOlderPageAnchor, captureNewerPageAnchor,
}
}
diff --git a/src/web/src/lib/community/conversation-entry.new-boundary.sql.test.ts b/src/web/src/lib/community/conversation-entry.new-boundary.sql.test.ts
new file mode 100644
index 000000000..22577a17d
--- /dev/null
+++ b/src/web/src/lib/community/conversation-entry.new-boundary.sql.test.ts
@@ -0,0 +1,82 @@
+import { afterEach, expect, it } from "vitest"
+import { BUSINESS_SCHEMA_VERSION, COMMUNITY_CONTRACT_HEADER } from "@alook/shared"
+import { createCommunitySqliteDb } from "@/test/community-sqlite-db"
+import { createCommunityQueryOwner } from "@/test/community-query-owner"
+import { captureCommunityLiveSnapshotToken } from "@/lib/community-db/sync"
+import { resolveMessageTarget } from "./message-door"
+import { parseCommunityMessageWindow } from "./messages"
+import { readCommunityConversationEntry } from "./conversation-entry.server"
+import { currentConversationReadState, publishConversationEntry } from "./conversation-entry"
+import { decodeCommunityReadResponse } from "./read-response"
+import { writeCommunityConversationEntryRead } from "./read-contract"
+import type { MessageWindowData } from "./message-window"
+
+const stores: ReturnType<typeof createCommunitySqliteDb>[] = []
+afterEach(() => { for (const store of stores) store.sqlite.close(); stores.length = 0 })
+
+function fixture() {
+ const store = createCommunitySqliteDb(); stores.push(store)
+ const stamp = "2026-11-04T00:00:00.000Z"
+ const insertUser = store.sqlite.prepare('INSERT INTO user (id,email,name,discriminator,"avatarVersion","createdAt","updatedAt") VALUES (?,?,?,?,0,?,?)')
+ for (const id of ["viewer", "peer"]) insertUser.run(id, `${id}@example.test`, id, id === "viewer" ? "0001" : "0002", stamp, stamp)
+ store.sqlite.prepare("INSERT INTO community_server (id,name,discriminator,description,owner_id,created_at) VALUES ('server','Server','0003','','viewer',?)").run(stamp)
+ store.sqlite.exec("INSERT INTO community_server_member (id,server_id,user_id,role) VALUES ('member','server','viewer','owner')")
+ store.sqlite.prepare("INSERT INTO community_channel (id,server_id,name,type,topic,position,archived,message_count,created_at,creator_id) VALUES ('channel','server','Channel','text','',0,0,99,?,'viewer')").run(stamp)
+ const insert = store.sqlite.prepare("INSERT INTO community_message (id,author_id,content,type,channel_id,seq,created_at) VALUES (?,?,?,'default','channel',?,?)")
+ for (let seq = 1; seq <= 100; seq++) if (seq !== 8) insert.run(`message-${seq}`, seq <= 7 ? "viewer" : "peer", `Body ${seq}`, seq, new Date(Date.parse(stamp) + seq * 1000).toISOString())
+ store.sqlite.prepare("INSERT INTO community_read_state (id,user_id,channel_id,last_read_at,last_read_message_id,last_read_seq) VALUES ('read','viewer','channel',?,'message-5',5)").run(new Date(Date.parse(stamp) + 5000).toISOString())
+ store.sqlite.exec("INSERT INTO community_read_state_revision (user_id,revision) VALUES ('viewer',1)")
+ return store
+}
+
+it("carries the original exact New target outside the newest window through real SQL, decoder and first publication after an ACK", async () => {
+ const store = fixture()
+ const resolved = await resolveMessageTarget(store.db, "viewer", { id: "channel" }, "human")
+ if (!resolved.ok) throw new Error(JSON.stringify(resolved))
+ store.sqlite.prepare("UPDATE community_read_state SET last_read_message_id='message-80', last_read_seq=80, last_read_at=?").run("2026-11-04T00:01:20.000Z")
+ store.sqlite.exec("UPDATE community_read_state_revision SET revision=2")
+ const result = await readCommunityConversationEntry(store.db, { viewerId: "viewer", target: resolved.value,
+ window: parseCommunityMessageWindow(new URLSearchParams()), preferTail: true, newAfterSeq: 5 })
+ if (!result.ok) throw new Error(JSON.stringify(result))
+ expect(result.entry.selection).toEqual({ reason: "tail", anchorMessageId: null })
+ expect(result.entry.readState.lastReadSeq).toBe(80)
+ expect(result.entry.newBoundary).toEqual({ afterSeq: 5, target: { id: "message-9", channelId: "channel", seq: 9, authorId: "peer" } })
+ expect(result.entry.messages.at(-1)?.id).toBe("message-100")
+ expect(result.entry.messages.some(message => message.id === "message-9")).toBe(false)
+ const response = writeCommunityConversationEntryRead(result.entry)
+ expect(response.headers.get(COMMUNITY_CONTRACT_HEADER)).toBe(String(BUSINESS_SCHEMA_VERSION))
+ const body = await response.json()
+ expect(decodeCommunityReadResponse("/api/community/channels/channel/messages?entry=1&window=tail&newAfterSeq=5", "GET", response, body)).toEqual(result.entry)
+ expect(() => decodeCommunityReadResponse("/api/community/channels/channel/messages?entry=1&newAfterSeq=6", "GET", response, body)).toThrow("New snapshot mismatch")
+ const { client, registry } = await createCommunityQueryOwner("viewer")
+ const target = { channelId: "channel", serverId: "server", preferTail: true, newAfterSeq: 5 }
+ const proof = { token: captureCommunityLiveSnapshotToken(client, "channel") }
+ expect(() => publishConversationEntry(client, { ...target, newAfterSeq: 6 }, result.entry, proof)).toThrow("target mismatch")
+ expect(registry.collections.channels.size).toBe(0)
+ expect(registry.collections.messages.size).toBe(0)
+ const resource = await publishConversationEntry(client, target, result.entry, proof)
+ expect(resource.newBoundaryAtEntry).toEqual(result.entry.newBoundary)
+ expect(currentConversationReadState(client, "channel")?.lastReadSeq).toBe(80)
+ const window = client.getQueryData<MessageWindowData>(resource.windowKey)!
+ expect(window.pages[0].messages.at(-1)?.id).toBe("message-100")
+ expect(registry.collections.messages.has("message-9")).toBe(false)
+})
+
+it("keeps an explicit anchor, handles a deleted read pointer, and rejects a cursor beyond the real receipt", async () => {
+ const store = fixture()
+ const resolved = await resolveMessageTarget(store.db, "viewer", { id: "channel" }, "human")
+ if (!resolved.ok) throw new Error(JSON.stringify(resolved))
+ store.sqlite.exec("DELETE FROM community_message WHERE id='message-5'; UPDATE community_channel SET message_count=98 WHERE id='channel'")
+ const base = { viewerId: "viewer", target: resolved.value, preferTail: true }
+ const explicit = await readCommunityConversationEntry(store.db, { ...base,
+ window: parseCommunityMessageWindow(new URLSearchParams({ anchor: "message-20" })) })
+ if (!explicit.ok) throw new Error(JSON.stringify(explicit))
+ expect(explicit.entry.selection).toEqual({ reason: "explicit_anchor", anchorMessageId: "message-20" })
+ expect(explicit.entry.newBoundary.target?.id).toBe("message-9")
+ const tail = await readCommunityConversationEntry(store.db, { ...base, window: parseCommunityMessageWindow(new URLSearchParams()) })
+ if (!tail.ok) throw new Error(JSON.stringify(tail))
+ expect(tail.entry.selection.reason).toBe("tail")
+ expect(tail.entry.newBoundary.target?.id).toBe("message-9")
+ await expect(readCommunityConversationEntry(store.db, { ...base,
+ window: parseCommunityMessageWindow(new URLSearchParams()), newAfterSeq: 101 })).resolves.toMatchObject({ ok: false, status: 400 })
+})
diff --git a/src/web/src/lib/community/conversation-entry.server.ts b/src/web/src/lib/community/conversation-entry.server.ts
index f7d658399..7f7e13eb3 100644
--- a/src/web/src/lib/community/conversation-entry.server.ts
+++ b/src/web/src/lib/community/conversation-entry.server.ts
@@ -14,6 +14,7 @@ type ConversationEntryInput = {
target: DoorTarget
window: ReturnType<typeof parseCommunityMessageWindow>
preferTail: boolean
+ newAfterSeq?: number
tag?: string
}
@@ -43,14 +44,14 @@ export async function readCommunityConversationEntry(db: Database, input: Conver
...communityMessagesReadFromPage(channelId, read.page), profiles, viewerId, channel, peer,
...(opener ? { opener: opener.message, relatedMessages: [...new Map([...(read.page.relatedMessages ?? []), ...opener.relatedMessages].filter(message => !read.page.messages.some(root => (root as { id: string }).id === message.id) && message.id !== opener.message.id).map(message => [message.id, message])).values()] } : {}),
...(parent ? { parent } : {}),
- readState: read.readState, readStateRevision: read.revision, selection: read.selection,
+ readState: read.readState, readStateRevision: read.revision, newBoundary: read.newBoundary, selection: read.selection,
...("forumFeed" in read ? { forumFeed: read.forumFeed } : {}),
access: { channelId, canRead: true, canSend,
canCreateDiscussion: !channel.parentChannelId && (channel.type === "text" || channel.type === "forum") },
}) }
}
-async function readEntryWindow(db: Database, { viewerId, target, window, preferTail, tag }: ConversationEntryInput, readProfiles: CommunityResourceProfileReader) {
+async function readEntryWindow(db: Database, { viewerId, target, window, preferTail, newAfterSeq, tag }: ConversationEntryInput, readProfiles: CommunityResourceProfileReader) {
const channelId = target.target.channelId
const { readState: row, revision } = await withD1Retry(() => queries.communityReadState.getChannelReadStateSnapshot(db, { userId: viewerId, channelId }), {
route: "community/messages:entry-read-state",
@@ -59,12 +60,17 @@ async function readEntryWindow(db: Database, { viewerId, target, window, preferT
channelId, lastReadMessageId: row?.lastReadMessageId ?? null,
lastReadAt: row?.lastReadAt ?? null, lastReadSeq: row?.lastReadSeq ?? 0,
}
+ if (newAfterSeq !== undefined && (!Number.isSafeInteger(newAfterSeq) || newAfterSeq < 0)) {
+ return { ok: false as const, status: 400 as const, error: "invalid New snapshot" }
+ }
+ const boundarySeq = newAfterSeq ?? readState.lastReadSeq
if (target.access.channel.type === "forum" && !window.anchorId) {
+ if (boundarySeq > readState.lastReadSeq) return { ok: false as const, status: 400 as const, error: "New snapshot exceeds the conversation receipt" }
const page = await readCommunityForumRows(db, channelId, { tag, pageSize: window.pageSize, includes: new Set(["parentMessage", "firstMessage", "tags", "participants"]) })
const forumFeed = CommunityThreadsReadSchema.parse(await readCommunityThreadsResource(db, viewerId, target.access.channel, page.threads,
{ messages: [...page.parentMessages, ...page.firstMessages], tags: page.tags, participants: page.participants }, { hasMore: page.hasMore, nextCursor: page.nextCursor ?? null }, COMMUNITY_RESOURCE_CONTRACT_VERSION))
return { ok: true as const, page: { messages: [], relatedMessages: [], profiles: [], latestSeq: readState.lastReadSeq, hasMoreOlder: false, hasMoreNewer: false, surfaceReceipt: { channelId, surfaceKind: "forum" as const } },
- readState, revision, selection: { reason: "tail" as const, anchorMessageId: null }, forumFeed }
+ readState, revision, newBoundary: { afterSeq: boundarySeq, target: null }, selection: { reason: "tail" as const, anchorMessageId: null }, forumFeed }
}
const anchorId = window.anchorId ?? (preferTail ? undefined : readState.lastReadMessageId ?? undefined)
let selection: CommunityConversationEntryRead["selection"] = {
@@ -80,7 +86,11 @@ async function readEntryWindow(db: Database, { viewerId, target, window, preferT
})
}
if (!result.ok) return { ...result, ...(window.anchorId ? { details: [COMMUNITY_CONVERSATION_ANCHOR_MISSING] } : {}) }
- return { ok: true as const, page: result.page, readState, revision, selection }
+ if (boundarySeq > Math.max(readState.lastReadSeq, result.page.latestSeq)) return { ok: false as const, status: 400 as const, error: "New snapshot exceeds the conversation receipt" }
+ const newTarget = target.access.channel.type === "forum" ? null : await withD1Retry(() => queries.communityMessage.getFirstPeerMessageAfterSeq(db, {
+ channelId, viewerId, afterSeq: boundarySeq, throughSeq: result.page.latestSeq,
+ }), { route: "community/messages:entry-new-target" })
+ return { ok: true as const, page: result.page, readState, revision, newBoundary: { afterSeq: boundarySeq, target: newTarget }, selection }
}
async function readPeer(db: Database, peerId: string, readProfiles: CommunityResourceProfileReader) {
diff --git a/src/web/src/lib/community/conversation-entry.test.ts b/src/web/src/lib/community/conversation-entry.test.ts
index be639e0a1..c68289fb3 100644
--- a/src/web/src/lib/community/conversation-entry.test.ts
+++ b/src/web/src/lib/community/conversation-entry.test.ts
@@ -233,7 +233,7 @@ describe("conversation entry canonical publication", () => {
for (const forum of [false, true]) {
const { client } = await createCommunityQueryOwner()
const value = forum ? forumConversationEntryFixture() : entry()
- const key = forum ? communityKeys.forumFeed("c1", null) : communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "m1" })
+ const key = forum ? communityKeys.forumFeed("c1", null) : communityKeys.channelMessagesWindow("c1", { mode: "newest" })
client.getQueryCache().build(client, { queryKey: key })
if (state === "failed-query") await expect(client.query({ queryKey: key, queryFn: () => Promise.reject(new Error("first read failed")), retry: false, select: undefined })).rejects.toThrow("first read failed")
if (state === "empty-pages") client.setQueryData(key, { pages: [], pageParams: [] })
@@ -300,7 +300,7 @@ describe("conversation entry canonical publication", () => {
load.mockResolvedValue(entry())
const resource = await client.query({ ...conversationEntryOptions(client, target), select: undefined })
expect(load).toHaveBeenCalledOnce()
- expect(load).toHaveBeenCalledWith("/api/community/channels/c1/messages?entry=1", expect.objectContaining({
+ expect(load).toHaveBeenCalledWith("/api/community/channels/c1/messages?entry=1&window=tail", expect.objectContaining({
authenticationAccount: "viewer", signal: expect.any(AbortSignal), headers: { [COMMUNITY_CONTRACT_HEADER]: String(BUSINESS_SCHEMA_VERSION) },
}))
expect(registry.collections.channels.get("c1")).toMatchObject({ name: "Channel" })
@@ -308,7 +308,7 @@ describe("conversation entry canonical publication", () => {
expect(registry.collections.readStates.get("c1")).toMatchObject({ lastReadSeq: 1, observedRevision: 4 })
expect(registry.collections.readStateClock.get("account")).toBeUndefined()
const window = client.getQueryData<MessageWindowData>(resource.windowKey)!
- expect(window.pageParams).toEqual([{ mode: "anchor", anchor: "m1" }])
+ expect(window.pageParams).toEqual([{ mode: "newest" }])
expect(window.pages[0].messages).toEqual([{ id: "m1", seq: 1 }])
expect(JSON.stringify(window)).not.toContain("Body")
await client.query({ ...conversationEntryOptions(client, target), select: undefined })
@@ -417,10 +417,11 @@ describe("conversation entry canonical publication", () => {
const { client } = await createCommunityQueryOwner()
const value = entry()
value.readState = { channelId: "c1", lastReadMessageId: "missing", lastReadAt: "at", lastReadSeq: 10 }
- value.selection = { reason: "read_pointer_missing", anchorMessageId: null }
+ value.selection = { reason: "tail", anchorMessageId: null }
+ value.newBoundary = { afterSeq: 10, target: null }
const resource = await publishConversationEntry(client, target, value, { token: captureCommunityLiveSnapshotToken(client, "c1") })
expect(findConversationEntryWindow(client, target, resource, value.readState)?.initial).toEqual({ mode: "newest" })
- expect(findConversationEntryWindow(client, target, resource, { ...value.readState, lastReadMessageId: "newer" })).toBeUndefined()
+ expect(findConversationEntryWindow(client, target, resource, { ...value.readState, lastReadMessageId: "newer", lastReadSeq: 11 })).toBeUndefined()
expect(findConversationEntryWindow(client, { ...target, anchorMessageId: "explicit" }, resource, value.readState)).toBeUndefined()
const data = client.getQueryData<MessageWindowData>(resource.windowKey)!
client.setQueryData(resource.windowKey, { ...data, pages: data.pages.map(page => ({ ...page, hasMoreNewer: true })) })
diff --git a/src/web/src/lib/community/conversation-entry.ts b/src/web/src/lib/community/conversation-entry.ts
index f90e2ce4f..c37a15860 100644
--- a/src/web/src/lib/community/conversation-entry.ts
+++ b/src/web/src/lib/community/conversation-entry.ts
@@ -31,6 +31,7 @@ export type ConversationEntryTarget = {
anchorMessageId?: string | null
tag?: string | null
preferTail?: boolean
+ newAfterSeq?: number | null
}
export type ConversationEntryResource = {
@@ -40,13 +41,15 @@ export type ConversationEntryResource = {
windowKey: QueryKey
readStateAtEntry: CommunityReadStateResource
readStateRevision: number
+ latestSeqAtEntry: number
+ newBoundaryAtEntry: CommunityConversationEntryRead["newBoundary"]
selection: CommunityConversationEntryRead["selection"]
access: CommunityConversationEntryRead["access"]
proof: ReturnType<typeof captureCommunityLiveSnapshotToken>
}
export type ConversationWindowScope = Pick<ConversationEntryResource, "channelId" | "proof">
- & Partial<Pick<ConversationEntryResource, "windowKey" | "readStateAtEntry" | "selection">>
+ & Partial<Pick<ConversationEntryResource, "windowKey" | "readStateAtEntry" | "readStateRevision" | "selection">>
type ConversationDisplayWindow = { key: QueryKey; initial: InitialMessageWindow; tag: string | null; resources?: CommunityMessageResources }
const qualifiedWindows = new WeakMap<Query, { resources: CommunityMessageResources; window: ConversationDisplayWindow }>()
@@ -99,7 +102,9 @@ export function publishConversationEntry(
const channel = entry.channel
if (entry.viewerId !== proof.token.viewerId || proof.token.channelId !== target.channelId || entry.channelId !== target.channelId || channel.serverId !== target.serverId
|| (target.serverId === null ? channel.type !== "dm" : channel.type === "dm")
- || target.anchorMessageId && (entry.selection.reason !== "explicit_anchor" || entry.selection.anchorMessageId !== target.anchorMessageId)) throw new Error("Conversation entry target mismatch")
+ || target.anchorMessageId && (entry.selection.reason !== "explicit_anchor" || entry.selection.anchorMessageId !== target.anchorMessageId)
+ || !target.anchorMessageId && target.preferTail !== false && (entry.selection.reason !== "tail" || entry.selection.anchorMessageId !== null)
+ || target.newAfterSeq != null && entry.newBoundary.afterSeq !== target.newAfterSeq) throw new Error("Conversation entry target mismatch")
const registry = proof.token.registry!
const parent = channel.parentChannelId
if (parent && (registry.runtime.ws.get().channelAccessScopes.get(parent)?.generation ?? 0) !== (proof.token.channelScopes.get(parent)?.generation ?? 0)) throw new DOMException("Retired conversation parent", "AbortError")
@@ -140,7 +145,7 @@ export function publishConversationEntry(
})
}
})
- return { channelId: channel.id, source, initialWindow, windowKey, readStateAtEntry: entry.readState, readStateRevision: entry.readStateRevision, selection: entry.selection, access: entry.access, proof: qualified }
+ return { channelId: channel.id, source, initialWindow, windowKey, readStateAtEntry: entry.readState, readStateRevision: entry.readStateRevision, latestSeqAtEntry: entry.page.latestSeq, newBoundaryAtEntry: entry.newBoundary, selection: entry.selection, access: entry.access, proof: qualified }
}, () => assertCommunityLiveSnapshotTokenCurrent(client, proof.token, proof.signal))
}
@@ -204,15 +209,21 @@ function conversationDisplayWindows(client: QueryClient, target: ConversationEnt
}
export function findConversationDisplayWindow(client: QueryClient, target: ConversationEntryTarget, scope: ConversationWindowScope) {
- return conversationDisplayWindows(client, target, scope)?.[0]
+ return conversationDisplayWindows(client, target, scope)?.find(window => !messageWindowIdentity(window.key) || target.preferTail === false || !!target.anchorMessageId
+ || window.initial.mode === "newest" && client.getQueryData<MessageWindowData>(window.key)?.pages[0]?.hasMoreNewer === false)
}
export function findConversationEntryWindow(client: QueryClient, target: ConversationEntryTarget, resource: ConversationWindowScope, pointer: CommunityReadStateResource | undefined) {
if (!pointer && !target.anchorMessageId) return
- const anchor = target.anchorMessageId ?? (target.preferTail ? null : pointer?.lastReadMessageId)
+ const anchor = target.anchorMessageId ?? (target.preferTail !== false ? null : pointer?.lastReadMessageId)
return conversationDisplayWindows(client, target, resource)?.find(window => {
if (!messageWindowIdentity(window.key)) return true
const data = client.getQueryData<MessageWindowData>(window.key)!
+ if (target.preferTail !== false && !target.anchorMessageId) {
+ if (window.initial.mode !== "newest") return false
+ const latest = Math.max(0, ...data.pages.map(page => page.latestSeq ?? 0))
+ if (pointer && pointer.lastReadSeq > latest && (resource.readStateAtEntry?.lastReadSeq ?? -1) < pointer.lastReadSeq) return false
+ }
const anchored = !!anchor && data.pages.some(page => page.messages.some(message => message.id === anchor))
const missingPointer = !target.anchorMessageId && pointer?.lastReadMessageId === resource.readStateAtEntry?.lastReadMessageId && resource.selection?.reason === "read_pointer_missing"
&& hashKey(window.key) === hashKey(resource.windowKey ?? []) && window.initial.mode === "newest" && data.pages[0].hasMoreNewer === false
@@ -232,10 +243,24 @@ export function conversationEntryOptions(client: QueryClient, target: Conversati
accountEpoch: qualification.accountEpoch, accessEpoch: qualification.accessEpoch,
channelGeneration: qualification.channelScopes.get(target.channelId)?.generation ?? 0,
})
+ const expectedInitial: InitialMessageWindow = target.anchorMessageId ? { mode: "anchor", anchor: target.anchorMessageId } : { mode: "newest" }
+ const expectedWindow = communityKeys.channelMessagesWindow(target.channelId, expectedInitial, target.tag)
+ const reusable = target.newAfterSeq == null || !assessConversationScope(client, target).scope ? undefined : client.getQueryCache().findAll({ queryKey: communityKeys.conversationEntries(target.channelId) })
+ .filter(query => {
+ const resource = query.state.data as ConversationEntryResource | undefined
+ return query.state.status === "success" && query.state.fetchStatus === "idle"
+ && hashKey([query.queryKey.at(-1)]) === hashKey([queryKey.at(-1)])
+ && resource && isChannelMetadataTokenCurrent(resource.proof) && resource.channelId === target.channelId
+ && resource.newBoundaryAtEntry.afterSeq === target.newAfterSeq
+ && hashKey(resource.windowKey) === hashKey(expectedWindow)
+ && (target.preferTail === false || target.anchorMessageId || resource.selection.reason === "tail")
+ }).sort((left, right) => right.state.dataUpdatedAt - left.state.dataUpdatedAt)[0]
const cached = client.getQueryData<ConversationEntryResource>(queryKey)
const knownPointer = cached && isChannelMetadataTokenCurrent(cached.proof) ? currentConversationReadState(client, target.channelId) : undefined
return queryOptions<ConversationEntryResource>({
queryKey,
+ initialData: reusable?.state.data as ConversationEntryResource | undefined,
+ initialDataUpdatedAt: reusable?.state.dataUpdatedAt,
queryFn: async ({ signal }) => {
const token = captureCommunityLiveSnapshotToken(client, target.channelId)
const original = client.getQueryCache().find({ queryKey, exact: true })
@@ -245,7 +270,8 @@ export function conversationEntryOptions(client: QueryClient, target: Conversati
}
const search = new URLSearchParams({ entry: "1" })
if (target.anchorMessageId) search.set("anchor", target.anchorMessageId)
- else if (target.preferTail) search.set("window", "tail")
+ else if (target.preferTail !== false) search.set("window", "tail")
+ if (target.newAfterSeq != null) search.set("newAfterSeq", String(target.newAfterSeq))
if (target.tag) search.set("tag", target.tag)
const expectedPath = target.serverId === null ? `/c/me/${encodeURIComponent(target.channelId)}` : channelHref(target.serverId, target.channelId)
const action = typeof window !== "undefined" && window.location.pathname === expectedPath ? navigationForHref(window.location.pathname + window.location.search) : undefined
diff --git a/src/web/src/lib/community/desktop-system-notification.test.ts b/src/web/src/lib/community/desktop-system-notification.test.ts
index 66b6f3990..74081bc55 100644
--- a/src/web/src/lib/community/desktop-system-notification.test.ts
+++ b/src/web/src/lib/community/desktop-system-notification.test.ts
@@ -260,7 +260,7 @@ describe("desktop system notification candidates", () => {
title: "Studio · #general",
body: "Ada: Hello there",
})
- expect(channelMetadataMocks.fetch).toHaveBeenCalledWith("/api/community/channels/channel_1/messages?entry=1", expect.objectContaining({ signal: expect.any(AbortSignal), authenticationAccount: "viewer_1" }))
+ expect(channelMetadataMocks.fetch).toHaveBeenCalledWith("/api/community/channels/channel_1/messages?entry=1&window=tail", expect.objectContaining({ signal: expect.any(AbortSignal), authenticationAccount: "viewer_1" }))
})
it("uses the default empty snapshot while resolving cold channel metadata", async () => {
@@ -287,7 +287,7 @@ describe("desktop system notification candidates", () => {
title: "Server · #general",
body: "Ada: Hello there",
})
- expect(channelMetadataMocks.fetch).toHaveBeenCalledWith("/api/community/channels/channel_1/messages?entry=1", expect.objectContaining({ signal: expect.any(AbortSignal), authenticationAccount: "viewer_1" }))
+ expect(channelMetadataMocks.fetch).toHaveBeenCalledWith("/api/community/channels/channel_1/messages?entry=1&window=tail", expect.objectContaining({ signal: expect.any(AbortSignal), authenticationAccount: "viewer_1" }))
})
it("resolves cold thread and parent channel names before formatting the desktop copy", async () => {
@@ -325,7 +325,7 @@ describe("desktop system notification candidates", () => {
title: "Studio · #general · Release notes",
body: "Ada: Hello there",
})
- expect(channelMetadataMocks.fetch.mock.calls.map(([path]) => path)).toEqual(["/api/community/channels/thread_1/messages?entry=1", "/api/community/channels/channel_1/messages?entry=1"])
+ expect(channelMetadataMocks.fetch.mock.calls.map(([path]) => path)).toEqual(["/api/community/channels/thread_1/messages?entry=1&window=tail", "/api/community/channels/channel_1/messages?entry=1&window=tail"])
})
it("uses complete current-account collections without metadata I/O", async () => {
diff --git a/src/web/src/lib/community/message-position.ts b/src/web/src/lib/community/message-position.ts
index 47e3eeccc..c6f78cebe 100644
--- a/src/web/src/lib/community/message-position.ts
+++ b/src/web/src/lib/community/message-position.ts
@@ -1,9 +1,15 @@
export type MessagePositionState = "pending" | "ready" | "empty" | "error"
export type MessageRequestResult =
- | { status: "success"; window: object }
- | { status: "error" | "retired" }
+ | { status: "success"; window: object; windowState?: (window: object | undefined) => "pending" | "ready" | "retired" }
+ | { status: "error" | "retired" | "missing" }
+
+export type NewPositionResult = "success" | "error" | "retired" | "missing" | "cancelled"
+
+export type NewPositionRequest =
+ | { accepted: false }
+ | { accepted: true; completed: Promise<NewPositionResult> }
export type MessageRequest =
| { accepted: false }
- | { accepted: true; completed: Promise<MessageRequestResult> }
+ | { accepted: true; completed: Promise<MessageRequestResult>; cancel?: () => void }
diff --git a/src/web/src/lib/community/message-read-projection.test.ts b/src/web/src/lib/community/message-read-projection.test.ts
index 52bb9b59b..5d623d611 100644
--- a/src/web/src/lib/community/message-read-projection.test.ts
+++ b/src/web/src/lib/community/message-read-projection.test.ts
@@ -1,63 +1,5 @@
import { describe, expect, it } from "vitest"
-import { resolveMessageReadProjection, resolveUnreadMessageCount } from "./message-read-projection"
-
-const messages = [
- { id: "self", authorId: "viewer" },
- { id: "anchor", authorId: "viewer" },
- { id: "peer", authorId: "peer" },
-]
-
-describe("resolveMessageReadProjection", () => {
- it("settles a warm canonical window without waiting for its query page marker", () => {
- expect(resolveMessageReadProjection({
- messages,
- lastReadMessageId: "anchor",
- viewerUserId: "viewer",
- anchorReconciled: false,
- })).toEqual({ newDividerBefore: "peer", anchorFound: true })
- })
-
- it("keeps an anchor-incomplete window unresolved until the anchor arrives", () => {
- expect(resolveMessageReadProjection({
- messages: [messages[2]],
- lastReadMessageId: "anchor",
- viewerUserId: "viewer",
- anchorReconciled: false,
- })).toEqual({ newDividerBefore: undefined, anchorFound: false })
-
- expect(resolveMessageReadProjection({
- messages: messages.slice(1),
- lastReadMessageId: "anchor",
- viewerUserId: "viewer",
- anchorReconciled: true,
- })).toEqual({ newDividerBefore: "peer", anchorFound: true })
- })
-
- it("distinguishes a pending first visit from a reconciled empty window", () => {
- expect(resolveMessageReadProjection({
- messages: [],
- lastReadMessageId: null,
- viewerUserId: "viewer",
- anchorReconciled: false,
- }).anchorFound).toBe(false)
- expect(resolveMessageReadProjection({
- messages: [],
- lastReadMessageId: null,
- viewerUserId: "viewer",
- anchorReconciled: true,
- }).anchorFound).toBe(true)
- })
-
- it("places a first-visit divider before the first peer row already in canonical data", () => {
- expect(resolveMessageReadProjection({
- messages,
- lastReadMessageId: null,
- viewerUserId: "viewer",
- anchorReconciled: false,
- })).toEqual({ newDividerBefore: "peer", anchorFound: true })
- })
-})
-
+import { resolveUnreadMessageCount } from "./message-read-projection"
describe("qualified unread message counts", () => {
const count = (input: Partial<Parameters<typeof resolveUnreadMessageCount>[0]> = {}) => resolveUnreadMessageCount({ messages: [{ seq: 2 }, { seq: 5 }, { seq: 9 }], lastReadSeq: 2, latestSeq: 9, historyStartKnown: false, hasMoreNewer: false, ...input })
diff --git a/src/web/src/lib/community/message-read-projection.ts b/src/web/src/lib/community/message-read-projection.ts
index 63968fa14..e7ac0a451 100644
--- a/src/web/src/lib/community/message-read-projection.ts
+++ b/src/web/src/lib/community/message-read-projection.ts
@@ -1,42 +1,3 @@
-type ProjectionMessage = {
- id: string
- authorId?: string | null
-}
-
-export type MessageReadProjection = {
- newDividerBefore: string | undefined
- anchorFound: boolean
-}
-
-export function resolveMessageReadProjection({
- messages,
- lastReadMessageId,
- viewerUserId,
- anchorReconciled,
-}: {
- messages: ProjectionMessage[]
- lastReadMessageId: string | null
- viewerUserId: string
- anchorReconciled: boolean
-}): MessageReadProjection {
- if (!lastReadMessageId) {
- if (messages.length === 0 && !anchorReconciled) {
- return { newDividerBefore: undefined, anchorFound: false }
- }
- const firstUnread = messages.find((message) => message.authorId !== viewerUserId)
- return { newDividerBefore: firstUnread?.id, anchorFound: true }
- }
-
- const anchorIndex = messages.findIndex((message) => message.id === lastReadMessageId)
- if (anchorIndex === -1) {
- return { newDividerBefore: undefined, anchorFound: false }
- }
- const firstUnread = messages
- .slice(anchorIndex + 1)
- .find((message) => message.authorId !== viewerUserId)
- return { newDividerBefore: firstUnread?.id, anchorFound: true }
-}
-
export function resolveUnreadMessageCount({ messages, lastReadSeq, latestSeq, historyStartKnown, hasMoreNewer }: {
messages: readonly { seq?: number }[]
lastReadSeq: number
diff --git a/src/web/src/lib/community/navigation-metadata.dom.test.tsx b/src/web/src/lib/community/navigation-metadata.dom.test.tsx
index 7401d1533..ef8915ee7 100644
--- a/src/web/src/lib/community/navigation-metadata.dom.test.tsx
+++ b/src/web/src/lib/community/navigation-metadata.dom.test.tsx
@@ -77,11 +77,13 @@ describe("native navigation warming and DM consumer mounting", () => {
if (mode === "return") {
await seedConversationEntry(owner.client, entry)
ingestReadStateSnapshot(owner.registry, { revision: 22, readStates: [{ channelId: "c1", lastReadMessageId: "m28", lastReadSeq: 28, lastReadAt: "later" }] })
- entry.messages = Array.from({ length: 26 }, (_, n) => ({ ...entry.messages[0], id: `m${n + 3}`, seq: n + 3 }))
+ entry.messages = Array.from({ length: 27 }, (_, n) => ({ ...entry.messages[0], id: `m${n + 2}`, seq: n + 2,
+ createdAt: new Date(Date.UTC(2026, 9, 1, 0, 0, n + 2)).toISOString() }))
entry.channel.messageCount = 28
entry.readState = { ...entry.readState, lastReadMessageId: "m28", lastReadSeq: 28, lastReadAt: "later" }
entry.readStateRevision = 22
- entry.selection = { reason: "read_pointer", anchorMessageId: "m28" }
+ entry.selection = { reason: "tail", anchorMessageId: null }
+ entry.newBoundary = { afterSeq: 28, target: null }
entry.page.latestSeq = 28
} else {
await publishCommunityLiveSnapshot(owner.client, { snapshot: { kind: "dms", data: { conversations: [dmListRowFixture({ id: "c1", userId: "peer", name: "Peer", discriminator: "0042", avatarVersion: 0, avatar: "P", status: "offline", preview: "" })] } }, proof: { kind: "structural", token: captureCommunityLiveSnapshotToken(owner.client), signal: undefined } })
@@ -142,7 +144,7 @@ describe("native navigation warming and DM consumer mounting", () => {
const href = source === "route" ? "/c/channels/s1/c1?tag=explicit" : "/c/channels/s1/c1"
await prepareNavigationMetadata(owner.client, href, "prefetch")
await prepareNavigationMetadata(owner.client, href, "foreground")
- expect(load.mock.calls.map(([url]) => url)).toEqual([`/api/community/channels/c1/messages?entry=1&tag=${source === "route" ? "explicit" : "saved"}`])
+ expect(load.mock.calls.map(([url]) => url)).toEqual([`/api/community/channels/c1/messages?entry=1&window=tail&tag=${source === "route" ? "explicit" : "saved"}`])
} finally { localStorage.clear() }
})
diff --git a/src/web/src/lib/community/read-contract.test.ts b/src/web/src/lib/community/read-contract.test.ts
index 002cf6e05..f47f30b77 100644
--- a/src/web/src/lib/community/read-contract.test.ts
+++ b/src/web/src/lib/community/read-contract.test.ts
@@ -71,7 +71,7 @@ describe("current conversation entry ingress", () => {
channel: channel,
access: { channelId: "channel", canRead: true, canSend: false, canCreateDiscussion: false },
readState: { channelId: "channel", lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 },
- readStateRevision: 0, selection: { reason: "tail", anchorMessageId: null },
+ readStateRevision: 0, newBoundary: { afterSeq: 0, target: null }, selection: { reason: "tail", anchorMessageId: null },
surfaceReceipt: { channelId: "channel", surfaceKind: "dm" }, messages: [], profiles: [],
page: { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 0 },
})
diff --git a/src/web/src/lib/community/read-response.ts b/src/web/src/lib/community/read-response.ts
index 4286d399e..97f3a18ff 100644
--- a/src/web/src/lib/community/read-response.ts
+++ b/src/web/src/lib/community/read-response.ts
@@ -34,6 +34,8 @@ export function decodeCommunityReadResponse(path: string, method: string | undef
if (target.resource === "entry") {
const data = CommunityConversationEntryReadSchema.parse(value)
assertScope(data.channelId)
+ const requestedBoundary = new URL(path, "https://alook.invalid").searchParams.get("newAfterSeq")
+ if (requestedBoundary !== null && String(data.newBoundary.afterSeq) !== requestedBoundary) throw new Error("Community entry New snapshot mismatch")
return { ...data, messages: data.messages }
}
if (target.resource === "message") {
diff --git a/src/web/src/lib/community/testids.ts b/src/web/src/lib/community/testids.ts
index 79728ce01..9ab90f416 100644
--- a/src/web/src/lib/community/testids.ts
+++ b/src/web/src/lib/community/testids.ts
@@ -85,6 +85,7 @@ export const tid = {
settingsChannels: "community-settings-channels",
settingsChannel: (id: string) => `community-settings-channel-${id}`,
newDivider: "community-new-divider",
+ scrollToNew: "community-scroll-to-new",
typingIndicator: "community-typing-indicator",
dmBlockedNotice: "community-dm-blocked-notice",
dmHeader: "community-dm-header",
diff --git a/src/web/src/lib/query-keys.ts b/src/web/src/lib/query-keys.ts
index 665e61b7f..ba7d5d2f8 100644
--- a/src/web/src/lib/query-keys.ts
+++ b/src/web/src/lib/query-keys.ts
@@ -73,9 +73,9 @@ export const communityKeys = {
initial.mode === "newest" && !tag ? communityKeys.channelMessages(channelId)
: [...communityKeys.channelMessages(channelId), "window", { ...initial, tag: tag ?? null }] as const,
conversationEntries: (channelId: string) => [...communityKeys.all, "channel", channelId, "entry"] as const,
- conversationEntry: (channelId: string, intent: { serverId?: string | null; anchorMessageId?: string | null; tag?: string | null; preferTail?: boolean } = {}, qualification?: { accountEpoch: number; accessEpoch: number; channelGeneration: number }) =>
+ conversationEntry: (channelId: string, intent: { serverId?: string | null; anchorMessageId?: string | null; tag?: string | null; preferTail?: boolean; newAfterSeq?: number | null } = {}, qualification?: { accountEpoch: number; accessEpoch: number; channelGeneration: number }) =>
[...communityKeys.conversationEntries(channelId), {
- serverId: intent.serverId ?? null, anchorMessageId: intent.anchorMessageId ?? null, tag: intent.tag ?? null, preferTail: intent.preferTail === true,
+ serverId: intent.serverId ?? null, anchorMessageId: intent.anchorMessageId ?? null, tag: intent.tag ?? null, preferTail: intent.preferTail !== false, newAfterSeq: intent.newAfterSeq ?? null,
}, ...(qualification ? [qualification] : [])] as const,
dmMessages: (dmId: string) =>
communityKeys.channelMessages(dmId),
diff --git a/src/web/src/test/conversation-entry-fixtures.ts b/src/web/src/test/conversation-entry-fixtures.ts
index 82f1e559e..36a2724ef 100644
--- a/src/web/src/test/conversation-entry-fixtures.ts
+++ b/src/web/src/test/conversation-entry-fixtures.ts
@@ -9,8 +9,8 @@ export function conversationEntryFixture(): CommunityConversationEntryRead {
profiles: [profileResourceFixture({ id: "peer", name: "Peer", discriminator: "0042", avatarVersion: 5 })],
channel: { id: "c1", type: "text", serverId: "s1", categoryId: null, name: "Channel", topic: "", parentChannelId: null, parentMessageId: null, creatorId: "viewer", position: 0, archived: false, createdAt: at, lastMessageAt: at, messageCount: 1 },
access: { channelId: "c1", canRead: true, canSend: true, canCreateDiscussion: true },
- readState: { channelId: "c1", lastReadMessageId: "m1", lastReadAt: at, lastReadSeq: 1 }, readStateRevision: 4,
- selection: { reason: "read_pointer", anchorMessageId: "m1" },
+ readState: { channelId: "c1", lastReadMessageId: "m1", lastReadAt: at, lastReadSeq: 1 }, readStateRevision: 4, newBoundary: { afterSeq: 1, target: null },
+ selection: { reason: "tail", anchorMessageId: null },
surfaceReceipt: { channelId: "c1", surfaceKind: "channel" },
messages: [{ id: "m1", channelId: "c1", seq: 1, authorId: "peer", createdAt: at, type: "chat", content: "Body", replyToId: null, clientNonce: null, attachments: [] }],
page: { olderCursor: "older", newerCursor: null, hasMoreOlder: true, hasMoreNewer: false, latestSeq: 1 },
@@ -45,7 +45,7 @@ export function conversationEntryFromChannel(value: CommunityChannelIdentity, vi
return { contractVersion: BUSINESS_SCHEMA_VERSION, channelId: channel.id, viewerId, channel,
peer: channel.type === "dm" ? { id: "peer", name: "Peer", discriminator: "0042", avatar: null, avatarVersion: 0 } : null,
access: { channelId: channel.id, canRead: true, canSend: true, canCreateDiscussion: channel.type === "text" || channel.type === "forum" },
- readState: { channelId: channel.id, lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 }, readStateRevision: 0,
+ readState: { channelId: channel.id, lastReadMessageId: null, lastReadAt: null, lastReadSeq: 0 }, readStateRevision: 0, newBoundary: { afterSeq: 0, target: null },
selection: { reason: "tail", anchorMessageId: null }, surfaceReceipt: { channelId: channel.id, surfaceKind: channel.type === "text" ? "channel" : channel.type },
messages: [], profiles: [], page: { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 0 } }
}
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
index 38baa7af8..a934b2edc 100644
--- 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
@@ -32,7 +32,7 @@ test("anchored channel jumps to the newest tail with one request", async ({ case
expect(readResponse.ok).toBe(true)
const { page } = await asUser("alice")
- await page.goto(`/c/channels/${serverId}/${channelId}`)
+ await page.goto(`/c/channels/${serverId}/${channelId}?msg=${anchorId}`)
await expect(page.getByTestId(tid.message(anchorId))).toBeVisible({ timeout: 30_000 })
const jumpButton = page.getByRole("button", { name: "Jump to present", exact: true })
await expect(jumpButton).toBeVisible({ timeout: 20_000 })
diff --git a/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.ts b/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.ts
index 747552850..912e566b7 100644
--- a/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.ts
+++ b/src/web/src/test/e2e-ui/18-new-divider-scroll.spec.ts
@@ -78,11 +78,20 @@ test("NEW divider does not fight upward scrolling while a peer message arrives",
})
await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)
await page.waitForURL(new RegExp(channelId), { timeout: 20_000, waitUntil: "commit" })
- const divider = page.getByTestId(tid.newDivider)
- await expect(divider).toBeVisible({ timeout: 30_000 })
-
const scroller = page.getByTestId(tid.messageScroller)
await expect(scroller).toHaveCount(1)
+ await expect.poll(() => scroller.evaluate(root => root.scrollHeight - root.clientHeight - root.scrollTop)).toBeLessThanOrEqual(1)
+ const jumpToNew = page.getByTestId(tid.scrollToNew)
+ await expect(jumpToNew).toBeVisible({ timeout: 30_000 })
+ await jumpToNew.click()
+ const divider = page.getByTestId(tid.newDivider)
+ await expect(divider).toBeInViewport()
+ await expect.poll(() => divider.evaluate((element, scrollerTestId) => {
+ const root = element.closest(`[data-testid="${scrollerTestId}"]`)!
+ return Math.abs(element.getBoundingClientRect().top - root.getBoundingClientRect().top)
+ }, tid.messageScroller)).toBeLessThanOrEqual(1)
+ await expect(jumpToNew).toBeHidden()
+
const box = await scroller.boundingBox()
expect(box).not.toBeNull()
await page.mouse.move(box!.x + box!.width / 2, box!.y + box!.height / 2)
diff --git a/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts b/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts
index 69082055c..3b2c70346 100644
--- a/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts
+++ b/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts
@@ -512,15 +512,17 @@ test("a visible live tail clears both devices while an unseen tail stays unread"
const channelId = await seedChannel("alice", serverId, `visible-sync-${stamp}`)
const siblingId = await seedChannel("alice", serverId, `visible-sibling-${stamp}`)
await seedJoinServer("alice", "bob", serverId)
+ let firstBaselineId = ""
for (let index = 0; index < 28; index += 1) {
- await seedMessage("alice", channelId, `visible baseline ${index} ${stamp}`)
+ const id = await seedMessage("alice", channelId, `visible baseline ${index} ${stamp}`)
+ if (index === 0) firstBaselineId = id
}
const deviceA = await asUser("bob")
const deviceB = await asUser("bob")
const proxyA = await proxyCommunityWebSockets(deviceA.context)
const proxyB = await proxyCommunityWebSockets(deviceB.context)
- await gotoAfterUserWsAuth(deviceA.page, `/c/channels/${serverId}/${channelId}`)
+ await gotoAfterUserWsAuth(deviceA.page, `/c/channels/${serverId}/${channelId}?msg=${firstBaselineId}`)
await gotoAfterUserWsAuth(deviceB.page, `/c/channels/${serverId}/${siblingId}`)
await deviceB.page.getByRole("button", { name: "Inbox" }).click()
await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(channelId))).toBeVisible()
diff --git a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
index 83b3e8d9f..5c1dac601 100644
--- a/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
+++ b/src/web/src/test/e2e-ui/39-mobile-message-interactions.spec.ts
@@ -1095,15 +1095,25 @@ test("mobile reply, avatar mention, and typing rail keep exact backend and WS id
await expect.poll(() => dmScroller.evaluate((element) => (
element.scrollHeight - element.clientHeight
))).toBeGreaterThan(1600)
- const departedDmScrollTop = await dmScroller.evaluate((element) => {
- element.scrollTop = 900
+ const dmDeparture = await dmScroller.evaluate((element, messageId) => {
+ const message = Array.from(element.querySelectorAll<HTMLElement>("[data-msg-id]"))
+ .find(row => row.dataset.msgId === messageId)
+ const body = message?.querySelector<HTMLElement>("[data-community-message-body]")
+ if (!body) throw new Error(`Missing departure fixture body: ${messageId}`)
+ const rect = body.getBoundingClientRect()
+ const requested = Math.round(element.scrollTop + rect.top - element.getBoundingClientRect().top
+ + Math.min(900, rect.height / 2))
+ element.scrollTop = requested
element.dispatchEvent(new Event("scroll"))
- return element.scrollTop
- })
- expect(departedDmScrollTop).toBe(900)
+ return { requested, actual: element.scrollTop }
+ }, dmScrollMessageId)
+ expect(dmDeparture.actual).toBe(dmDeparture.requested)
const dmReadState = await settledReadState(alice.page, dmId)
const dmReadingPosition = await settledReadingPosition(dmScroller)
- expect(Math.abs(dmReadingPosition.scrollTop - departedDmScrollTop)).toBeLessThanOrEqual(1)
+ const departedDmFixture = dmReadingPosition.rows.find(row => row.id === dmScrollMessageId)
+ expect(departedDmFixture, `visible departure fixture ${dmScrollMessageId}`).toBeDefined()
+ expect(departedDmFixture?.paragraphs).toEqual(dmScrollLines)
+ expect(Math.abs(dmReadingPosition.scrollTop - dmDeparture.actual)).toBeLessThanOrEqual(1)
expect(dmReadingPosition.scrollHeight - dmReadingPosition.clientHeight - dmReadingPosition.scrollTop).toBeGreaterThan(1)
const departedDmRoot = await readingRoot(dmScroller)
const dmReturnGets = trackSurfaceGets(alice.page, dmId)
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 e7f2dbb8a..40f70b989 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
@@ -341,9 +341,6 @@ test("server unread owns exact rail geometry, folder aggregation, read clear, an
void clearResponse.catch(() => {})
await page.getByTestId(tid.channelRow(backgroundChannel)).click()
await expect(page.getByTestId(tid.message(lastMessageId))).toBeVisible()
- 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)
diff --git a/src/web/src/test/e2e-ui/55-history-local-remote-owners.spec.ts b/src/web/src/test/e2e-ui/55-history-local-remote-owners.spec.ts
index 5f380dc9f..7c6a2c4e0 100644
--- a/src/web/src/test/e2e-ui/55-history-local-remote-owners.spec.ts
+++ b/src/web/src/test/e2e-ui/55-history-local-remote-owners.spec.ts
@@ -1,5 +1,5 @@
import { communityFixtureFetch } from "./_fixtures/business-contract"
-import type { CommunityConversationEntryRead } from "@alook/shared"
+import { CommunityMessagesReadSchema, type CommunityConversationEntryRead } from "@alook/shared"
import { test, expect } from "./_fixtures/case-fixture"
import { gotoAfterUserWsAuth, sendMessage } from "./_fixtures/actions"
import { communityFrameEvents, proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"
@@ -40,8 +40,29 @@ test("local history submission and passive remote append use distinct owners", a
expect(anchored.status()).toBe(200)
expectPublicCommunityDocument(await (await documentResponse).text())
const anchorPage = await anchored.json() as CommunityConversationEntryRead
- expect(anchorPage.selection.reason).toBe("read_pointer")
- expect(anchorPage.page.hasMoreNewer).toBe(true)
+ expect(anchorPage.selection.reason).toBe("tail")
+ expect(anchorPage.page.hasMoreNewer).toBe(false)
+ await expect.poll(() => scroller.evaluate(root => root.scrollHeight - root.clientHeight - root.scrollTop)).toBeLessThanOrEqual(1)
+ const newTarget = anchorPage.newBoundary.target
+ expect(newTarget).not.toBeNull()
+ const historyResponse = alice.page.waitForResponse(response => {
+ const url = new URL(response.url())
+ return response.request().method() === "GET" && url.pathname === `/api/community/channels/${channelId}/messages`
+ && url.searchParams.get("anchor") === newTarget!.id && !url.searchParams.has("entry")
+ })
+ const newAction = alice.page.getByTestId(tid.scrollToNew)
+ await expect(newAction).toBeVisible()
+ await newAction.click()
+ const history = await historyResponse
+ expect(history.ok()).toBe(true)
+ const historyPage = CommunityMessagesReadSchema.parse(await history.json())
+ expect(historyPage.page.hasMoreNewer).toBe(true)
+ expect(historyPage.messages.some(message => message.id === newTarget!.id)).toBe(true)
+ const newDivider = alice.page.getByTestId(tid.newDivider)
+ await expect.poll(() => newDivider.evaluate((element, scrollerTestId) => Math.abs(element.getBoundingClientRect().top
+ - element.closest(`[data-testid="${scrollerTestId}"]`)!.getBoundingClientRect().top), tid.messageScroller)).toBeLessThanOrEqual(1)
+ await expect(newAction).toBeHidden()
+ await expect(scroller.locator('[data-message-list-content]')).toHaveAttribute("data-read-position-ready", "true")
let newestGets = 0
alice.page.on("request", request => {
const url = new URL(request.url())
diff --git a/src/web/src/test/e2e-ui/55-jump-peer-tail-follow.spec.ts b/src/web/src/test/e2e-ui/55-jump-peer-tail-follow.spec.ts
index 5f78732c4..b87ec81de 100644
--- a/src/web/src/test/e2e-ui/55-jump-peer-tail-follow.spec.ts
+++ b/src/web/src/test/e2e-ui/55-jump-peer-tail-follow.spec.ts
@@ -14,7 +14,7 @@ test("jumping to present lets the next peer message follow the tail", async ({ c
const alice = await actors.asUser("alice")
await alice.page.setViewportSize(VIEWPORT)
const proxy = await proxyCommunityWebSockets(alice.context)
- await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${channelId}`)
+ await gotoAfterUserWsAuth(alice.page, `/c/channels/${serverId}/${channelId}?msg=${profile.ids[23]}`)
const scroller = alice.page.getByTestId(tid.messageScroller)
await expect(scroller).toBeVisible({ timeout: 30_000 })
const present = alice.page.getByTestId(tid.scrollToPresent)
diff --git a/src/web/src/test/e2e-ui/55-scroll-loading-prepend-jump.spec.ts b/src/web/src/test/e2e-ui/55-scroll-loading-prepend-jump.spec.ts
index 788436e84..1e79ae3e7 100644
--- a/src/web/src/test/e2e-ui/55-scroll-loading-prepend-jump.spec.ts
+++ b/src/web/src/test/e2e-ui/55-scroll-loading-prepend-jump.spec.ts
@@ -8,7 +8,7 @@ test("cold and warm loading, older prepend, and jump-to-present remain observabl
test.setTimeout(180_000)
const actors = await caseActors(["alice", "bob", "carol"])
const asUser = tracedAsUser(actors)
- const { serverId, coldChannelId, loadingChannelId, loadingProfile } = await seedScrollCase(actors)
+ const { serverId, coldChannelId, loadingChannelId, upwardChannelId, loadingProfile } = await seedScrollCase(actors)
const alice = await asUser("alice")
await alice.page.setViewportSize(VIEWPORT)
@@ -82,8 +82,8 @@ test("cold and warm loading, older prepend, and jump-to-present remain observabl
await mobileInitialMessages.dispose()
await installScrollTraceInCurrentDocument(alice.page)
- await alice.page.getByTestId(tid.channelRow(loadingChannelId)).click()
- await alice.page.waitForURL(new RegExp(loadingChannelId), { waitUntil: "commit" })
+ await alice.page.getByTestId(tid.channelRow(upwardChannelId)).click()
+ await alice.page.waitForURL(new RegExp(upwardChannelId), { waitUntil: "commit" })
await expect(alice.page.getByTestId(tid.messageScroller)).toBeVisible()
const warmRequest = await holdNextRequest(actors,
alice.page,
@@ -115,7 +115,15 @@ test("cold and warm loading, older prepend, and jump-to-present remain observabl
await anchored.page.setViewportSize(VIEWPORT)
await installScrollTrace(anchored.page)
await anchored.page.goto(`/c/channels/${serverId}/${loadingChannelId}`, { waitUntil: "commit" })
+ const anchoredScroller = anchored.page.getByTestId(tid.messageScroller)
+ await expect.poll(() => anchoredScroller.evaluate(root => root.scrollHeight - root.clientHeight - root.scrollTop)).toBeLessThanOrEqual(1)
+ const newAction = anchored.page.getByTestId(tid.scrollToNew)
+ await expect(newAction).toBeVisible({ timeout: 30_000 })
+ await newAction.click()
const anchoredNewDivider = anchored.page.getByTestId(tid.newDivider)
+ await expect.poll(() => anchoredNewDivider.evaluate((element, scrollerTestId) => Math.abs(element.getBoundingClientRect().top
+ - element.closest(`[data-testid="${scrollerTestId}"]`)!.getBoundingClientRect().top), tid.messageScroller)).toBeLessThanOrEqual(1)
+ await expect(newAction).toBeHidden()
await expect(async () => {
expect(await anchoredNewDivider.count()).toBe(1)
expect(await anchoredNewDivider.isVisible()).toBe(true)
diff --git a/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.ts b/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.ts
index 34dbdb98e..0717452de 100644
--- a/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.ts
+++ b/src/web/src/test/e2e-ui/59-message-pagination-anchor.spec.ts
@@ -4,6 +4,7 @@ import type { Page, Route } from "@playwright/test"
import { test, expect } from "./_fixtures/case-fixture"
import { tid } from "./_fixtures/testids"
+import { createScrollTraceIdentity } from "./_fixtures/scroll-trace"
import { WEB_URL } from "./_setup/paths"
import { gotoAfterUserWsAuth } from "./_fixtures/actions"
import type { CaseActors, CaseResources } from "./_fixtures/case-fixture"
@@ -233,12 +234,8 @@ test("older and newer pages preserve a real-message anchor and do not replay", a
olderRequests.push(url.search)
}
})
- await olderUser.page.goto(`/c/channels/${serverId}/${channelId}`, { waitUntil: "commit" })
- const olderNewDivider = olderUser.page.getByTestId(tid.newDivider)
- await expect(async () => {
- expect(await olderNewDivider.count()).toBe(1)
- expect(await olderNewDivider.isVisible()).toBe(true)
- }).toPass({ timeout: 30_000 })
+ await olderUser.page.goto(`/c/channels/${serverId}/${channelId}?msg=${ids[65]}`, { waitUntil: "commit" })
+ await expect(olderUser.page.getByTestId(tid.message(ids[65]))).toBeInViewport({ timeout: 30_000 })
await expect(olderUser.page.getByTestId(tid.messageScroller).locator('[data-message-list-content][data-read-position-ready="true"][data-initial-position-phase="revealed"]')).toBeVisible()
const olderPage = await holdNextPage(olderUser.page, channelId, "cursor", caseResources)
await moveToEdge(olderUser.page, "start")
@@ -260,12 +257,8 @@ test("older and newer pages preserve a real-message anchor and do not replay", a
newerRequests.push(url.search)
}
})
- await newerUser.page.goto(`/c/channels/${serverId}/${channelId}`, { waitUntil: "commit" })
- const newerNewDivider = newerUser.page.getByTestId(tid.newDivider)
- await expect(async () => {
- expect(await newerNewDivider.count()).toBe(1)
- expect(await newerNewDivider.isVisible()).toBe(true)
- }).toPass({ timeout: 30_000 })
+ await newerUser.page.goto(`/c/channels/${serverId}/${channelId}?msg=${ids[65]}`, { waitUntil: "commit" })
+ await expect(newerUser.page.getByTestId(tid.message(ids[65]))).toBeInViewport({ timeout: 30_000 })
await expect(newerUser.page.getByTestId(tid.messageScroller).locator('[data-message-list-content][data-read-position-ready="true"][data-initial-position-phase="revealed"]')).toBeVisible()
const newerPage = await holdNextPage(newerUser.page, channelId, "since", caseResources)
await moveToEdge(newerUser.page, "end")
@@ -279,7 +272,7 @@ test("older and newer pages preserve a real-message anchor and do not replay", a
await testInfo.attach("pagination-anchor-trajectory.json", {
body: JSON.stringify({
- sourceSha: "b1ea24a7f73778717662b5d894f1e14b019c8c08",
+ sourceSha: createScrollTraceIdentity({ account: actors.userId("alice"), channel: channelId, viewport: VIEWPORT }).sourceSha,
older: { before: olderBefore, after: olderAfter, retainedOffset: olderRetainedOffset, requests: olderRequests },
newer: { before: newerBefore, after: newerAfter, retainedOffset: newerRetainedOffset, requests: newerRequests },
}, null, 2),