Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(web): preserve qualified conversation reading and content (#1032)
Gener86e2fc7ad39e
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 91b2fb4b9..0cb499438 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -94,6 +94,55 @@ chore(deps): update dependenciesUse the body to explain *what and why*, not how. Reference issues with `Closes #123`.+## Community conversation maintenance contract++Forums are channels with a different presentation. Share account/access qualification, canonical entities, message commands and reading ownership. Keep post ID windows, tag filters and retained view lifetimes where their consumers require them.++### State owners and cache coverage++| State | Owner and contract |+|---|---|+| Canonical channel, message, membership and read facts | [community DB](src/web/src/lib/community-db/sync.ts). HTTP and WS publish through the same qualified writers. Transport windows contain IDs, cursors and page boundaries. |+| Entry qualification and selected window | [conversation-entry](src/web/src/lib/community/conversation-entry.ts) and [use-conversation-entry](src/web/src/hooks/community/use-conversation-entry.ts). Bind account, channel/server, access generation, original request and Query identity. A cached entity or anchor parameter alone does not prove target coverage. |+| Local reading and PUT confirmation | [read-coordinator](src/web/src/hooks/community/read-coordinator.ts). Keep exact accepted message ID/sequence and original authority. Normal viewport progress survives release, ACK and failed canonical readback; cancel-uncommitted opener handoff does not supply a viewport position. |+| Initial viewport and active user input | [use-scroll-anchor](src/web/src/hooks/community/use-scroll-anchor.ts). A fresh ordinary entry can consume a newer qualified local target once. Explicit message/sequence navigation wins; active entries and retained parent resume keep their original position ownership. |+| Navigation completion and role display | [navigation controller](src/web/src/components/community/shell/use-community-navigation-controller.ts), [shell frame](src/web/src/components/community/shell/shell-frame.tsx), [channel route](src/web/src/components/community/channels/channel-route.tsx) and [member VM](src/web/src/components/community/members/channel-member-view-model.tsx). The existing navigation owner completes URL publication plus structural frame; the existing server-role authority supplies display facts. |++Use a qualified cached window only when its IDs and complete canonical entities cover the requested target. Display and position from that coverage immediately while an ordinary entry refresh runs in the background. A missing ordinary-entry key does not retire another valid entry's qualification. Otherwise obtain coverage through the existing entry/window request. Preserve valid older windows and the actual selected Query's pages/page parameters. Landing reconciliation carries its sequence high waterline through the existing [reconnect owner](src/web/src/hooks/community/community-ws/reconnect-messages.ts), including a newer requirement that arrives during an older read.++Freshness and retention are different. Entry and message-window options own stale/GC policy; [query-persister](src/web/src/lib/query-persister.ts) owns the bounded persisted closure and restore eligibility. A prior visit, restored entity or fresh metadata does not establish an available, qualified landing window. Account retirement and channel/parent access generation changes retire original authority before reuse; never recapture new permission for old work or carry an old generation's maximum into the new one.++Presence revisions protect confirmed rows from older snapshot omissions. An existing row may accept an in-flight snapshot when only its presence revision is newer; a real newer field update retains the existing whole-row protection.++### Request, merge and action boundaries++Capture account, target and allowed lifetime before an async command. Keep that qualification through transport, authentication effects and canonical publication. View-dependent actions also keep their original view guard. An accepted send has its existing account/target lifetime across view changes; that does not authorize old UI completion or a stale retry.++| Action | Required merge/display boundary |+|---|---|+| Entry, pagination, explicit jump, present | Existing Query/window owner reads and reconciles IDs. Keep the selected window and captured canonical read snapshot; do not wait for all background synchronization or clear unrelated caches. |+| Read | Real visible reading admits the intent. Local progress, server-confirmed sequence and canonical read snapshot are separate. Local and confirmed progress each advance monotonically within a valid generation; jumping to older content changes the viewport only. |+| Send, edit, reaction, pin, mark, tags and thread actions | Existing command/transaction owners publish their qualified result. Preserve field revisions, original optimistic rollback and newer WS facts; one command's completion cannot settle another view or overwrite a newer field. |+| First-body edit and forum preview | The shared accepted content writer mirrors full content only for exact child `firstMessageId`. Mirror optimistic content in the same native transaction. HTTP acceptance of another field does not authorize rejected content. Title/opener, later replies and missing first-body identity do not grant preview ownership. Keep the forum ID window. |+| Back and resumed-parent role display | `hasPendingParentReturn` derives the accepted return from the original resume intent and exact pending target/state. Repeated Back merges until URL and structural frame both complete; the next Back then goes higher. Ordinary forward cancellation remains. `roleDisplayAllowed` can use qualified cached own role for a ready/hydrated resumed forum; member reads and action source guards still require their original access/current view. |++Preserve each action's existing confirmation model: Pin/Mark update after ACK; forum posting uses two HTTP commands and does not promise an atomic post transaction. Ordinary message deletion is not a supported action. Post archive/deletion keep their existing qualified command and retirement paths.++### Display evidence and regressions++[use-messages](src/web/src/hooks/community/use-messages.ts) exposes `historyStartKnown` only when the selected qualified page explicitly confirms no older history. Leading and empty heroes require that evidence. No selected page means unknown history, even if live rows are visible. Content visibility and read-position readiness remain separate; showing content alone does not acknowledge reading. `initialPositionMessageId` supplies only the one-shot local landing, without rewriting canonical snapshot/NEW or fabricating server confirmation.++The target root in [CommunityPendingFrame](src/web/src/components/community/shell/community-pending-frame.tsx) paints the theme background over retained content during cross-scope loading. Preserve old DOM/inert and drawer-exit ownership. Opaque coverage does not require another MobilePage, transition state, request or fixed animation wait.++Keep these existing regression entry points when changing the contract:++- Reading/coverage and canonical roles: `use-conversation-entry.dom.test.tsx`, `read-coordinator.test.ts`, `use-read-observer.dom.test.ts`, `use-messages.window.dom.test.tsx`, `use-scroll-anchor.repin.dom.test.ts`, `use-servers.dom.test.ts` under `src/web/src/hooks/community/`.+- Boundary display: `message-list-row.dom.test.ts`, `message-list-view.dom.test.ts`, `message-list.older-load.dom.test.ts` under `src/web/src/components/community/messages/`.+- Content/commands: `forum-preview-live-edit.dom.test.ts`, `accepted-send-lifecycle.dom.test.ts` and `mutations/message-field-owner.dom.test.tsx` under `src/web/src/hooks/community/`.+- Navigation/role/target container: `shell-frame.dom.test.ts`, `use-community-navigation-controller.dom.test.ts`, `community-pending-frame.dom.test.ts`, `channel-route.text-scroll-target.dom.test.ts` and `channel-member-view-model.dom.test.ts` in their corresponding component directories.++Use the normal Web Vitest configs and repository gates. Real QA must also bind target/scope, actual input, visible landing and backend read/message evidence. HTTP body completion, canonical publication and final viewport are different events; component/system-event controls do not establish native bridge behavior.+## Testing- **Framework:** Vitestdiff --git a/src/web/src/components/community/channels/dm-view.tsx b/src/web/src/components/community/channels/dm-view.tsxindex b0abd0ff8..40cb39968 100644--- a/src/web/src/components/community/channels/dm-view.tsx+++ b/src/web/src/components/community/channels/dm-view.tsx@@ -125,6 +125,8 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCommessages: fetchedMessages,isLoading: messagesLoading,hasMoreOlder: hasMoreMessages,+ historyStartKnown,+ initialPositionMessageId,hasMoreNewer: hasMoreNewerMessages,isFetchingOlder: isFetchingOlderMessages,isFetchingNewer: isFetchingNewerMessages,@@ -468,6 +470,8 @@ export function DmView({ dmId, routeCommitted = true }: { dmId: string; routeCom// `anchorInCache`'s doc comment above.initialScrollReady={!readSnapshotFetching && (anchorInCache || initialPositionKnown)}hasMore={hasMoreMessages}+ historyStartKnown={historyStartKnown}+ initialPositionMessageId={initialPositionMessageId}isFetching={messagesFetching}isFetchingOlder={isFetchingOlderMessages}onLoadOlder={fetchOlderMessages}diff --git a/src/web/src/components/community/channels/text-channel-surface.tsx b/src/web/src/components/community/channels/text-channel-surface.tsxindex 00faaf60c..4aeddbcde 100644--- a/src/web/src/components/community/channels/text-channel-surface.tsx+++ b/src/web/src/components/community/channels/text-channel-surface.tsx@@ -159,6 +159,8 @@ export function TextChannelSurface({initialScrollReady={!feed.readSnapshotFetching && feed.anchorInCache}onScrollTargetConsumed={controller.consumeScrollTarget}hasMore={feed.hasMoreOlder}+ historyStartKnown={feed.historyStartKnown}+ initialPositionMessageId={feed.initialPositionMessageId}isFetching={feed.isFetching}isFetchingOlder={feed.isFetchingOlder}onLoadOlder={feed.fetchOlder}diff --git a/src/web/src/components/community/channels/thread-channel-surface.tsx b/src/web/src/components/community/channels/thread-channel-surface.tsxindex 852779e40..679039ba4 100644--- a/src/web/src/components/community/channels/thread-channel-surface.tsx+++ b/src/web/src/components/community/channels/thread-channel-surface.tsx@@ -271,6 +271,8 @@ export function ThreadChannelSurface({initialScrollReady={!controller.feed.readSnapshotFetching && controller.feed.anchorInCache}onScrollTargetConsumed={controller.consumeScrollTarget}hasMore={controller.feed.hasMoreOlder}+ historyStartKnown={controller.feed.historyStartKnown}+ initialPositionMessageId={controller.feed.initialPositionMessageId}isFetching={controller.feed.isFetching}isFetchingOlder={controller.feed.isFetchingOlder}onLoadOlder={controller.feed.fetchOlder}diff --git a/src/web/src/components/community/messages/message-list-controller.ts b/src/web/src/components/community/messages/message-list-controller.tsindex 32d0e1f48..c97cff070 100644--- a/src/web/src/components/community/messages/message-list-controller.ts+++ b/src/web/src/components/community/messages/message-list-controller.ts@@ -15,6 +15,7 @@ export function useMessageListController({initialLoadError,newDividerBefore,scrollToMessageId,+ initialPositionMessageId,initialScrollReady,hasMore,hasMoreNewer,@@ -99,6 +100,7 @@ export function useMessageListController({newDividerBefore,initialScrollReady,scrollToMessageId,+ initialPositionMessageId,onScrollTargetCancelled: onScrollTargetConsumed,onScrollTargetPositioned: (id) => { setJumped(id); setJumpRevision((value) => value + 1); onScrollTargetConsumed?.(id) },hasMoreNewer,diff --git a/src/web/src/components/community/messages/message-list-facade.contract.test.ts b/src/web/src/components/community/messages/message-list-facade.contract.test.tsindex 5fec6f56b..c0a26f587 100644--- a/src/web/src/components/community/messages/message-list-facade.contract.test.ts+++ b/src/web/src/components/community/messages/message-list-facade.contract.test.ts@@ -31,6 +31,7 @@ type ExpectedMessageListProps = {onPreviewAttachment?: (attachment: FileAttachment) => voidresolveUserName?: (userId: string) => stringscrollToMessageId?: string | null+ initialPositionMessageId?: string | nullhero?: ReactNodevariant?: "channel" | "dm"onScrollRoot?: (element: HTMLDivElement | null) => void@@ -38,6 +39,7 @@ type ExpectedMessageListProps = {initialScrollReady?: booleanonScrollTargetConsumed?: (id: string) => voidhasMore?: boolean+ historyStartKnown?: booleanisFetching?: booleanisFetchingOlder?: booleanonLoadOlder?: () => voiddiff --git a/src/web/src/components/community/messages/message-list-row.tsx b/src/web/src/components/community/messages/message-list-row.tsxindex 29cb7bcc8..adfc497eb 100644--- a/src/web/src/components/community/messages/message-list-row.tsx+++ b/src/web/src/components/community/messages/message-list-row.tsx@@ -30,7 +30,7 @@ export function renderMessageListRow(return (<div className="flow-root" data-message-row-key={item.key}><div className="flex flex-col gap-2 py-4">- {props.hasMore ? (+ {!props.historyStartKnown ? (<div className="flex h-8 items-center justify-center text-xs text-muted-foreground">{props.isFetchingOlder ? "Loading older messages…" : ""}</div>diff --git a/src/web/src/components/community/messages/message-list-types.ts b/src/web/src/components/community/messages/message-list-types.tsindex ca6d212af..c277bbd44 100644--- a/src/web/src/components/community/messages/message-list-types.ts+++ b/src/web/src/components/community/messages/message-list-types.ts@@ -31,6 +31,7 @@ export type MessageListProps = {onPreviewAttachment?: (attachment: FileAttachment) => voidresolveUserName?: (userId: string) => stringscrollToMessageId?: string | null+ initialPositionMessageId?: string | nullhero?: ReactNodevariant?: "channel" | "dm"onScrollRoot?: (el: HTMLDivElement | null) => void@@ -38,6 +39,7 @@ export type MessageListProps = {initialScrollReady?: booleanonScrollTargetConsumed?: (id: string) => voidhasMore?: boolean+ historyStartKnown?: booleanisFetching?: booleanisFetchingOlder?: booleanonLoadOlder?: () => voiddiff --git a/src/web/src/components/community/messages/message-list-view.dom.test.ts b/src/web/src/components/community/messages/message-list-view.dom.test.tsindex 608fab0de..11ca40ff8 100644--- a/src/web/src/components/community/messages/message-list-view.dom.test.ts+++ b/src/web/src/components/community/messages/message-list-view.dom.test.ts@@ -305,9 +305,11 @@ describe("renderMessageListView", () => {expect(content).toHaveAttribute("data-read-position-ready", "false")expect(renderer.queryByText(/Beginning of the channel/)).toBeNull()expect(renderer.container.querySelectorAll(".h-8")).toHaveLength(0)- renderer.rerender(renderMessageListView(props({ messages: [] }), state, renderRows))+ renderer.rerender(renderMessageListView(props({ messages: [], historyStartKnown: true }), state, renderRows))expect(content).toHaveClass("pt-8", "justify-end", "min-h-full")expect(renderer.getByText(/Beginning of the channel/)).toBeInTheDocument()+ renderer.rerender(renderMessageListView(props({ messages: [] }), state, renderRows))+ expect(renderer.queryByText(/Beginning of the channel/)).toBeNull()})it("keeps the original scroller mounted through a cold error and retry, without rendering an empty hero", () => {diff --git a/src/web/src/components/community/messages/message-list-view.tsx b/src/web/src/components/community/messages/message-list-view.tsxindex 28eb9762c..98d26a7d9 100644--- a/src/web/src/components/community/messages/message-list-view.tsx+++ b/src/web/src/components/community/messages/message-list-view.tsx@@ -67,7 +67,7 @@ export function renderMessageListView(<>{props.messages.length === 0? <>- <div className="mb-6">{renderMessageListHero(props)}</div>+ {props.historyStartKnown && <div className="mb-6">{renderMessageListHero(props)}</div>}<div aria-hidden="true" data-message-empty-tail className="shrink-0" style={{ height: CONVERSATION_TAIL_SPACE_PX }} /></>: renderRows()}diff --git a/src/web/src/hooks/community/forum-preview-live-edit.dom.test.ts b/src/web/src/hooks/community/forum-preview-live-edit.dom.test.tsindex a631b9a2d..b1914615b 100644--- a/src/web/src/hooks/community/forum-preview-live-edit.dom.test.ts+++ b/src/web/src/hooks/community/forum-preview-live-edit.dom.test.ts@@ -4,7 +4,7 @@ import { act, renderHook, waitFor } from "@/test/react-dom-harness"import { CommunityTestProvider } from "@/test/community-owner-fixture"import { createCommunityQueryOwner } from "@/test/community-query-owner"import { dispatchCommunityWsEvent } from "./community-ws/registry"-import { captureCommunityLiveSnapshotToken, publishCommunityForumFeed, publishCommunityMessages } from "@/lib/community-db/sync"+import { captureCommunityLiveSnapshotToken, publishCommunityForumFeed, publishCommunityMessages, publishCommunityMessageFields } from "@/lib/community-db/sync"import { normalizeThreadResources } from "./forum-feed-window"import { forumConversationEntryFixture } from "@/test/conversation-entry-fixtures"import { conversationEntryOptions, publishConversationEntry } from "@/lib/community/conversation-entry"@@ -16,6 +16,7 @@ vi.mock("./use-channel-panels", () => ({useForumTags: () => ({ data: { tags: [] }, isSuccess: true }),}))import { useForumFeed } from "./use-forum-feed"+import { useEditMessage } from "./mutations/messages"const original = "original first body ".repeat(34)const edited = "edited first body with complete content ".repeat(29)@@ -53,7 +54,7 @@ async function mount(contractVersion: 2 | 3 = 2, firstSeq = 1) {function Wrapper({ children }: PropsWithChildren) {return createElement(CommunityTestProvider, { client: owner.client, registry: owner.registry }, children)}- const view = renderHook(() => useForumFeed("server", "forum"), { wrapper: Wrapper })+ const view = renderHook(() => ({ ...useForumFeed("server", "forum"), editCommand: useEditMessage() }), { wrapper: Wrapper })await waitFor(() => expect(view.result.current.posts.find((post) => post.id === "post")?.preview).toBe(original))const context = { contract: contractVersion, deliveryMode: "single" as const,queryClient: owner.client, communityStore: owner.runtime.ui, wsStore: owner.runtime.ws,@@ -67,6 +68,71 @@ async function mount(contractVersion: 2 | 3 = 2, firstSeq = 1) {}describe("Forum first body through the actual edited dispatcher", () => {+ it("keeps the same forum window and confirms its exact first-body preview after HTTP edit without self WS", async () => {+ const view = await mount(3, 7)+ const key = communityKeys.forumFeed("forum", null)+ const window = view.client.getQueryData(key)+ let resolve!: (value: unknown) => void+ let command!: Promise<unknown>+ apiFetch.mockImplementation((_path: string, options?: { method?: string }) => options?.method === "PATCH"+ ? new Promise(done => { resolve = done })+ : Promise.resolve(page(3, 7)))+ try {+ expect(view.registry.collections.channels.get("post")?.firstMessageId).toBe("first")+ expect(view.registry.collections.messages.get("first")?.seq).toBe(7)+ act(() => { command = view.result.current.editCommand.mutateAsync({ serverId: "server", channelId: "post", messageId: "first", content: edited }) })+ await waitFor(() => expect(resolve).toBeTypeOf("function"))+ expect(view.registry.collections.messages.get("first")?.content).toBe(edited)+ await waitFor(() => expect(view.preview()).toBe(edited))+ expect(view.client.getQueryData(key)).toBe(window)+ await act(async () => { resolve(undefined); await command })+ expect(view.registry.collections.messages.get("first")?.content).toBe(edited)+ expect(view.client.getQueryData(key)).toBe(window)+ expect(view.preview("other")).toBe("Other original")+ expect(apiFetch.mock.calls.filter(([, options]) => options?.method === "PATCH")).toHaveLength(1)+ expect(view.preview()).toBe(edited)+ } finally {+ resolve?.(undefined)+ await command?.catch(() => undefined)+ view.unmount()+ }+ })++ it.each(["rollback", "WS then success", "WS then failure"] as const)("keeps first-body preview under the original edit transaction: %s", async outcome => {+ const view = await mount(3, 7)+ const key = communityKeys.forumFeed("forum", null), window = view.client.getQueryData(key)+ let resolve!: (value: unknown) => void, reject!: (reason: Error) => void+ apiFetch.mockImplementation((_path: string, options?: { method?: string }) => options?.method === "PATCH"+ ? new Promise((done, fail) => { resolve = done; reject = fail }) : Promise.resolve(page(3, 7)))+ let command!: Promise<unknown>+ try {+ act(() => { command = view.result.current.editCommand.mutateAsync({ serverId: "server", channelId: "post", messageId: "first", content: edited }).catch(error => error) })+ await waitFor(() => expect(resolve).toBeTypeOf("function"))+ await waitFor(() => expect(view.preview()).toBe(edited))+ if (outcome !== "rollback") view.edit("post", "first", "newer WS content")+ await act(async () => { if (outcome === "WS then success") resolve(undefined); else reject(new Error("edit denied")); await command })+ const expected = outcome === "rollback" ? original : "newer WS content"+ await waitFor(() => expect(view.preview()).toBe(expected))+ expect(view.registry.collections.messages.get("first")?.content).toBe(expected)+ expect(view.preview("other")).toBe("Other original")+ expect(view.client.getQueryData(key)).toBe(window)+ } finally { resolve?.(undefined); await command?.catch(() => undefined); view.unmount() }+ })++ it("does not mirror rejected content when another HTTP field is accepted", async () => {+ const view = await mount(3, 7)+ try {+ const token = captureCommunityLiveSnapshotToken(view.client, "post")+ view.edit("post", "first", "newer WS content")+ let published = false+ act(() => { published = publishCommunityMessageFields(view.client, "first", { content: "old HTTP content", authorName: "HTTP author" }, { token }) })+ expect(published).toBe(true)+ expect(view.registry.collections.messages.get("first")?.authorName).toBe("HTTP author")+ expect(view.registry.collections.messages.get("first")?.content).toBe("newer WS content")+ await waitFor(() => expect(view.preview()).toBe("newer WS content"))+ } finally { view.unmount() }+ })+it.each([{ contract: 2 as const, firstSeq: 1 }, { contract: 3 as const, firstSeq: 7 }])("updates the existing full preview from contract$contract first-body identity, not a sequence guess",async ({ contract, firstSeq }) => {diff --git a/src/web/src/hooks/community/mutations/messages.ts b/src/web/src/hooks/community/mutations/messages.tsindex 788b91658..beb05b4e1 100644--- a/src/web/src/hooks/community/mutations/messages.ts+++ b/src/web/src/hooks/community/mutations/messages.ts@@ -17,7 +17,7 @@ import { apiFetch, toastApiError } from "@/lib/api/client"import { ApiError, isAbortError } from "@/lib/errors"import { communityKeys } from "@/lib/query-keys"import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"-import { captureCommunityLiveSnapshotToken, publishCommunityMessageFields, publishCommunityMessages, publishCommunityCreatedChannel } from "@/lib/community-db/sync"+import { captureCommunityLiveSnapshotToken, publishCommunityMessageFields, publishCommunityMessages, publishCommunityCreatedChannel, updateCommunityMessageContentOptimistically } from "@/lib/community-db/sync"import { presentMessageAttachment } from "@/lib/community/attachment-presentation"import { attachmentThumbnailUrl, attachmentUrl } from "@/lib/community/storage"import {@@ -85,7 +85,7 @@ export function useEditMessage() {const registry = origin.registryawait registry?.readyorigin.assert(token); assertActive?.()- await registry!.collections.messages.preload()+ await Promise.all([registry!.collections.messages.preload(), registry!.collections.channels.preload()])origin.assert(token); assertActive?.()await Promise.all([queryClient.cancelQueries({ queryKey: communityKeys.channelMessages(channelId) }),@@ -104,11 +104,7 @@ export function useEditMessage() {} catch (error) { origin.assert(token); throw error }}const transaction = registry!.dbClient.createTransaction({ autoCommit: false, mutationFn: persist })- transaction.mutate(() => {- if (registry!.collections.messages.has(messageId)) {- registry!.collections.messages.update(messageId, (row) => { row.content = content })- }- })+ transaction.mutate(() => updateCommunityMessageContentOptimistically(registry!, messageId, content))try { if (transaction.mutations.length) await transaction.commit(); else await persist() } catch (error) { origin.assert(token); throw error }},})diff --git a/src/web/src/hooks/community/read-coordinator.test.ts b/src/web/src/hooks/community/read-coordinator.test.tsindex 5ffa76097..787d696c9 100644--- a/src/web/src/hooks/community/read-coordinator.test.ts+++ b/src/web/src/hooks/community/read-coordinator.test.ts@@ -37,6 +37,7 @@ import {disposeReadCoordinator,flushPendingReadIntents,getReadCoordinator,+ getLocalReadingPosition,projectReadCoordinatorSnapshot,READ_COORDINATOR_DEBOUNCE_MS,registerReadSurface,@@ -108,6 +109,54 @@ describe("read coordinator", () => {vi.useRealTimers()})+ it("retains exact normal reading after ACK and failed reconciliation without lowering local progress", async () => {+ const client = createOwnedClient(), lease = timelineLease(client)+ apiFetch.mockResolvedValue({ changed: true, revision: 1, targetSeq: 8 })+ reconcileAccountReadState.mockRejectedValue(new Error("readback unavailable"))+ expect(submitTimeline(lease, 8)).toBe(true)+ expect(submitTimeline(lease, 4)).toBe(false)+ expect(getLocalReadingPosition(client, "channel-1")).toEqual({ kind: "timeline", channelId: "channel-1", messageId: "message-8", seq: 8 })+ releaseReadSurface(lease)+ await vi.advanceTimersByTimeAsync(0)+ const scope = getReadCoordinator(client, "user-1").state.get().scopes.get("timeline:channel-1")!+ expect(scope.inFlight).toBeNull()+ expect(scope.confirmedSeq).toBe(8)+ expect(getLocalReadingPosition(client, "channel-1")?.messageId).toBe("message-8")+ })++ it("does not lend an opener handoff as a viewport reading position", () => {+ const client = createOwnedClient()+ const lease = registerReadSurface(client, "user-1", { kind: "timeline", channelId: "channel-1" }, 0, "cancel-uncommitted")+ expect(submitTimeline(lease, 8)).toBe(true)+ expect(getLocalReadingPosition(client, "channel-1")).toBeNull()+ releaseReadSurface(lease)+ expect(getLocalReadingPosition(client, "channel-1")).toBeNull()+ })++ it("retires local and confirmed maxima with original access instead of borrowing the next generation", () => {+ const client = createOwnedClient(), runtime = getCommunityDbRegistry(client)!.runtime+ runtime.ws.actions.rememberChannelAccess("server", "channel-1")+ const old = timelineLease(client, 40)+ expect(submitTimeline(old, 80)).toBe(true)+ client.setQueryData(communityKeys.accountReadStateSnapshot(), { revision: 1, readStates: [{ channelId: "channel-1", lastReadSeq: 80 }] })+ runtime.ws.actions.revokeChannelAccess("server", "channel-1")+ runtime.ws.actions.rememberChannelAccess("server", "channel-1")+ expect(getLocalReadingPosition(client, "channel-1")).toBeNull()+ expect(submitTimeline(old, 90)).toBe(false)+ const current = timelineLease(client, 2)+ expect(getReadCoordinator(client, "user-1").state.get().scopes.get("timeline:channel-1")?.confirmedSeq).toBe(2)+ expect(submitTimeline(current, 3)).toBe(true)+ expect(getLocalReadingPosition(client, "channel-1")?.seq).toBe(3)+ })++ it("drops local position when its original account retires", () => {+ const client = createOwnedClient(), lease = timelineLease(client)+ expect(submitTimeline(lease, 8)).toBe(true)+ getCommunityDbRegistry(client)!.runtime.ws.actions.activateProfileAccount("replacement")+ expect(getLocalReadingPosition(client, "channel-1")).toBeNull()+ expect(submitTimeline(lease, 9)).toBe(false)+ })+it("is an account-owned singleton and returns an unconsumed flush before and after disposal", async () => {const queryClient = createOwnedClient()expect(getReadCoordinator(queryClient, "user-1"))diff --git a/src/web/src/hooks/community/read-coordinator.ts b/src/web/src/hooks/community/read-coordinator.tsindex a2311c4f3..3cf02ef44 100644--- a/src/web/src/hooks/community/read-coordinator.ts+++ b/src/web/src/hooks/community/read-coordinator.ts@@ -4,7 +4,7 @@ import type { CommunityReadAdvanceSchema } from "@alook/shared"import type { z } from "zod"import { createStore } from "@tanstack/react-store"import type { Mutation, QueryClient } from "@tanstack/react-query"-import { communityRequestOptions } from "@/lib/community-db/sync"+import { communityRequestOptions } from "@/lib/community/account-cache-lifecycle"import { apiFetch } from "@/lib/api/client"import { ApiError } from "@/lib/errors"import { communityKeys } from "@/lib/query-keys"@@ -22,8 +22,10 @@ import {} from "./inbox-read-reservation"import { getAccountUnreadProjection } from "./account-unread-projection"import { getCommunityDbRegistry, type CommunityDbRegistry } from "@/lib/community-db/collections"+import type { ReadStateRow } from "@/lib/community-db/schema"import {clearAttentionScopeOptimistically,+ captureCommunityLiveSnapshotToken,commitAttentionScopeOptimisticSnapshot,hasAttentionScopeOptimisticFence,projectConfirmedAttention,@@ -79,6 +81,8 @@ type SurfaceLease = {type ScopeState = {surface: ReadSurface+ authority: ReturnType<typeof communityRequestOptions>+ localPosition: QueuedReadIntent | nullepoch: numberleases: Set<symbol>releaseTimer: ReturnType<typeof setTimeout> | null@@ -153,14 +157,25 @@ class ReadCoordinator {register(surface: ReadSurface, confirmedSeq: number, releasePolicy: SurfaceLease["releasePolicy"]): SurfaceLease {this.assertActive()- const key = scopeKey(surface), token = Symbol(key), current = this.scope(key)+ const registry = getCommunityDbRegistry(this.queryClient)+ const canonical = this.queryClient.getQueryData<ReadStateRow[]>(communityKeys.communityDbCollection(registry?.scopeId ?? "anon", "readStates"))?.find(row => row.channelId === surface.channelId)+ ?? registry?.collections.readStates.get(surface.channelId)+ confirmedSeq = Math.max(confirmedSeq, canonical?.lastReadSeq ?? 0)+ const key = scopeKey(surface), token = Symbol(key), previous = this.scope(key)+ const current = previous && this.authorityCurrent(previous) ? previous : undefined+ if (previous && !current) {+ if (previous.timer !== null) clearTimeout(previous.timer)+ if (previous.releaseTimer !== null) clearTimeout(previous.releaseTimer)+ previous.inFlight?.controller.abort()+ if (previous.attentionOptimistic) commitAttentionScopeOptimisticSnapshot(previous.attentionOptimistic.registry, previous.attentionOptimistic.snapshot)+ }if (current?.releaseTimer !== null && current?.releaseTimer !== undefined) clearTimeout(current.releaseTimer)const state: ScopeState = current? { ...current, confirmedSeq: Math.max(current.confirmedSeq, confirmedSeq), releaseTimer: null, leases: new Set([...current.leases, token]) }- : { surface: { ...surface }, epoch: 0, leases: new Set([token]), releaseTimer: null, timer: null, accepted: null, dirty: null, inFlight: null, attemptEpoch: 0, confirmedSeq, attentionOptimistic: null }+ : { surface: { ...surface }, authority: communityRequestOptions(this.queryClient, captureCommunityLiveSnapshotToken(this.queryClient, surface.channelId)), localPosition: null,+ epoch: (previous?.epoch ?? -1) + 1, leases: new Set([token]), releaseTimer: null, timer: null, accepted: null, dirty: null, inFlight: null, attemptEpoch: (previous?.attemptEpoch ?? -1) + 1, confirmedSeq, attentionOptimistic: null }this.state.setState((owner) => ({ ...owner, scopes: new Map(owner.scopes).set(key, state) }))- const cached = this.queryClient.getQueryData<ReadCoordinatorSnapshot>(communityKeys.accountReadStateSnapshot())- if (cached) this.applySnapshot(cached)+ if ([state.accepted, state.dirty, state.inFlight?.target].some(target => target && target.intent.seq <= state.confirmedSeq)) this.cancelConfirmedWork(key)return { coordinator: this, key, token, epoch: state.epoch, releasePolicy }}@@ -212,10 +227,11 @@ class ReadCoordinator {if (Math.max(state.accepted?.intent.seq ?? 0, state.dirty?.intent.seq ?? 0, state.inFlight?.target.intent.seq ?? 0) >= intent.seq) return nullconst superseded = [state.accepted, state.dirty].filter((pending) => pending && pending.intent.seq < intent.seq && pending.generation !== state.inFlight?.target.generation)const generation = this.latestIntentGeneration + 1- const queued: QueuedReadIntent = { intent: { ...intent }, generation, dueAt: Date.now() + READ_COORDINATOR_DEBOUNCE_MS, ownerToken: lease.token, request: communityRequestOptions(this.queryClient) }+ const queued: QueuedReadIntent = { intent: { ...intent }, generation, dueAt: Date.now() + READ_COORDINATOR_DEBOUNCE_MS, ownerToken: lease.token, request: state.authority }queued.request.assertActive()this.state.setState((owner) => ({ ...owner, latestIntentGeneration: generation }))- this.update(lease.key, (scope) => ({ ...scope, accepted: laterIntent(scope.accepted, queued), dirty: laterIntent(scope.dirty, queued) }))+ this.update(lease.key, (scope) => ({ ...scope, accepted: laterIntent(scope.accepted, queued), dirty: laterIntent(scope.dirty, queued),+ localPosition: lease.releasePolicy === "flush" ? laterIntent(scope.localPosition, queued) : scope.localPosition }))this.beginAttentionOptimisticRead(lease.key)for (const pending of superseded) getAccountUnreadProjection(this.queryClient, this.ownerUserId).settleOptimisticRead(pending!.generation, false)this.schedule(lease.key, READ_COORDINATOR_DEBOUNCE_MS)@@ -231,7 +247,7 @@ class ReadCoordinator {resume() {if (this.disposed) returnfor (const [key, scope] of this.state.get().scopes) {- if (!scope.dirty || scope.confirmedSeq >= scope.dirty.intent.seq) continue+ if (!this.authorityCurrent(scope) || !scope.dirty || scope.confirmedSeq >= scope.dirty.intent.seq) continuethis.update(key, (current) => ({ ...current, accepted: laterIntent(current.accepted, current.dirty!) }))this.schedule(key, 0)}@@ -241,11 +257,20 @@ class ReadCoordinator {if (this.disposed) returnconst byChannel = new Map(snapshot.readStates.map((row) => [row.channelId, row.lastReadSeq]))for (const [key, scope] of this.state.get().scopes) {+ if (!this.authorityCurrent(scope)) continuethis.update(key, (current) => ({ ...current, confirmedSeq: Math.max(current.confirmedSeq, byChannel.get(scope.surface.channelId) ?? 0) }))this.cancelConfirmedWork(key)}}+ localReadingPosition(channelId: string): ReadIntent | null {+ const scope = this.scope(scopeKey({ kind: "timeline", channelId }))+ const message = scope?.localPosition ? getCommunityDbRegistry(this.queryClient)?.collections.messages.get(scope.localPosition.intent.messageId) : undefined+ if (message && (message.channelId !== channelId || message.seq !== scope?.localPosition?.intent.seq)) return null+ return !this.disposed && scope && this.authorityCurrent(scope) && scope.localPosition+ ? { ...scope.localPosition.intent } : null+ }+dispose() {if (this.disposed) returnconst scopes = this.state.get().scopes@@ -484,11 +509,14 @@ class ReadCoordinator {private validState(lease: SurfaceLease) {const scope = this.scope(lease.key)- return !this.disposed && lease.coordinator === this && scope?.epoch === lease.epoch && scope.leases.has(lease.token) ? scope : null+ return !this.disposed && lease.coordinator === this && scope?.epoch === lease.epoch && scope.leases.has(lease.token) && this.authorityCurrent(scope) ? scope : null+ }+ private authorityCurrent(scope: ScopeState) {+ try { scope.authority.assertActive(); return true } catch { return false }}private attemptActive(key: string, attemptEpoch: number, identityEpoch: number) {const scope = this.scope(key)- return !this.disposed && this.state.get().identityEpoch === identityEpoch && scope?.inFlight?.attemptEpoch === attemptEpoch && scope.attemptEpoch === attemptEpoch+ return !this.disposed && this.state.get().identityEpoch === identityEpoch && scope?.inFlight?.attemptEpoch === attemptEpoch && scope.attemptEpoch === attemptEpoch && this.authorityCurrent(scope)}private assertActive() { if (this.disposed) throw new Error("read coordinator disposed") }}@@ -520,6 +548,10 @@ export function disposeReadCoordinator(queryClient: QueryClient) {unregisterReadCoordinatorSnapshotProjector(queryClient)}+export function getLocalReadingPosition(queryClient: QueryClient, channelId: string) {+ return coordinators.get(queryClient)?.localReadingPosition(channelId) ?? null+}+export function projectReadCoordinatorSnapshot(queryClient: QueryClient,snapshot: ReadCoordinatorSnapshot,diff --git a/src/web/src/hooks/community/use-conversation-entry.dom.test.tsx b/src/web/src/hooks/community/use-conversation-entry.dom.test.tsxindex 23de686ab..1a7b062b3 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,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from "vitest"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"import { createElement, type PropsWithChildren } from "react"import { QueryClientProvider } from "@tanstack/react-query"import { act, render, renderHook, waitFor } from "@/test/react-dom-harness"@@ -6,15 +6,24 @@ import { createCommunityQueryOwner } from "@/test/community-query-owner"import { conversationEntryFixture as fixture, dmConversationEntryFixture, conversationEntryTarget as target } from "@/test/conversation-entry-fixtures"import { CommunityDbProvider } from "@/lib/community-db/projections"import { registerCommunityDbRegistry } from "@/lib/community-db/collections"-import { captureCommunityLiveSnapshotToken, ingestReadStateSnapshot } from "@/lib/community-db/sync"-import { conversationEntryOptions, publishConversationEntry } from "@/lib/community/conversation-entry"+import { captureCommunityLiveSnapshotToken, ingestMessages, ingestReadStateSnapshot } from "@/lib/community-db/sync"+import { conversationEntryOptions, currentConversationReadState, publishConversationEntry } from "@/lib/community/conversation-entry"import { communityKeys } from "@/lib/query-keys"import { ConversationReadTimeoutError } from "@/lib/community/conversation-read"import { CommunityRouteContext } from "@/contexts/community/route-frame"import { ConversationActivityContext } from "@/contexts/community/conversation-activity"import { useConversationEntry } from "./use-conversation-entry"import { useChannelMetadata } from "./use-channel-metadata"-import { useDmMessages } from "./use-messages"+import { useDmMessages, useMessages } from "./use-messages"+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"+import type { FlatItem } from "@/lib/community/message-list-items"+import { renderMessageListRow } from "@/components/community/messages/message-list-row"+import { confirmReadSurface, disposeReadCoordinator, getReadCoordinator, registerReadSurface, releaseReadSurface, submitReadIntentGeneration } from "./read-coordinator"+import { disposeAccountReadStateReconciliation } from "./community-ws/read-state-reconciliation"+import { getAccountUnreadProjection } from "./account-unread-projection"const load = vi.hoisted(() => vi.fn())vi.mock("@/lib/api/client", async (original) => ({ ...await original<typeof import("@/lib/api/client")>(), apiFetch: (...args: unknown[]) => load(...args) }))@@ -246,3 +255,513 @@ describe("conversation entry selection", () => {})})++describe("conversation entry return during accepted reading", () => {+ beforeEach(installMessageScrollFixture)+ afterEach(restoreMessageScrollFixture)++ async function readingOwner() {+ const owner = await setup()+ const value = fixture()+ value.messages = Array.from({ length: 42 }, (_, index) => ({+ ...value.messages[0], id: `m${index + 1}`, seq: index + 1,+ createdAt: new Date(Date.UTC(2026, 9, 1, 0, 0, index + 1)).toISOString(),+ }))+ 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.page = { olderCursor: null, newerCursor: null, hasMoreOlder: false, hasMoreNewer: false, latestSeq: 42 }+ owner.publish(value)+ const put = deferred<{ changed: boolean; revision: number; targetSeq: number }>()+ const canonical = deferred<{ revision: number; readStates: typeof value.readState[] }>()+ load.mockImplementation((url: string) => {+ if (url === "/api/community/channels/c1/read") return put.promise+ if (url === "/api/community/users/me/read-state") return canonical.promise+ if (url === "/api/community/users/me/attention") return Promise.resolve({ scopes: [], items: [], limit: 100, truncated: false })+ throw new Error(`Unexpected reading transport ${url}`)+ })+ const coordinator = getReadCoordinator(owner.client, "viewer")+ const lease = registerReadSurface(owner.client, "viewer", { kind: "timeline", channelId: "c1" }, 30)+ const read42 = { ...value.readState, lastReadMessageId: "m42", lastReadSeq: 42, lastReadAt: value.messages[41].createdAt }+ const finish = async () => {+ disposeReadCoordinator(owner.client)+ disposeAccountReadStateReconciliation(owner.client)+ await act(async () => {+ put.resolve({ changed: true, revision: 5, targetSeq: 42 })+ canonical.resolve({ revision: 5, readStates: [read42] })+ })+ }+ return { ...owner, put, canonical, coordinator, lease, read42, finish,+ scope: () => coordinator.state.get().scopes.get("timeline:c1")!,+ }+ }++ function mountReadingEntry(owner: Awaited<ReturnType<typeof readingOwner>>, scrollToMessageId?: string) {+ let latest!: {+ feed: ReturnType<typeof useMessages>+ controller: ReturnType<typeof useMessageListController>+ newDividerBefore: string | undefined+ }+ 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 props = { channel: "Channel", messages: feed.messages,+ loading: feed.isLoading, initialLoadError: feed.initialLoadError,+ newDividerBefore: projection.newDividerBefore, scrollToMessageId,+ initialScrollReady: !feed.readSnapshotFetching && (projection.anchorFound || feed.initialPositionKnown),+ hasMore: feed.hasMoreOlder, hasMoreNewer: feed.hasMoreNewer,+ historyStartKnown: feed.historyStartKnown,+ initialPositionMessageId: feed.initialPositionMessageId,+ isFetching: feed.isFetching, isFetchingOlder: feed.isFetchingOlder, isFetchingNewer: feed.isFetchingNewer,+ presentVersion: feed.presentVersion, variant: "channel" as const, hoverCapable: false,+ onOpenThread: () => undefined,+ }+ const controller = useMessageListController(props)+ latest = { feed, controller, newDividerBefore: projection.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) },+ createElement(VirtualRows<FlatItem>, {+ items: controller.items, virtualizer: controller.virtualizer, reactLayout: true,+ renderItem: (item, index) => item.kind === "leading" ? renderMessageListRow(item, props, controller, index) : createElement("div", {+ "data-message-row-key": item.key, "data-fixture-kind": item.kind,+ "data-fixture-date": String(item.kind === "divider" && !!item.dateLabel),+ "data-message-divider-for": item.kind === "divider" ? item.messageId : undefined,+ }, item.kind === "message" ? createElement("div", { "data-msg-id": item.m.id }) :+ item.kind === "divider" && item.newDivider ? createElement("div", { "data-new-divider": "" }) : null),+ }))),+ createElement("div", { "data-slot": "community-conversation-footer" }))+ }+ const view = render(createElement(EntryList), { wrapper: owner.wrapper })+ const root = view.getByTestId("community-message-scroller")+ resize()+ const visible = (id: string) => {+ const row = root.querySelector<HTMLElement>(`[data-msg-id="${id}"]`)+ if (!row) return false+ const rect = row.getBoundingClientRect(), viewport = root.getBoundingClientRect()+ return rect.top >= viewport.top && rect.bottom <= viewport.bottom+ }+ return { view, root, visible, get latest() { return latest } }+ }++ it.each(["before PUT confirmation", "after PUT before canonical publication", "after ACK and failed canonical readback"] as const)(+ "keeps accepted local reading in the returned viewport %s without confirming the entry snapshot", async boundary => {+ const owner = await readingOwner()+ const first = mountReadingEntry(owner)+ let returned: ReturnType<typeof mountReadingEntry> | undefined+ try {+ expect(first.latest.feed.readSnapshot?.lastReadSeq).toBe(30)+ act(() => first.latest.controller.pillOnClick())+ resize()+ expect(first.latest.controller.readPositionReady).toBe(true)+ expect(first.visible("m42")).toBe(true)+ const generation = submitReadIntentGeneration(owner.lease, { kind: "timeline", channelId: "c1", messageId: "m42", seq: 42 })+ expect(generation).not.toBeNull()+ expect(owner.scope().accepted?.intent).toEqual({ kind: "timeline", channelId: "c1", messageId: "m42", seq: 42 })+ getAccountUnreadProjection(owner.client, "viewer").recordOptimisticRead("c1", 42, generation!)+ expect(submitReadIntentGeneration(owner.lease, { kind: "timeline", channelId: "c1", messageId: "m31", seq: 31 })).toBeNull()+ first.view.unmount()+ releaseReadSurface(owner.lease)+ await act(async () => vi.advanceTimersByTimeAsync(0))+ expect(load).toHaveBeenCalledWith("/api/community/channels/c1/read", expect.objectContaining({+ method: "PUT", body: JSON.stringify({ lastReadMessageId: "m42" }),+ }))+ expect(owner.scope().inFlight?.phase).toBe("mutation")+ if (boundary !== "before PUT confirmation") {+ await act(async () => owner.put.resolve({ changed: true, revision: 5, targetSeq: 42 }))+ expect(load.mock.calls.some(([url]) => url === "/api/community/users/me/read-state")).toBe(true)+ expect(owner.scope().inFlight?.phase).toBe("reconciling")+ expect(owner.scope().confirmedSeq).toBe(42)+ if (boundary === "after ACK and failed canonical readback") {+ await act(async () => owner.canonical.reject(new Error("canonical readback unavailable")))+ expect(owner.scope().inFlight).toBeNull()+ expect(owner.scope().accepted).toBeNull()+ expect(owner.scope().dirty).toBeNull()+ }+ } else {+ expect(owner.scope().confirmedSeq).toBe(30)+ expect(load.mock.calls.some(([url]) => url === "/api/community/users/me/read-state")).toBe(false)+ }+ expect(currentConversationReadState(owner.client, "c1")?.lastReadSeq).toBe(30)+ returned = mountReadingEntry(owner)+ expect(returned.latest.feed.messages).toHaveLength(42)+ expect(returned.latest.feed.readSnapshot?.lastReadSeq).toBe(30)+ expect(returned.latest.newDividerBefore).toBe("m31")+ expect(returned.latest.controller.readPositionReady).toBe(true)+ expect(returned.visible("m42")).toBe(true)+ const offset = returned.root.scrollTop, captured = returned.latest.feed.readSnapshot+ await act(async () => ingestReadStateSnapshot(owner.registry, { revision: 6, readStates: [owner.read42] }))+ resize()+ expect(returned.latest.feed.readSnapshot).toBe(captured)+ expect(returned.root.scrollTop).toBe(offset)+ } finally {+ first.view.unmount()+ returned?.view.unmount()+ await owner.finish()+ }+ },+ )++ it("reads a qualified covering window when the accepted target survives only as a canonical entity", async () => {+ const owner = await readingOwner()+ const originalKey = communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "m30" })+ const originalWindow = owner.client.getQueryData<import("@/lib/community/message-window").MessageWindowData>(originalKey)!+ const entryRead = deferred<ReturnType<typeof fixture>>()+ const originalLoad = load.getMockImplementation()!+ let view: ReturnType<typeof mountReadingEntry> | undefined+ try {+ expect(submitReadIntentGeneration(owner.lease, { kind: "timeline", channelId: "c1", messageId: "m42", seq: 42 })).not.toBeNull()+ owner.client.setQueryData(originalKey, { ...originalWindow, pages: originalWindow.pages.map(page => ({ ...page,+ messages: page.messages.filter(message => message.id !== "m42"), hasMoreNewer: 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)+ 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.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.visible("m42")).toBe(true)+ expect(view.latest.feed.readSnapshot?.lastReadSeq).toBe(30)+ expect(owner.client.getQueryData(originalKey)).toBe(retainedWindow)+ expect(view.latest.feed.historyStartKnown).toBe(false)+ } finally { view?.view.unmount(); releaseReadSurface(owner.lease); await owner.finish() }+ })++ function evictOrdinaryEntryWithAlternateCoverage(owner: Awaited<ReturnType<typeof readingOwner>>) {+ const alternateTarget = { ...target, anchorMessageId: "m42" }+ const alternate = fixture()+ alternate.messages = [{ ...alternate.messages[0], id: "m42", seq: 42, createdAt: owner.read42.lastReadAt! }]+ alternate.channel.messageCount = 42+ alternate.readState = { channelId: "c1", lastReadMessageId: "m30", lastReadSeq: 30, lastReadAt: "2026-10-01T00:00:30.000Z" }+ alternate.selection = { reason: "explicit_anchor", anchorMessageId: "m42" }+ alternate.page = { ...alternate.page, hasMoreOlder: true, hasMoreNewer: false, latestSeq: 42 }+ const alternateResource = publishConversationEntry(owner.client, alternateTarget, alternate,+ { token: captureCommunityLiveSnapshotToken(owner.client, "c1") })+ const alternateKey = conversationEntryOptions(owner.client, alternateTarget).queryKey+ owner.client.setQueryData(alternateKey, alternateResource)+ const retainedWindow = owner.client.getQueryData(alternateResource.windowKey)+ 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 })+ return { alternate, alternateResource, alternateKey, retainedWindow, ordinaryKey }+ }++ it.each([true, false])("uses alternate entry coverage after ordinary entry eviction only with qualification: %s", async qualified => {+ const owner = await readingOwner()+ const { alternate, alternateResource, alternateKey, retainedWindow, ordinaryKey } = evictOrdinaryEntryWithAlternateCoverage(owner)+ if (!qualified) owner.client.removeQueries({ queryKey: alternateKey, exact: true })+ 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 entryRead = deferred<ReturnType<typeof fixture>>()+ const originalLoad = load.getMockImplementation()!+ const expectedRequest = `/api/community/channels/c1/messages?entry=1${qualified ? "" : "&anchor=m42"}`+ 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}`)+ return entryRead.promise+ })+ let view: ReturnType<typeof mountReadingEntry> | undefined+ try {+ expect(submitReadIntentGeneration(owner.lease, { kind: "timeline", channelId: "c1", messageId: "m42", seq: 42 })).not.toBeNull()+ view = mountReadingEntry(owner)+ expect(view.latest.feed.initialPositionKnown).toBe(qualified)+ 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(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.messages.map(message => message.id)).toEqual(["m42"])+ expect(view.visible("m42")).toBe(true)+ expect(view.latest.feed.readSnapshot?.lastReadSeq).toBe(30)+ expect(currentConversationReadState(owner.client, "c1")?.lastReadSeq).toBe(30)+ 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])+ if (qualified) {+ expect(view.latest.feed.readSnapshot).toBe(capturedSnapshot)+ expect(view.root.scrollTop).toBe(capturedOffset)+ await act(async () => ingestReadStateSnapshot(owner.registry, { revision: 5, readStates: [owner.read42] }))+ resize()+ expect(view.latest.feed.readSnapshot).toBe(capturedSnapshot)+ expect(view.root.scrollTop).toBe(capturedOffset)+ expect(view.visible("m42")).toBe(true)+ }+ } finally {+ view?.view.unmount()+ entryRead.resolve(response)+ releaseReadSurface(owner.lease)+ await owner.finish()+ }+ })++ it.each([42, 100])("uses the higher canonical target %i with qualified cached coverage or its actual read", async seq => {+ const owner = await readingOwner()+ const { alternate, alternateResource, retainedWindow } = evictOrdinaryEntryWithAlternateCoverage(owner)+ 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 },+ 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"+ 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}`)+ return entryRead.promise+ })+ let view: ReturnType<typeof mountReadingEntry> | undefined+ try {+ 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.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).toBeNull()+ expect(view.latest.controller.readPositionReady).toBe(false)+ }+ 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.initialPositionKnown).toBe(true)+ expect(view.latest.feed.initialPositionMessageId).toBeNull()+ expect(view.latest.feed.readSnapshot?.lastReadSeq).toBe(seq)+ expect(view.visible(read.lastReadMessageId)).toBe(true)+ expect(owner.client.getQueryData(alternateResource.windowKey)).toBe(retainedWindow)+ expect(load.mock.calls.filter(([url]) => url.includes("/messages?entry=1")).map(([url]) => url)).toEqual([expectedRequest])+ } finally {+ view?.view.unmount()+ entryRead.resolve(response)+ releaseReadSurface(owner.lease)+ await owner.finish()+ }+ })++ it("keeps canonical NEW when no reading was accepted, then leaves that active entry frozen after canonical publication", async () => {+ const owner = await readingOwner()+ const first = mountReadingEntry(owner)+ let returned: ReturnType<typeof mountReadingEntry> | undefined+ try {+ act(() => first.latest.controller.pillOnClick())+ resize()+ expect(first.visible("m42")).toBe(true)+ expect(owner.scope().accepted).toBeNull()+ first.view.unmount()+ releaseReadSurface(owner.lease)+ await act(async () => vi.advanceTimersByTimeAsync(0))+ 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(load).not.toHaveBeenCalled()+ const captured = returned.latest.feed.readSnapshot, offset = returned.root.scrollTop+ await act(async () => ingestReadStateSnapshot(owner.registry, { revision: 5, readStates: [owner.read42] }))+ resize()+ expect(currentConversationReadState(owner.client, "c1")?.lastReadSeq).toBe(42)+ expect(returned.latest.feed.readSnapshot).toBe(captured)+ expect(returned.latest.newDividerBefore).toBe("m31")+ expect(returned.root.scrollTop).toBe(offset)+ } finally {+ first.view.unmount()+ returned?.view.unmount()+ await owner.finish()+ }+ })++ it.each(["covering response", "canonical publication before the covering response"] as const)("takes higher progress from %s through its own qualified 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>>()+ 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))+ 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 }+ await act(async () => {+ if (boundary !== "covering response") ingestReadStateSnapshot(owner.registry, { revision: 5, readStates: [higher] })+ localRead.resolve(aroundLocal)+ })+ 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(view.latest.feed.initialPositionMessageId).toBeNull()+ expect(view.visible("m100")).toBe(true)+ } finally { view?.view.unmount(); releaseReadSurface(owner.lease); await owner.finish() }+ })++ it("allows an explicit older viewport target without lowering accepted or confirmed reading", async () => {+ const owner = await readingOwner()+ let entry: ReturnType<typeof mountReadingEntry> | undefined+ try {+ expect(submitReadIntentGeneration(owner.lease, { kind: "timeline", channelId: "c1", messageId: "m42", seq: 42 })).not.toBeNull()+ confirmReadSurface(owner.lease, 29)+ expect(owner.scope().confirmedSeq).toBe(30)+ entry = mountReadingEntry(owner, "m12")+ expect(entry.visible("m12")).toBe(true)+ expect(owner.scope().dirty?.intent.seq).toBe(42)+ confirmReadSurface(owner.lease, 42)+ confirmReadSurface(owner.lease, 31)+ expect(owner.scope().confirmedSeq).toBe(42)+ expect(submitReadIntentGeneration(owner.lease, { kind: "timeline", channelId: "c1", messageId: "m31", seq: 31 })).toBeNull()+ expect(entry.visible("m12")).toBe(true)+ } finally {+ entry?.view.unmount()+ releaseReadSurface(owner.lease)+ await owner.finish()+ }+ })++ it("uses higher canonical reading for a fresh entry instead of an older local target", async () => {+ const owner = await readingOwner()+ let view: ReturnType<typeof mountReadingEntry> | undefined+ 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] }))+ view = mountReadingEntry(owner)+ expect(view.latest.feed.initialPositionMessageId).toBeNull()+ expect(view.latest.feed.readSnapshot?.lastReadSeq).toBe(42)+ expect(view.latest.newDividerBefore).toBeUndefined()+ expect(view.visible("m42")).toBe(true)+ expect(load).not.toHaveBeenCalled()+ } finally { view?.view.unmount(); releaseReadSurface(owner.lease); await owner.finish() }+ })++ it.each(["seq=12", "msg=m12"])("leaves explicit route %s ahead of the local landing", async search => {+ const owner = await readingOwner(), Owner = owner.wrapper+ const navigation = { entryIntent: { href: `/c/channels/s1/c1?${search}` } }+ function Wrapper({ children }: PropsWithChildren) {+ return createElement(Owner, null, createElement(CommunityRouteContext, { value: { navigation } as never }, children))+ }+ const view = renderHook(() => useMessages("c1", { serverId: "s1" }), { wrapper: Wrapper })+ try {+ expect(submitReadIntentGeneration(owner.lease, { kind: "timeline", channelId: "c1", messageId: "m42", seq: 42 })).not.toBeNull()+ navigation.entryIntent = { href: `/c/channels/s1/c1?${search}` }+ view.rerender()+ expect(view.result.current.initialPositionMessageId).toBeNull()+ expect(view.result.current.readSnapshot?.lastReadSeq).toBe(30)+ expect(owner.scope().dirty?.intent.seq).toBe(42)+ expect(load).not.toHaveBeenCalled()+ } finally { view.unmount(); releaseReadSurface(owner.lease); await owner.finish() }+ })++ it("does not claim the beginning from a live row before the selected history window is known", async () => {+ const owner = await readingOwner()+ const entryRead = deferred<ReturnType<typeof fixture>>()+ const previousKey = communityKeys.channelMessagesWindow("c1", { mode: "anchor", anchor: "m30" })+ const previousWindow = owner.client.getQueryData(previousKey)+ expect(previousWindow).toBeDefined()+ const fresh = fixture()+ fresh.messages = Array.from({ length: 22 }, (_, index) => ({+ ...fresh.messages[0], id: `m${index + 59}`, seq: index + 59,+ createdAt: new Date(Date.UTC(2026, 9, 1, 0, 0, index + 59)).toISOString(),+ }))+ 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.channel.messageCount = 80+ fresh.channel.lastMessageAt = fresh.messages.at(-1)!.createdAt+ fresh.page = { olderCursor: "older", newerCursor: null, hasMoreOlder: true, hasMoreNewer: false, latestSeq: 80 }+ await act(async () => {+ ingestReadStateSnapshot(owner.registry, { revision: 5, readStates: [read60] })+ ingestMessages(owner.registry, "c1", [{ ...fresh.messages.at(-1)!, resourceComplete: true }])+ owner.runtime.messageStream.actions.dispatch({ kind: "channel", id: "c1", serverId: "s1" }, {+ type: "wsMessage", message: fresh.messages.at(-1)!,+ })+ })+ load.mockImplementation((url: string) => {+ if (url === "/api/community/channels/c1/messages?entry=1") return entryRead.promise+ throw new Error(`Unexpected history transport ${url}`)+ })+ const view = mountReadingEntry(owner)+ try {+ expect(view.latest.feed.messages.map(message => message.id)).toEqual(["m80"])+ expect(view.latest.feed.initialPositionKnown).toBe(false)+ expect(owner.client.getQueryData(previousKey)).toBe(previousWindow)+ expect(view.latest.feed.readSnapshot).toBeNull()+ expect(view.latest.feed.isLoading).toBe(true)+ expect(view.latest.controller.initialPosition.contentVisible).toBe(true)+ expect(view.latest.controller.readPositionReady).toBe(false)+ expect(view.latest.feed.hasMoreOlder).toBe(false)+ expect.soft(view.root.textContent).not.toContain("Beginning of the channel")+ await act(async () => entryRead.resolve(fresh))+ resize()+ expect(view.latest.feed.initialPositionKnown).toBe(true)+ expect(view.latest.feed.hasMoreOlder).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")+ } finally {+ view.view.unmount()+ entryRead.resolve(fresh)+ releaseReadSurface(owner.lease)+ await owner.finish()+ }+ })+})diff --git a/src/web/src/hooks/community/use-conversation-entry.ts b/src/web/src/hooks/community/use-conversation-entry.tsindex 16a599341..79d9b8ec6 100644--- a/src/web/src/hooks/community/use-conversation-entry.ts+++ b/src/web/src/hooks/community/use-conversation-entry.ts@@ -12,16 +12,17 @@ import { getCommunityDbRegistry } from "@/lib/community-db/collections"import { useCommunityRuntime } from "@/stores/community/runtime"import { isChannelMetadataTokenCurrent } from "@/lib/community/conversation-qualification"import {- conversationEntryOptions, currentConversationReadState, findConversationEntryWindow,+ conversationEntryOptions, currentConversationReadState, findConversationEntryWindow, getQualifiedConversationEntry,type ConversationEntryResource, type ConversationEntryTarget,} from "@/lib/community/conversation-entry"import type { MessageWindowData } from "@/lib/community/message-window"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 } | null) {+export function useConversationResource(target: ConversationEntryTarget | null, intent?: { href: string; resume?: boolean } | null, useLocalPosition = false) {const client = useQueryClient()const runtime = useCommunityRuntime()const canonical = useRouteChannelProjection(target?.channelId ?? null)@@ -38,18 +39,34 @@ export function useConversationResource(target: ConversationEntryTarget | null,const tag = target?.tag ?? nullconst preferTail = target?.preferTail === trueconst enabled = target !== null- const input = useMemo(() => ({ channelId, serverId, anchorMessageId, tag, preferTail }), [channelId, serverId, anchorMessageId, tag, preferTail])- const options = useMemo(() => conversationEntryOptions(client, input), [client, input, accountEpoch, accessEpoch, generation, parentGeneration, intent])+ const baseInput = useMemo(() => ({ channelId, serverId, anchorMessageId, tag, preferTail }), [channelId, serverId, anchorMessageId, tag, preferTail])+ const cachedResource = useMemo(() => {+ const cached = client.getQueryData<ConversationEntryResource>(conversationEntryOptions(client, baseInput).queryKey)+ return cached && isChannelMetadataTokenCurrent(cached.proof) ? cached : getQualifiedConversationEntry(client, channelId)+ }, [client, baseInput, channelId, accountEpoch, accessEpoch, generation, parentGeneration, intent])+ 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 { input: baseInput, requestInput: baseInput, position: null }+ const input = { ...baseInput, anchorMessageId: position.messageId }+ const covered = cachedResource && findConversationEntryWindow(client, input, cachedResource, pointer)+ return { input, requestInput: covered ? baseInput : input, position }+ }, [client, baseInput, cachedResource, accountEpoch, accessEpoch, generation, parentGeneration, intent, useLocalPosition, enabled, anchorMessageId, channelId, tag, preferTail])+ const input = landing.input+ const options = useMemo(() => conversationEntryOptions(client, landing.requestInput), [client, landing, accountEpoch, accessEpoch, generation, parentGeneration, intent])const parentId = canonical?.parentChannelId ?? undefinedconst verification = useMemo(() => ({ needed: !serverRevoked && runtime.ws.actions.isChannelAccessRevoked(channelId, serverId, parentId), generation }), [runtime, channelId, serverId])const query = useQuery({ ...options, enabled: !!target && !revoked, refetchOnReconnect: false, refetchOnWindowFocus: false })const anchorMissing = isConversationAnchorMissingError(query.error)- const fallbackInput = useMemo(() => ({ ...input, anchorMessageId: null }), [input])+ const fallbackInput = useMemo(() => ({ ...baseInput, anchorMessageId: null }), [baseInput])const fallbackOptions = useMemo(() => conversationEntryOptions(client, fallbackInput), [client, fallbackInput, accountEpoch, accessEpoch, generation, parentGeneration])const fallback = useQuery({ ...fallbackOptions, enabled: !!target && anchorMissing && !revoked, subscribed: !!target && anchorMissing,refetchOnReconnect: false, refetchOnWindowFocus: false })const resource = query.data && isChannelMetadataTokenCurrent(query.data.proof) ? query.data- : fallback.data && isChannelMetadataTokenCurrent(fallback.data.proof) ? fallback.data : undefined+ : fallback.data && isChannelMetadataTokenCurrent(fallback.data.proof) ? fallback.data+ : cachedResource && isChannelMetadataTokenCurrent(cachedResource.proof) ? cachedResource : undefinedconst qualified = !!target && !!canonical && !!resource && !revoked&& canonical.id === channelId && canonical.serverId === serverId && !canonical.archivedconst refetch = query.refetch@@ -65,7 +82,8 @@ export function useConversationResource(target: ConversationEntryTarget | null,const pointer = currentConversationReadState(client, channelId)if (pointer && !findConversationEntryWindow(client, input, query.data, pointer)) void client.query({ ...options, select: undefined }).catch(() => undefined)}, [client, intent, input, options, revoked])- return { client, input, options, query, canonical, resource: qualified ? resource : undefined, canRead: qualified, revoked,+ return { client, cachedResource, input: anchorMissing && landing.position ? baseInput : input, options, query, canonical, resource: qualified ? resource : undefined, canRead: qualified, revoked,+ localPosition: anchorMissing ? null : landing.position,denied: serverRevoked || revoked && (!verification.needed || generation !== verification.generation) || isConversationAccessError(query.error) && Number((query.error as { status?: unknown } | null)?.status) !== 401, anchorMissing,verificationError: (!qualified && anchorMissing ? fallback.error : query.error)?.name === "AbortError" ? null : !qualified && anchorMissing ? fallback.error : query.error,verificationPending: !qualified && (anchorMissing ? fallback.isPending : query.isPending),@@ -87,25 +105,35 @@ 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, input, options, query, canonical, resource, canRead, revoked, denied, anchorMissing } = useConversationResource(target, intent)+ const { client, cachedResource, input, query, canonical, resource, canRead, revoked, denied, anchorMissing, localPosition } = useConversationResource(target, intent, true)+ const canonicalInput = useMemo(() => localPosition ? { ...input, anchorMessageId: null } : input, [input, localPosition])const entry = useMemo(() => {- const cached = client.getQueryData<ConversationEntryResource>(options.queryKey)- const pointer = cached && isChannelMetadataTokenCurrent(cached.proof) ? currentConversationReadState(client, input.channelId) : undefined- const window = cached && pointer ? findConversationEntryWindow(client, input, cached, pointer) : undefined+ const pointer = cachedResource && isChannelMetadataTokenCurrent(cachedResource.proof) ? currentConversationReadState(client, input.channelId) : undefined+ const window = cachedResource && pointer ? findConversationEntryWindow(client,+ localPosition && pointer.lastReadSeq >= localPosition.seq ? canonicalInput : input, cachedResource, pointer) : undefinedreturn { knownRevision: pointer?.observedRevision ?? -1, state: createStore<{ snapshot: CommunityReadStateResource | null; window: EntryWindow | null }>({snapshot: window ? pointer! : null,window: window ?? null,}) }- }, [client, input, options, intent])+ }, [client, cachedResource, input, canonicalInput, localPosition, intent])const selected = useSelector(entry.state, (state) => state)- const candidate = !selected.window && resource && resource.readStateRevision >= entry.knownRevision- ? findConversationEntryWindow(client, input, resource, resource.readStateAtEntry) : undefined+ const currentRevision = currentConversationReadState(client, input.channelId)?.observedRevision ?? -1+ const needsCanonicalWindow = !!localPosition && !selected.window && !!resource && (resource.readStateRevision < currentRevision+ || resource.readStateAtEntry.lastReadSeq >= localPosition.seq && !findConversationEntryWindow(client, canonicalInput, resource, resource.readStateAtEntry))+ const canonicalQuery = useQuery({ ...conversationEntryOptions(client, canonicalInput), enabled: 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 candidateTarget = localPosition && candidateResource && candidateResource.readStateAtEntry.lastReadSeq >= localPosition.seq+ ? canonicalInput : input+ const candidate = !selected.window && candidateResource && candidateResource.readStateRevision >= Math.max(entry.knownRevision, currentRevision)+ ? findConversationEntryWindow(client, candidateTarget, candidateResource, candidateResource.readStateAtEntry) : undefinedconst window = canRead ? selected.window ?? candidate ?? null : null- const snapshot = window ? selected.snapshot ?? resource!.readStateAtEntry : null+ const snapshot = window ? selected.snapshot ?? candidateResource!.readStateAtEntry : nulluseLayoutEffect(() => {- if (!candidate || !resource) return- entry.state.setState((state) => state.window ? state : { window: candidate, snapshot: resource.readStateAtEntry })- }, [candidate, entry, resource])+ if (!candidate || !candidateResource) return+ entry.state.setState((state) => state.window ? state : { window: candidate, snapshot: candidateResource.readStateAtEntry })+ }, [candidate, entry, candidateResource])useEffect(() => {if (!canRead || !window || !resource || hashKey(window.key) === hashKey(resource.windowKey)) returnconst landing = client.getQueryData<MessageWindowData>(resource.windowKey)@@ -114,11 +142,13 @@ export function useConversationEntry(target: ConversationEntryTarget | null) {kind: input.serverId === null ? "dm" : "channel", scopeId: input.channelId, serverId: input.serverId ?? undefined,}, window.key, target).catch(() => undefined)}, [canRead, client, input.channelId, input.serverId, resource, window])- const refetch = query.refetch+ const activeQuery = needsCanonicalWindow ? canonicalQuery : query+ const refetch = activeQuery.refetchconst retry = useCallback(() => { void refetch({ cancelRefetch: false }) }, [refetch])- return { ...query, intent, resource, canonical, canRead, window, snapshot, revoked, denied, anchorMissing,- isPending: !!target && !window && !denied && !anchorMissing && !query.isError && query.errorUpdatedAt === 0,- failed: !window && query.errorUpdatedAt > 0,- retry, retrying: query.isFetching,+ return { ...activeQuery, intent, resource, canonical, canRead, window, snapshot, revoked, denied, anchorMissing,+ initialPositionMessageId: window && localPosition && snapshot && snapshot.lastReadSeq < localPosition.seq ? localPosition.messageId : null,+ isPending: !!target && !window && !denied && !anchorMissing && !activeQuery.isError && activeQuery.errorUpdatedAt === 0,+ failed: !window && activeQuery.errorUpdatedAt > 0,+ retry, retrying: activeQuery.isFetching,}}diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.tsindex 8f0d3930e..d9861b0e2 100644--- a/src/web/src/hooks/community/use-messages.ts+++ b/src/web/src/hooks/community/use-messages.ts@@ -132,6 +132,7 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undeficonst oldest = pages.at(-1)const newest = pages[0]const hasMoreOlder = (oldest?.hasMoreOlder ?? oldest?.hasMore) ?? false+ const historyStartKnown = !!selectedWindow && (oldest?.hasMoreOlder ?? oldest?.hasMore) === falseconst hasMoreNewer = newest?.hasMoreNewer ?? falseconst fetchPage = useCallback((direction: "older" | "newer") => {const original = committed.current@@ -182,7 +183,7 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefi...query, observation: { snapshot_source: entry.resource?.source ?? "unknown" as const, target_coverage: windowAvailable ? "covered" as const : "uncovered" as const,wait_reason: !entry.canRead ? "entry" as const : !windowAvailable ? "window" as const : loading ? "projection" as const : "none" as const },messages, canonicalMessages: canonicalBase, canonicalById,- latestSeq, hasMoreOlder, hasMoreNewer, hasMore: hasMoreOlder,+ latestSeq, hasMoreOlder, hasMoreNewer, historyStartKnown, hasMore: hasMoreOlder,isLoading: loading, isPending: loading, isError: !!initialLoadError && !query.data,error, initialLoadError, isFetching: entry.isFetching || query.isFetching,isFetchingOlder: query.isFetchingNextPage,@@ -192,6 +193,7 @@ function useMessageSurface(channelId: string | null, opts: MessagesOpts | undefinavigationBlocked: !entry.canRead,readSnapshot: entry.snapshot, readSnapshotFetching: entry.isPending,initialPositionKnown: !!selectedWindow && entry.snapshot !== null && !loading,+ initialPositionMessageId: entry.initialPositionMessageId,retryInitialLoad, retryingInitialLoad: entry.isFetching || query.isFetching,entryCanRead: entry.canRead, entryDenied: entry.denied, entryAnchorMissing: entry.anchorMissing,}diff --git a/src/web/src/hooks/community/use-scroll-anchor.ts b/src/web/src/hooks/community/use-scroll-anchor.tsindex 5a012d920..705ecc2c0 100644--- a/src/web/src/hooks/community/use-scroll-anchor.ts+++ b/src/web/src/hooks/community/use-scroll-anchor.ts@@ -76,6 +76,7 @@ export function useScrollAnchor({newDividerBefore,initialScrollReady,scrollToMessageId,+ initialPositionMessageId,onScrollTargetPositioned,onScrollTargetCancelled,hasMoreOlder,@@ -91,6 +92,7 @@ export function useScrollAnchor({newDividerBefore?: stringinitialScrollReady: booleanscrollToMessageId?: string | null+ initialPositionMessageId?: string | nullonScrollTargetPositioned?: (id: string) => voidonScrollTargetCancelled?: (id: string) => voidhasMoreOlder?: boolean@@ -875,10 +877,10 @@ export function useScrollAnchor({if (positionKind.get() !== "initial" || initialRetiredRef.current || !hasMessages || !viewportReady) returnif (initialScrollReady && !entryResolvedRef.current) {entryResolvedRef.current = true- startIntent(newDividerBefore ? "unread" : "end", newDividerBefore ?? null)+ startIntent(initialPositionMessageId ? "target" : newDividerBefore ? "unread" : "end", initialPositionMessageId ?? newDividerBefore ?? null)} else if (!initialScrollReady && !hasMoreNewer && !semanticIntentRef.current) startIntent("end", null)else scheduleInitialPositionSettled()- }, [cancelFrame, hasMessages, hasMoreNewer, initialScrollReady, items, newDividerBefore, positionKind, releasePosition, scheduleInitialPositionSettled, startIntent, virtualItems])+ }, [cancelFrame, hasMessages, hasMoreNewer, initialScrollReady, initialPositionMessageId, items, newDividerBefore, positionKind, releasePosition, scheduleInitialPositionSettled, startIntent, virtualItems])const requestPresentPosition = useCallback(() => {presentIntentRef.current = { epoch: claimPosition("present"), allowAttachedTail: false, fetching: false }diff --git a/src/web/src/lib/community-db/sync.ts b/src/web/src/lib/community-db/sync.tsindex 988fbb2a3..560f6594a 100644--- a/src/web/src/lib/community-db/sync.ts+++ b/src/web/src/lib/community-db/sync.ts@@ -2171,9 +2171,36 @@ function publishConfirmedFields<N extends CollectionName>())if (!fields.length) return falseconst accepted = Object.fromEntries(fields.map((field) => [field, changes[field as keyof CommunityCollectionRows[N]]]))- return withCanonicalWriteContext(queryClient, { kind: "event" }, () => (- patchRows(registry, name, (row) => ({ ...row, ...accepted }), (row) => getKey(row) === id, [id], fields)- ))+ return withCanonicalWriteContext(queryClient, { kind: "event" }, () => notifyManager.batch(() => {+ const published = patchRows(registry, name, (row) => ({ ...row, ...accepted }), (row) => getKey(row) === id, [id], fields)+ if (name === "messages" && fields.includes("content")) {+ const message = collectionRows(registry, "messages").find((row) => row.id === id)+ if (message?.channelId && typeof message.content === "string") patchMessageFirstPreview(registry, message.channelId, id, message.content)+ }+ return published+ }))+}++function firstMessageChannel(registry: CommunityDbRegistry, channelId: string, messageId: string) {+ return collectionRows(registry, "channels").find((row) => row.id === channelId+ && row.type === "thread" && row.firstMessageId === messageId)+}++function patchMessageFirstPreview(registry: CommunityDbRegistry, channelId: string, messageId: string, content: string) {+ if (!firstMessageChannel(registry, channelId, messageId)) return+ patchRows(registry, "channels", (row) => ({ ...row, preview: content }),+ (row) => row.id === channelId && row.type === "thread" && row.firstMessageId === messageId,+ [channelId], ["preview"])+}++export function updateCommunityMessageContentOptimistically(registry: CommunityDbRegistry, messageId: string, content: string) {+ const message = registry.collections.messages.get(messageId)+ if (!message) return+ registry.collections.messages.update(messageId, (row) => { row.content = content })+ const channel = firstMessageChannel(registry, message.channelId, messageId)+ if (channel && registry.collections.channels.has(channel.id)) {+ registry.collections.channels.update(channel.id, (row) => { row.preview = content })+ }}export function publishCommunityServerFields(@@ -2684,14 +2711,7 @@ export function projectCommunityWsEventToDb([event.messageId],["content"],)- const thread = registry.collections.channels.get(event.channelId)- if (thread?.type === "thread" && thread.firstMessageId === event.messageId) {- const ownsPreview = (row: ChannelRow) => row.id === event.channelId- && row.type === "thread" && row.firstMessageId === event.messageId- patchRows(registry, "channels",- (row) => ownsPreview(row) ? { ...row, preview: event.content } : row,- ownsPreview, [event.channelId], ["preview"])- }+ patchMessageFirstPreview(registry, event.channelId, event.messageId, event.content)return}case "community:message.updated":diff --git a/src/web/src/lib/community/conversation-entry.ts b/src/web/src/lib/community/conversation-entry.tsindex ad230c2bb..36742d7c5 100644--- a/src/web/src/lib/community/conversation-entry.ts+++ b/src/web/src/lib/community/conversation-entry.ts@@ -137,7 +137,7 @@ export function findConversationEntryWindow(client: QueryClient, target: Conversif (!Array.isArray(data?.pages) || !Array.isArray(data.pageParams) || !data.pages.length || data.pageParams.length !== data.pages.length || data.pages.some((page) => !Array.isArray(page.messages))) continueconst ids = data.pages.flatMap((page) => page.messages.map((message) => message.id))if (ids.length && !ids.some((id) => messages.get(id)?.resourceComplete === true)) continue- const anchored = !!anchor && (ids.includes(anchor) || data.pageParams.some((param) => param.mode === "anchor" && param.anchor === anchor))+ const anchored = !!anchor && ids.includes(anchor) && messages.get(anchor)?.resourceComplete === trueconst missingPointer = !target.anchorMessageId && pointer.lastReadMessageId === resource.readStateAtEntry.lastReadMessageId && resource.selection.reason === "read_pointer_missing"&& hashKey(window.queryKey) === hashKey(resource.windowKey) && identity.initial.mode === "newest" && data.pages[0].hasMoreNewer === falseif (anchor ? !anchored && !missingPointer : data.pages[0].hasMoreNewer !== false) continuediff --git a/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.ts b/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.tsindex 44d1cffcd..06f03a938 100644--- a/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.ts+++ b/src/web/src/test/e2e-ui/40-mobile-server-header-hierarchy.spec.ts@@ -1,5 +1,6 @@-import type { Page, Response } from "@playwright/test"+import type { Page, Request, Response } from "@playwright/test"import { test, expect } from "./_fixtures/case-fixture"+import { proxyCommunityWebSockets } from "./_fixtures/community-ws-proxy"import { tid } from "./_fixtures/testids"import type { CaseActors } from "./_fixtures/case-fixture"@@ -150,36 +151,111 @@ test.describe("mobile server header direct hierarchy", () => {}})- test("639↔640 preserves the header and composer owners without resize requests", async ({ caseActors }) => {+ test("639↔640 preserves the header and composer owners without resize requests", async ({ caseActors, caseResources }) => {const actors = await caseActors(["alice"])const { asUser } = actorsconst { serverId, threadId } = await prepareCase1(actors)- const { page } = await asUser("alice")- const startupAttentionPaths = [- "/api/community/users/me/attention",- ] as const- const startupAttentionGenerations = new Map<string, number>(- startupAttentionPaths.map((pathname) => [pathname, 0]),- )- const observeStartupAttention = (response: Response) => {- const pathname = new URL(response.url()).pathname- if (response.request().method() !== "GET" || !response.ok()) return- if (!startupAttentionGenerations.has(pathname)) return- startupAttentionGenerations.set(pathname, (startupAttentionGenerations.get(pathname) ?? 0) + 1)+ const { context, page } = await asUser("alice")+ let holdAuthentication = true+ const proxy = await proxyCommunityWebSockets(context, {+ decideConnectionFrame: (frame) => frame.type === "auth.ok" && holdAuthentication ? "hold" : "forward",+ })+ type StartupPhase = "initial" | "authenticated"+ let phase: StartupPhase | "resize" = "initial"+ const startupRequests = new Map<Request, {+ phase: StartupPhase | "resize"+ pathname: string+ method: string+ status?: number+ terminal: "pending" | "finished" | "failed"+ failure?: string+ }>()+ const observeRequest = (request: Request) => {+ const pathname = new URL(request.url()).pathname+ if (pathname.startsWith("/api/community/")) {+ startupRequests.set(request, { phase, pathname, method: request.method(), terminal: "pending" })+ }+ }+ const observeResponse = (response: Response) => {+ const record = startupRequests.get(response.request())+ if (record) record.status = response.status()+ }+ const observeFinished = (request: Request) => {+ const record = startupRequests.get(request)+ if (record) record.terminal = "finished"+ }+ const observeFailed = (request: Request) => {+ const record = startupRequests.get(request)+ if (record) {+ record.terminal = "failed"+ record.failure = request.failure()?.errorText+ }+ }+ caseResources.own(proxy, async (captured) => {+ holdAuthentication = false+ page.off("request", observeRequest)+ page.off("response", observeResponse)+ page.off("requestfinished", observeFinished)+ page.off("requestfailed", observeFailed)+ try {+ captured.releaseHeldConnections()+ } finally {+ await caseResources.closeContext(context)+ }+ await test.info().attach("header-hierarchy-startup", {+ body: JSON.stringify({+ connections: captured.connectionFrames,+ requests: [...startupRequests].map(([request, record]) => ({ ...record, timing: request.timing() })),+ }),+ contentType: "application/json",+ })+ })+ page.on("request", observeRequest)+ page.on("response", observeResponse)+ page.on("requestfinished", observeFinished)+ page.on("requestfailed", observeFailed)+ const directoryPaths = [+ "/api/community/servers",+ `/api/community/servers/${serverId}/categories`,+ `/api/community/servers/${serverId}/channels`,+ ]+ const readStatePath = "/api/community/users/me/read-state"+ const expectStartupFinished = async (generation: StartupPhase, paths: string[]) => {+ await expect.poll(() => {+ const records = [...startupRequests].map(([request, record]) => ({ ...record, timing: request.timing() }))+ const readStateEnd = Math.max(-1, ...records.filter((record) => record.phase === "authenticated"+ && record.pathname === readStatePath && record.method === "GET"+ && record.terminal === "finished" && record.status === 200 && record.timing.responseEnd >= 0)+ .map((record) => record.timing.startTime + record.timing.responseEnd))+ return {+ failed: records.filter((record) => record.terminal === "failed"+ || (record.status !== undefined && (record.status < 200 || record.status >= 300))),+ pending: records.filter((record) => record.terminal === "pending"),+ missing: paths.filter((pathname) => !records.some((record) => record.phase === generation+ && record.pathname === pathname && record.method === "GET"+ && record.terminal === "finished" && record.status === 200+ && (generation === "initial" || !directoryPaths.includes(pathname)+ || (readStateEnd >= 0 && record.timing.startTime >= readStateEnd)))),+ }+ }).toEqual({ failed: [], pending: [], missing: [] })}- page.on("response", observeStartupAttention)await page.setViewportSize({ width: 639, height: 844 })await page.goto(`/c/channels/${serverId}/${threadId}`, { waitUntil: "commit" })await expect(page.getByTestId(tid.threadSplitPanel).getByTestId(tid.composerInput)).toBeVisible({ timeout: 20_000 })await expectMobileBack(page)- // The shell-owned attention query settles once on cold mount. Keep that- // generation outside the resize measurement window.- await expect.poll(() => startupAttentionPaths.every(- (pathname) => (startupAttentionGenerations.get(pathname) ?? 0) >= 1,- )).toBe(true)- page.off("response", observeStartupAttention)+ // RULE: Cold HTTP reads and first-auth read-state/directory reconciliation+ // must finish before the all-community resize measurement begins.+ await expectStartupFinished("initial", ["/api/community/users/me/attention", ...directoryPaths])+ await expect.poll(() => proxy.heldConnectionCount()).toBe(1)+ expect(proxy.connectionCount()).toBe(1)+ phase = "authenticated"+ holdAuthentication = false+ expect(proxy.releaseHeldConnections((frame) => frame.type === "auth.ok")).toBe(1)+ await expectStartupFinished("authenticated", [readStatePath, ...directoryPaths])await page.waitForLoadState("networkidle")+ await expectStartupFinished("authenticated", [readStatePath, ...directoryPaths])+ expect(proxy.connectionCount()).toBe(1)await page.evaluate(({ composerTestId, threadPanelTestId }) => {const backControl = document.querySelector(`[data-testid="${threadPanelTestId}"]`)?.querySelector('button[aria-label="Back"]')@@ -189,8 +265,10 @@ test.describe("mobile server header direct hierarchy", () => {composerTestId: tid.channelComposerShell,threadPanelTestId: tid.threadSplitPanel,})+ phase = "resize"let communityRequests = 0let newSockets = 0+ const connectionCount = proxy.connectionCount()page.on("request", (request) => {if (new URL(request.url()).pathname.startsWith("/api/community/")) communityRequests += 1})@@ -220,5 +298,6 @@ test.describe("mobile server header direct hierarchy", () => {expect(new URL(page.url()).pathname).toBe(pathname)expect(communityRequests).toBe(0)expect(newSockets).toBe(0)+ expect(proxy.connectionCount() - connectionCount).toBe(0)})})