Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(web): retain cached messages when anchor repair fails (#794)
Gustavo Ye5c5d9797515b
diff --git a/src/web/src/hooks/community/use-messages.anchor-retry.dom.test.ts b/src/web/src/hooks/community/use-messages.anchor-retry.dom.test.tsnew file mode 100644index 000000000..850b3d4a5--- /dev/null+++ b/src/web/src/hooks/community/use-messages.anchor-retry.dom.test.ts@@ -0,0 +1,224 @@+import { createElement, type PropsWithChildren } from "react"+import { focusManager, onlineManager, QueryClient, QueryClientProvider } from "@tanstack/react-query"+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"+import { act, renderHook } from "@/test/react-dom-harness"+import { communityKeys } from "@/lib/query-keys"+import { useCommunityWsStore } from "@/stores/community/ws"+import { useMessageStreamStore } from "@/stores/community/message-stream"+import { useInitialPositionTransition } from "@/components/community/messages/initial-position-transition"+import { useDmMessages, useMessages } from "./use-messages"++const apiFetchMock = vi.fn()+vi.mock("@/lib/api/client", () => ({ apiFetch: (...args: unknown[]) => apiFetchMock(...args) }))++const clients: QueryClient[] = []+const renders: Array<{ ids: string[]; phase: string }> = []+const page = { messages: [{ id: "anchor", seq: 1 }, { id: "cached", seq: 2 }], hasMoreOlder: false, hasMoreNewer: false }++beforeEach(() => {+ vi.useFakeTimers()+ apiFetchMock.mockReset()+ useCommunityWsStore.getState().reset()+ useMessageStreamStore.getState().resetAll()+ focusManager.setFocused(true)+ onlineManager.setOnline(true)+ renders.length = 0+})+afterEach(() => {+ for (const client of clients.splice(0)) client.clear()+ vi.useRealTimers()+})++async function advance(ms = 0) {+ await act(async () => { await vi.advanceTimersByTimeAsync(ms) })+ await act(async () => { await vi.advanceTimersByTimeAsync(1) })+}++function mount(kind: "channel" | "dm" = "channel", stale = false) {+ const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: Infinity } } })+ clients.push(client)+ const key = kind === "channel" ? communityKeys.channelMessages("scope") : communityKeys.dmMessages("scope")+ client.setQueryData(key, {+ pages: [{ messages: [{ id: "cached", seq: 2 }], hasMoreOlder: true, hasMoreNewer: false }],+ pageParams: [{ mode: "newest" }],+ }, { updatedAt: Date.now() - (stale ? 120_000 : 0) })+ function Wrapper({ children }: PropsWithChildren) { return createElement(QueryClientProvider, { client }, children) }+ const useFeed = kind === "channel"+ ? (anchor: string) => useMessages("scope", { serverId: "server", lastReadMessageId: anchor })+ : (anchor: string) => useDmMessages("scope", { lastReadMessageId: anchor })+ const rendered = renderHook(({ anchor }) => {+ const feed = useFeed(anchor)+ const position = useInitialPositionTransition({+ firstWindowReady: !feed.isLoading || feed.messages.length > 0,+ authoritativeEmpty: false,+ positionSettled: false,+ })+ renders.push({ ids: feed.messages.map((message) => message.id), phase: position.phase })+ return feed+ }, { wrapper: Wrapper, initialProps: { anchor: "anchor" } })+ return { client, key, rendered }+}++describe("anchor repair retains the message window", () => {+ it.each(["channel", "dm"] as const)("keeps %s rows and initial positioning through failure then retries the anchor", async (kind) => {+ let fail!: (error: Error) => void+ apiFetchMock.mockImplementationOnce(() => new Promise((_resolve, reject) => { fail = reject }))+ .mockResolvedValue(page)+ const { rendered } = mount(kind)+ await advance(900)+ expect(renders.at(-1)?.phase).toBe("aurora")+ await act(async () => { fail(new Error("offline")) })+ await advance()+ expect(rendered.result.current.messages.map((message) => message.id)).toEqual(["cached"])+ await advance(1000)+ expect(apiFetchMock.mock.calls.map(([url]) => url)).toEqual([+ "/api/community/channels/scope/messages?anchor=anchor",+ "/api/community/channels/scope/messages?anchor=anchor",+ ])+ expect(rendered.result.current.messages.map((message) => message.id)).toEqual(["anchor", "cached"])+ expect(renders.every((row) => row.ids.length > 0 && row.phase !== "skeleton")).toBe(true)+ rendered.unmount()+ })++ it.each(["focus", "online"])("bounds failed retries and allows recovery on %s", async (event) => {+ apiFetchMock.mockRejectedValue(new Error("offline"))+ const { rendered } = mount()+ await advance()+ await advance(1000)+ await advance(2000)+ expect(apiFetchMock).toHaveBeenCalledTimes(3)+ await advance(60_000)+ expect(apiFetchMock).toHaveBeenCalledTimes(3)+ expect(rendered.result.current.messages.map((message) => message.id)).toEqual(["cached"])+ apiFetchMock.mockResolvedValue(page)+ act(() => {+ if (event === "focus") { focusManager.setFocused(false); focusManager.setFocused(true) }+ else { onlineManager.setOnline(false); onlineManager.setOnline(true) }+ })+ await advance()+ expect(apiFetchMock).toHaveBeenCalledTimes(4)+ expect(rendered.result.current.messages.map((message) => message.id)).toEqual(["anchor", "cached"])+ rendered.unmount()+ })++ it("does not restart backoff when ordinary messages update the cached window", async () => {+ apiFetchMock.mockRejectedValue(new Error("offline"))+ const { client, key, rendered } = mount()+ await advance()+ for (let index = 0; index < 5; index++) {+ act(() => {+ client.setQueryData(key, {+ pages: [{ messages: [{ id: "cached", seq: 2 }, { id: `new-${index}`, seq: index + 3 }], hasMoreOlder: true, hasMoreNewer: false }],+ pageParams: [{ mode: "newest" }],+ })+ })+ await advance(40)+ }+ expect(apiFetchMock).toHaveBeenCalledTimes(1)+ await advance(1000)+ expect(apiFetchMock).toHaveBeenCalledTimes(2)+ await advance(2000)+ expect(apiFetchMock).toHaveBeenCalledTimes(3)+ await advance(10_000)+ expect(apiFetchMock).toHaveBeenCalledTimes(3)+ expect(rendered.result.current.messages.map((message) => message.id)).toEqual(["cached", "new-4"])+ rendered.unmount()+ })++ it.each(["unmount", "evict", "revoke"])("stops scheduled retries after %s", async (change) => {+ apiFetchMock.mockRejectedValue(new Error("offline"))+ const { client, key, rendered } = mount()+ await advance()+ act(() => {+ if (change === "unmount") rendered.unmount()+ if (change === "evict") client.removeQueries({ queryKey: key, exact: true })+ if (change === "revoke") {+ useCommunityWsStore.getState().revokeChannelAccess("server", "scope")+ rendered.unmount()+ }+ })+ await advance(10_000)+ expect(apiFetchMock).toHaveBeenCalledTimes(change === "evict" ? 2 : 1)+ if (change === "evict") {+ expect(client.getQueryData(key)).toBeUndefined()+ rendered.unmount()+ }+ })++ it("retries the same anchor after the access epoch changes without accepting the old result", async () => {+ let resolveOld!: (value: typeof page) => void+ apiFetchMock.mockImplementationOnce(() => new Promise((resolve) => { resolveOld = resolve }))+ .mockResolvedValue(page)+ const { rendered } = mount()+ await advance()+ act(() => { useCommunityWsStore.setState((state) => ({ accessEpoch: state.accessEpoch + 1 })) })+ await advance()+ expect(apiFetchMock).toHaveBeenCalledTimes(2)+ expect(rendered.result.current.messages.map((message) => message.id)).toEqual(["anchor", "cached"])+ await act(async () => { resolveOld({ ...page, messages: [{ id: "old-secret", seq: 1 }] }) })+ await advance()+ expect(rendered.result.current.messages.some((message) => message.id === "old-secret")).toBe(false)+ rendered.unmount()+ })++ it("replaces a stale window only after a retry succeeds", async () => {+ apiFetchMock.mockRejectedValueOnce(new Error("offline"))+ .mockResolvedValue({ ...page, messages: [{ id: "anchor", seq: 1 }] })+ const { rendered } = mount("channel", true)+ await advance()+ expect(rendered.result.current.messages.map((message) => message.id)).toEqual(["cached"])+ await advance(1000)+ expect(rendered.result.current.messages.map((message) => message.id)).toEqual(["anchor"])+ expect(renders.every((row) => row.ids.length > 0)).toBe(true)+ rendered.unmount()+ })++ it("does not repeat a completed repair when the server window cannot contain a deleted anchor", async () => {+ const remainingPage = { ...page, messages: [{ id: "cached", seq: 2 }] }+ let resolveRefresh!: (value: typeof remainingPage) => void+ apiFetchMock.mockResolvedValueOnce(remainingPage)+ .mockImplementationOnce(() => new Promise((resolve) => { resolveRefresh = resolve }))+ .mockResolvedValue(remainingPage)+ const { rendered } = mount()+ await advance()+ act(() => { void rendered.result.current.refetch() })+ await advance()+ await act(async () => { resolveRefresh(remainingPage) })+ await advance()+ await advance(10_000)+ expect(apiFetchMock).toHaveBeenCalledTimes(2)+ expect(rendered.result.current.messages.map((message) => message.id)).toEqual(["cached"])+ rendered.unmount()+ })++ it("does not restore a window deliberately reset while a fresh repair was pending", async () => {+ let resolveOld!: (value: typeof page) => void+ apiFetchMock.mockImplementationOnce(() => new Promise((resolve) => { resolveOld = resolve }))+ .mockImplementation(() => new Promise(() => undefined))+ const { client, key, rendered } = mount()+ await advance()+ await act(async () => {+ void client.resetQueries({ queryKey: key, exact: true })+ resolveOld(page)+ await Promise.resolve()+ })+ await advance()+ expect(client.getQueryData(key)).toBeUndefined()+ rendered.unmount()+ })++ it("ignores an old anchor result after the anchor changes", async () => {+ let resolveOld!: (value: typeof page) => void+ apiFetchMock.mockImplementationOnce(() => new Promise((resolve) => { resolveOld = resolve }))+ .mockResolvedValue({ ...page, messages: [{ id: "new-anchor", seq: 3 }] })+ const { rendered } = mount()+ await advance()+ rendered.rerender({ anchor: "new-anchor" })+ await advance()+ await act(async () => { resolveOld({ ...page, messages: [{ id: "old-secret", seq: 1 }] }) })+ await advance()+ expect(rendered.result.current.messages.some((message) => message.id === "new-anchor")).toBe(true)+ expect(rendered.result.current.messages.some((message) => message.id === "old-secret")).toBe(false)+ rendered.unmount()+ })+})diff --git a/src/web/src/hooks/community/use-messages.ts b/src/web/src/hooks/community/use-messages.tsindex 90e11bc5f..a6002c41e 100644--- a/src/web/src/hooks/community/use-messages.ts+++ b/src/web/src/hooks/community/use-messages.ts@@ -2,6 +2,8 @@import {useInfiniteQuery,+ focusManager,+ onlineManager,useQueryClient,type UseInfiniteQueryResult,type InfiniteData,@@ -467,131 +469,106 @@ function useMessagesInner(current?.attemptId === presentOverride.attemptId ? null : current)}, [jumpPending, presentOverride, query.isError, queryClient, queryKey, viewKey])- // Fix 3 — anchor re-validation.- //- // When a persisted cache is rehydrated, TanStack uses the cached `pages`- // even if `initialPageParam` says "anchor at m_42". If m_42 isn't in the- // hydrated window (e.g. the persisted cache was a newest-tail and the- // read pointer has since advanced past it), `newDividerBefore` computes- // to `undefined` and the list snaps to bottom — no NEW divider, wrong- // position.- //- // Detect that shape and re-anchor. Fire exactly once per (scopeId,- // anchorId) pair via a ref — a subsequent watermark tick that advances- // lastReadMessageId is a different pair and gets its own single- // re-anchor opportunity.- //- // Two different causes need two different repairs:- // - Genuinely stale cache (cross-session IDB hydration, e.g. the Inbox-- // to-unread-channel case) — `resetQueries` is correct: the whole- // window is untrustworthy anyway.- // - Same-session anchor drift with a still-fresh cache (e.g. returning- // from a Thread after the watermark advanced past the window) — the- // already-loaded history is still valid. `resetQueries` would clear- // `pages` to empty and flash a blank list while it refetches. Instead,- // fetch a fresh anchor-centered page out of band and swap the query- // data directly once it lands — the view jumps straight from the old- // (valid) window to the new one, never passing through an empty state.- const anchorResetKeyRef = useRef<string | null>(null)+ const anchorRepairNeeded = cachedWindowNeedsAnchorReconcile(query.data, anchorId, reconcileLateAnchor)+ const messageQuery = queryClient.getQueryCache().find({ queryKey, exact: true })+ const settledAnchorRepairRef = useRef<{ key: string; query: unknown } | null>(null)+ const anchorRepairFailedRef = useRef(false)+ const [anchorRetryEpoch, setAnchorRetryEpoch] = useState(0)+ useEffect(() => {+ const retry = (ready: boolean) => {+ if (ready && anchorRepairFailedRef.current) setAnchorRetryEpoch((epoch) => epoch + 1)+ }+ const unsubscribeFocus = focusManager.subscribe(retry)+ const unsubscribeOnline = onlineManager.subscribe(retry)+ return () => {+ unsubscribeFocus()+ unsubscribeOnline()+ }+ }, [])useEffect(() => {if (!enabled) returnif (forceNewest) returnif (!anchorId) returnif (query.isFetching) returnif (query.isPending) return- if (!cachedWindowNeedsAnchorReconcile(- query.data,- anchorId,- reconcileLateAnchor,- )) return- const resetKey = `${scopeId ?? ""}::${anchorId}`- if (anchorResetKeyRef.current === resetKey) return- anchorResetKeyRef.current = resetKey-- const updatedAt = query.dataUpdatedAt+ if (!anchorRepairNeeded || !messageQuery) return+ const updatedAt = messageQuery.state.dataUpdatedAtconst isFresh = !!updatedAt && Date.now() - updatedAt < ANCHOR_CACHE_FRESHNESS_MS-- // Both branches fetch a fresh anchor-centered page out of band and swap- // it in via `setQueryData` — NEITHER uses `resetQueries`. `resetQueries`- // clears `pages` to empty synchronously, which flashes a second loading- // skeleton mid-mount and, worse, wipes the virtualizer's measurement- // cache so the one-shot mount scroll (fired once the refetch lands)- // mis-targets and settles at the top hero instead of the NEW divider —- // and the unread rows near the tail then never enter the viewport, so- // the read watermark never advances. Keeping the old (renderable) window- // on screen until the fresh page lands makes the transition a direct- // swap with no empty frame (DESIGN.md "Fade, don't swap").- //- // The branches differ only in what they keep:- // - FRESH cache (same-session drift, e.g. returning from a Thread after- // the watermark advanced): the already-loaded history is still valid,- // so MERGE the new anchor page into it — dropping it would lose rows- // the user paged in via `fetchOlder`.- // - STALE cache (cross-session IDB hydration): the loaded window is- // untrustworthy, so REPLACE it with just the fresh anchor page.const anchorPageParam: MessagesPageParam = { mode: "anchor", anchor: anchorId }const accessToken = captureChannelMetadataToken(scopeId!)- const currentQuery = queryClient.getQueryCache().find({ queryKey, exact: true })- const isCurrent = () => isChannelMetadataTokenCurrent(accessToken)+ const currentQuery = messageQuery+ let active = true+ let retryTimer: ReturnType<typeof setTimeout> | undefined+ const isCurrent = () => active && isChannelMetadataTokenCurrent(accessToken)&& queryClient.getQueryCache().find({ queryKey, exact: true }) === currentQueryconst anchorRequestKey = JSON.stringify([queryKey, anchorPageParam, accessToken])- fetchSharedAnchorRepair(- queryClient,- anchorRequestKey,- () => queryFn({ pageParam: anchorPageParam }),- )- .then((page) => {- // Re-check right before the swap — a concurrent send/WS update or a- // second re-anchor attempt in the interim shouldn't be clobbered by- // a now-outdated fetch result landing late.- if (anchorResetKeyRef.current !== resetKey || !isCurrent()) return- queryClient.setQueryData<PageCache>(queryKey, (current) => {- // Stale replace-path: use the fresh page even if `current` is- // somehow absent — never fall back to leaving an un-anchored- // window in place.- if (!isFresh) {- return { pages: [page], pageParams: [anchorPageParam] }- }- if (!current) return current- // Fresh merge-path: fold the freshly-fetched anchor page into the- // ALREADY-LOADED history rather than replacing `pages` outright —- // discarding it would drop every page the user loaded via- // `fetchOlder` (scroll-up pagination), which surfaced as history- // vanishing on channel switch. `mergeMessagesPages` sorts +- // dedupes by id, so overlapping rows between the old window and- // the new anchor page collapse cleanly. The merged set collapses- // into a single page — `hasMoreOlder`/`hasMoreNewer` come from the- // new anchor page since it alone knows the true state of both- // edges relative to the (possibly wider) merged window.- const currentMessages = mergeMessagesPages(current.pages)- const anchorAlreadyPainted = opts?.waitForAnchor === false- && currentMessages.some((message) => message.id === anchorId)- const merged = anchorAlreadyPainted- ? currentMessages- : mergeMessagesPages([...current.pages, page])- const mergedPage: MessagesPage = {- ...page,- messages: merged,- }- return { pages: [mergedPage], pageParams: [anchorPageParam] }+ if (settledAnchorRepairRef.current?.key === anchorRequestKey+ && settledAnchorRepairRef.current.query === currentQuery) return+ anchorRepairFailedRef.current = false+ const repair = (attempt: number) => {+ if (!isCurrent()) return+ void fetchSharedAnchorRepair(+ queryClient,+ anchorRequestKey,+ () => queryFn({ pageParam: anchorPageParam }),+ )+ .then((page) => {+ // Re-check right before the swap — a concurrent send/WS update or a+ // second re-anchor attempt in the interim shouldn't be clobbered by+ // a now-outdated fetch result landing late.+ if (!isCurrent()) return+ settledAnchorRepairRef.current = { key: anchorRequestKey, query: currentQuery }+ anchorRepairFailedRef.current = false+ queryClient.setQueryData<PageCache>(queryKey, (current) => {+ // Stale replace-path: use the fresh page even if `current` is+ // somehow absent — never fall back to leaving an un-anchored+ // window in place.+ if (!isFresh) {+ return { pages: [page], pageParams: [anchorPageParam] }+ }+ if (!current) return current+ // Fresh merge-path: fold the freshly-fetched anchor page into the+ // ALREADY-LOADED history rather than replacing `pages` outright —+ // discarding it would drop every page the user loaded via+ // `fetchOlder` (scroll-up pagination), which surfaced as history+ // vanishing on channel switch. `mergeMessagesPages` sorts ++ // dedupes by id, so overlapping rows between the old window and+ // the new anchor page collapse cleanly. The merged set collapses+ // into a single page — `hasMoreOlder`/`hasMoreNewer` come from the+ // new anchor page since it alone knows the true state of both+ // edges relative to the (possibly wider) merged window.+ const currentMessages = mergeMessagesPages(current.pages)+ const anchorAlreadyPainted = opts?.waitForAnchor === false+ && currentMessages.some((message) => message.id === anchorId)+ const merged = anchorAlreadyPainted+ ? currentMessages+ : mergeMessagesPages([...current.pages, page])+ const mergedPage: MessagesPage = {+ ...page,+ messages: merged,+ }+ return { pages: [mergedPage], pageParams: [anchorPageParam] }+ })+ })+ .catch(() => {+ if (!isCurrent()) return+ anchorRepairFailedRef.current = true+ if (attempt < 2) retryTimer = setTimeout(() => repair(attempt + 1), 1000 * (2 ** attempt))})- })- .catch(() => {- if (!isCurrent()) return- // Out-of-band fetch failed — fall back to the reset path so the- // scope isn't stuck showing a stale, un-anchored window forever.- // This is the ONLY `resetQueries` path left: an outright fetch- // failure has no fresh page to swap in, so the empty-then-refetch- // flash is the acceptable last resort rather than the common case.- void queryClient.resetQueries({ queryKey })- })+ }+ repair(0)+ return () => {+ active = false+ clearTimeout(retryTimer)+ }}, [+ anchorRetryEpoch,enabled,forceNewest,anchorId,scopeId,- query.data,- query.dataUpdatedAt,+ anchorRepairNeeded,+ messageQuery,query.isFetching,query.isPending,queryClient,