Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

fix(web): bound message reconnect reconciliation (#473)

Gener70b3c417a84b
diff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts
new file mode 100644
index 000000000..5a826e23f
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.test.ts
@@ -0,0 +1,617 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+import {
+ InfiniteQueryObserver,
+ QueryClient,
+ QueryObserver,
+} from "@tanstack/react-query"
+import { communityKeys } from "@/lib/query-keys"
+import { reconcileFocusedMessageQueries } from "./reconnect-messages"
+
+const apiFetchMock = vi.hoisted(() => vi.fn())
+
+vi.mock("@/lib/api/client", () => ({
+ apiFetch: (...args: unknown[]) => apiFetchMock(...args),
+}))
+
+function seedActiveQuery(
+ queryClient: QueryClient,
+ queryKey: readonly unknown[],
+) {
+ queryClient.setQueryData(queryKey, {
+ pages: [
+ {
+ messages: [{
+ id: "m_2",
+ type: "chat",
+ seq: 2,
+ createdAt: "2026-08-15T00:00:02.000Z",
+ }],
+ hasMore: true,
+ cursor: "older-2",
+ latestSeq: 2,
+ },
+ {
+ messages: [{
+ id: "m_1",
+ type: "chat",
+ seq: 1,
+ createdAt: "2026-08-15T00:00:01.000Z",
+ }],
+ hasMore: false,
+ latestSeq: 2,
+ },
+ ],
+ pageParams: [
+ { mode: "newest" },
+ { mode: "older", cursor: "older-2" },
+ ],
+ })
+ const queryFn = vi.fn(async () => ({ stale: true }))
+ const observer = new QueryObserver(queryClient, {
+ queryKey,
+ queryFn,
+ staleTime: Infinity,
+ })
+ return { queryFn, unsubscribe: observer.subscribe(() => undefined) }
+}
+
+function seedEmptyActiveQuery(
+ queryClient: QueryClient,
+ queryKey: readonly unknown[],
+) {
+ queryClient.setQueryData(queryKey, {
+ pages: [{
+ messages: [],
+ hasMore: false,
+ latestSeq: 0,
+ }],
+ pageParams: [{ mode: "newest" }],
+ })
+ const queryFn = vi.fn(async () => ({ stale: true }))
+ const observer = new QueryObserver(queryClient, {
+ queryKey,
+ queryFn,
+ staleTime: Infinity,
+ })
+ return { queryFn, unsubscribe: observer.subscribe(() => undefined) }
+}
+
+beforeEach(() => {
+ apiFetchMock.mockReset()
+})
+
+describe("focused message reconnect catch-up", () => {
+ it("cancels and replays an in-flight older-page fetch so neither side overwrites the other", async () => {
+ const queryClient = new QueryClient()
+ const queryKey = communityKeys.channelMessages("ch_race")
+ let resolveStaleOlder!: (page: {
+ messages: Array<Record<string, unknown>>
+ hasMore: boolean
+ latestSeq: number
+ }) => void
+ const staleOlder = new Promise<{
+ messages: Array<Record<string, unknown>>
+ hasMore: boolean
+ latestSeq: number
+ }>((resolve) => {
+ resolveStaleOlder = resolve
+ })
+ const olderSignals: AbortSignal[] = []
+ let olderCallCount = 0
+ const queryFn = vi.fn(async ({
+ pageParam,
+ signal,
+ }: {
+ pageParam: { mode: string }
+ signal: AbortSignal
+ }) => {
+ if (pageParam.mode === "newest") {
+ return {
+ messages: [{
+ id: "m_2",
+ type: "chat",
+ seq: 2,
+ createdAt: "2026-08-15T00:00:02.000Z",
+ }],
+ hasMore: true,
+ cursor: "older-2",
+ latestSeq: 2,
+ }
+ }
+ olderCallCount += 1
+ olderSignals.push(signal)
+ if (olderCallCount === 1) return staleOlder
+ return {
+ messages: [{
+ id: "m_1",
+ type: "chat",
+ seq: 1,
+ createdAt: "2026-08-15T00:00:01.000Z",
+ }],
+ hasMore: false,
+ latestSeq: 3,
+ }
+ })
+ const observer = new InfiniteQueryObserver(queryClient, {
+ queryKey,
+ queryFn,
+ initialPageParam: { mode: "newest" } as const,
+ getNextPageParam: (last) => last.hasMore && last.cursor
+ ? { mode: "older" as const, cursor: last.cursor }
+ : undefined,
+ })
+ const unsubscribe = observer.subscribe(() => undefined)
+ await vi.waitFor(() => {
+ expect(observer.getCurrentResult().isSuccess).toBe(true)
+ })
+ const pendingOlder = observer.fetchNextPage()
+ await vi.waitFor(() => {
+ expect(olderCallCount).toBe(1)
+ })
+ apiFetchMock
+ .mockResolvedValueOnce({
+ messages: [{
+ id: "m_2",
+ type: "chat",
+ seq: 2,
+ createdAt: "2026-08-15T00:00:02.000Z",
+ }, {
+ id: "m_3",
+ type: "chat",
+ seq: 3,
+ createdAt: "2026-08-15T00:00:03.000Z",
+ }],
+ hasMore: true,
+ cursor: "older-2",
+ latestSeq: 3,
+ })
+ .mockResolvedValueOnce({
+ messages: [{
+ id: "m_3",
+ type: "chat",
+ seq: 3,
+ createdAt: "2026-08-15T00:00:03.000Z",
+ }],
+ hasMoreNewer: false,
+ latestSeq: 3,
+ })
+
+ await reconcileFocusedMessageQueries(queryClient, "channel", "ch_race")
+ resolveStaleOlder({
+ messages: [{ id: "stale_m_1" }],
+ hasMore: false,
+ latestSeq: 2,
+ })
+ await pendingOlder
+
+ expect(olderSignals[0]?.aborted).toBe(true)
+ expect(olderCallCount).toBe(2)
+ expect(queryClient.getQueryData<{
+ pages: Array<{ messages: Array<{ id: string }> }>
+ }>(queryKey)?.pages.flatMap((page) => page.messages.map((message) => message.id))).toEqual([
+ "m_2",
+ "m_3",
+ "m_1",
+ ])
+ unsubscribe()
+ })
+
+ it.each([
+ ["channel", communityKeys.channelMessages("ch_empty"), "ch_empty"],
+ ["dm", communityKeys.dmMessages("dm_empty"), "dm_empty"],
+ ] as const)(
+ "refreshes an empty active %s query so its first missed message appears",
+ async (kind, queryKey, scopeId) => {
+ const queryClient = new QueryClient()
+ const { queryFn, unsubscribe } = seedEmptyActiveQuery(queryClient, queryKey)
+ apiFetchMock.mockResolvedValue({
+ messages: [{
+ id: "m_first",
+ type: "chat",
+ seq: 1,
+ createdAt: "2026-08-15T00:00:01.000Z",
+ }],
+ hasMore: false,
+ latestSeq: 1,
+ })
+
+ await reconcileFocusedMessageQueries(queryClient, kind, scopeId)
+
+ expect(apiFetchMock).toHaveBeenCalledOnce()
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ `/api/community/channels/${scopeId}/messages`,
+ )
+ expect(queryFn).not.toHaveBeenCalled()
+ const messages = queryClient.getQueryData<{
+ pages: Array<{ messages: Array<{ id: string }> }>
+ }>(queryKey)?.pages[0].messages ?? []
+ expect(messages.map((message) => message.id)).toEqual(["m_first"])
+ unsubscribe()
+ },
+ )
+
+ it.each([
+ ["channel", communityKeys.channelMessages("ch_cold"), "ch_cold"],
+ ["dm", communityKeys.dmMessages("dm_cold"), "dm_cold"],
+ ] as const)(
+ "recovers a cold failed active %s query through its canonical queryFn",
+ async (kind, queryKey, scopeId) => {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ })
+ const queryFn = vi.fn()
+ .mockRejectedValueOnce(new Error("offline"))
+ .mockResolvedValueOnce({
+ messages: [{
+ id: "m_after_reconnect",
+ type: "chat",
+ seq: 1,
+ createdAt: "2026-08-15T00:00:01.000Z",
+ }],
+ hasMore: false,
+ latestSeq: 1,
+ })
+ const observer = new InfiniteQueryObserver(queryClient, {
+ queryKey,
+ queryFn,
+ initialPageParam: { mode: "newest" } as const,
+ getNextPageParam: () => undefined,
+ retry: false,
+ })
+ const unsubscribe = observer.subscribe(() => undefined)
+ await vi.waitFor(() => {
+ expect(observer.getCurrentResult().isError).toBe(true)
+ })
+
+ await reconcileFocusedMessageQueries(queryClient, kind, scopeId)
+
+ expect(queryFn).toHaveBeenCalledTimes(2)
+ expect(apiFetchMock).not.toHaveBeenCalled()
+ const data = queryClient.getQueryData<{
+ pages: Array<{ messages: Array<{ id: string }> }>
+ }>(queryKey)
+ expect(data?.pages[0].messages.map((message) => message.id)).toEqual([
+ "m_after_reconnect",
+ ])
+ unsubscribe()
+ },
+ )
+
+ it("refreshes an anchor window, then catches up only from its newest cached row", async () => {
+ const queryClient = new QueryClient()
+ const queryKey = communityKeys.channelMessages("ch_anchor")
+ queryClient.setQueryData(queryKey, {
+ pages: [{
+ messages: [{
+ id: "m_10",
+ type: "chat",
+ seq: 10,
+ createdAt: "2026-08-15T00:00:10.000Z",
+ }],
+ hasMoreOlder: true,
+ olderCursor: "older-10",
+ hasMoreNewer: true,
+ newerCursor: "newer-10",
+ latestSeq: 10,
+ }],
+ pageParams: [{ mode: "anchor", anchor: "m_10" }],
+ })
+ const observer = new QueryObserver(queryClient, {
+ queryKey,
+ queryFn: vi.fn(async () => ({ stale: true })),
+ staleTime: Infinity,
+ })
+ const unsubscribe = observer.subscribe(() => undefined)
+ apiFetchMock
+ .mockResolvedValueOnce({
+ messages: [{
+ id: "m_10",
+ type: "chat",
+ seq: 10,
+ createdAt: "2026-08-15T00:00:10.000Z",
+ }],
+ hasMoreOlder: true,
+ olderCursor: "older-10",
+ hasMoreNewer: true,
+ newerCursor: "newer-10",
+ latestSeq: 11,
+ })
+ .mockResolvedValueOnce({
+ messages: [{
+ id: "m_11",
+ type: "chat",
+ seq: 11,
+ createdAt: "2026-08-15T00:00:11.000Z",
+ }],
+ hasMoreNewer: false,
+ latestSeq: 11,
+ })
+
+ await reconcileFocusedMessageQueries(queryClient, "channel", "ch_anchor")
+
+ expect(apiFetchMock.mock.calls.map(([url]) => url)).toEqual([
+ "/api/community/channels/ch_anchor/messages?anchor=m_10",
+ "/api/community/channels/ch_anchor/messages?since=2026-08-15T00%3A00%3A10.000Z%7Cm_10",
+ ])
+ expect(queryClient.getQueryData<{
+ pages: Array<{ messages: Array<{ id: string }> }>
+ pageParams: unknown[]
+ }>(queryKey)).toMatchObject({
+ pages: [{ messages: [{ id: "m_10" }, { id: "m_11" }] }],
+ pageParams: [{ mode: "anchor", anchor: "m_10" }],
+ })
+ unsubscribe()
+ })
+
+ it("walks only forward delta pages and preserves every cached history page", async () => {
+ const queryClient = new QueryClient()
+ const queryKey = communityKeys.channelMessages("ch_1")
+ const { queryFn, unsubscribe } = seedActiveQuery(queryClient, queryKey)
+ apiFetchMock
+ .mockResolvedValueOnce({
+ messages: [{
+ id: "m_2",
+ type: "chat",
+ seq: 2,
+ createdAt: "2026-08-15T00:00:02.000Z",
+ }],
+ hasMore: true,
+ cursor: "older-2",
+ latestSeq: 4,
+ })
+ .mockResolvedValueOnce({
+ messages: [{
+ id: "m_3",
+ type: "chat",
+ seq: 3,
+ createdAt: "2026-08-15T00:00:03.000Z",
+ }],
+ hasMoreNewer: true,
+ newerCursor: "2026-08-15T00:00:03.000Z|m_3",
+ latestSeq: 4,
+ })
+ .mockResolvedValueOnce({
+ messages: [{
+ id: "m_4",
+ type: "chat",
+ seq: 4,
+ createdAt: "2026-08-15T00:00:04.000Z",
+ }],
+ hasMoreNewer: false,
+ latestSeq: 4,
+ })
+
+ await reconcileFocusedMessageQueries(queryClient, "channel", "ch_1")
+
+ expect(apiFetchMock).toHaveBeenCalledTimes(3)
+ expect(apiFetchMock.mock.calls.map(([url]) => url)).toEqual([
+ "/api/community/channels/ch_1/messages",
+ "/api/community/channels/ch_1/messages?since=2026-08-15T00%3A00%3A02.000Z%7Cm_2",
+ "/api/community/channels/ch_1/messages?since=2026-08-15T00%3A00%3A03.000Z%7Cm_3",
+ ])
+ expect(queryFn).not.toHaveBeenCalled()
+ expect(queryClient.getQueryData<{
+ pages: Array<{
+ messages: Array<{ id: string }>
+ latestSeq?: number
+ hasMore?: boolean
+ cursor?: string
+ hasMoreNewer?: boolean
+ }>
+ pageParams: unknown[]
+ }>(queryKey)).toMatchObject({
+ pages: [
+ {
+ messages: [{ id: "m_2" }, { id: "m_3" }, { id: "m_4" }],
+ latestSeq: 4,
+ hasMore: true,
+ cursor: "older-2",
+ hasMoreNewer: false,
+ },
+ { messages: [{ id: "m_1" }] },
+ ],
+ pageParams: [
+ { mode: "newest" },
+ { mode: "older", cursor: "older-2" },
+ ],
+ })
+ unsubscribe()
+ })
+
+ it("caps forward catch-up at eight pages and leaves the newer cursor resumable", async () => {
+ const queryClient = new QueryClient()
+ const queryKey = communityKeys.channelMessages("ch_bounded")
+ const { unsubscribe } = seedActiveQuery(queryClient, queryKey)
+ apiFetchMock.mockResolvedValueOnce({
+ messages: [{
+ id: "m_2",
+ type: "chat",
+ seq: 2,
+ createdAt: "2026-08-15T00:00:02.000Z",
+ }],
+ hasMore: true,
+ cursor: "older-2",
+ latestSeq: 100,
+ })
+ for (let seq = 3; seq <= 10; seq += 1) {
+ apiFetchMock.mockResolvedValueOnce({
+ messages: [{
+ id: `m_${seq}`,
+ type: "chat",
+ seq,
+ createdAt: `2026-08-15T00:00:${String(seq).padStart(2, "0")}.000Z`,
+ }],
+ hasMoreNewer: true,
+ newerCursor: `2026-08-15T00:00:${String(seq).padStart(2, "0")}.000Z|m_${seq}`,
+ latestSeq: 100,
+ })
+ }
+
+ await reconcileFocusedMessageQueries(queryClient, "channel", "ch_bounded")
+
+ expect(apiFetchMock).toHaveBeenCalledTimes(9)
+ expect(apiFetchMock.mock.calls.at(-1)?.[0]).toBe(
+ "/api/community/channels/ch_bounded/messages?since=2026-08-15T00%3A00%3A09.000Z%7Cm_9",
+ )
+ expect(queryClient.getQueryData<{
+ pages: Array<{
+ messages: Array<{ id: string }>
+ hasMoreNewer?: boolean
+ newerCursor?: string
+ }>
+ }>(queryKey)?.pages[0]).toMatchObject({
+ messages: Array.from({ length: 9 }, (_, index) => ({ id: `m_${index + 2}` })),
+ hasMoreNewer: true,
+ newerCursor: "2026-08-15T00:00:10.000Z|m_10",
+ })
+ unsubscribe()
+ })
+
+ it("refreshes one visible window for missed edits without walking history", async () => {
+ const queryClient = new QueryClient()
+ const queryKey = communityKeys.channelMessages("ch_1")
+ const { queryFn, unsubscribe } = seedActiveQuery(queryClient, queryKey)
+ apiFetchMock.mockResolvedValue({
+ messages: [{
+ id: "m_2",
+ type: "chat",
+ seq: 2,
+ content: "edited while disconnected",
+ createdAt: "2026-08-15T00:00:02.000Z",
+ }],
+ hasMore: true,
+ cursor: "older-2",
+ latestSeq: 2,
+ })
+
+ await reconcileFocusedMessageQueries(queryClient, "channel", "ch_1")
+
+ expect(apiFetchMock).toHaveBeenCalledOnce()
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/channels/ch_1/messages",
+ )
+ expect(queryFn).not.toHaveBeenCalled()
+ expect(queryClient.getQueryData<{
+ pages: Array<{ messages: Array<{ id: string; content?: string }> }>
+ }>(queryKey)?.pages[0].messages[0]).toMatchObject({
+ id: "m_2",
+ content: "edited while disconnected",
+ })
+ unsubscribe()
+ })
+
+ it("merges into the latest cache so a live WS row arriving mid-reconcile is preserved", async () => {
+ const queryClient = new QueryClient()
+ const queryKey = communityKeys.channelMessages("ch_1")
+ const { unsubscribe } = seedActiveQuery(queryClient, queryKey)
+ apiFetchMock.mockImplementationOnce(async () => {
+ queryClient.setQueryData(queryKey, (current: {
+ pages: Array<{ messages: Array<Record<string, unknown>> }>
+ pageParams: unknown[]
+ } | undefined) => current
+ ? {
+ ...current,
+ pages: [{
+ ...current.pages[0],
+ messages: [...current.pages[0].messages, {
+ id: "m_live",
+ type: "chat",
+ seq: 3,
+ createdAt: "2026-08-15T00:00:03.000Z",
+ }],
+ }, ...current.pages.slice(1)],
+ }
+ : current)
+ return {
+ messages: [{
+ id: "m_2",
+ type: "chat",
+ seq: 2,
+ content: "refreshed",
+ createdAt: "2026-08-15T00:00:02.000Z",
+ }],
+ hasMore: true,
+ cursor: "older-2",
+ latestSeq: 2,
+ }
+ })
+
+ await reconcileFocusedMessageQueries(queryClient, "channel", "ch_1")
+
+ expect(queryClient.getQueryData<{
+ pages: Array<{ messages: Array<{ id: string; content?: string }> }>
+ }>(queryKey)?.pages[0].messages).toMatchObject([
+ { id: "m_2", content: "refreshed" },
+ { id: "m_live" },
+ ])
+ unsubscribe()
+ })
+
+ it("keeps a DM's loaded history pages while refreshing its current window", async () => {
+ const queryClient = new QueryClient()
+ const queryKey = communityKeys.dmMessages("dm_1")
+ const { queryFn, unsubscribe } = seedActiveQuery(queryClient, queryKey)
+ apiFetchMock.mockResolvedValue({
+ messages: [{
+ id: "m_2",
+ type: "chat",
+ seq: 2,
+ createdAt: "2026-08-15T00:00:02.000Z",
+ }],
+ hasMore: true,
+ cursor: "older-2",
+ latestSeq: 2,
+ })
+
+ await reconcileFocusedMessageQueries(queryClient, "dm", "dm_1")
+
+ expect(apiFetchMock).toHaveBeenCalledOnce()
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/channels/dm_1/messages",
+ )
+ expect(queryFn).not.toHaveBeenCalled()
+ expect(queryClient.getQueryData<{
+ pages: Array<{ messages: Array<{ id: string }> }>
+ pageParams: unknown[]
+ }>(queryKey)).toMatchObject({
+ pages: [
+ { messages: [{ id: "m_2" }] },
+ { messages: [{ id: "m_1" }] },
+ ],
+ pageParams: [
+ { mode: "newest" },
+ { mode: "older", cursor: "older-2" },
+ ],
+ })
+ unsubscribe()
+ })
+
+ it("keeps a tag-filtered active query scoped to the same tag", async () => {
+ const queryClient = new QueryClient()
+ const queryKey = [...communityKeys.channelMessages("forum_1"), "tag", "bug"] as const
+ const { unsubscribe } = seedActiveQuery(queryClient, queryKey)
+ apiFetchMock.mockResolvedValue({ messages: [], hasMoreNewer: false, latestSeq: 2 })
+
+ await reconcileFocusedMessageQueries(queryClient, "channel", "forum_1")
+
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/channels/forum_1/messages?tag=bug",
+ )
+ unsubscribe()
+ })
+
+ it("leaves rendered cache untouched when catch-up fails", async () => {
+ const queryClient = new QueryClient()
+ const queryKey = communityKeys.dmMessages("dm_1")
+ const { unsubscribe } = seedActiveQuery(queryClient, queryKey)
+ const before = queryClient.getQueryData(queryKey)
+ apiFetchMock.mockRejectedValue(new Error("network unavailable"))
+
+ await expect(
+ reconcileFocusedMessageQueries(queryClient, "dm", "dm_1"),
+ ).rejects.toThrow("focused messages failed")
+
+ expect(queryClient.getQueryData(queryKey)).toBe(before)
+ unsubscribe()
+ })
+})
diff --git a/src/web/src/hooks/community/community-ws/reconnect-messages.ts b/src/web/src/hooks/community/community-ws/reconnect-messages.ts
new file mode 100644
index 000000000..de904a003
--- /dev/null
+++ b/src/web/src/hooks/community/community-ws/reconnect-messages.ts
@@ -0,0 +1,251 @@
+import type { InfiniteData, QueryClient, QueryKey } from "@tanstack/react-query"
+import { apiFetch } from "@/lib/api/client"
+import { communityKeys } from "@/lib/query-keys"
+import type {
+ MessagesPage,
+ MessagesPageParam,
+ Msg,
+} from "@/lib/community/models/message"
+
+type MessageCache = InfiniteData<MessagesPage, MessagesPageParam>
+
+type WarmReconnectWindow = {
+ cursor: string | null
+ latestSeq: number
+ pageParam: MessagesPageParam
+ tag: string | null
+}
+
+const MAX_CATCH_UP_PAGES = 8
+
+function isMessageCache(value: unknown): value is MessageCache {
+ if (!value || typeof value !== "object") return false
+ const candidate = value as Partial<MessageCache>
+ return Array.isArray(candidate.pages) && Array.isArray(candidate.pageParams)
+}
+
+function compareMessages(a: Msg, b: Msg): number {
+ const aCreatedAt = a.createdAt ?? ""
+ const bCreatedAt = b.createdAt ?? ""
+ if (aCreatedAt !== bCreatedAt) return aCreatedAt.localeCompare(bCreatedAt)
+ return a.id.localeCompare(b.id)
+}
+
+function newestMessageCursor(cache: MessageCache): string | null {
+ let newest: Msg | null = null
+ for (const page of cache.pages) {
+ for (const message of page.messages) {
+ if (!message.createdAt) continue
+ if (!newest || compareMessages(newest, message) < 0) newest = message
+ }
+ }
+ return newest?.createdAt ? `${newest.createdAt}|${newest.id}` : null
+}
+
+function queryTag(queryKey: QueryKey): string | null {
+ return queryKey[4] === "tag" && typeof queryKey[5] === "string"
+ ? queryKey[5]
+ : null
+}
+
+function buildMessagesUrl(
+ scopeId: string,
+ pageParam: MessagesPageParam,
+ tag: string | null,
+): string {
+ const params = new URLSearchParams()
+ if (tag) params.set("tag", tag)
+ switch (pageParam.mode) {
+ case "newest":
+ break
+ case "older":
+ params.set("cursor", pageParam.cursor)
+ break
+ case "newer":
+ params.set("since", pageParam.cursor)
+ break
+ case "since":
+ params.set("since", pageParam.since)
+ break
+ case "anchor":
+ params.set("anchor", pageParam.anchor)
+ break
+ }
+ const query = params.toString()
+ const base = `/api/community/channels/${scopeId}/messages`
+ return query ? `${base}?${query}` : base
+}
+
+function cachedLatestSeq(cache: MessageCache): number {
+ return cache.pages.reduce((latest, page) => Math.max(
+ latest,
+ page.latestSeq ?? 0,
+ ...page.messages.map((message) => message.seq ?? 0),
+ ), 0)
+}
+
+/**
+ * Classify an active query as a paint-preserving warm window or a cold query.
+ *
+ * A warm window always has a rendered page plus the page parameter that
+ * produced it. Empty conversations are still warm: their empty newest page is
+ * valuable UI state and must be refreshed in place. Undefined, failed, or
+ * malformed data is cold and is recovered through the query's own fetch
+ * function instead of inventing pagination state here.
+ */
+function warmReconnectWindow(
+ queryKey: QueryKey,
+ data: unknown,
+): WarmReconnectWindow | null {
+ if (!isMessageCache(data) || data.pages.length === 0) return null
+ const pageParam = data.pageParams[0]
+ if (!pageParam) return null
+ return {
+ cursor: newestMessageCursor(data),
+ latestSeq: cachedLatestSeq(data),
+ pageParam,
+ tag: queryTag(queryKey),
+ }
+}
+
+async function fetchCurrentWindow(
+ scopeId: string,
+ pageParam: MessagesPageParam,
+ tag: string | null,
+): Promise<MessagesPage> {
+ return apiFetch<MessagesPage>(buildMessagesUrl(scopeId, pageParam, tag))
+}
+
+async function fetchCatchUp(
+ scopeId: string,
+ cursor: string,
+ tag: string | null,
+): Promise<MessagesPage> {
+ const messages: Msg[] = []
+ let latestSeq = 0
+ let nextCursor = cursor
+ let hasMoreNewer = false
+ let newerCursor: string | undefined
+
+ for (let pageIndex = 0; pageIndex < MAX_CATCH_UP_PAGES; pageIndex += 1) {
+ const params = new URLSearchParams({ since: nextCursor })
+ if (tag) params.set("tag", tag)
+ const page = await apiFetch<MessagesPage>(
+ `/api/community/channels/${scopeId}/messages?${params}`,
+ )
+ messages.push(...page.messages)
+ latestSeq = Math.max(latestSeq, page.latestSeq ?? 0)
+ hasMoreNewer = page.hasMoreNewer ?? false
+ newerCursor = page.newerCursor
+ if (!hasMoreNewer || !newerCursor) break
+ nextCursor = newerCursor
+ }
+
+ return {
+ messages,
+ latestSeq,
+ hasMoreNewer,
+ newerCursor,
+ }
+}
+
+function mergeReconciledPages(
+ cache: MessageCache,
+ refreshed: MessagesPage,
+ catchUp: MessagesPage | null,
+): MessageCache {
+ if (cache.pages.length === 0) return cache
+
+ const reconciled = catchUp
+ ? [...refreshed.messages, ...catchUp.messages]
+ : refreshed.messages
+ const incoming = new Map(reconciled.map((message) => [message.id, message]))
+ const pages = cache.pages.map((page) => ({
+ ...page,
+ messages: page.messages.map((message) => {
+ const replacement = incoming.get(message.id)
+ if (!replacement) return message
+ incoming.delete(message.id)
+ return replacement
+ }),
+ }))
+ const first = pages[0]
+ const messages = [...first.messages, ...incoming.values()].sort(compareMessages)
+ pages[0] = {
+ ...first,
+ messages,
+ latestSeq: Math.max(
+ first.latestSeq ?? 0,
+ refreshed.latestSeq ?? 0,
+ catchUp?.latestSeq ?? 0,
+ ),
+ hasMoreNewer: catchUp?.hasMoreNewer ?? refreshed.hasMoreNewer ?? false,
+ newerCursor: catchUp?.newerCursor ?? refreshed.newerCursor,
+ }
+ return { ...cache, pages }
+}
+
+export async function reconcileFocusedMessageQueries(
+ queryClient: QueryClient,
+ kind: "channel" | "dm",
+ scopeId: string,
+): Promise<void> {
+ const queryKey = kind === "channel"
+ ? communityKeys.channelMessages(scopeId)
+ : communityKeys.dmMessages(scopeId)
+ const queries = queryClient.getQueryCache().findAll({
+ queryKey,
+ type: "active",
+ })
+ const operations = queries.map(async (query) => {
+ // Infinite-query pagination computes its result from the data snapshot at
+ // fetch start. If that generation completes after reconciliation, TanStack
+ // can replace the reconciled cache with its stale snapshot. Capture the
+ // user's pagination intent, cancel that exact generation, then replay the
+ // same direction against the reconciled cache below.
+ const pendingDirection = query.state.fetchMeta?.fetchMore?.direction
+ await queryClient.cancelQueries(
+ { queryKey: query.queryKey, exact: true },
+ { revert: true, silent: true },
+ )
+
+ const window = warmReconnectWindow(query.queryKey, query.state.data)
+ if (!window) {
+ // There is no painted history to protect. Delegate recovery to the
+ // query's canonical queryFn so cold/failed active screens do not remain
+ // stuck after `refetchOnReconnect` is intentionally disabled.
+ await queryClient.refetchQueries(
+ { queryKey: query.queryKey, exact: true, type: "active" },
+ { throwOnError: true },
+ )
+ return
+ }
+
+ try {
+ const refreshed = await fetchCurrentWindow(
+ scopeId,
+ window.pageParam,
+ window.tag,
+ )
+ const catchUp = window.cursor !== null
+ && (refreshed.latestSeq ?? 0) > window.latestSeq
+ ? await fetchCatchUp(scopeId, window.cursor, window.tag)
+ : null
+ queryClient.setQueryData<MessageCache>(query.queryKey, (current) => (
+ isMessageCache(current)
+ ? mergeReconciledPages(current, refreshed, catchUp)
+ : current
+ ))
+ } finally {
+ if (pendingDirection) {
+ await query.fetch(undefined, {
+ meta: { fetchMore: { direction: pendingDirection } },
+ })
+ }
+ }
+ })
+ const settled = await Promise.allSettled(operations)
+ if (settled.some((result) => result.status === "rejected")) {
+ throw new Error("focused messages failed")
+ }
+}
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 a9f1608a4..ddd383313 100644
--- a/src/web/src/hooks/community/community-ws/reconnect.test.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect.test.ts
@@ -47,7 +47,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
})
})
- it("invalidates the focused channel's messages + inbox on reconnect, but NOT the read-state snapshot", async () => {
+ it("reconciles the focused channel's messages + inbox on reconnect, but NOT the read-state snapshot", async () => {
const { useCommunityStore } = await import("@/stores/community")
useCommunityStore.getState().subscribe({ channelId: "ch_focus" })
@@ -60,7 +60,8 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
const invalidatedKeys = spy.mock.calls.map(
(c) => c[0]?.queryKey as unknown[] | undefined,
)
- // Focused channel messages — a legitimate top-up refetch that keeps data.
+ // Focused channel messages use the bounded catch-up path instead of a
+ // TanStack invalidation that would refetch every cached infinite page.
expect(
invalidatedKeys.some(
(k) =>
@@ -70,7 +71,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
k[2] === "ch_focus" &&
k[3] === "messages",
),
- ).toBe(true)
+ ).toBe(false)
expect(
invalidatedKeys.some(
(k) => JSON.stringify(k) === JSON.stringify(communityKeys.channelMembers("ch_focus")),
@@ -200,7 +201,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
})).toEqual([])
})
- it("invalidates the focused DM's messages on reconnect, but NOT its read-state snapshot", async () => {
+ it("reconciles the focused DM's messages on reconnect, but NOT its read-state snapshot", async () => {
const { useCommunityStore } = await import("@/stores/community")
useCommunityStore.getState().subscribe({ dmConversationId: "dm_focus" })
@@ -222,7 +223,7 @@ describe("useCommunityWs — resyncs machines on WS reconnect", () => {
k[2] === "dm_focus" &&
k[3] === "messages",
),
- ).toBe(true)
+ ).toBe(false)
// Read-state snapshot MUST NOT be invalidated — same rationale as the
// channel case (mirrors `useChannelReadStateSnapshot`'s freeze contract).
expect(
diff --git a/src/web/src/hooks/community/community-ws/reconnect.ts b/src/web/src/hooks/community/community-ws/reconnect.ts
index 12bc9c2bf..070cd8e0c 100644
--- a/src/web/src/hooks/community/community-ws/reconnect.ts
+++ b/src/web/src/hooks/community/community-ws/reconnect.ts
@@ -5,6 +5,7 @@ import { useCommunityWsStore } from "@/stores/community/ws"
import { invalidateForumSidebarBaseExact } from "@/hooks/community/use-forum-sidebar-threads"
import { clearAllTypingIndicators } from "@/hooks/community/community-ws/typing"
import { communityWsReconnectPolicies } from "@/hooks/community/community-ws/registry"
+import { reconcileFocusedMessageQueries } from "@/hooks/community/community-ws/reconnect-messages"
import {
trackCommunityWsReconcileComplete,
trackCommunityWsReconcileFailure,
@@ -107,16 +108,18 @@ function policyExecutors(queryClient: QueryClient): Record<CommunityWsReconcileP
"focused-messages": async () => {
const operations: Promise<unknown>[] = []
if (sub.channelId) {
- operations.push(queryClient.invalidateQueries({
- queryKey: communityKeys.channelMessages(sub.channelId),
- refetchType: "active",
- }))
+ operations.push(reconcileFocusedMessageQueries(
+ queryClient,
+ "channel",
+ sub.channelId,
+ ))
}
if (sub.dmConversationId) {
- operations.push(queryClient.invalidateQueries({
- queryKey: communityKeys.dmMessages(sub.dmConversationId),
- refetchType: "active",
- }))
+ operations.push(reconcileFocusedMessageQueries(
+ queryClient,
+ "dm",
+ sub.dmConversationId,
+ ))
}
const settled = await Promise.allSettled(operations)
if (settled.some((result) => result.status === "rejected")) throw new Error("focused messages failed")
diff --git a/src/web/src/hooks/community/use-messages.activation-refetch.test.ts b/src/web/src/hooks/community/use-messages.activation-refetch.test.ts
index 81f2cfabd..5a5954999 100644
--- a/src/web/src/hooks/community/use-messages.activation-refetch.test.ts
+++ b/src/web/src/hooks/community/use-messages.activation-refetch.test.ts
@@ -78,6 +78,34 @@ beforeEach(() => {
})
describe("useMessagesInner — disabled-to-enabled cache revalidation", () => {
+ it("leaves browser network reconnect reconciliation to the bounded WS path", () => {
+ const queryClient = new QueryClient()
+ queryClient.setQueryData(communityKeys.dmMessages("dm_activation"), {
+ pages: [{
+ messages: [{ id: "m_cached", seq: 1, createdAt: "2026-08-09T00:00:00.000Z" }],
+ hasMore: false,
+ latestSeq: 1,
+ }],
+ pageParams: [{ mode: "newest" }],
+ })
+ apiFetchMock.mockResolvedValue({
+ messages: [{ id: "m_cached", seq: 1, createdAt: "2026-08-09T00:00:00.000Z" }],
+ hasMore: false,
+ latestSeq: 1,
+ })
+ const renderer = renderCapture(
+ queryClient,
+ React.createElement(DmCapture, {
+ lastReadMessageId: null,
+ onRender: () => undefined,
+ }),
+ )
+ expect(queryClient.getQueryCache().find({
+ queryKey: communityKeys.dmMessages("dm_activation"),
+ })?.options.refetchOnReconnect).toBe(false)
+ renderer.unmount()
+ })
+
it("refetches a fresh persisted empty DM on activation and converges to server truth", async () => {
const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 5_000 } } })
queryClient.setQueryData(communityKeys.dmMessages("dm_activation"), {
@@ -102,7 +130,10 @@ describe("useMessagesInner — disabled-to-enabled cache revalidation", () => {
React.createElement(DmCapture, { lastReadMessageId: null, onRender }),
)
await waitFor(() => apiFetchMock.mock.calls.length === 1)
- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/dm_activation/messages")
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/channels/dm_activation/messages",
+ { signal: expect.any(AbortSignal) },
+ )
response.resolve({
messages: [{ id: "m_server", seq: 1, createdAt: "2026-08-09T00:00:00.000Z" }],
@@ -204,6 +235,7 @@ describe("useMessagesInner — disabled-to-enabled cache revalidation", () => {
expect(apiFetchMock).toHaveBeenNthCalledWith(
1,
"/api/community/channels/ch_activation/messages?anchor=m_anchor",
+ { signal: expect.any(AbortSignal) },
)
for (const snapshot of snapshots) expect(snapshot.ids.length).toBeGreaterThan(0)
@@ -218,6 +250,7 @@ describe("useMessagesInner — disabled-to-enabled cache revalidation", () => {
expect(apiFetchMock).toHaveBeenNthCalledWith(
2,
"/api/community/channels/ch_activation/messages?cursor=fresh-cursor",
+ { signal: expect.any(AbortSignal) },
)
for (const snapshot of snapshots) expect(snapshot.ids.length).toBeGreaterThan(0)
diff --git a/src/web/src/hooks/community/use-messages.jump-to-present.test.ts b/src/web/src/hooks/community/use-messages.jump-to-present.test.ts
index 411c0e321..994bd92d7 100644
--- a/src/web/src/hooks/community/use-messages.jump-to-present.test.ts
+++ b/src/web/src/hooks/community/use-messages.jump-to-present.test.ts
@@ -168,7 +168,10 @@ describe("useMessages jumpToPresent", () => {
expect(resetSpy).toHaveBeenCalledTimes(1)
expect(resetSpy).toHaveBeenCalledWith({ queryKey, exact: true })
expect(apiFetchMock).toHaveBeenCalledTimes(1)
- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/channel_1/messages")
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/channels/channel_1/messages",
+ { signal: expect.any(AbortSignal) },
+ )
expect(latest.hasMoreNewer).toBe(false)
act(() => latest.jumpToPresent())
@@ -383,7 +386,10 @@ describe("useDmMessages jumpToPresent", () => {
expect(resetSpy).toHaveBeenCalledTimes(1)
expect(resetSpy).toHaveBeenCalledWith({ queryKey, exact: true })
expect(apiFetchMock).toHaveBeenCalledTimes(1)
- expect(apiFetchMock).toHaveBeenCalledWith("/api/community/channels/dm_1/messages")
+ expect(apiFetchMock).toHaveBeenCalledWith(
+ "/api/community/channels/dm_1/messages",
+ { signal: expect.any(AbortSignal) },
+ )
update(
renderer,
diff --git a/src/web/src/hooks/community/use-messages.test.ts b/src/web/src/hooks/community/use-messages.test.ts
index 78a961a69..5d6445ea5 100644
--- a/src/web/src/hooks/community/use-messages.test.ts
+++ b/src/web/src/hooks/community/use-messages.test.ts
@@ -75,6 +75,22 @@ describe("channelMessagesQueryFn — url per mode", () => {
})
describe("channelMessagesQueryFn — queryClient integration", () => {
+ it("passes TanStack's AbortSignal to apiFetch", async () => {
+ const { channelMessagesQueryFn } = await loadHook()
+ const controller = new AbortController()
+ apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false, latestSeq: 0 })
+
+ await channelMessagesQueryFn("ch_abort")({
+ pageParam: { mode: "newest" },
+ signal: controller.signal,
+ })
+
+ expect(apiFetchMock).toHaveBeenLastCalledWith(
+ "/api/community/channels/ch_abort/messages",
+ { signal: controller.signal },
+ )
+ })
+
it("populates queryClient at communityKeys.channelMessages(channelId)", async () => {
const { channelMessagesQueryFn } = await loadHook()
apiFetchMock.mockResolvedValueOnce({ messages: [{ id: "m_1" }], hasMore: false })
@@ -104,6 +120,22 @@ describe("channelMessagesQueryFn — queryClient integration", () => {
})
describe("dmMessagesQueryFn", () => {
+ it("passes TanStack's AbortSignal to apiFetch", async () => {
+ const { dmMessagesQueryFn } = await loadHook()
+ const controller = new AbortController()
+ apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false, latestSeq: 0 })
+
+ await dmMessagesQueryFn("dm_abort")({
+ pageParam: { mode: "newest" },
+ signal: controller.signal,
+ })
+
+ expect(apiFetchMock).toHaveBeenLastCalledWith(
+ "/api/community/channels/dm_abort/messages",
+ { signal: controller.signal },
+ )
+ })
+
it("newest → no query params", async () => {
const { dmMessagesQueryFn } = await loadHook()
apiFetchMock.mockResolvedValueOnce({ messages: [], hasMore: false, latestSeq: 0 })
diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.ts
index 449a5d3e2..61a298708 100644
--- a/src/web/src/hooks/community/use-messages.ts
+++ b/src/web/src/hooks/community/use-messages.ts
@@ -67,18 +67,39 @@ function buildMessagesUrl(base: string, pageParam: MessagesPageParam, tag?: stri
export const channelMessagesQueryFn =
(channelId: string, tag?: string | null) =>
- async ({ pageParam }: { pageParam: MessagesPageParam }): Promise<MessagesPage> => {
- return apiFetch<MessagesPage>(
- buildMessagesUrl(`/api/community/channels/${channelId}/messages`, pageParam, tag),
+ async ({
+ pageParam,
+ signal,
+ }: {
+ pageParam: MessagesPageParam
+ signal?: AbortSignal
+ }): Promise<MessagesPage> => {
+ const url = buildMessagesUrl(
+ `/api/community/channels/${channelId}/messages`,
+ pageParam,
+ tag,
)
+ return signal
+ ? apiFetch<MessagesPage>(url, { signal })
+ : apiFetch<MessagesPage>(url)
}
export const dmMessagesQueryFn =
(dmId: string) =>
- async ({ pageParam }: { pageParam: MessagesPageParam }): Promise<MessagesPage> => {
- return apiFetch<MessagesPage>(
- buildMessagesUrl(`/api/community/channels/${dmId}/messages`, pageParam),
+ async ({
+ pageParam,
+ signal,
+ }: {
+ pageParam: MessagesPageParam
+ signal?: AbortSignal
+ }): Promise<MessagesPage> => {
+ const url = buildMessagesUrl(
+ `/api/community/channels/${dmId}/messages`,
+ pageParam,
)
+ return signal
+ ? apiFetch<MessagesPage>(url, { signal })
+ : apiFetch<MessagesPage>(url)
}
export function messageMatchesTag(message: Msg, tag?: string | null): boolean {
@@ -198,7 +219,10 @@ type PresentOverride = {
function useMessagesInner(
scopeId: string | null,
queryKey: readonly unknown[],
- queryFn: ({ pageParam }: { pageParam: MessagesPageParam }) => Promise<MessagesPage>,
+ queryFn: (context: {
+ pageParam: MessagesPageParam
+ signal?: AbortSignal
+ }) => Promise<MessagesPage>,
opts: MessagesOpts | undefined,
): MessagesReturn {
const queryClient = useQueryClient()
@@ -265,6 +289,7 @@ function useMessagesInner(
return { mode: "newer", cursor }
},
enabled,
+ refetchOnReconnect: false,
// Message bases are persisted, while accepted/session rows live in an
// in-memory overlay. Treat each ordinary active message query as stale so
// disabled→enabled activation revalidates even inside the global 5-second
diff --git a/src/web/src/lib/community/models/message.ts b/src/web/src/lib/community/models/message.ts
index 57eb59c04..9e225bd37 100644
--- a/src/web/src/lib/community/models/message.ts
+++ b/src/web/src/lib/community/models/message.ts
@@ -144,8 +144,8 @@ export type MessagesPage = {
// Discriminated pageParam. The queryFn dispatches on `mode` — the URL param
// map is: newest → no param, older → cursor, newer/since → since, anchor →
-// anchor. Since is reserved for future direct catch-up; the type covers it so
-// the server contract stays honest.
+// anchor. Since also powers bounded reconnect catch-up without refetching
+// every cached historical page.
export type MessagesPageParam =
| { mode: "newest" }
| { mode: "anchor"; anchor: string }