Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): prevent inbox read-state race (#576)

Generc74e30f2fd4f
diff --git a/scripts/ci/e2e-shards.mjs b/scripts/ci/e2e-shards.mjs
index 48a65a9db..6e83800fd 100644
--- a/scripts/ci/e2e-shards.mjs
+++ b/scripts/ci/e2e-shards.mjs
@@ -42,6 +42,7 @@ export const SPEC_SECONDS = {
"31-mention-candidate-pagination.spec.ts": 10,
"32-mobile-ws-foreground-validation.spec.ts": 80,
"33-picker-async-layout.spec.ts": 57,
+ "34-inbox-read-race.spec.ts": 42,
}
function walk(directory) {
diff --git a/scripts/ci/e2e-shards.test.ts b/scripts/ci/e2e-shards.test.ts
index 7f62e2df1..2fa90c278 100644
--- a/scripts/ci/e2e-shards.test.ts
+++ b/scripts/ci/e2e-shards.test.ts
@@ -70,7 +70,7 @@ describe("planE2eShards", () => {
expect(first).toHaveLength(E2E_SHARD_COUNT)
expect([...assigned].sort()).toEqual(specs)
expect(new Set(assigned).size).toBe(specs.length)
- expect(totals.sort((left, right) => left - right)).toEqual([248, 249, 249, 249, 250])
+ expect(totals.sort((left, right) => left - right)).toEqual([256, 256, 257, 259, 259])
expect(Math.max(...totals) / Math.min(...totals)).toBeLessThanOrEqual(1.15)
})
diff --git a/src/web/src/hooks/community/community-ws/bundle-events.test.ts b/src/web/src/hooks/community/community-ws/bundle-events.test.ts
index 2f978249c..ea4d4e581 100644
--- a/src/web/src/hooks/community/community-ws/bundle-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/bundle-events.test.ts
@@ -22,11 +22,21 @@ import {
capturedQueryClient,
cleanupCommunityWsHarness,
forumSidebarFixture,
+ getCommunityApiFetchMock,
mountHook,
resetCommunityWsHarness,
} from "./test-harness"
import { useCommunityStore } from "@/stores/community"
import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
+import {
+ SEEN_DELIVERY_OPERATION_MAX,
+ SEEN_DELIVERY_OPERATION_TRIM_TO,
+} from "@/stores/community/ws"
+import {
+ registerReadSurface,
+ releaseReadSurface,
+ submitReadIntent,
+} from "@/hooks/community/read-coordinator"
beforeEach(async () => {
reconcileCommunityWsReconnect.mockClear()
@@ -86,46 +96,273 @@ function invalidationCount(queryKey: readonly unknown[]): number {
}
describe("useCommunityWs — operation bundles", () => {
+ it("merges multiple requests into one queued successor generation", async () => {
+ vi.useFakeTimers()
+ try {
+ useCommunityStore.getState().subscribe({ channelId: "ch-1" })
+ await mountHook({ viewerUserId: "viewer-1" })
+ let releaseRead!: () => void
+ const readGate = new Promise<void>((resolve) => {
+ releaseRead = resolve
+ })
+ getCommunityApiFetchMock().mockImplementation(async (url: unknown) => {
+ if (typeof url === "string" && url.endsWith("/read")) {
+ await readGate
+ return { changed: true, revision: 1, targetSeq: 1 }
+ }
+ if (url === "/api/community/users/me/read-state") {
+ return {
+ revision: 1,
+ readStates: [{
+ channelId: "ch-1",
+ lastReadMessageId: "message-1",
+ lastReadAt: "2026-08-27T00:00:00.000Z",
+ lastReadSeq: 1,
+ }],
+ }
+ }
+ throw new Error(`unexpected API fetch: ${String(url)}`)
+ })
+ vi.spyOn(capturedQueryClient, "invalidateQueries")
+ const lease = registerReadSurface(
+ capturedQueryClient,
+ "viewer-1",
+ { kind: "timeline", channelId: "ch-1" },
+ )
+
+ capturedOnMessage!({
+ type: "community:mention.create",
+ userId: "viewer-1",
+ messageId: "mention-current",
+ channelId: "ch-1",
+ authorName: "Alice",
+ })
+ expect(submitReadIntent(lease, {
+ kind: "timeline",
+ channelId: "ch-1",
+ messageId: "message-1",
+ seq: 1,
+ })).toBe(true)
+ await vi.advanceTimersByTimeAsync(500)
+ await vi.waitFor(() => expect(getCommunityApiFetchMock()).toHaveBeenCalledWith(
+ "/api/community/channels/ch-1/read",
+ expect.anything(),
+ ))
+
+ capturedOnMessage!({
+ type: "community:mention.create",
+ userId: "viewer-1",
+ messageId: "mention-next",
+ channelId: "ch-1",
+ authorName: "Alice",
+ })
+ capturedOnMessage!({
+ ...message,
+ message: { ...message.message, id: "message-next", seq: 2 },
+ })
+ releaseRead()
+ await vi.advanceTimersByTimeAsync(500)
+
+ expect(invalidationCount(communityKeys.inbox())).toBe(1)
+ expect(invalidationCount(communityKeys.dms())).toBe(1)
+ releaseReadSurface(lease)
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it("carries a deferred wide generation into its narrower successor", async () => {
+ vi.useFakeTimers()
+ try {
+ useCommunityStore.getState().subscribe({ channelId: "ch-1" })
+ await mountHook({ viewerUserId: "viewer-1" })
+ let releaseRead!: () => void
+ const readGate = new Promise<void>((resolve) => {
+ releaseRead = resolve
+ })
+ getCommunityApiFetchMock().mockImplementation(async (url: unknown) => {
+ if (typeof url === "string" && url.endsWith("/read")) {
+ await readGate
+ return { changed: true, revision: 1, targetSeq: 1 }
+ }
+ if (url === "/api/community/users/me/read-state") {
+ return {
+ revision: 1,
+ readStates: [{
+ channelId: "ch-1",
+ lastReadMessageId: "message-1",
+ lastReadAt: "2026-08-27T00:00:00.000Z",
+ lastReadSeq: 1,
+ }],
+ }
+ }
+ throw new Error(`unexpected API fetch: ${String(url)}`)
+ })
+ vi.spyOn(capturedQueryClient, "invalidateQueries")
+ const lease = registerReadSurface(
+ capturedQueryClient,
+ "viewer-1",
+ { kind: "timeline", channelId: "ch-1" },
+ )
+
+ capturedOnMessage!(message)
+ expect(submitReadIntent(lease, {
+ kind: "timeline",
+ channelId: "ch-1",
+ messageId: "message-1",
+ seq: 1,
+ })).toBe(true)
+ await vi.advanceTimersByTimeAsync(500)
+ await vi.waitFor(() => expect(getCommunityApiFetchMock()).toHaveBeenCalledWith(
+ "/api/community/channels/ch-1/read",
+ expect.anything(),
+ ))
+
+ capturedOnMessage!({
+ type: "community:mention.create",
+ userId: "viewer-1",
+ messageId: "mention-2",
+ channelId: "ch-1",
+ authorName: "Alice",
+ })
+ releaseRead()
+ await vi.advanceTimersByTimeAsync(500)
+
+ expect(invalidationCount(communityKeys.inbox())).toBe(1)
+ expect(invalidationCount(communityKeys.dms())).toBe(1)
+ releaseReadSurface(lease)
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it("skips current raw refresh when a deferred later intent has no owner successor", async () => {
+ vi.useFakeTimers()
+ try {
+ useCommunityStore.getState().subscribe({ channelId: "ch-1" })
+ await mountHook({ viewerUserId: "viewer-1" })
+ let releaseFirstRead!: () => void
+ const firstReadGate = new Promise<void>((resolve) => {
+ releaseFirstRead = resolve
+ })
+ let readCalls = 0
+ getCommunityApiFetchMock().mockImplementation(async (url: unknown) => {
+ if (typeof url === "string" && url.endsWith("/read")) {
+ readCalls += 1
+ if (readCalls === 1) await firstReadGate
+ return { changed: true, revision: readCalls, targetSeq: readCalls }
+ }
+ if (url === "/api/community/users/me/read-state") {
+ return {
+ revision: readCalls,
+ readStates: [{
+ channelId: "ch-1",
+ lastReadMessageId: `message-${readCalls}`,
+ lastReadAt: "2026-08-27T00:00:00.000Z",
+ lastReadSeq: readCalls,
+ }],
+ }
+ }
+ throw new Error(`unexpected API fetch: ${String(url)}`)
+ })
+ vi.spyOn(capturedQueryClient, "invalidateQueries")
+ const lease = registerReadSurface(
+ capturedQueryClient,
+ "viewer-1",
+ { kind: "timeline", channelId: "ch-1" },
+ )
+
+ capturedOnMessage!(message)
+ expect(submitReadIntent(lease, {
+ kind: "timeline",
+ channelId: "ch-1",
+ messageId: "message-1",
+ seq: 1,
+ })).toBe(true)
+ await vi.advanceTimersByTimeAsync(500)
+ await vi.waitFor(() => expect(readCalls).toBe(1))
+
+ expect(submitReadIntent(lease, {
+ kind: "timeline",
+ channelId: "ch-1",
+ messageId: "message-2",
+ seq: 2,
+ })).toBe(true)
+ releaseFirstRead()
+ await vi.advanceTimersByTimeAsync(499)
+ expect(readCalls).toBe(1)
+ expect(invalidationCount(communityKeys.inbox())).toBe(0)
+ expect(invalidationCount(communityKeys.dms())).toBe(0)
+
+ await vi.advanceTimersByTimeAsync(1)
+ await vi.waitFor(() => expect(readCalls).toBe(2))
+ await vi.waitFor(() => {
+ expect(invalidationCount(communityKeys.inbox())).toBe(1)
+ expect(invalidationCount(communityKeys.dms())).toBe(1)
+ })
+ releaseReadSurface(lease)
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
it("decodes all children before one dispatch, deduplicates invalidations, and suppresses same-digest replay", async () => {
- await mountHook({ viewerUserId: "viewer-1" })
- capturedQueryClient.setQueryData(communityKeys.servers(), {
- servers: [{ id: "server-1", mentions: 5 }],
- })
- vi.spyOn(capturedQueryClient, "invalidateQueries")
- const frame = await batchFor("message-1", mentionEvents)
+ vi.useFakeTimers()
+ try {
+ await mountHook({ viewerUserId: "viewer-1" })
+ capturedQueryClient.setQueryData(communityKeys.servers(), {
+ servers: [{ id: "server-1", mentions: 5 }],
+ })
+ vi.spyOn(capturedQueryClient, "invalidateQueries")
+ const frame = await batchFor("message-1", mentionEvents)
- capturedOnMessage!(frame)
- expect(capturedQueryClient.getQueryData<{ servers: Array<{ id: string; mentions: number }> }>(
- communityKeys.servers(),
- )?.servers[0]?.mentions).toBe(5)
- expect(invalidationCount(communityKeys.inbox())).toBe(1)
- expect(invalidationCount(communityKeys.dms())).toBe(1)
- expect(invalidationCount(communityKeys.servers())).toBe(1)
-
- const callsAfterFirst = vi.mocked(capturedQueryClient.invalidateQueries).mock.calls.length
- capturedOnMessage!(frame)
- expect(vi.mocked(capturedQueryClient.invalidateQueries)).toHaveBeenCalledTimes(callsAfterFirst)
- const { useCommunityWsStore } = await import("@/stores/community/ws")
- expect(useCommunityWsStore.getState().seenDeliveryOperations.get(frame.operationId))
- .toEqual({ digest: frame.operationDigest, completed: true })
+ capturedOnMessage!(frame)
+ expect(capturedQueryClient.getQueryData<{ servers: Array<{ id: string; mentions: number }> }>(
+ communityKeys.servers(),
+ )?.servers[0]?.mentions).toBe(5)
+ expect(invalidationCount(communityKeys.inbox())).toBe(0)
+ expect(invalidationCount(communityKeys.dms())).toBe(0)
+ expect(invalidationCount(communityKeys.servers())).toBe(1)
+ await vi.advanceTimersByTimeAsync(500)
+ expect(invalidationCount(communityKeys.inbox())).toBe(1)
+ expect(invalidationCount(communityKeys.dms())).toBe(1)
+
+ const callsAfterFirst = vi.mocked(capturedQueryClient.invalidateQueries).mock.calls.length
+ capturedOnMessage!(frame)
+ await vi.advanceTimersByTimeAsync(500)
+ expect(vi.mocked(capturedQueryClient.invalidateQueries)).toHaveBeenCalledTimes(callsAfterFirst)
+ const { useCommunityWsStore } = await import("@/stores/community/ws")
+ expect(useCommunityWsStore.getState().seenDeliveryOperations.get(frame.operationId))
+ .toEqual({ digest: frame.operationDigest, completed: true })
+ } finally {
+ vi.useRealTimers()
+ }
})
it("treats repair-then-late-bundle mention state as authoritative invalidation, never arithmetic", async () => {
- await mountHook({ viewerUserId: "viewer-1" })
- const { useCommunityWsStore } = await import("@/stores/community/ws")
- useCommunityWsStore.getState().markSeenMessage(message.message.id)
- capturedQueryClient.setQueryData(communityKeys.servers(), {
- servers: [{ id: "server-1", mentions: 9 }],
- })
- vi.spyOn(capturedQueryClient, "invalidateQueries")
+ vi.useFakeTimers()
+ try {
+ await mountHook({ viewerUserId: "viewer-1" })
+ const { useCommunityWsStore } = await import("@/stores/community/ws")
+ useCommunityWsStore.getState().markSeenMessage(message.message.id)
+ capturedQueryClient.setQueryData(communityKeys.servers(), {
+ servers: [{ id: "server-1", mentions: 9 }],
+ })
+ vi.spyOn(capturedQueryClient, "invalidateQueries")
- capturedOnMessage!(await batchFor("message-late", mentionEvents))
- expect(capturedQueryClient.getQueryData<{ servers: Array<{ mentions: number }> }>(
- communityKeys.servers(),
- )?.servers[0]?.mentions).toBe(9)
- expect(invalidationCount(communityKeys.inbox())).toBe(1)
- expect(invalidationCount(communityKeys.dms())).toBe(1)
- expect(invalidationCount(communityKeys.servers())).toBe(1)
+ capturedOnMessage!(await batchFor("message-late", mentionEvents))
+ expect(capturedQueryClient.getQueryData<{ servers: Array<{ mentions: number }> }>(
+ communityKeys.servers(),
+ )?.servers[0]?.mentions).toBe(9)
+ expect(invalidationCount(communityKeys.inbox())).toBe(0)
+ expect(invalidationCount(communityKeys.dms())).toBe(0)
+ expect(invalidationCount(communityKeys.servers())).toBe(1)
+ await vi.advanceTimersByTimeAsync(500)
+ expect(invalidationCount(communityKeys.inbox())).toBe(1)
+ expect(invalidationCount(communityKeys.dms())).toBe(1)
+ } finally {
+ vi.useRealTimers()
+ }
})
it("rejects malformed children without poisoning the operation map", async () => {
@@ -408,6 +645,136 @@ describe("useCommunityWs — operation bundles", () => {
.toHaveBeenCalledTimes(invalidationsAfterSuccess)
})
+ it.each(["before", "after"] as const)(
+ "keeps one barrier-owned refresh when an identical retry lands %s the first deadline",
+ async (retryTiming) => {
+ vi.useFakeTimers()
+ try {
+ useCommunityStore.getState().subscribe({ channelId: "ch-1" })
+ await mountHook({ viewerUserId: "viewer-1" })
+ capturedQueryClient.setQueryData(communityKeys.server("s1"), {
+ id: "s1",
+ categories: [{
+ id: "category-1",
+ channels: [{ id: "parent-1", type: "text", unread: false }],
+ }],
+ })
+ getCommunityApiFetchMock().mockImplementation(async (url: unknown) => {
+ if (typeof url === "string" && url.endsWith("/read")) {
+ return { changed: true, revision: 1, targetSeq: 1 }
+ }
+ if (url === "/api/community/users/me/read-state") {
+ return {
+ revision: 1,
+ readStates: [{
+ channelId: "ch-1",
+ lastReadMessageId: `retry-${retryTiming}`,
+ lastReadAt: "2026-08-27T00:00:00.000Z",
+ lastReadSeq: 1,
+ }],
+ }
+ }
+ throw new Error(`unexpected API fetch: ${String(url)}`)
+ })
+ const setQueryData = vi.spyOn(capturedQueryClient, "setQueryData")
+ .mockImplementationOnce(() => { throw new Error("later child fault") })
+ vi.spyOn(capturedQueryClient, "invalidateQueries")
+ const messageId = `retry-${retryTiming}`
+ const frame = await batchFor(messageId, [
+ {
+ ...message,
+ serverId: "s1",
+ parentChannelId: "parent-1",
+ message: { ...message.message, id: messageId },
+ },
+ {
+ type: "community:unread.bump",
+ userId: "viewer-1",
+ channelId: "ch-1",
+ serverId: "s1",
+ railChannelId: "parent-1",
+ isMention: false,
+ },
+ ])
+ const lease = registerReadSurface(
+ capturedQueryClient,
+ "viewer-1",
+ { kind: "timeline", channelId: "ch-1" },
+ )
+
+ capturedOnMessage!(frame)
+ expect(reconcileCommunityWsReconnect).toHaveBeenCalledWith(
+ capturedQueryClient,
+ 0,
+ { excludePolicies: ["inbox-dms"] },
+ )
+ expect(invalidationCount(communityKeys.inbox())).toBe(0)
+ expect(invalidationCount(communityKeys.dms())).toBe(0)
+ expect(submitReadIntent(lease, {
+ kind: "timeline",
+ channelId: "ch-1",
+ messageId,
+ seq: 1,
+ })).toBe(true)
+
+ setQueryData.mockRestore()
+ if (retryTiming === "before") capturedOnMessage!(frame)
+ await vi.advanceTimersByTimeAsync(500)
+ expect(invalidationCount(communityKeys.inbox())).toBe(1)
+ expect(invalidationCount(communityKeys.dms())).toBe(1)
+ if (retryTiming === "after") capturedOnMessage!(frame)
+ await vi.advanceTimersByTimeAsync(500)
+
+ expect(invalidationCount(communityKeys.inbox())).toBe(1)
+ expect(invalidationCount(communityKeys.dms())).toBe(1)
+ const { useCommunityWsStore } = await import("@/stores/community/ws")
+ expect(useCommunityWsStore.getState().seenDeliveryOperations.get(frame.operationId))
+ .toEqual({ digest: frame.operationDigest, completed: true })
+ releaseReadSurface(lease)
+ } finally {
+ vi.useRealTimers()
+ }
+ },
+ )
+
+ it("bounds normal and conflict refresh keys with the delivery-operation limits", async () => {
+ vi.useFakeTimers()
+ try {
+ await mountHook({ viewerUserId: "viewer-1" })
+ vi.spyOn(capturedQueryClient, "invalidateQueries")
+ const original = await batchFor("bounded-operation", [{
+ ...message,
+ message: { ...message.message, id: "bounded-operation" },
+ }])
+ capturedOnMessage!(original)
+ const conflicts: Awaited<ReturnType<typeof batchFor>>[] = []
+ for (let index = 0; index < SEEN_DELIVERY_OPERATION_MAX; index += 1) {
+ const conflict = await batchFor("bounded-operation", [{
+ ...message,
+ message: {
+ ...message.message,
+ id: "bounded-operation",
+ content: `conflict-${index}`,
+ },
+ }])
+ conflicts.push(conflict)
+ capturedOnMessage!(conflict)
+ }
+
+ await vi.advanceTimersByTimeAsync(500)
+ expect(invalidationCount(communityKeys.inbox())).toBe(1)
+ capturedOnMessage!(conflicts[0]!)
+ await vi.advanceTimersByTimeAsync(500)
+ expect(invalidationCount(communityKeys.inbox())).toBe(2)
+ capturedOnMessage!(conflicts.at(-1)!)
+ await vi.advanceTimersByTimeAsync(500)
+ expect(invalidationCount(communityKeys.inbox())).toBe(2)
+ expect(SEEN_DELIVERY_OPERATION_TRIM_TO).toBeLessThan(SEEN_DELIVERY_OPERATION_MAX)
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
it("reports a rejected authoritative reconciliation after a digest conflict", async () => {
const warn = vi.spyOn(console, "warn").mockImplementation(() => {})
reconcileCommunityWsReconnect.mockRejectedValueOnce(new Error("reconcile unavailable"))
diff --git a/src/web/src/hooks/community/community-ws/handler-context.ts b/src/web/src/hooks/community/community-ws/handler-context.ts
index 3a3c80481..f92462b9c 100644
--- a/src/web/src/hooks/community/community-ws/handler-context.ts
+++ b/src/web/src/hooks/community/community-ws/handler-context.ts
@@ -21,6 +21,11 @@ export type UseCommunityWsOptions = {
viewerUserId?: string | null
}
+export type CommunityInboxRefreshRequest = {
+ inbox: true
+ dms: boolean
+}
+
export type CommunityWsDispatchContext = {
deliveryMode: "single" | "batch"
queryClient: QueryClient
@@ -29,7 +34,7 @@ export type CommunityWsDispatchContext = {
sub: Subscription
viewerUserIdRef: { current: string | null }
matchesFocus: (event: { channelId?: string }) => boolean
- scheduleInboxInvalidate: () => void
+ scheduleInboxInvalidate: (request: CommunityInboxRefreshRequest) => void
}
export type CommunityWsHandlerContext = CommunityWsDispatchContext & {
@@ -52,6 +57,7 @@ export type MembershipEventContext = Pick<
export type SocialEventContext = Pick<
CommunityWsHandlerContext,
"deliveryMode" | "queryClient" | "sub" | "viewerUserIdRef" | "projection"
+ | "scheduleInboxInvalidate"
>
export type PresenceMachineEventContext = Pick<
CommunityWsHandlerContext,
diff --git a/src/web/src/hooks/community/community-ws/message-events.test.ts b/src/web/src/hooks/community/community-ws/message-events.test.ts
index 184b50741..f7700d3b9 100644
--- a/src/web/src/hooks/community/community-ws/message-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/message-events.test.ts
@@ -7,11 +7,17 @@ import type {
} from "@alook/shared"
import { getMessageOverlay, useMessageStreamStore } from "@/stores/community/message-stream"
import { communityKeys } from "@/lib/query-keys"
+import {
+ registerReadSurface,
+ releaseReadSurface,
+ submitReadIntent,
+} from "@/hooks/community/read-coordinator"
import {
capturedOnMessage,
capturedQueryClient,
cleanupCommunityWsHarness,
forumSidebarFixture,
+ getCommunityApiFetchMock,
markReadMutate,
messageCreate,
mountHook,
@@ -500,7 +506,7 @@ describe("useCommunityWs — message.create", () => {
// Before debounce window, no invalidate.
expect(invalidateSpy).not.toHaveBeenCalled()
// Advance past the debounce window — exactly one invalidate.
- vi.advanceTimersByTime(500)
+ await vi.advanceTimersByTimeAsync(500)
const inboxCalls = invalidateSpy.mock.calls.filter((c) => {
const key = c[0]?.queryKey
return Array.isArray(key) && key.includes("inbox")
@@ -511,6 +517,71 @@ describe("useCommunityWs — message.create", () => {
}
})
+ it("holds a focused refresh until the visible read reconciles authoritatively", async () => {
+ vi.useFakeTimers()
+ try {
+ const order: string[] = []
+ getCommunityApiFetchMock().mockImplementation(async (url: unknown) => {
+ if (typeof url === "string" && url.endsWith("/read")) {
+ order.push("read-put")
+ return { changed: true, revision: 1, targetSeq: 1 }
+ }
+ if (url === "/api/community/users/me/read-state") {
+ order.push("read-snapshot")
+ return {
+ revision: 1,
+ readStates: [{
+ channelId: "ch_focused",
+ lastReadMessageId: "m_visible",
+ lastReadAt: "2026-08-27T00:00:00.000Z",
+ lastReadSeq: 1,
+ }],
+ }
+ }
+ throw new Error(`unexpected API fetch: ${String(url)}`)
+ })
+ await mountHook({ viewerUserId: "u_me" })
+ const { useCommunityStore } = await import("@/stores/community")
+ useCommunityStore.getState().subscribe({ channelId: "ch_focused" })
+ resetHookMemoization()
+ await mountHook({ viewerUserId: "u_me" })
+ const originalInvalidate = capturedQueryClient.invalidateQueries.bind(capturedQueryClient)
+ const invalidate = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ .mockImplementation((filters, options) => {
+ const key = filters.queryKey as unknown[] | undefined
+ if (Array.isArray(key) && key.includes("inbox")) order.push("inbox-refresh")
+ return originalInvalidate(filters, options)
+ })
+ const lease = registerReadSurface(
+ capturedQueryClient,
+ "u_me",
+ { kind: "timeline", channelId: "ch_focused" },
+ )
+ const event = messageCreate("ch_focused", "m_visible")
+
+ capturedOnMessage!(event)
+ expect(submitReadIntent(lease, {
+ kind: "timeline",
+ channelId: "ch_focused",
+ messageId: "m_visible",
+ seq: 1,
+ })).toBe(true)
+ expect(invalidate).not.toHaveBeenCalled()
+
+ await vi.advanceTimersByTimeAsync(500)
+ await vi.waitFor(() => expect(order).toContain("inbox-refresh"))
+ expect(order.indexOf("read-put")).toBeLessThan(order.indexOf("inbox-refresh"))
+ expect(order.indexOf("read-snapshot")).toBeLessThan(order.indexOf("inbox-refresh"))
+ expect(invalidate.mock.calls.filter(([filters]) => {
+ const key = filters.queryKey as unknown[] | undefined
+ return Array.isArray(key) && key.includes("inbox")
+ })).toHaveLength(1)
+ releaseReadSurface(lease)
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
})
describe("useCommunityWs — reactions", () => {
it("patches a mounted single-message opener idempotently under actor self-echo", async () => {
@@ -758,7 +829,7 @@ describe("useCommunityWs — DM message.create", () => {
[...getMessageOverlay({ kind: "dm", id: "dm_1" }).liveById.values()].map((message) => message.id),
).toEqual(["dm_m_1"])
// The inbox + `dms()` invalidation is batched behind the inbox debounce.
- vi.advanceTimersByTime(600)
+ await vi.advanceTimersByTimeAsync(600)
expect(
spy.mock.calls.some((c) => {
const key = c[0]?.queryKey as unknown[] | undefined
diff --git a/src/web/src/hooks/community/community-ws/message-events.ts b/src/web/src/hooks/community/community-ws/message-events.ts
index 3f99870c2..c9908da80 100644
--- a/src/web/src/hooks/community/community-ws/message-events.ts
+++ b/src/web/src/hooks/community/community-ws/message-events.ts
@@ -28,9 +28,7 @@ import {
} from "@/hooks/community/community-ws/message-projections"
import {
invalidateChannelMembers,
- invalidateDms,
invalidateFriends,
- invalidateInbox,
invalidatePins,
} from "@/hooks/community/community-ws/invalidation-projections"
@@ -80,8 +78,7 @@ export function handleMessageCreate(
}
const viewerId = viewerUserIdRef.current
if (deliveryMode === "batch" && event.message.authorId !== viewerId) {
- invalidateInbox(projection)
- invalidateDms(projection)
+ scheduleInboxInvalidate({ inbox: true, dms: true })
}
if (wsStore.hasSeenMessage(event.message.id)) return
wsStore.markSeenMessage(event.message.id)
@@ -132,7 +129,7 @@ export function handleMessageCreate(
// debounced inbox invalidation. Skip messages authored by the
// viewer since they never affect their own unreads.
if (deliveryMode === "single" && event.message.authorId !== viewerId) {
- scheduleInboxInvalidate()
+ scheduleInboxInvalidate({ inbox: true, dms: true })
}
// 3) Live channel-sidebar unread dot is NO LONGER flipped here.
diff --git a/src/web/src/hooks/community/community-ws/read-state-events.test.ts b/src/web/src/hooks/community/community-ws/read-state-events.test.ts
index 47b6c4ded..5def451f6 100644
--- a/src/web/src/hooks/community/community-ws/read-state-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/read-state-events.test.ts
@@ -10,7 +10,10 @@ vi.mock("@/lib/api/client", () => ({
import { dispatchCommunityWsEvent } from "./registry"
import type { CommunityWsDispatchContext } from "./handler-context"
-function context(queryClient: QueryClient): CommunityWsDispatchContext {
+function context(
+ queryClient: QueryClient,
+ scheduleInboxInvalidate = vi.fn(),
+): CommunityWsDispatchContext {
return {
deliveryMode: "single",
queryClient,
@@ -19,7 +22,7 @@ function context(queryClient: QueryClient): CommunityWsDispatchContext {
sub: {},
viewerUserIdRef: { current: "u1" },
matchesFocus: () => false,
- scheduleInboxInvalidate: vi.fn(),
+ scheduleInboxInvalidate,
}
}
@@ -146,4 +149,45 @@ describe("same-account read-state WS events", () => {
expect(queryClient.getQueryData(communityKeys.accountReadStateSnapshot()))
.toMatchObject({ revision: 2 })
})
+
+ it("schedules the owner immediately while the snapshot repairs only non-Inbox surfaces", async () => {
+ queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
+ revision: 2,
+ readStates: [],
+ })
+ let resolveSnapshot!: (value: unknown) => void
+ apiFetch.mockReturnValue(new Promise((resolve) => { resolveSnapshot = resolve }))
+ const invalidate = vi.spyOn(queryClient, "invalidateQueries")
+ const scheduleInboxInvalidate = vi.fn()
+
+ dispatchCommunityWsEvent({
+ type: "community:inbox.changed",
+ revision: 3,
+ inboxChanged: true,
+ reason: "read_all",
+ }, context(queryClient, scheduleInboxInvalidate))
+
+ expect(scheduleInboxInvalidate).toHaveBeenCalledOnce()
+ expect(scheduleInboxInvalidate).toHaveBeenCalledWith({ inbox: true, dms: true })
+ expect(invalidate).not.toHaveBeenCalledWith(expect.objectContaining({
+ queryKey: communityKeys.inbox(),
+ }), expect.anything())
+ expect(invalidate).not.toHaveBeenCalledWith(expect.objectContaining({
+ queryKey: communityKeys.dms(),
+ }), expect.anything())
+
+ resolveSnapshot({ revision: 3, readStates: [] })
+ await vi.waitFor(() => {
+ expect(invalidate).toHaveBeenCalledWith(
+ expect.objectContaining({ queryKey: communityKeys.servers() }),
+ expect.anything(),
+ )
+ })
+ expect(invalidate).not.toHaveBeenCalledWith(expect.objectContaining({
+ queryKey: communityKeys.inbox(),
+ }), expect.anything())
+ expect(invalidate).not.toHaveBeenCalledWith(expect.objectContaining({
+ queryKey: communityKeys.dms(),
+ }), expect.anything())
+ })
})
diff --git a/src/web/src/hooks/community/community-ws/read-state-reconciliation.test.ts b/src/web/src/hooks/community/community-ws/read-state-reconciliation.test.ts
index 019e328b3..013d78b62 100644
--- a/src/web/src/hooks/community/community-ws/read-state-reconciliation.test.ts
+++ b/src/web/src/hooks/community/community-ws/read-state-reconciliation.test.ts
@@ -73,6 +73,26 @@ describe("account read-state reconciliation", () => {
})
})
+ it("uses all surfaces when options are omitted", async () => {
+ apiFetch.mockResolvedValue({ revision: 1, readStates: [] })
+ const invalidate = vi.spyOn(queryClient, "invalidateQueries")
+
+ await expect(reconcileAccountReadState(queryClient)).resolves.toEqual({
+ revision: 1,
+ readStates: [],
+ })
+
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: communityKeys.inbox(),
+ refetchType: "active",
+ }, { throwOnError: true, cancelRefetch: true })
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: communityKeys.servers(),
+ exact: true,
+ refetchType: "active",
+ }, { throwOnError: true, cancelRefetch: true })
+ })
+
it("reprojects leaf caches when a lifecycle read returns the current revision", async () => {
queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
revision: 10,
@@ -277,6 +297,31 @@ describe("account read-state reconciliation", () => {
vi.useRealTimers()
})
+ it("contains a rejected snapshot retry and rearms the next backoff", async () => {
+ vi.useFakeTimers()
+ queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
+ revision: 4,
+ readStates: [],
+ })
+ apiFetch
+ .mockRejectedValueOnce(new Error("first snapshot failure"))
+ .mockRejectedValueOnce(new Error("second snapshot failure"))
+ .mockResolvedValueOnce({ revision: 5, readStates: [] })
+
+ await expect(reconcileAccountReadState(queryClient, {
+ invalidateSurfaces: false,
+ targetRevision: 5,
+ })).rejects.toThrow("first snapshot failure")
+ await vi.advanceTimersByTimeAsync(100)
+ await vi.waitFor(() => expect(apiFetch).toHaveBeenCalledTimes(2))
+ await vi.advanceTimersByTimeAsync(200)
+ await vi.waitFor(() => expect(queryClient.getQueryData(
+ communityKeys.accountReadStateSnapshot(),
+ )).toMatchObject({ revision: 5 }))
+ expect(apiFetch).toHaveBeenCalledTimes(3)
+ vi.useRealTimers()
+ })
+
it("cancels retained retry work on exit without another GET or projection", async () => {
vi.useFakeTimers()
queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
@@ -393,6 +438,86 @@ describe("account read-state reconciliation", () => {
unsubscribe()
})
+ it("contains a rejected Inbox retry and rearms the next backoff", async () => {
+ vi.useFakeTimers()
+ apiFetch.mockResolvedValue({ revision: 1, readStates: [] })
+ let inboxFetches = 0
+ const inboxObserver = new QueryObserver(queryClient, {
+ queryKey: communityKeys.inbox(),
+ queryFn: async () => {
+ inboxFetches += 1
+ if (inboxFetches === 2 || inboxFetches === 3) {
+ throw new Error("temporary inbox failure")
+ }
+ return []
+ },
+ })
+ const unsubscribe = inboxObserver.subscribe(() => undefined)
+ await vi.waitFor(() => expect(inboxObserver.getCurrentResult().status).toBe("success"))
+
+ await expect(reconcileAccountReadState(queryClient, {
+ surfaceMode: "inbox-dms",
+ targetRevision: 1,
+ })).rejects.toThrow("read-state surface reconciliation failed")
+ await vi.advanceTimersByTimeAsync(100)
+ await vi.waitFor(() => expect(inboxFetches).toBe(3))
+ await vi.advanceTimersByTimeAsync(200)
+ await vi.waitFor(() => expect(inboxFetches).toBe(4))
+
+ expect(inboxObserver.getCurrentResult()).toMatchObject({ status: "success", data: [] })
+ unsubscribe()
+ vi.useRealTimers()
+ })
+
+ it("contains failed surface kicks after snapshot recovery and retries both families", async () => {
+ vi.useFakeTimers()
+ apiFetch
+ .mockRejectedValueOnce(new Error("snapshot unavailable"))
+ .mockResolvedValueOnce({ revision: 1, readStates: [] })
+ let inboxFetches = 0
+ const inboxObserver = new QueryObserver(queryClient, {
+ queryKey: communityKeys.inbox(),
+ queryFn: async () => {
+ inboxFetches += 1
+ if (inboxFetches === 2) throw new Error("inbox kick failed")
+ return []
+ },
+ })
+ let serverFetches = 0
+ const serverObserver = new QueryObserver(queryClient, {
+ queryKey: communityKeys.server("server-1"),
+ queryFn: async () => {
+ serverFetches += 1
+ if (serverFetches === 2) throw new Error("server kick failed")
+ return { id: "server-1" }
+ },
+ })
+ const unsubscribeInbox = inboxObserver.subscribe(() => undefined)
+ const unsubscribeServer = serverObserver.subscribe(() => undefined)
+ await Promise.all([
+ vi.waitFor(() => expect(inboxObserver.getCurrentResult().status).toBe("success")),
+ vi.waitFor(() => expect(serverObserver.getCurrentResult().status).toBe("success")),
+ ])
+
+ await expect(reconcileAccountReadState(queryClient, {
+ targetRevision: 1,
+ })).rejects.toThrow("snapshot unavailable")
+ await vi.advanceTimersByTimeAsync(100)
+ await vi.waitFor(() => {
+ expect(inboxFetches).toBe(2)
+ expect(serverFetches).toBe(2)
+ })
+ await vi.advanceTimersByTimeAsync(100)
+ await vi.waitFor(() => {
+ expect(inboxFetches).toBe(3)
+ expect(serverFetches).toBe(3)
+ })
+
+ unsubscribeInbox()
+ unsubscribeServer()
+ vi.useRealTimers()
+ })
+
it("coalesces repeated live hints into one retry worker without a request storm", async () => {
queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
revision: 4,
@@ -413,7 +538,61 @@ describe("account read-state reconciliation", () => {
expect(apiFetch).toHaveBeenCalledTimes(1)
})
- it("runs a second derived pass when a newer hint arrives during invalidation", async () => {
+ it("lets post-PUT consumption finish on Inbox/DM while server retry stays independent", async () => {
+ vi.useFakeTimers()
+ queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
+ revision: 4,
+ readStates: [],
+ })
+ apiFetch.mockResolvedValue({ revision: 5, readStates: [] })
+
+ let inboxFetches = 0
+ const inboxObserver = new QueryObserver(queryClient, {
+ queryKey: communityKeys.inbox(),
+ queryFn: async () => {
+ inboxFetches += 1
+ return []
+ },
+ })
+ const unsubscribeInbox = inboxObserver.subscribe(() => undefined)
+
+ let serverFetches = 0
+ const serverObserver = new QueryObserver(queryClient, {
+ queryKey: communityKeys.server("server-1"),
+ queryFn: async () => {
+ serverFetches += 1
+ if (serverFetches === 2) throw new Error("temporary server detail failure")
+ return { id: "server-1" }
+ },
+ })
+ const unsubscribeServer = serverObserver.subscribe(() => undefined)
+ await Promise.all([
+ vi.waitFor(() => expect(inboxObserver.getCurrentResult().status).toBe("success")),
+ vi.waitFor(() => expect(serverObserver.getCurrentResult().status).toBe("success")),
+ ])
+
+ await expect(reconcileAccountReadState(queryClient, {
+ surfaceMode: "all",
+ awaitSurfaceMode: "inbox-dms",
+ targetRevision: 5,
+ })).resolves.toMatchObject({ revision: 5 })
+ await vi.waitFor(() => expect(serverFetches).toBe(2))
+ expect(inboxFetches).toBe(2)
+ expect(projectReadStateEnvelope(queryClient, {
+ revision: 5,
+ inboxChanged: true,
+ })).toBe("stale")
+
+ await vi.advanceTimersByTimeAsync(100)
+ await vi.waitFor(() => expect(serverFetches).toBe(3))
+ expect(inboxFetches).toBe(2)
+
+ unsubscribeInbox()
+ unsubscribeServer()
+ vi.useRealTimers()
+ })
+
+ it("advances the snapshot and runs a second derived pass during invalidation", async () => {
queryClient.setQueryData(communityKeys.accountReadStateSnapshot(), {
revision: 4,
readStates: [],
@@ -431,7 +610,7 @@ describe("account read-state reconciliation", () => {
const first = reconcileAccountReadState(queryClient, { targetRevision: 5 })
await vi.waitFor(() => expect(invalidate).toHaveBeenCalledTimes(3))
const second = reconcileAccountReadState(queryClient, { targetRevision: 6 })
- expect(apiFetch).toHaveBeenCalledTimes(1)
+ await vi.waitFor(() => expect(apiFetch).toHaveBeenCalledTimes(2))
releaseSurface()
await expect(Promise.all([first, second])).resolves.toEqual([
diff --git a/src/web/src/hooks/community/community-ws/read-state-reconciliation.ts b/src/web/src/hooks/community/community-ws/read-state-reconciliation.ts
index c4b44b943..38cdf30db 100644
--- a/src/web/src/hooks/community/community-ws/read-state-reconciliation.ts
+++ b/src/web/src/hooks/community/community-ws/read-state-reconciliation.ts
@@ -24,16 +24,26 @@ type ReconciliationState = {
highestPendingTargetRevision: number | null
snapshotRequestedGeneration: number
snapshotCompletedGeneration: number
- surfaceRequestedGeneration: number
- surfaceCompletedGeneration: number
- worker: Promise<AccountReadStateSnapshot> | null
- retryTimer: ReturnType<typeof setTimeout> | null
- retryDelayMs: number
+ inboxDmsRequestedGeneration: number
+ inboxDmsCompletedGeneration: number
+ serverRequestedGeneration: number
+ serverCompletedGeneration: number
+ snapshotWorker: Promise<AccountReadStateSnapshot> | null
+ inboxDmsWorker: Promise<void> | null
+ serverWorker: Promise<void> | null
+ snapshotRetryTimer: ReturnType<typeof setTimeout> | null
+ snapshotRetryDelayMs: number
+ inboxDmsRetryTimer: ReturnType<typeof setTimeout> | null
+ inboxDmsRetryDelayMs: number
+ serverRetryTimer: ReturnType<typeof setTimeout> | null
+ serverRetryDelayMs: number
requestController: AbortController | null
epoch: number
disposed: boolean
}
+export type ReadStateSurfaceMode = "all" | "inbox-dms" | "non-inbox" | "none"
+
const INITIAL_RETRY_DELAY_MS = 100
const MAX_RETRY_DELAY_MS = 5_000
const reconciliationStates = new WeakMap<QueryClient, ReconciliationState>()
@@ -98,7 +108,24 @@ function applyAccountReadStateSnapshot(
return "applied" as const
}
-async function invalidateReadStateSurfaces(queryClient: QueryClient) {
+async function invalidateInboxDmsSurfaces(queryClient: QueryClient) {
+ const refetchOptions = { throwOnError: true, cancelRefetch: true }
+ const settled = await Promise.allSettled([
+ queryClient.invalidateQueries(
+ { queryKey: communityKeys.inbox(), refetchType: "active" },
+ refetchOptions,
+ ),
+ queryClient.invalidateQueries(
+ { queryKey: communityKeys.dms(), refetchType: "active" },
+ refetchOptions,
+ ),
+ ])
+ if (settled.some((result) => result.status === "rejected")) {
+ throw new Error("read-state Inbox/DM reconciliation failed")
+ }
+}
+
+async function invalidateServerSurfaces(queryClient: QueryClient) {
const serverIds = new Set<string>()
for (const query of queryClient.getQueryCache().getAll()) {
const key = query.queryKey
@@ -112,14 +139,6 @@ async function invalidateReadStateSurfaces(queryClient: QueryClient) {
}
const refetchOptions = { throwOnError: true, cancelRefetch: true }
const settled = await Promise.allSettled([
- queryClient.invalidateQueries(
- { queryKey: communityKeys.inbox(), refetchType: "active" },
- refetchOptions,
- ),
- queryClient.invalidateQueries(
- { queryKey: communityKeys.dms(), refetchType: "active" },
- refetchOptions,
- ),
queryClient.invalidateQueries(
{ queryKey: communityKeys.servers(), exact: true, refetchType: "active" },
refetchOptions,
@@ -131,13 +150,18 @@ async function invalidateReadStateSurfaces(queryClient: QueryClient) {
}, refetchOptions)),
])
if (settled.some((result) => result.status === "rejected")) {
- throw new Error("read-state surface reconciliation failed")
+ throw new Error("read-state server reconciliation failed")
}
}
export async function reconcileAccountReadState(
queryClient: QueryClient,
- options: { invalidateSurfaces?: boolean; targetRevision?: number } = {},
+ options: {
+ invalidateSurfaces?: boolean
+ surfaceMode?: ReadStateSurfaceMode
+ awaitSurfaceMode?: ReadStateSurfaceMode
+ targetRevision?: number
+ } = {},
) {
if (disposedReconciliationClients.has(queryClient)) {
throw new Error("account read-state reconciliation disposed")
@@ -161,22 +185,55 @@ export async function reconcileAccountReadState(
state.snapshotRequestedGeneration += 1
}
- if (
- options.invalidateSurfaces !== false
- && state.snapshotRequestedGeneration > state.surfaceRequestedGeneration
- ) {
- // Bind derived work to the authoritative snapshot generation that caused
- // it. Callers joining the same primary read coalesce, while a newer hint
- // arriving during invalidation advances both generations and therefore
- // receives a second surface pass after its newer snapshot lands.
- state.surfaceRequestedGeneration = state.snapshotRequestedGeneration
+ const surfaceMode = options.invalidateSurfaces === false
+ ? "none"
+ : (options.surfaceMode ?? "all")
+ const awaitSurfaceMode = options.awaitSurfaceMode ?? surfaceMode
+ const requestedGeneration = state.snapshotRequestedGeneration
+ if (surfaceMode === "all" || surfaceMode === "inbox-dms") {
+ state.inboxDmsRequestedGeneration = Math.max(
+ state.inboxDmsRequestedGeneration,
+ requestedGeneration,
+ )
+ }
+ if (surfaceMode === "all" || surfaceMode === "non-inbox") {
+ state.serverRequestedGeneration = Math.max(
+ state.serverRequestedGeneration,
+ requestedGeneration,
+ )
}
- if (state.retryTimer !== null) {
- clearTimeout(state.retryTimer)
- state.retryTimer = null
+ clearReconciliationRetry(state, "snapshot")
+ if (awaitSurfaceMode === "all" || awaitSurfaceMode === "inbox-dms") {
+ clearReconciliationRetry(state, "inbox-dms")
+ }
+ if (awaitSurfaceMode === "all" || awaitSurfaceMode === "non-inbox") {
+ clearReconciliationRetry(state, "non-inbox")
+ }
+ await ensureSnapshotWorker(queryClient, state)
+ const inboxWorker = surfaceMode === "all" || surfaceMode === "inbox-dms"
+ ? ensureInboxDmsWorker(queryClient, state)
+ : null
+ const serverWorker = surfaceMode === "all" || surfaceMode === "non-inbox"
+ ? ensureServerWorker(queryClient, state)
+ : null
+ const awaited: Promise<void>[] = []
+ if (awaitSurfaceMode === "all" || awaitSurfaceMode === "inbox-dms") {
+ awaited.push(inboxWorker ?? ensureInboxDmsWorker(queryClient, state))
+ } else {
+ void inboxWorker?.catch(() => undefined)
}
- return ensureReconciliationWorker(queryClient, state)
+ if (awaitSurfaceMode === "all" || awaitSurfaceMode === "non-inbox") {
+ awaited.push(serverWorker ?? ensureServerWorker(queryClient, state))
+ } else {
+ void serverWorker?.catch(() => undefined)
+ }
+ await Promise.all(awaited)
+ const snapshot = queryClient.getQueryData<AccountReadStateSnapshot>(
+ communityKeys.accountReadStateSnapshot(),
+ )
+ if (!snapshot) throw new Error("account read-state reconciliation produced no snapshot")
+ return snapshot
}
function getReconciliationState(queryClient: QueryClient) {
@@ -186,11 +243,19 @@ function getReconciliationState(queryClient: QueryClient) {
highestPendingTargetRevision: null,
snapshotRequestedGeneration: 0,
snapshotCompletedGeneration: 0,
- surfaceRequestedGeneration: 0,
- surfaceCompletedGeneration: 0,
- worker: null,
- retryTimer: null,
- retryDelayMs: INITIAL_RETRY_DELAY_MS,
+ inboxDmsRequestedGeneration: 0,
+ inboxDmsCompletedGeneration: 0,
+ serverRequestedGeneration: 0,
+ serverCompletedGeneration: 0,
+ snapshotWorker: null,
+ inboxDmsWorker: null,
+ serverWorker: null,
+ snapshotRetryTimer: null,
+ snapshotRetryDelayMs: INITIAL_RETRY_DELAY_MS,
+ inboxDmsRetryTimer: null,
+ inboxDmsRetryDelayMs: INITIAL_RETRY_DELAY_MS,
+ serverRetryTimer: null,
+ serverRetryDelayMs: INITIAL_RETRY_DELAY_MS,
requestController: null,
epoch: 0,
disposed: false,
@@ -213,99 +278,202 @@ function hasSnapshotWork(state: ReconciliationState, currentRevision: number) {
)
}
-function hasSurfaceWork(state: ReconciliationState) {
- return state.surfaceCompletedGeneration < state.surfaceRequestedGeneration
+function hasInboxDmsWork(state: ReconciliationState) {
+ return state.inboxDmsCompletedGeneration < state.inboxDmsRequestedGeneration
}
-function hasReconciliationWork(queryClient: QueryClient, state: ReconciliationState) {
- return hasSnapshotWork(state, cachedAccountRevision(queryClient)) || hasSurfaceWork(state)
+function hasServerWork(state: ReconciliationState) {
+ return state.serverCompletedGeneration < state.serverRequestedGeneration
}
-function scheduleReconciliationRetry(queryClient: QueryClient, state: ReconciliationState) {
- if (
- state.disposed
- || state.retryTimer !== null
- || !hasReconciliationWork(queryClient, state)
- ) return
- const delay = state.retryDelayMs
- state.retryDelayMs = Math.min(delay * 2, MAX_RETRY_DELAY_MS)
- state.retryTimer = setTimeout(() => {
- state.retryTimer = null
- void ensureReconciliationWorker(queryClient, state).catch(() => undefined)
- }, delay)
+type RetryFamily = "snapshot" | "inbox-dms" | "non-inbox"
+
+function hasFamilyWork(
+ queryClient: QueryClient,
+ state: ReconciliationState,
+ family: RetryFamily,
+) {
+ if (family === "snapshot") {
+ return hasSnapshotWork(state, cachedAccountRevision(queryClient))
+ }
+ return family === "inbox-dms" ? hasInboxDmsWork(state) : hasServerWork(state)
}
-function ensureReconciliationWorker(queryClient: QueryClient, state: ReconciliationState) {
- if (state.disposed) return Promise.reject(new Error("account read-state reconciliation disposed"))
- if (state.worker) return state.worker
- const worker = runReconciliationWorker(queryClient, state).finally(() => {
- if (state.worker === worker) state.worker = null
- if (hasReconciliationWork(queryClient, state)) {
- scheduleReconciliationRetry(queryClient, state)
+function clearReconciliationRetry(state: ReconciliationState, family: RetryFamily) {
+ const timer = family === "snapshot"
+ ? state.snapshotRetryTimer
+ : family === "inbox-dms"
+ ? state.inboxDmsRetryTimer
+ : state.serverRetryTimer
+ if (timer !== null) clearTimeout(timer)
+ if (family === "snapshot") state.snapshotRetryTimer = null
+ else if (family === "inbox-dms") state.inboxDmsRetryTimer = null
+ else state.serverRetryTimer = null
+}
+
+function scheduleReconciliationRetry(
+ queryClient: QueryClient,
+ state: ReconciliationState,
+ family: RetryFamily,
+) {
+ const timer = family === "snapshot"
+ ? state.snapshotRetryTimer
+ : family === "inbox-dms"
+ ? state.inboxDmsRetryTimer
+ : state.serverRetryTimer
+ if (state.disposed || timer !== null || !hasFamilyWork(queryClient, state, family)) return
+ const delay = family === "snapshot"
+ ? state.snapshotRetryDelayMs
+ : family === "inbox-dms"
+ ? state.inboxDmsRetryDelayMs
+ : state.serverRetryDelayMs
+ if (family === "snapshot") {
+ state.snapshotRetryDelayMs = Math.min(delay * 2, MAX_RETRY_DELAY_MS)
+ } else if (family === "inbox-dms") {
+ state.inboxDmsRetryDelayMs = Math.min(delay * 2, MAX_RETRY_DELAY_MS)
+ } else {
+ state.serverRetryDelayMs = Math.min(delay * 2, MAX_RETRY_DELAY_MS)
+ }
+ const callback = () => {
+ if (family === "snapshot") state.snapshotRetryTimer = null
+ else if (family === "inbox-dms") state.inboxDmsRetryTimer = null
+ else state.serverRetryTimer = null
+ if (family === "snapshot") {
+ void ensureSnapshotWorker(queryClient, state)
+ .then(() => kickPendingSurfaceWorkers(queryClient, state))
+ .catch(() => undefined)
+ } else if (family === "inbox-dms") {
+ void ensureInboxDmsWorker(queryClient, state).catch(() => undefined)
+ } else {
+ void ensureServerWorker(queryClient, state).catch(() => undefined)
}
+ }
+ const nextTimer = setTimeout(callback, delay)
+ if (family === "snapshot") state.snapshotRetryTimer = nextTimer
+ else if (family === "inbox-dms") state.inboxDmsRetryTimer = nextTimer
+ else state.serverRetryTimer = nextTimer
+}
+
+function ensureSnapshotWorker(queryClient: QueryClient, state: ReconciliationState) {
+ if (state.disposed) return Promise.reject(new Error("account read-state reconciliation disposed"))
+ if (state.snapshotWorker) return state.snapshotWorker
+ const worker = runSnapshotWorker(queryClient, state).finally(() => {
+ if (state.snapshotWorker === worker) state.snapshotWorker = null
})
- state.worker = worker
+ state.snapshotWorker = worker
return worker
}
-async function runReconciliationWorker(
+async function runSnapshotWorker(
queryClient: QueryClient,
state: ReconciliationState,
): Promise<AccountReadStateSnapshot> {
const epoch = state.epoch
- while (true) {
+ while (hasSnapshotWork(state, cachedAccountRevision(queryClient))) {
+ assertReconciliationActive(queryClient, state, epoch)
+ const requestGeneration = state.snapshotRequestedGeneration
+ let snapshot: AccountReadStateSnapshot
+ try {
+ snapshot = await startAccountReadStateRequest(state)
+ } catch (error) {
+ scheduleReconciliationRetry(queryClient, state, "snapshot")
+ throw error
+ }
assertReconciliationActive(queryClient, state, epoch)
- const currentRevision = cachedAccountRevision(queryClient)
- if (hasSnapshotWork(state, currentRevision)) {
- const requestGeneration = state.snapshotRequestedGeneration
- let snapshot: AccountReadStateSnapshot
- try {
- snapshot = await startAccountReadStateRequest(state)
- } catch (error) {
- scheduleReconciliationRetry(queryClient, state)
- throw error
- }
- assertReconciliationActive(queryClient, state, epoch)
- applyAccountReadStateSnapshot(queryClient, snapshot)
- state.snapshotCompletedGeneration = Math.max(
- state.snapshotCompletedGeneration,
- requestGeneration,
- )
- const appliedRevision = cachedAccountRevision(queryClient)
- if (
- state.highestPendingTargetRevision !== null
- && appliedRevision >= state.highestPendingTargetRevision
- ) {
- state.highestPendingTargetRevision = null
- }
- // If this primary read was older than a live target, or another caller
- // arrived while it was in flight, loop immediately and issue a genuinely
- // fresh request. No timer/backoff is needed for a successful stale read.
- continue
+ applyAccountReadStateSnapshot(queryClient, snapshot)
+ state.snapshotCompletedGeneration = Math.max(
+ state.snapshotCompletedGeneration,
+ requestGeneration,
+ )
+ state.snapshotRetryDelayMs = INITIAL_RETRY_DELAY_MS
+ const appliedRevision = cachedAccountRevision(queryClient)
+ if (
+ state.highestPendingTargetRevision !== null
+ && appliedRevision >= state.highestPendingTargetRevision
+ ) {
+ state.highestPendingTargetRevision = null
}
+ // If this primary read was older than a live target, or another caller
+ // arrived while it was in flight, loop immediately and issue a genuinely
+ // fresh request. No timer/backoff is needed for a successful stale read.
+ }
+ const snapshot = queryClient.getQueryData<AccountReadStateSnapshot>(
+ communityKeys.accountReadStateSnapshot(),
+ )
+ if (!snapshot) throw new Error("account read-state reconciliation produced no snapshot")
+ return snapshot
+}
- if (hasSurfaceWork(state)) {
- const surfaceGeneration = state.surfaceRequestedGeneration
- try {
- await invalidateReadStateSurfaces(queryClient)
- } catch (error) {
- scheduleReconciliationRetry(queryClient, state)
- throw error
- }
- assertReconciliationActive(queryClient, state, epoch)
- state.surfaceCompletedGeneration = Math.max(
- state.surfaceCompletedGeneration,
- surfaceGeneration,
- )
- continue
+function ensureInboxDmsWorker(queryClient: QueryClient, state: ReconciliationState) {
+ if (state.disposed) return Promise.reject(new Error("account read-state reconciliation disposed"))
+ if (!hasInboxDmsWork(state)) return Promise.resolve()
+ if (state.inboxDmsWorker) return state.inboxDmsWorker
+ const worker = runInboxDmsWorker(queryClient, state).finally(() => {
+ if (state.inboxDmsWorker === worker) state.inboxDmsWorker = null
+ })
+ state.inboxDmsWorker = worker
+ return worker
+}
+
+async function runInboxDmsWorker(queryClient: QueryClient, state: ReconciliationState) {
+ const epoch = state.epoch
+ while (hasInboxDmsWork(state)) {
+ await ensureSnapshotWorker(queryClient, state)
+ assertReconciliationActive(queryClient, state, epoch)
+ const surfaceGeneration = state.inboxDmsRequestedGeneration
+ try {
+ await invalidateInboxDmsSurfaces(queryClient)
+ } catch {
+ scheduleReconciliationRetry(queryClient, state, "inbox-dms")
+ throw new Error("read-state surface reconciliation failed")
}
+ assertReconciliationActive(queryClient, state, epoch)
+ state.inboxDmsCompletedGeneration = Math.max(
+ state.inboxDmsCompletedGeneration,
+ surfaceGeneration,
+ )
+ state.inboxDmsRetryDelayMs = INITIAL_RETRY_DELAY_MS
+ }
+}
- const snapshot = queryClient.getQueryData<AccountReadStateSnapshot>(
- communityKeys.accountReadStateSnapshot(),
+function ensureServerWorker(queryClient: QueryClient, state: ReconciliationState) {
+ if (state.disposed) return Promise.reject(new Error("account read-state reconciliation disposed"))
+ if (!hasServerWork(state)) return Promise.resolve()
+ if (state.serverWorker) return state.serverWorker
+ const worker = runServerWorker(queryClient, state).finally(() => {
+ if (state.serverWorker === worker) state.serverWorker = null
+ })
+ state.serverWorker = worker
+ return worker
+}
+
+async function runServerWorker(queryClient: QueryClient, state: ReconciliationState) {
+ const epoch = state.epoch
+ while (hasServerWork(state)) {
+ await ensureSnapshotWorker(queryClient, state)
+ assertReconciliationActive(queryClient, state, epoch)
+ const surfaceGeneration = state.serverRequestedGeneration
+ try {
+ await invalidateServerSurfaces(queryClient)
+ } catch {
+ scheduleReconciliationRetry(queryClient, state, "non-inbox")
+ throw new Error("read-state surface reconciliation failed")
+ }
+ assertReconciliationActive(queryClient, state, epoch)
+ state.serverCompletedGeneration = Math.max(
+ state.serverCompletedGeneration,
+ surfaceGeneration,
)
- if (!snapshot) throw new Error("account read-state reconciliation produced no snapshot")
- state.retryDelayMs = INITIAL_RETRY_DELAY_MS
- return snapshot
+ state.serverRetryDelayMs = INITIAL_RETRY_DELAY_MS
+ }
+}
+
+function kickPendingSurfaceWorkers(queryClient: QueryClient, state: ReconciliationState) {
+ if (state.inboxDmsRetryTimer === null && hasInboxDmsWork(state)) {
+ void ensureInboxDmsWorker(queryClient, state).catch(() => undefined)
+ }
+ if (state.serverRetryTimer === null && hasServerWork(state)) {
+ void ensureServerWorker(queryClient, state).catch(() => undefined)
}
}
@@ -340,11 +508,11 @@ export function disposeAccountReadStateReconciliation(queryClient: QueryClient)
state.epoch += 1
state.highestPendingTargetRevision = null
state.snapshotCompletedGeneration = state.snapshotRequestedGeneration
- state.surfaceCompletedGeneration = state.surfaceRequestedGeneration
- if (state.retryTimer !== null) {
- clearTimeout(state.retryTimer)
- state.retryTimer = null
- }
+ state.inboxDmsCompletedGeneration = state.inboxDmsRequestedGeneration
+ state.serverCompletedGeneration = state.serverRequestedGeneration
+ clearReconciliationRetry(state, "snapshot")
+ clearReconciliationRetry(state, "inbox-dms")
+ clearReconciliationRetry(state, "non-inbox")
state.requestController?.abort()
state.requestController = null
}
@@ -358,7 +526,7 @@ export function projectReadStateEnvelope(
)
if (!snapshot) return "gap" as const
const state = reconciliationStates.get(queryClient)
- if (state && hasSurfaceWork(state) && envelope.revision <= snapshot.revision) {
+ if (state && hasInboxDmsWork(state) && envelope.revision <= snapshot.revision) {
return "gap" as const
}
if (envelope.revision <= snapshot.revision) return "stale" as const
diff --git a/src/web/src/hooks/community/community-ws/reconnect.test.ts b/src/web/src/hooks/community/community-ws/reconnect.test.ts
index 80b004a64..40a3435ab 100644
--- a/src/web/src/hooks/community/community-ws/reconnect.test.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect.test.ts
@@ -2,11 +2,16 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { QueryClient, QueryObserver } from "@tanstack/react-query"
import { communityKeys } from "@/lib/query-keys"
import {
+ capturedOnMessage,
capturedOnReconnect,
capturedQueryClient,
cleanupCommunityWsHarness,
+ flushEffects,
+ messageCreate,
mountHook,
+ resetHookMemoization,
resetCommunityWsHarness,
+ unmountHook,
} from "./test-harness"
const telemetry = vi.hoisted(() => ({
@@ -31,6 +36,52 @@ async function flushMicrotasks(iterations = 12) {
}
describe("useCommunityWs — resyncs machines on WS reconnect", () => {
+ it("reactivates the Inbox owner after a Strict Effects cleanup/setup replay", async () => {
+ vi.useFakeTimers()
+ await mountHook()
+ flushEffects()
+ unmountHook()
+
+ resetHookMemoization()
+ await mountHook()
+ flushEffects()
+ const invalidate = vi.spyOn(capturedQueryClient, "invalidateQueries")
+
+ capturedOnMessage?.(messageCreate("ch_effect_replay"))
+ await vi.advanceTimersByTimeAsync(500)
+
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: communityKeys.inbox() })
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: communityKeys.dms() })
+ })
+
+ it("does not re-arm the Inbox owner when reconnect repair settles after unmount", async () => {
+ vi.useFakeTimers()
+ await mountHook()
+ flushEffects()
+ let releaseRepair!: () => void
+ const repairGate = new Promise<void>((resolve) => {
+ releaseRepair = resolve
+ })
+ const invalidate = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ .mockReturnValue(repairGate)
+
+ const reconnect = capturedOnReconnect!({ reconnectDurationMs: 0 })
+ await flushMicrotasks()
+ expect(invalidate).toHaveBeenCalled()
+ unmountHook()
+ const callsAtUnmount = invalidate.mock.calls.length
+
+ releaseRepair()
+ await reconnect
+ await vi.advanceTimersByTimeAsync(500)
+
+ const lateKeys = invalidate.mock.calls.slice(callsAtUnmount).map(
+ (call) => JSON.stringify(call[0]?.queryKey),
+ )
+ expect(lateKeys).not.toContain(JSON.stringify(communityKeys.inbox()))
+ expect(lateKeys).not.toContain(JSON.stringify(communityKeys.dms()))
+ })
+
it("invalidates communityKeys.machines() when the captured onReconnect fires", async () => {
await mountHook()
const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
@@ -52,6 +103,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
})
it("reconciles the focused channel's messages + inbox on reconnect, but NOT the read-state snapshot", async () => {
+ vi.useFakeTimers()
const { useCommunityStore } = await import("@/stores/community")
useCommunityStore.getState().subscribe({ channelId: "ch_focus" })
@@ -61,7 +113,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
expect(capturedOnReconnect).not.toBeNull()
await capturedOnReconnect!({ reconnectDurationMs: 0 })
- const invalidatedKeys = spy.mock.calls.map(
+ let invalidatedKeys = spy.mock.calls.map(
(c) => c[0]?.queryKey as unknown[] | undefined,
)
// Focused channel messages use the bounded catch-up path instead of a
@@ -102,7 +154,17 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
k[3] === "read-state-snapshot",
),
).toBe(false)
- // Inbox
+ // Reconnect owns focused repair first; only after it completes does it
+ // schedule the single account owner generation.
+ expect(
+ invalidatedKeys.some(
+ (k) => Array.isArray(k) && k[0] === "community" && k[1] === "inbox",
+ ),
+ ).toBe(false)
+ await vi.advanceTimersByTimeAsync(500)
+ invalidatedKeys = spy.mock.calls.map(
+ (c) => c[0]?.queryKey as unknown[] | undefined,
+ )
expect(
invalidatedKeys.some(
(k) => Array.isArray(k) && k[0] === "community" && k[1] === "inbox",
@@ -377,6 +439,22 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
expect(JSON.stringify(telemetry.failure.mock.calls)).not.toContain("private sync detail")
})
+ it("can exclude only Inbox/DM repair while completing every other reconnect policy", async () => {
+ const { reconcileCommunityWsReconnect } = await import("./reconnect")
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+
+ const summary = await reconcileCommunityWsReconnect(capturedQueryClient, 0, {
+ excludePolicies: ["inbox-dms"],
+ })
+
+ const keys = spy.mock.calls.map(([filters]) => JSON.stringify(filters.queryKey))
+ expect(keys).not.toContain(JSON.stringify(communityKeys.inbox()))
+ expect(keys).not.toContain(JSON.stringify(communityKeys.dms()))
+ expect(keys).toContain(JSON.stringify(communityKeys.friends()))
+ expect(keys).toContain(JSON.stringify(communityKeys.servers()))
+ expect(summary).toMatchObject({ policyCount: 13, successCount: 13, failureCount: 0 })
+ })
+
it("resets presence and status overlays before authoritative invalidation starts", async () => {
const { reconcileCommunityWsReconnect } = await import("./reconnect")
const { useCommunityWsStore } = await import("@/stores/community/ws")
diff --git a/src/web/src/hooks/community/community-ws/reconnect.ts b/src/web/src/hooks/community/community-ws/reconnect.ts
index 32ed2b552..ad0494880 100644
--- a/src/web/src/hooks/community/community-ws/reconnect.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect.ts
@@ -272,18 +272,25 @@ export type CommunityWsReconcileSummary = {
reconnectDurationMs: number
}
+type CommunityWsReconnectOptions = {
+ excludePolicies?: readonly CommunityWsReconcilePolicy[]
+}
+
export async function reconcileCommunityWsReconnect(
queryClient: QueryClient,
reconnectDurationMs = 0,
+ options: CommunityWsReconnectOptions = {},
): Promise<CommunityWsReconcileSummary> {
const startedAt = Date.now()
const executors = policyExecutors(queryClient)
- const resetPolicies = communityWsReconnectPolicies.filter((policy) => RESET_POLICIES.has(policy))
- const focusedMessagePolicies = communityWsReconnectPolicies.filter((policy) => policy === "focused-messages")
- const focusedRoutePolicies = communityWsReconnectPolicies.filter(
+ const excludedPolicies = new Set(options.excludePolicies ?? [])
+ const policies = communityWsReconnectPolicies.filter((policy) => !excludedPolicies.has(policy))
+ const resetPolicies = policies.filter((policy) => RESET_POLICIES.has(policy))
+ const focusedMessagePolicies = policies.filter((policy) => policy === "focused-messages")
+ const focusedRoutePolicies = policies.filter(
(policy) => FOCUSED_POLICIES.has(policy) && policy !== "focused-messages",
)
- const backgroundPolicies = communityWsReconnectPolicies.filter(
+ const backgroundPolicies = policies.filter(
(policy) => !RESET_POLICIES.has(policy) && !FOCUSED_POLICIES.has(policy),
)
diff --git a/src/web/src/hooks/community/community-ws/social-events.test.ts b/src/web/src/hooks/community/community-ws/social-events.test.ts
index 9a33d4f8d..02ecf06c9 100644
--- a/src/web/src/hooks/community/community-ws/social-events.test.ts
+++ b/src/web/src/hooks/community/community-ws/social-events.test.ts
@@ -375,7 +375,7 @@ describe("useCommunityWs — message.create patches channel unread in the open s
const invalidateSpy = vi.spyOn(capturedQueryClient, "invalidateQueries")
capturedOnMessage!(messageCreate("ch_focused"))
- vi.advanceTimersByTime(500)
+ await vi.advanceTimersByTimeAsync(500)
const messagesCache = capturedQueryClient.getQueryData<{ pages: { messages: { id: string }[] }[] }>(
communityKeys.channelMessages("ch_focused"),
@@ -415,22 +415,29 @@ describe("useCommunityWs — friend + mention → invalidate", () => {
).toBe(true)
})
- it("mention.create invalidates communityKeys.inbox() immediately (no debounce)", async () => {
- await mountHook()
- const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
- const event: CommunityMentionCreate = {
- type: "community:mention.create",
- userId: "u_1",
- messageId: "m_1",
- authorName: "A",
+ it("routes mention.create through the debounced Inbox owner", async () => {
+ vi.useFakeTimers()
+ try {
+ await mountHook()
+ const spy = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ const event: CommunityMentionCreate = {
+ type: "community:mention.create",
+ userId: "u_1",
+ messageId: "m_1",
+ authorName: "A",
+ }
+ capturedOnMessage!(event)
+ expect(spy).not.toHaveBeenCalledWith({ queryKey: communityKeys.inbox() })
+ await vi.advanceTimersByTimeAsync(500)
+ expect(
+ spy.mock.calls.some((c) => {
+ const key = c[0]?.queryKey as unknown[] | undefined
+ return Array.isArray(key) && key.includes("inbox")
+ }),
+ ).toBe(true)
+ } finally {
+ vi.useRealTimers()
}
- capturedOnMessage!(event)
- expect(
- spy.mock.calls.some((c) => {
- const key = c[0]?.queryKey as unknown[] | undefined
- return Array.isArray(key) && key.includes("inbox")
- }),
- ).toBe(true)
})
it("mention.create also invalidates communityKeys.servers() so the rail badge ticks", async () => {
diff --git a/src/web/src/hooks/community/community-ws/social-events.ts b/src/web/src/hooks/community/community-ws/social-events.ts
index 001aa4dbd..fff7ff6e7 100644
--- a/src/web/src/hooks/community/community-ws/social-events.ts
+++ b/src/web/src/hooks/community/community-ws/social-events.ts
@@ -22,7 +22,6 @@ import {
import type { SocialEventContext } from "@/hooks/community/community-ws/handler-context"
import {
invalidateFriends,
- invalidateInbox,
invalidateServersList,
} from "./invalidation-projections"
import {
@@ -43,7 +42,9 @@ function applyReadStateEnvelope(
) {
const outcome = projectReadStateEnvelope(context.queryClient, event)
if (outcome === "gap") {
+ context.scheduleInboxInvalidate({ inbox: true, dms: true })
void reconcileAccountReadState(context.queryClient, {
+ surfaceMode: "non-inbox",
targetRevision: event.revision,
}).catch(() => undefined)
}
@@ -173,9 +174,9 @@ export function handleFriendEvent(
export function handleMentionCreate(
_event: CommunityMentionCreate,
- { projection }: SocialEventContext,
+ { projection, scheduleInboxInvalidate }: SocialEventContext,
) {
- invalidateInbox(projection)
+ scheduleInboxInvalidate({ inbox: true, dms: false })
// The server rail badge counts unread mentions per server; refresh
// it on every new mention. `exact: true` is essential: the mention
// count lives in the `servers()` LIST query, but members/presence/
diff --git a/src/web/src/hooks/community/community-ws/test-harness.ts b/src/web/src/hooks/community/community-ws/test-harness.ts
index c87268f88..b2c53ed8f 100644
--- a/src/web/src/hooks/community/community-ws/test-harness.ts
+++ b/src/web/src/hooks/community/community-ws/test-harness.ts
@@ -12,6 +12,10 @@ const communityApiFetch = vi.hoisted(() => vi.fn(async (...args: unknown[]) => {
throw new Error(`unexpected API fetch: ${url}`)
}))
+export function getCommunityApiFetchMock() {
+ return communityApiFetch
+}
+
vi.mock("@/lib/api/client", async () => {
const actual = await vi.importActual<typeof import("@/lib/api/client")>("@/lib/api/client")
return { ...actual, apiFetch: (...args: unknown[]) => communityApiFetch(...args) }
@@ -158,8 +162,7 @@ export async function resetCommunityWsHarness() {
}
export async function cleanupCommunityWsHarness() {
- flushEffects()
- for (const cleanup of effectCleanups.splice(0).reverse()) cleanup()
+ unmountHook()
await resetStore()
vi.clearAllTimers()
vi.useRealTimers()
@@ -168,6 +171,11 @@ export async function cleanupCommunityWsHarness() {
resetHarnessState()
}
+export function unmountHook() {
+ flushEffects()
+ for (const cleanup of effectCleanups.splice(0).reverse()) cleanup()
+}
+
export function messageCreate(channelId: string, msgId = "m_1"): CommunityMessageCreate {
return {
type: "community:message.create",
diff --git a/src/web/src/hooks/community/read-coordinator.test.ts b/src/web/src/hooks/community/read-coordinator.test.ts
index 135f8c528..0d6541b8f 100644
--- a/src/web/src/hooks/community/read-coordinator.test.ts
+++ b/src/web/src/hooks/community/read-coordinator.test.ts
@@ -15,6 +15,7 @@ vi.mock("./community-ws/read-state-reconciliation", () => ({
import {
disposeReadCoordinator,
+ flushPendingReadIntents,
getReadCoordinator,
projectReadCoordinatorSnapshot,
READ_COORDINATOR_DEBOUNCE_MS,
@@ -57,14 +58,22 @@ describe("read coordinator", () => {
vi.useRealTimers()
})
- it("is an account-owned singleton and cannot be rebuilt after disposal", () => {
+ it("is an account-owned singleton and returns an unconsumed flush before and after disposal", async () => {
const queryClient = new QueryClient()
expect(getReadCoordinator(queryClient, "user-1"))
.toBe(getReadCoordinator(queryClient, "user-1"))
expect(() => getReadCoordinator(queryClient, "user-2"))
.toThrow("read coordinator owner mismatch")
+ await expect(flushPendingReadIntents(queryClient)).resolves.toEqual({
+ consumed: false,
+ cutoff: null,
+ })
disposeReadCoordinator(queryClient)
+ await expect(flushPendingReadIntents(queryClient)).resolves.toEqual({
+ consumed: false,
+ cutoff: null,
+ })
expect(() => getReadCoordinator(queryClient, "user-1"))
.toThrow("read coordinator disposed")
})
@@ -89,6 +98,8 @@ describe("read coordinator", () => {
}),
)
expect(reconcileAccountReadState).toHaveBeenCalledWith(queryClient, {
+ awaitSurfaceMode: "inbox-dms",
+ surfaceMode: "all",
targetRevision: 9,
})
expect(submitTimeline(lease, 7)).toBe(false)
@@ -134,6 +145,8 @@ describe("read coordinator", () => {
await vi.runAllTimersAsync()
expect(apiFetch).toHaveBeenCalledTimes(5)
expect(reconcileAccountReadState).toHaveBeenCalledWith(queryClient, {
+ awaitSurfaceMode: "inbox-dms",
+ surfaceMode: "all",
targetRevision: 11,
})
})
@@ -212,8 +225,13 @@ describe("read coordinator", () => {
submitTimeline(lease, 8)
expect(apiFetch).toHaveBeenCalledTimes(1)
+ await vi.advanceTimersByTimeAsync(100)
resolveFirst({ changed: true, revision: 5, targetSeq: 3 })
- await vi.runAllTimersAsync()
+ await vi.advanceTimersByTimeAsync(0)
+
+ await vi.advanceTimersByTimeAsync(399)
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ await vi.advanceTimersByTimeAsync(1)
expect(apiFetch).toHaveBeenCalledTimes(2)
expect(apiFetch.mock.calls[1]?.[1]).toEqual(expect.objectContaining({
@@ -314,6 +332,8 @@ describe("read coordinator", () => {
expect(apiFetch).toHaveBeenCalledOnce()
expect(reconcileAccountReadState).toHaveBeenCalledWith(queryClient, {
+ awaitSurfaceMode: "inbox-dms",
+ surfaceMode: "all",
targetRevision: 14,
})
})
@@ -333,4 +353,162 @@ describe("read coordinator", () => {
await vi.advanceTimersByTimeAsync(10_000)
expect(apiFetch).toHaveBeenCalledOnce()
})
+
+ it("flushes accepted work before its debounce and consumes only after reconciliation", async () => {
+ const queryClient = new QueryClient()
+ const lease = timelineLease(queryClient)
+ apiFetch.mockResolvedValue({ changed: true, revision: 15, targetSeq: 4 })
+
+ submitTimeline(lease, 4)
+ const work = flushPendingReadIntents(queryClient)
+ expect(apiFetch).toHaveBeenCalledOnce()
+ await expect(work).resolves.toEqual({ consumed: true, cutoff: 1 })
+ expect(reconcileAccountReadState).toHaveBeenCalledWith(queryClient, {
+ awaitSurfaceMode: "inbox-dms",
+ surfaceMode: "all",
+ targetRevision: 15,
+ })
+ })
+
+ it("joins an active attempt and drains only work accepted by its cutoff", async () => {
+ const queryClient = new QueryClient()
+ const lease = timelineLease(queryClient)
+ let resolveFirst!: (value: unknown) => void
+ apiFetch
+ .mockReturnValueOnce(new Promise((resolve) => { resolveFirst = resolve }))
+ .mockResolvedValueOnce({ changed: true, revision: 17, targetSeq: 8 })
+
+ submitTimeline(lease, 3)
+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
+ submitTimeline(lease, 8)
+ const work = flushPendingReadIntents(queryClient)
+ resolveFirst({ changed: true, revision: 16, targetSeq: 3 })
+
+ await expect(work).resolves.toEqual({ consumed: true, cutoff: 2 })
+ expect(apiFetch).toHaveBeenCalledTimes(2)
+ expect(apiFetch.mock.calls[1]?.[1]).toEqual(expect.objectContaining({
+ body: JSON.stringify({ lastReadMessageId: "message-8" }),
+ }))
+ })
+
+ it("freezes the cutoff and preserves a later intent's original debounce", async () => {
+ const queryClient = new QueryClient()
+ const lease = timelineLease(queryClient)
+ let resolvePut!: (value: unknown) => void
+ let resolveReconcile!: () => void
+ apiFetch
+ .mockReturnValueOnce(new Promise((resolve) => { resolvePut = resolve }))
+ .mockResolvedValueOnce({ changed: true, revision: 19, targetSeq: 9 })
+ reconcileAccountReadState
+ .mockReturnValueOnce(new Promise<void>((resolve) => { resolveReconcile = resolve }))
+ .mockResolvedValue(undefined)
+
+ submitTimeline(lease, 3)
+ const firstFlush = flushPendingReadIntents(queryClient)
+ submitTimeline(lease, 6)
+ await vi.advanceTimersByTimeAsync(100)
+ resolvePut({ changed: true, revision: 18, targetSeq: 3 })
+ await vi.waitFor(() => expect(reconcileAccountReadState).toHaveBeenCalledOnce())
+ submitTimeline(lease, 9)
+ resolveReconcile()
+
+ await expect(firstFlush).resolves.toEqual({
+ consumed: false,
+ cutoff: 1,
+ deferred: true,
+ })
+ expect(reconcileAccountReadState).toHaveBeenCalledWith(queryClient, {
+ awaitSurfaceMode: "none",
+ surfaceMode: "non-inbox",
+ targetRevision: 18,
+ })
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ await vi.advanceTimersByTimeAsync(499)
+ expect(apiFetch).toHaveBeenCalledTimes(1)
+ await vi.advanceTimersByTimeAsync(1)
+ expect(apiFetch).toHaveBeenCalledTimes(2)
+ expect(apiFetch.mock.calls[1]?.[1]).toEqual(expect.objectContaining({
+ body: JSON.stringify({ lastReadMessageId: "message-9" }),
+ }))
+ })
+
+ it("defers Inbox/DM when the owner already queued a later generation", async () => {
+ const queryClient = new QueryClient()
+ const lease = timelineLease(queryClient)
+ apiFetch.mockResolvedValue({ changed: true, revision: 20, targetSeq: 4 })
+
+ submitTimeline(lease, 4)
+ const work = flushPendingReadIntents(queryClient, {
+ deferInboxDms: () => true,
+ })
+
+ await expect(work).resolves.toEqual({
+ consumed: false,
+ cutoff: 1,
+ deferred: true,
+ })
+ expect(reconcileAccountReadState).toHaveBeenCalledWith(queryClient, {
+ awaitSurfaceMode: "none",
+ surfaceMode: "non-inbox",
+ targetRevision: 20,
+ })
+ })
+
+ it("returns an unconsumed result without waiting through retry backoff", async () => {
+ const queryClient = new QueryClient()
+ const lease = timelineLease(queryClient)
+ apiFetch.mockRejectedValue(new ApiError("busy", 503))
+
+ submitTimeline(lease, 4)
+ await expect(flushPendingReadIntents(queryClient)).resolves.toEqual({
+ consumed: false,
+ cutoff: 1,
+ })
+ expect(apiFetch).toHaveBeenCalledOnce()
+ })
+
+ it("returns unconsumed when a joined active attempt fails", async () => {
+ const queryClient = new QueryClient()
+ const lease = timelineLease(queryClient)
+ let rejectRequest!: (error: unknown) => void
+ apiFetch.mockReturnValue(new Promise((_resolve, reject) => {
+ rejectRequest = reject
+ }))
+
+ submitTimeline(lease, 4)
+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
+ const work = flushPendingReadIntents(queryClient)
+ rejectRequest(new ApiError("busy", 503))
+
+ await expect(work).resolves.toEqual({ consumed: false, cutoff: 1 })
+ expect(apiFetch).toHaveBeenCalledOnce()
+ })
+
+ it("fences a rejected mutation completion after disposal", async () => {
+ const queryClient = new QueryClient()
+ const lease = timelineLease(queryClient)
+ let rejectRequest!: (error: unknown) => void
+ apiFetch.mockReturnValue(new Promise((_resolve, reject) => {
+ rejectRequest = reject
+ }))
+
+ submitTimeline(lease, 4)
+ await vi.advanceTimersByTimeAsync(READ_COORDINATOR_DEBOUNCE_MS)
+ disposeReadCoordinator(queryClient)
+ rejectRequest(new Error("aborted"))
+ await vi.waitFor(() => expect(reconcileAccountReadState).not.toHaveBeenCalled())
+ })
+
+ it("does not consume a committed read whose authoritative refresh fails", async () => {
+ const queryClient = new QueryClient()
+ const lease = timelineLease(queryClient)
+ apiFetch.mockResolvedValue({ changed: true, revision: 20, targetSeq: 4 })
+ reconcileAccountReadState.mockRejectedValue(new Error("surface refresh failed"))
+
+ submitTimeline(lease, 4)
+ await expect(flushPendingReadIntents(queryClient)).resolves.toEqual({
+ consumed: false,
+ cutoff: 1,
+ })
+ })
})
diff --git a/src/web/src/hooks/community/read-coordinator.ts b/src/web/src/hooks/community/read-coordinator.ts
index 192091b7a..43bce0411 100644
--- a/src/web/src/hooks/community/read-coordinator.ts
+++ b/src/web/src/hooks/community/read-coordinator.ts
@@ -23,6 +23,28 @@ export type ReadIntent = {
export type ReadSurface = { kind: "timeline"; channelId: string }
+type QueuedReadIntent = {
+ intent: ReadIntent
+ generation: number
+ dueAt: number
+}
+
+export type PendingReadFlushOutcome = {
+ consumed: boolean
+ cutoff: number | null
+ deferred?: true
+}
+
+type ReadAttemptOutcome = {
+ committed: boolean
+ reconciled: boolean
+ deferred?: true
+}
+
+type PendingReadFlushOptions = {
+ deferInboxDms?: () => boolean
+}
+
type ReadMutationResponse = {
changed: boolean
revision: number
@@ -43,12 +65,16 @@ type ScopeState = {
releaseTimer: ReturnType<typeof setTimeout> | null
timer: ReturnType<typeof setTimeout> | null
retryTimer: ReturnType<typeof setTimeout> | null
- accepted: ReadIntent | null
- dirty: ReadIntent | null
+ accepted: QueuedReadIntent | null
+ dirty: QueuedReadIntent | null
inFlight: {
- target: ReadIntent
+ target: QueuedReadIntent
controller: AbortController
attemptEpoch: number
+ phase: "mutation" | "reconciling"
+ completion: Promise<ReadAttemptOutcome>
+ drainCutoff?: number
+ deferInboxDms?: () => boolean
} | null
attemptEpoch: number
retryCount: number
@@ -62,13 +88,14 @@ function scopeKey(surface: ReadSurface) {
return `timeline:${surface.channelId}`
}
-function sameIntent(left: ReadIntent, right: ReadIntent) {
- return left.channelId === right.channelId && left.seq === right.seq
+function sameIntent(left: QueuedReadIntent, right: QueuedReadIntent) {
+ return left.intent.channelId === right.intent.channelId
+ && left.intent.seq === right.intent.seq
}
-function laterIntent(current: ReadIntent | null, incoming: ReadIntent) {
+function laterIntent(current: QueuedReadIntent | null, incoming: QueuedReadIntent) {
if (!current) return incoming
- return incoming.seq > current.seq ? incoming : current
+ return incoming.intent.seq > current.intent.seq ? incoming : current
}
function retryable(error: unknown) {
@@ -83,6 +110,7 @@ class ReadCoordinator {
private readonly states = new Map<string, ScopeState>()
private disposed = false
private identityEpoch = 0
+ private latestIntentGeneration = 0
constructor(
private readonly queryClient: QueryClient,
@@ -145,8 +173,13 @@ class ReadCoordinator {
return false
}
if (this.confirmed(state, intent)) return false
- state.accepted = laterIntent(state.accepted, intent)
- state.dirty = laterIntent(state.dirty, intent)
+ const queued = {
+ intent,
+ generation: ++this.latestIntentGeneration,
+ dueAt: Date.now() + READ_COORDINATOR_DEBOUNCE_MS,
+ }
+ state.accepted = laterIntent(state.accepted, queued)
+ state.dirty = laterIntent(state.dirty, queued)
this.schedule(state, READ_COORDINATOR_DEBOUNCE_MS)
return true
}
@@ -154,7 +187,7 @@ class ReadCoordinator {
resume() {
if (this.disposed) return
for (const state of this.states.values()) {
- if (state.dirty && !this.confirmed(state, state.dirty)) {
+ if (state.dirty && !this.confirmed(state, state.dirty.intent)) {
state.accepted = laterIntent(state.accepted, state.dirty)
state.retryCount = 0
this.schedule(state, 0)
@@ -199,7 +232,7 @@ class ReadCoordinator {
if (this.disposed || state.inFlight || state.timer !== null) return
state.timer = setTimeout(() => {
state.timer = null
- void this.send(state)
+ void this.startSend(state)
}, delay)
}
@@ -208,40 +241,128 @@ class ReadCoordinator {
clearTimeout(state.timer)
state.timer = null
}
- if (state.accepted && !state.inFlight) void this.send(state)
+ if (state.accepted && !state.inFlight) void this.startSend(state)
+ }
+
+ async flushPending(
+ options: PendingReadFlushOptions = {},
+ ): Promise<PendingReadFlushOutcome> {
+ if (this.disposed || this.latestIntentGeneration === 0) {
+ return { consumed: false, cutoff: null }
+ }
+ const cutoff = this.latestIntentGeneration
+ const results = await Promise.all(
+ [...this.states.values()].map((state) => this.flushState(state, cutoff, options)),
+ )
+ const eligible = results.filter((result) => result.eligible)
+ const settled = eligible.length > 0
+ && eligible.every((result) => result.consumed || result.deferred)
+ const consumed = eligible.length > 0
+ && eligible.every((result) => result.consumed)
+ return {
+ consumed,
+ cutoff,
+ ...(settled && !consumed ? { deferred: true as const } : {}),
+ }
}
- private async send(state: ScopeState) {
- if (this.disposed || state.inFlight) return
+ private async flushState(
+ state: ScopeState,
+ cutoff: number,
+ options: PendingReadFlushOptions,
+ ) {
+ let eligible = false
+ let deferred = false
+ while (!this.disposed) {
+ const active = state.inFlight
+ if (active) {
+ if (active.target.generation > cutoff) break
+ active.drainCutoff = Math.max(active.drainCutoff ?? cutoff, cutoff)
+ if (options.deferInboxDms) active.deferInboxDms = options.deferInboxDms
+ eligible = true
+ const outcome = await active.completion
+ if (!outcome.committed || (!outcome.reconciled && !outcome.deferred)) {
+ return { eligible, consumed: false }
+ }
+ deferred ||= outcome.deferred === true
+ continue
+ }
+
+ const target = state.accepted ?? state.dirty
+ if (!target || target.generation > cutoff) break
+ eligible = true
+ if (state.retryTimer !== null) return { eligible, consumed: false }
+ if (state.timer !== null) {
+ clearTimeout(state.timer)
+ state.timer = null
+ }
+ const outcome = await this.startSend(state, cutoff, options)
+ if (!outcome.committed || (!outcome.reconciled && !outcome.deferred)) {
+ return { eligible, consumed: false }
+ }
+ deferred ||= outcome.deferred === true
+ }
+ return { eligible, consumed: eligible && !deferred, deferred }
+ }
+
+ private startSend(
+ state: ScopeState,
+ drainCutoff?: number,
+ options: PendingReadFlushOptions = {},
+ ): Promise<ReadAttemptOutcome> {
+ /* istanbul ignore next -- private callers synchronously gate disposal before entry */
+ if (this.disposed) {
+ return Promise.resolve({ committed: false, reconciled: false })
+ }
+ if (state.inFlight) return state.inFlight.completion
const target = state.accepted ?? state.dirty
/* istanbul ignore next -- reachable transitions cancel an empty target's timer eagerly */
- if (!target || this.confirmed(state, target)) {
+ if (!target || this.confirmed(state, target.intent)) {
this.cancelConfirmedWork(state)
- return
+ return Promise.resolve({ committed: false, reconciled: false })
}
state.accepted = null
const controller = new AbortController()
const attemptEpoch = ++state.attemptEpoch
- state.inFlight = { target, controller, attemptEpoch }
+ let resolveCompletion!: (outcome: ReadAttemptOutcome) => void
+ const completion = new Promise<ReadAttemptOutcome>((resolve) => {
+ resolveCompletion = resolve
+ })
+ state.inFlight = {
+ target,
+ controller,
+ attemptEpoch,
+ phase: "mutation",
+ completion,
+ drainCutoff,
+ deferInboxDms: options.deferInboxDms,
+ }
+ void this.performSend(state, target, controller, attemptEpoch)
+ .then(resolveCompletion)
+ return completion
+ }
+
+ private async performSend(
+ state: ScopeState,
+ target: QueuedReadIntent,
+ controller: AbortController,
+ attemptEpoch: number,
+ ): Promise<ReadAttemptOutcome> {
const identityEpoch = this.identityEpoch
+ let response: ReadMutationResponse
try {
- const response = await apiFetch<ReadMutationResponse>(
- `/api/community/channels/${target.channelId}/read`,
+ response = await apiFetch<ReadMutationResponse>(
+ `/api/community/channels/${target.intent.channelId}/read`,
{
method: "PUT",
- body: JSON.stringify({ lastReadMessageId: target.messageId }),
+ body: JSON.stringify({ lastReadMessageId: target.intent.messageId }),
signal: controller.signal,
},
)
- if (!this.attemptActive(state, attemptEpoch, identityEpoch)) return
- state.confirmedSeq = Math.max(state.confirmedSeq, response.targetSeq)
- state.dirty = sameIntent(state.dirty ?? target, target) ? null : state.dirty
- state.retryCount = 0
- void reconcileAccountReadState(this.queryClient, {
- targetRevision: response.revision,
- }).catch(() => undefined)
} catch (error) {
- if (!this.attemptActive(state, attemptEpoch, identityEpoch)) return
+ if (!this.attemptActive(state, attemptEpoch, identityEpoch)) {
+ return { committed: false, reconciled: false }
+ }
if (!retryable(error)) {
if (state.dirty && sameIntent(state.dirty, target)) state.dirty = null
state.retryCount = 0
@@ -254,18 +375,79 @@ class ReadCoordinator {
this.schedule(state, 0)
}, delay)
}
- } finally {
- if (state.inFlight?.attemptEpoch === attemptEpoch) state.inFlight = null
- if (!this.disposed && state.accepted && state.retryTimer === null) {
- this.schedule(state, 0)
+ this.finishAttempt(state, attemptEpoch)
+ return { committed: false, reconciled: false }
+ }
+
+ if (!this.attemptActive(state, attemptEpoch, identityEpoch)) {
+ return { committed: false, reconciled: false }
+ }
+ state.confirmedSeq = Math.max(state.confirmedSeq, response.targetSeq)
+ state.dirty = sameIntent(state.dirty ?? target, target) ? null : state.dirty
+ state.retryCount = 0
+ if (state.inFlight?.attemptEpoch === attemptEpoch) {
+ state.inFlight.phase = "reconciling"
+ }
+ const activeAttempt = state.inFlight?.attemptEpoch === attemptEpoch
+ ? state.inFlight
+ /* istanbul ignore next -- attemptActive succeeded and no write or await can replace inFlight */
+ : null
+ const deferInboxDms = activeAttempt?.deferInboxDms?.() === true
+ || (activeAttempt?.drainCutoff !== undefined
+ && state.accepted !== null
+ && state.accepted.generation > activeAttempt.drainCutoff)
+ try {
+ await reconcileAccountReadState(this.queryClient, {
+ surfaceMode: deferInboxDms ? "non-inbox" : "all",
+ awaitSurfaceMode: deferInboxDms ? "none" : "inbox-dms",
+ targetRevision: response.revision,
+ })
+ if (deferInboxDms) {
+ return {
+ committed: true,
+ reconciled: false,
+ deferred: true,
+ }
+ }
+ return {
+ committed: true,
+ reconciled: this.attemptActive(state, attemptEpoch, identityEpoch),
}
+ } catch {
+ return { committed: true, reconciled: false }
+ } finally {
+ this.finishAttempt(state, attemptEpoch)
}
}
+ private finishAttempt(
+ state: ScopeState,
+ attemptEpoch: number,
+ ) {
+ const drainCutoff = state.inFlight?.attemptEpoch === attemptEpoch
+ ? state.inFlight.drainCutoff
+ /* istanbul ignore next -- this reconciliation finally is the attempt's only finisher */
+ : undefined
+ if (state.inFlight?.attemptEpoch === attemptEpoch) state.inFlight = null
+ if (this.disposed || !state.accepted || state.retryTimer !== null) return
+ if (
+ drainCutoff !== undefined
+ && state.accepted.generation <= drainCutoff
+ ) {
+ this.schedule(state, 0)
+ return
+ }
+ this.schedule(state, Math.max(0, state.accepted.dueAt - Date.now()))
+ }
+
private cancelConfirmedWork(state: ScopeState) {
- if (state.accepted && this.confirmed(state, state.accepted)) state.accepted = null
- if (state.dirty && this.confirmed(state, state.dirty)) state.dirty = null
- if (state.inFlight && this.confirmed(state, state.inFlight.target)) {
+ if (state.accepted && this.confirmed(state, state.accepted.intent)) state.accepted = null
+ if (state.dirty && this.confirmed(state, state.dirty.intent)) state.dirty = null
+ if (
+ state.inFlight
+ && state.inFlight.phase === "mutation"
+ && this.confirmed(state, state.inFlight.target.intent)
+ ) {
state.attemptEpoch += 1
state.inFlight.controller.abort()
state.inFlight = null
@@ -361,6 +543,15 @@ export function submitReadIntent(lease: SurfaceLease, intent: ReadIntent) {
return lease.coordinator.submit(lease, intent)
}
+export function flushPendingReadIntents(
+ queryClient: QueryClient,
+ options?: PendingReadFlushOptions,
+): Promise<PendingReadFlushOutcome> {
+ const coordinator = coordinators.get(queryClient)
+ if (!coordinator) return Promise.resolve({ consumed: false, cutoff: null })
+ return coordinator.flushPending(options)
+}
+
export function resumeReadCoordinator(queryClient: QueryClient) {
coordinators.get(queryClient)?.resume()
}
diff --git a/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.test.ts b/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.test.ts
index 48ea5a7ff..0b1211a3c 100644
--- a/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.test.ts
+++ b/src/web/src/hooks/community/use-community-ws-read-state-lifecycle.test.ts
@@ -1,13 +1,22 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { communityKeys } from "@/lib/query-keys"
import {
+ capturedOnMessage,
capturedQueryClient,
capturedUseUserWsOptions,
cleanupCommunityWsHarness,
flushEffects,
+ getCommunityApiFetchMock,
mountHook,
resetCommunityWsHarness,
+ unmountHook,
} from "./community-ws/test-harness"
+import { useCommunityStore } from "@/stores/community"
+import {
+ registerReadSurface,
+ releaseReadSurface,
+ submitReadIntent,
+} from "./read-coordinator"
const documentListeners = new Map<string, () => void>()
const windowListeners = new Map<string, () => void>()
@@ -33,34 +42,112 @@ afterEach(async () => {
})
describe("community read-state lifecycle reconciliation", () => {
- it("loads the authoritative account snapshot on authentication", async () => {
+ it("fences owner fallback after cleanup during an active read barrier", async () => {
+ vi.useFakeTimers()
+ useCommunityStore.getState().subscribe({ channelId: "ch-1" })
+ await mountHook({ viewerUserId: "viewer-1" })
+ flushEffects()
+ let releaseRead!: () => void
+ const readGate = new Promise<void>((resolve) => {
+ releaseRead = resolve
+ })
+ getCommunityApiFetchMock().mockImplementation(async (url: unknown) => {
+ if (typeof url === "string" && url.endsWith("/read")) {
+ await readGate
+ return { changed: true, revision: 1, targetSeq: 1 }
+ }
+ if (url === "/api/community/users/me/read-state") {
+ return {
+ revision: 1,
+ readStates: [{
+ channelId: "ch-1",
+ lastReadMessageId: "message-1",
+ lastReadAt: "2026-08-27T00:00:00.000Z",
+ lastReadSeq: 1,
+ }],
+ }
+ }
+ throw new Error(`unexpected API fetch: ${String(url)}`)
+ })
+ const invalidate = vi.spyOn(capturedQueryClient, "invalidateQueries")
+ const lease = registerReadSurface(
+ capturedQueryClient,
+ "viewer-1",
+ { kind: "timeline", channelId: "ch-1" },
+ )
+
+ capturedOnMessage!({
+ type: "community:message.create",
+ channelId: "ch-1",
+ message: {
+ id: "message-1",
+ seq: 1,
+ authorId: "author-1",
+ authorName: "Alice",
+ content: "hello",
+ type: "chat",
+ createdAt: "2026-08-27T00:00:00.000Z",
+ },
+ })
+ expect(submitReadIntent(lease, {
+ kind: "timeline",
+ channelId: "ch-1",
+ messageId: "message-1",
+ seq: 1,
+ })).toBe(true)
+ await vi.advanceTimersByTimeAsync(500)
+ await vi.waitFor(() => expect(getCommunityApiFetchMock()).toHaveBeenCalledWith(
+ "/api/community/channels/ch-1/read",
+ expect.anything(),
+ ))
+
+ unmountHook()
+ releaseRead()
+ await vi.waitFor(() => {
+ expect(invalidate.mock.calls.filter(([filters]) => (
+ JSON.stringify(filters.queryKey) === JSON.stringify(communityKeys.inbox())
+ ))).toHaveLength(1)
+ })
+ await vi.runAllTimersAsync()
+ expect(invalidate.mock.calls.filter(([filters]) => (
+ JSON.stringify(filters.queryKey) === JSON.stringify(communityKeys.dms())
+ ))).toHaveLength(1)
+ releaseReadSurface(lease)
+ })
+
+ it("schedules the first-auth owner before non-Inbox reconciliation completes", async () => {
+ vi.useFakeTimers()
await mountHook()
+ let releaseSnapshot!: (value: unknown) => void
+ getCommunityApiFetchMock().mockReturnValueOnce(new Promise((resolve) => {
+ releaseSnapshot = resolve
+ }))
const invalidate = vi.spyOn(capturedQueryClient, "invalidateQueries")
- await capturedUseUserWsOptions?.onAuthenticated?.()
- expect(capturedQueryClient.getQueryData(
- communityKeys.accountReadStateSnapshot(),
- )).toEqual({ revision: 0, readStates: [] })
+ const authentication = capturedUseUserWsOptions?.onAuthenticated?.()
+
+ expect(getCommunityApiFetchMock()).toHaveBeenCalledOnce()
+ await vi.advanceTimersByTimeAsync(500)
expect(invalidate).toHaveBeenCalledWith({
queryKey: communityKeys.inbox(),
- refetchType: "active",
- }, {
- cancelRefetch: true,
- throwOnError: true,
})
expect(invalidate).toHaveBeenCalledWith({
queryKey: communityKeys.dms(),
- refetchType: "active",
- }, {
- cancelRefetch: true,
- throwOnError: true,
})
+
+ releaseSnapshot({ revision: 0, readStates: [] })
+ await authentication
+ expect(capturedQueryClient.getQueryData(
+ communityKeys.accountReadStateSnapshot(),
+ )).toEqual({ revision: 0, readStates: [] })
})
it.each(["visibilitychange", "pageshow"] as const)(
- "reconciles cached read state on %s",
+ "schedules the connected owner and reconciles non-Inbox state on %s",
async (eventType) => {
+ vi.useFakeTimers()
await mountHook()
flushEffects()
+ const invalidate = vi.spyOn(capturedQueryClient, "invalidateQueries")
const listener = eventType === "visibilitychange"
? documentListeners.get(eventType)
: windowListeners.get(eventType)
@@ -69,6 +156,28 @@ describe("community read-state lifecycle reconciliation", () => {
await vi.waitFor(() => expect(capturedQueryClient.getQueryData(
communityKeys.accountReadStateSnapshot(),
)).toEqual({ revision: 0, readStates: [] }))
+ expect(invalidate).not.toHaveBeenCalledWith({
+ queryKey: communityKeys.inbox(),
+ })
+ await vi.advanceTimersByTimeAsync(500)
+ expect(invalidate).toHaveBeenCalledWith({
+ queryKey: communityKeys.inbox(),
+ })
},
)
+
+ it("contains a visible lifecycle reconciliation failure while the owner still refreshes", async () => {
+ vi.useFakeTimers()
+ await mountHook()
+ flushEffects()
+ getCommunityApiFetchMock().mockRejectedValueOnce(new Error("snapshot unavailable"))
+ const invalidate = vi.spyOn(capturedQueryClient, "invalidateQueries")
+
+ documentListeners.get("visibilitychange")!()
+ await vi.waitFor(() => expect(getCommunityApiFetchMock()).toHaveBeenCalledOnce())
+ await vi.advanceTimersByTimeAsync(500)
+
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: communityKeys.inbox() })
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: communityKeys.dms() })
+ })
})
diff --git a/src/web/src/hooks/community/use-community-ws.ts b/src/web/src/hooks/community/use-community-ws.ts
index d6ca4300f..ebd209741 100644
--- a/src/web/src/hooks/community/use-community-ws.ts
+++ b/src/web/src/hooks/community/use-community-ws.ts
@@ -7,7 +7,11 @@ import {
type UserWsConnectionPhase,
} from "@/lib/use-user-ws"
import { useCommunityStore } from "@/stores/community"
-import { useCommunityWsStore } from "@/stores/community/ws"
+import {
+ SEEN_DELIVERY_OPERATION_MAX,
+ SEEN_DELIVERY_OPERATION_TRIM_TO,
+ useCommunityWsStore,
+} from "@/stores/community/ws"
import { reconcileCommunityWsReconnect } from "@/hooks/community/community-ws/reconnect"
import {
dispatchCommunityWsEvent,
@@ -20,16 +24,19 @@ import {
invalidateInbox,
} from "@/hooks/community/community-ws/invalidation-projections"
import type {
+ CommunityInboxRefreshRequest,
CommunityWsDispatchContext,
Subscription,
UseCommunityWsOptions,
} from "@/hooks/community/community-ws/handler-context"
+import { flushPendingReadIntents } from "@/hooks/community/read-coordinator"
import {
decodeCommunityBrowserEvent,
decodeCommunityBrowserEventBatch,
isCommunityBrowserEventBatchCandidate,
isCommunityEventType,
TYPING_INDICATOR_THROTTLE_MS,
+ type CommunityWsEvent,
} from "@alook/shared"
import { trackCommunityWsFrameDropped } from "@/lib/analytics"
import {
@@ -69,6 +76,75 @@ export type {
// message burst.
const INBOX_INVALIDATE_DEBOUNCE_MS = 500
+type InboxRefreshGeneration = CommunityInboxRefreshRequest & {
+ id: number
+ dueAt: number
+}
+
+type InboxRefreshOwner = {
+ current: InboxRefreshGeneration | null
+ next: InboxRefreshGeneration | null
+ timer: ReturnType<typeof setTimeout> | null
+ running: boolean
+ nextGenerationId: number
+ epoch: number
+ claimedOperationKeys: Set<string>
+ claimedOperationOrder: string[]
+ disposed: boolean
+}
+
+function mergeInboxRefresh(
+ target: CommunityInboxRefreshRequest,
+ incoming: CommunityInboxRefreshRequest,
+) {
+ target.dms ||= incoming.dms
+}
+
+function deliveryInboxRefresh(
+ events: readonly CommunityWsEvent[],
+ viewerId: string | null,
+): CommunityInboxRefreshRequest | null {
+ let inbox = false
+ let dms = false
+ for (const event of events) {
+ if (
+ event.type === "community:message.create"
+ && event.message.authorId !== viewerId
+ ) {
+ inbox = true
+ dms = true
+ }
+ if (event.type === "community:mention.create") inbox = true
+ }
+ return inbox ? { inbox: true, dms } : null
+}
+
+function claimInboxRefreshOperation(owner: InboxRefreshOwner, key: string) {
+ if (owner.claimedOperationKeys.has(key)) return false
+ owner.claimedOperationKeys.add(key)
+ owner.claimedOperationOrder.push(key)
+ if (owner.claimedOperationOrder.length > SEEN_DELIVERY_OPERATION_MAX) {
+ const retained = owner.claimedOperationOrder.slice(-SEEN_DELIVERY_OPERATION_TRIM_TO)
+ owner.claimedOperationOrder = retained
+ owner.claimedOperationKeys = new Set(retained)
+ }
+ return true
+}
+
+function armInboxRefreshGeneration(
+ owner: InboxRefreshOwner,
+ generation: InboxRefreshGeneration,
+ run: (generation: InboxRefreshGeneration, epoch: number) => Promise<void>,
+) {
+ if (owner.disposed) return
+ owner.timer = setTimeout(() => {
+ if (owner.disposed) return
+ owner.timer = null
+ owner.running = true
+ void run(generation, owner.epoch)
+ }, Math.max(0, generation.dueAt - Date.now()))
+}
+
// ── Public hook ────────────────────────────────────────────────────────────
// Module-level slot for the currently-active WS `send`. The root-mounted
@@ -143,30 +219,109 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
getConnectionController().handlePhase(phase)
}, [getConnectionController])
const viewerUserIdRef = useRef<string | null>(options?.viewerUserId ?? null)
+ const hasAuthenticatedRef = useRef(false)
useEffect(() => {
viewerUserIdRef.current = options?.viewerUserId ?? null
})
- // Debounced inbox invalidation. Grouping repeated invalidations into one
- // refetch cycle keeps the popover from re-rendering on every message tick.
- const inboxDebounce = useRef<ReturnType<typeof setTimeout> | null>(null)
- const scheduleInboxInvalidate = useCallback(() => {
- if (inboxDebounce.current) return
- inboxDebounce.current = setTimeout(() => {
- inboxDebounce.current = null
+ const inboxRefreshOwner = useRef<InboxRefreshOwner | null>(null)
+ if (inboxRefreshOwner.current === null) {
+ inboxRefreshOwner.current = {
+ current: null,
+ next: null,
+ timer: null,
+ running: false,
+ nextGenerationId: 0,
+ epoch: 0,
+ claimedOperationKeys: new Set(),
+ claimedOperationOrder: [],
+ disposed: false,
+ }
+ }
+ const runInboxGeneration = useCallback(async function runInboxGeneration(
+ generation: InboxRefreshGeneration,
+ epoch: number,
+ ) {
+ const owner = inboxRefreshOwner.current
+ if (
+ !owner
+ || owner.disposed
+ || owner.epoch !== epoch
+ || owner.current?.id !== generation.id
+ ) {
+ /* istanbul ignore next -- the sole timer caller validates and enters synchronously */
+ return
+ }
+ let consumed = false
+ let deferred = false
+ try {
+ const outcome = await flushPendingReadIntents(queryClient, {
+ deferInboxDms: () => {
+ const latest = inboxRefreshOwner.current
+ return latest?.epoch === epoch
+ && latest.current?.id === generation.id
+ && latest.next !== null
+ },
+ })
+ consumed = outcome.consumed
+ deferred = outcome.deferred === true
+ } catch {
+ /* istanbul ignore next -- the coordinator normalizes every real failure into an outcome */
+ consumed = false
+ /* istanbul ignore next -- the coordinator normalizes every real failure into an outcome */
+ deferred = false
+ }
+ const current = inboxRefreshOwner.current
+ if (
+ !current
+ || current.disposed
+ || current.epoch !== epoch
+ || current.current?.id !== generation.id
+ ) return
+ if (deferred && current.next) mergeInboxRefresh(current.next, generation)
+ if (!consumed && !deferred) {
runCommunityWsProjectionTransaction(queryClient, (projection) => {
- invalidateInbox(projection)
- // A DM is a channel now, so a DM message arrives as `message.create`
- // with no discriminator distinguishing it from a channel message. Fold
- // the old `dm.new_message` DM-sidebar refresh in here: invalidate the
- // DM list too so an unread DM's preview/unread flag updates live. Cheap
- // — `communityKeys.dms()` is only observed under the `/c/me` layout, so
- // this is a no-op (marks stale, no refetch) while viewing a server
- // channel where the DM sidebar isn't mounted.
- invalidateDms(projection)
+ if (generation.inbox) invalidateInbox(projection)
+ if (generation.dms) invalidateDms(projection)
})
- }, INBOX_INVALIDATE_DEBOUNCE_MS)
+ }
+ current.current = current.next
+ current.next = null
+ current.running = false
+ if (current.current) {
+ armInboxRefreshGeneration(current, current.current, runInboxGeneration)
+ }
}, [queryClient])
+ const scheduleInboxInvalidate = useCallback((
+ request: CommunityInboxRefreshRequest,
+ operationKey?: string,
+ ) => {
+ const owner = inboxRefreshOwner.current
+ if (!owner || owner.disposed) return
+ if (operationKey && !claimInboxRefreshOperation(owner, operationKey)) return
+ if (owner.current === null) {
+ owner.current = {
+ ...request,
+ id: ++owner.nextGenerationId,
+ dueAt: Date.now() + INBOX_INVALIDATE_DEBOUNCE_MS,
+ }
+ armInboxRefreshGeneration(owner, owner.current, runInboxGeneration)
+ return
+ }
+ if (!owner.running) {
+ mergeInboxRefresh(owner.current, request)
+ return
+ }
+ if (owner.next === null) {
+ owner.next = {
+ ...request,
+ id: ++owner.nextGenerationId,
+ dueAt: Date.now() + INBOX_INVALIDATE_DEBOUNCE_MS,
+ }
+ return
+ }
+ mergeInboxRefresh(owner.next, request)
+ }, [runInboxGeneration])
const handleMessage = useCallback(
(msg: { type: string;[key: string]: unknown }) => {
@@ -184,7 +339,10 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
if (!e.channelId) return false
return e.channelId === sub.channelId || e.channelId === sub.dmConversationId
}
- const context = (deliveryMode: "single" | "batch"): CommunityWsDispatchContext => ({
+ const context = (
+ deliveryMode: "single" | "batch",
+ requestInboxRefresh = scheduleInboxInvalidate,
+ ): CommunityWsDispatchContext => ({
deliveryMode,
queryClient,
communityStore,
@@ -192,10 +350,17 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
sub,
viewerUserIdRef,
matchesFocus,
- scheduleInboxInvalidate,
+ scheduleInboxInvalidate: requestInboxRefresh,
})
- const reconcileAfterBatchFailure = (reason: "digest-conflict" | "projection-failed") => {
- void reconcileCommunityWsReconnect(queryClient, 0).catch(() => {
+ const reconcileAfterBatchFailure = (
+ reason: "digest-conflict" | "projection-failed",
+ inboxOwned: boolean,
+ ) => {
+ void reconcileCommunityWsReconnect(
+ queryClient,
+ 0,
+ inboxOwned ? { excludePolicies: ["inbox-dms"] } : undefined,
+ ).catch(() => {
console.warn("[ws] batch reconciliation failed", {
event: "community_ws_batch_reconciliation_failed",
reason,
@@ -223,6 +388,11 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
decoded.batch.operationId,
decoded.batch.operationDigest,
)
+ const batchRefresh = deliveryInboxRefresh(
+ decoded.events,
+ viewerUserIdRef.current,
+ )
+ const operationKey = `delivery:${decoded.batch.operationId}:${decoded.batch.operationDigest}`
if (operationStatus === "duplicate") return
if (operationStatus === "conflict") {
console.warn("[ws] delivery operation digest conflict", {
@@ -231,11 +401,28 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
operationDigest: decoded.batch.operationDigest,
eventCount: decoded.events.length,
})
- reconcileAfterBatchFailure("digest-conflict")
+ if (batchRefresh) {
+ scheduleInboxInvalidate(
+ batchRefresh,
+ `conflict:${decoded.batch.operationId}:${decoded.batch.operationDigest}`,
+ )
+ }
+ reconcileAfterBatchFailure("digest-conflict", batchRefresh !== null)
return
}
+ let collectedRefresh: CommunityInboxRefreshRequest | null = null
+ const collectInboxRefresh = (request: CommunityInboxRefreshRequest) => {
+ if (collectedRefresh === null) {
+ collectedRefresh = { ...request }
+ } else {
+ mergeInboxRefresh(collectedRefresh, request)
+ }
+ }
try {
- dispatchCommunityWsEvents(decoded.events, context("batch"))
+ dispatchCommunityWsEvents(
+ decoded.events,
+ context("batch", collectInboxRefresh),
+ )
} catch {
console.warn("[ws] delivery operation projection failed", {
event: "community_ws_delivery_operation_projection_failed",
@@ -243,7 +430,8 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
operationDigest: decoded.batch.operationDigest,
eventCount: decoded.events.length,
})
- reconcileAfterBatchFailure("projection-failed")
+ if (batchRefresh) scheduleInboxInvalidate(batchRefresh, operationKey)
+ reconcileAfterBatchFailure("projection-failed", batchRefresh !== null)
return
}
// Complete dedup only after every child projected successfully. The
@@ -255,6 +443,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
// Keeping the failed operation locked but incomplete lets the
// identical bundle retry, so idempotent child projections can finish
// converging even when authoritative reconnect reconciliation fails.
+ if (collectedRefresh) scheduleInboxInvalidate(collectedRefresh, operationKey)
wsStore.completeDeliveryOperation(
decoded.batch.operationId,
decoded.batch.operationDigest,
@@ -281,12 +470,23 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
)
const handleReconnect = useCallback(async ({ reconnectDurationMs }: { reconnectDurationMs: number }) => {
- await reconcileCommunityWsReconnect(queryClient, reconnectDurationMs)
- }, [queryClient])
+ try {
+ await reconcileCommunityWsReconnect(queryClient, reconnectDurationMs, {
+ excludePolicies: ["inbox-dms"],
+ })
+ } finally {
+ scheduleInboxInvalidate({ inbox: true, dms: true })
+ }
+ }, [queryClient, scheduleInboxInvalidate])
const handleAuthenticated = useCallback(async () => {
useCommunityWsStore.getState().markAccessConnected()
- await reconcileAccountReadState(queryClient)
- }, [queryClient])
+ const firstAuthentication = !hasAuthenticatedRef.current
+ hasAuthenticatedRef.current = true
+ if (firstAuthentication) {
+ scheduleInboxInvalidate({ inbox: true, dms: true })
+ }
+ await reconcileAccountReadState(queryClient, { surfaceMode: "non-inbox" })
+ }, [queryClient, scheduleInboxInvalidate])
const { send, reconnectNow } = useUserWs(handleMessage, {
onReconnect: handleReconnect,
onDisconnect: useCommunityWsStore.getState().markAccessDisconnected,
@@ -302,7 +502,12 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
if (typeof document === "undefined" || typeof window === "undefined") return
const reconcileVisible = () => {
if (document.visibilityState !== "visible") return
- void reconcileAccountReadState(queryClient).catch(() => undefined)
+ if (useCommunityWsStore.getState().accessConnected) {
+ scheduleInboxInvalidate({ inbox: true, dms: true })
+ }
+ void reconcileAccountReadState(queryClient, {
+ surfaceMode: "non-inbox",
+ }).catch(() => undefined)
}
document.addEventListener("visibilitychange", reconcileVisible)
window.addEventListener("pageshow", reconcileVisible)
@@ -310,7 +515,7 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
document.removeEventListener("visibilitychange", reconcileVisible)
window.removeEventListener("pageshow", reconcileVisible)
}
- }, [queryClient])
+ }, [queryClient, scheduleInboxInvalidate])
// Publish the send binding so free helpers (`communityWsSendTyping`) can
// dispatch without holding a hook reference. Single-instance assumption
@@ -351,14 +556,19 @@ export function useCommunityWs(options?: UseCommunityWsOptions): void {
}
}, [getConnectionController])
- // Cleanup: flush the inbox debounce if the hook unmounts mid-window so the
- // parent surface doesn't leave a scheduled fetch dangling.
useEffect(() => {
+ const owner = inboxRefreshOwner.current
+ if (owner) owner.disposed = false
return () => {
- if (inboxDebounce.current) {
- clearTimeout(inboxDebounce.current)
- inboxDebounce.current = null
- }
+ const current = inboxRefreshOwner.current
+ if (!current) return
+ current.disposed = true
+ current.epoch += 1
+ if (current.timer !== null) clearTimeout(current.timer)
+ current.timer = null
+ current.current = null
+ current.next = null
+ current.running = false
}
}, [])
}
diff --git a/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts b/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts
index 63994fc08..41f98bc5a 100644
--- a/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts
+++ b/src/web/src/test/e2e-ui/22-committed-message-delivery.spec.ts
@@ -118,9 +118,12 @@ test.describe.serial("committed message delivery QA", () => {
const data = await response.json() as { servers: Array<{ id: string; mentions: number }> }
const authoritative = data.servers.find((server) => server.id === serverId)?.mentions ?? 0
const badge = bob.page.getByTestId(tid.railUnreadBadge(serverId))
- const displayed = await badge.count() === 0
+ const badgeTexts = await badge.allTextContents()
+ const displayed = badgeTexts.length === 0
? 0
- : Number((await badge.textContent())?.trim())
+ : badgeTexts.length === 1
+ ? Number(badgeTexts[0]?.trim())
+ : Number.NaN
return displayed === authoritative
}, { timeout: 20_000 }).toBe(true)
})
diff --git a/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts b/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts
index d85f769bf..6850f7f60 100644
--- a/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts
+++ b/src/web/src/test/e2e-ui/29-multi-device-read-state.spec.ts
@@ -170,6 +170,7 @@ test("one human account converges read state across two browser profiles", async
proxyB.replay(firstReadFrame!)
await expectJourneyUnreadsCleared()
+ await gotoAfterUserWsAuth(deviceA.page, "/c/me/friends")
await seedMessage("alice", channelId, `offline channel ${stamp}`)
await seedDmMessage("alice", dmId, `offline dm ${stamp}`)
await expect(deviceB.page.getByTestId(tid.inboxUnreadChannel(channelId))).toBeVisible({ timeout: 20_000 })
diff --git a/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts b/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts
new file mode 100644
index 000000000..8310ebdb6
--- /dev/null
+++ b/src/web/src/test/e2e-ui/34-inbox-read-race.spec.ts
@@ -0,0 +1,228 @@
+import { expect, test, userId } from "./_fixtures/community-fixture"
+import { gotoAfterUserWsAuth } from "./_fixtures/actions"
+import { tid } from "./_fixtures/testids"
+import {
+ seedChannel,
+ seedDm,
+ seedDmMessage,
+ seedJoinServer,
+ seedMessage,
+ seedServer,
+} from "./_fixtures/seed"
+import {
+ communityFrameEvents,
+ proxyCommunityWebSockets,
+} from "./_fixtures/community-ws-proxy"
+
+function deferred() {
+ let resolve!: () => void
+ const promise = new Promise<void>((done) => { resolve = done })
+ return { promise, resolve }
+}
+
+async function watchInboxRow(page: Parameters<typeof gotoAfterUserWsAuth>[0], testId: string) {
+ const key = `__inboxRace_${testId}`
+ await page.evaluate(({ key, testId }) => {
+ const target = window as unknown as Record<
+ string,
+ { seen: boolean; observer: MutationObserver }
+ >
+ const record = {
+ seen: false,
+ observer: new MutationObserver(() => {
+ if (document.querySelector(`[data-testid="${testId}"]`)) record.seen = true
+ }),
+ }
+ if (document.querySelector(`[data-testid="${testId}"]`)) record.seen = true
+ record.observer.observe(document.documentElement, { childList: true, subtree: true })
+ target[key] = record
+ }, { key, testId })
+ return async () => await page.evaluate((key) => {
+ const target = window as unknown as Record<
+ string,
+ { seen: boolean; observer: MutationObserver }
+ >
+ const seen = target[key]?.seen ?? false
+ target[key]?.observer.disconnect()
+ delete target[key]
+ return seen
+ }, key)
+}
+
+test.describe.serial("Inbox/read refresh ownership", () => {
+ test.setTimeout(180_000)
+
+ test("focused A never flashes while same-window B and DM remain unread", async ({ asUser }) => {
+ const stamp = Date.now()
+ const serverId = await seedServer("alice", `Inbox race mixed ${stamp}`)
+ const channelA = await seedChannel("alice", serverId, `focused-a-${stamp}`)
+ const channelB = await seedChannel("alice", serverId, `unread-b-${stamp}`)
+ await seedJoinServer("alice", "bob", serverId)
+ const dmId = await seedDm("alice", userId("bob"))
+ const { context, page } = await asUser("bob")
+ const proxy = await proxyCommunityWebSockets(context)
+ await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelA}`)
+ const initialInbox = page.waitForResponse((response) => (
+ response.request().method() === "GET"
+ && new URL(response.url()).pathname === "/api/community/users/me/inbox/unreads"
+ ))
+ await page.getByRole("button", { name: "Inbox" }).click()
+ expect((await initialInbox).status()).toBe(200)
+ await expect(page.getByTestId(tid.inboxUnreadChannel(channelA))).toHaveCount(0)
+
+ const stopWatchingA = await watchInboxRow(page, tid.inboxUnreadChannel(channelA))
+ const requests: Array<{ method: string; path: string; at: number }> = []
+ page.on("request", (request) => requests.push({
+ method: request.method(),
+ path: new URL(request.url()).pathname,
+ at: Date.now(),
+ }))
+ const requestStart = requests.length
+ const frameStart = proxy.frames.length
+ const firstReadGate = deferred()
+ const firstReadStarted = deferred()
+ await page.route(`**/api/community/channels/${channelA}/read`, async (route) => {
+ if (route.request().method() !== "PUT") return route.continue()
+ firstReadStarted.resolve()
+ await firstReadGate.promise
+ await route.continue()
+ })
+ const readResponse = page.waitForResponse((response) => (
+ response.request().method() === "PUT"
+ && new URL(response.url()).pathname === `/api/community/channels/${channelA}/read`
+ ))
+ const bodyA = `focused live ${stamp}`
+ const bodyB = `background channel ${stamp}`
+ const bodyDm = `background dm ${stamp}`
+ const messageA = await seedMessage("alice", channelA, bodyA)
+ await expect(page.getByText(bodyA, { exact: true })).toBeVisible({ timeout: 20_000 })
+ await firstReadStarted.promise
+ const messageB = await seedMessage("alice", channelB, bodyB)
+ const messageDm = await seedDmMessage("alice", dmId, bodyDm)
+ firstReadGate.resolve()
+ expect((await readResponse).status()).toBe(200)
+ await expect(page.getByTestId(tid.inboxUnreadChannel(channelB))).toBeVisible({ timeout: 20_000 })
+ await expect(page.getByTestId(tid.inboxUnreadDm(dmId))).toBeVisible({ timeout: 20_000 })
+ await expect(page.getByTestId(tid.inboxUnreadChannel(channelA))).toHaveCount(0)
+ await page.waitForTimeout(1_000)
+ expect(await stopWatchingA()).toBe(false)
+
+ await expect.poll(() => proxy.frames.slice(frameStart).filter((frame) => (
+ frame.type === "community:events.batch"
+ && communityFrameEvents(frame).some((event) => (
+ event.type === "community:message.create"
+ && [messageA, messageB, messageDm].includes(event.message?.id ?? "")
+ ))
+ )).length, { timeout: 20_000 }).toBe(3)
+ const journeyRequests = requests.slice(requestStart)
+ const readIndex = journeyRequests.findIndex((request) => (
+ request.method === "PUT"
+ && request.path === `/api/community/channels/${channelA}/read`
+ ))
+ const inboxIndex = journeyRequests.findIndex((request) => (
+ request.method === "GET"
+ && request.path === "/api/community/users/me/inbox/unreads"
+ ))
+ expect(readIndex).toBeGreaterThanOrEqual(0)
+ expect(inboxIndex).toBeGreaterThan(readIndex)
+
+ const snapshot = await (await page.request.get(
+ "/api/community/users/me/read-state",
+ )).json() as { readStates: Array<{ channelId: string; lastReadSeq: number }> }
+ const readSeq = (channelId: string) => (
+ snapshot.readStates.find((row) => row.channelId === channelId)?.lastReadSeq ?? 0
+ )
+ expect(readSeq(channelA)).toBeGreaterThan(0)
+ expect(readSeq(channelB)).toBe(0)
+ expect(readSeq(dmId)).toBe(0)
+ })
+
+ test("a failed focused read falls back once, then retry converges", async ({ asUser }) => {
+ const stamp = Date.now()
+ const serverId = await seedServer("alice", `Inbox race failure ${stamp}`)
+ const channelId = await seedChannel("alice", serverId, `failure-${stamp}`)
+ await seedJoinServer("alice", "bob", serverId)
+ const { page } = await asUser("bob")
+ await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)
+ const initialInbox = page.waitForResponse((response) => (
+ response.request().method() === "GET"
+ && new URL(response.url()).pathname === "/api/community/users/me/inbox/unreads"
+ ))
+ await page.getByRole("button", { name: "Inbox" }).click()
+ expect((await initialInbox).status()).toBe(200)
+ await expect(page.getByTestId(tid.inboxUnreadChannel(channelId))).toHaveCount(0)
+
+ const retryGate = deferred()
+ let puts = 0
+ await page.route(`**/api/community/channels/${channelId}/read`, async (route) => {
+ if (route.request().method() !== "PUT") return route.continue()
+ puts += 1
+ if (puts === 1) {
+ await route.fulfill({
+ status: 503,
+ contentType: "application/json",
+ body: '{"error":"retry"}',
+ })
+ return
+ }
+ await retryGate.promise
+ await route.continue()
+ })
+ const body = `retryable focused ${stamp}`
+ await seedMessage("alice", channelId, body)
+ await expect(page.getByText(body, { exact: true })).toBeVisible({ timeout: 20_000 })
+ await expect(page.getByTestId(tid.inboxUnreadChannel(channelId))).toBeVisible({ timeout: 20_000 })
+ await expect.poll(() => puts, { timeout: 20_000 }).toBe(2)
+ retryGate.resolve()
+ await expect(page.getByTestId(tid.inboxUnreadChannel(channelId))).toHaveCount(0, {
+ timeout: 20_000,
+ })
+ expect(puts).toBe(2)
+ })
+
+ test("a later focused intent keeps its own 500ms generation", async ({ asUser }) => {
+ const stamp = Date.now()
+ const serverId = await seedServer("alice", `Inbox race cutoff ${stamp}`)
+ const channelId = await seedChannel("alice", serverId, `cutoff-${stamp}`)
+ await seedJoinServer("alice", "bob", serverId)
+ const { page } = await asUser("bob")
+ await gotoAfterUserWsAuth(page, `/c/channels/${serverId}/${channelId}`)
+ const initialInbox = page.waitForResponse((response) => (
+ response.request().method() === "GET"
+ && new URL(response.url()).pathname === "/api/community/users/me/inbox/unreads"
+ ))
+ await page.getByRole("button", { name: "Inbox" }).click()
+ expect((await initialInbox).status()).toBe(200)
+ await expect(page.getByTestId(tid.inboxUnreadChannel(channelId))).toHaveCount(0)
+ const stopWatching = await watchInboxRow(page, tid.inboxUnreadChannel(channelId))
+
+ const firstGate = deferred()
+ const firstStarted = deferred()
+ const putStarts: number[] = []
+ await page.route(`**/api/community/channels/${channelId}/read`, async (route) => {
+ if (route.request().method() !== "PUT") return route.continue()
+ putStarts.push(Date.now())
+ if (putStarts.length === 1) {
+ firstStarted.resolve()
+ await firstGate.promise
+ }
+ await route.continue()
+ })
+ const firstBody = `cutoff first ${stamp}`
+ await seedMessage("alice", channelId, firstBody)
+ await expect(page.getByText(firstBody, { exact: true })).toBeVisible({ timeout: 20_000 })
+ await firstStarted.promise
+
+ const secondBody = `cutoff second ${stamp}`
+ const secondAcceptedAt = Date.now()
+ await seedMessage("alice", channelId, secondBody)
+ await expect(page.getByText(secondBody, { exact: true })).toBeVisible({ timeout: 20_000 })
+ firstGate.resolve()
+ await page.waitForTimeout(250)
+ expect(putStarts).toHaveLength(1)
+ await expect.poll(() => putStarts.length, { timeout: 20_000 }).toBe(2)
+ expect(putStarts[1]! - secondAcceptedAt).toBeGreaterThanOrEqual(400)
+ await expect(page.getByTestId(tid.inboxUnreadChannel(channelId))).toHaveCount(0)
+ expect(await stopWatching()).toBe(false)
+ })
+})