Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(topicComment): move the topic comments onto @lobechat/replica (#20621)

Arvin Xudda9c68c0b7b
diff --git a/src/features/Portal/TopicComments/Body.tsx b/src/features/Portal/TopicComments/Body.tsx
index e325e9b9665..f3444a20337 100644
--- a/src/features/Portal/TopicComments/Body.tsx
+++ b/src/features/Portal/TopicComments/Body.tsx
@@ -7,10 +7,9 @@ import { useTranslation } from 'react-i18next';
import AsyncError from '@/components/AsyncError';
import SurfaceSkeleton from '@/components/Skeleton/Surface';
import { useTopicCommentThreads } from '@/features/TopicComment/hooks';
-import { mutate } from '@/libs/swr';
-import { topicCommentKeys } from '@/libs/swr/keys';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
+import { useTopicCommentStore } from '@/store/topicComment';
import CommentCard from './CommentCard';
import Composer from './Composer';
@@ -34,12 +33,13 @@ const Body = memo(() => {
reload,
} = useTopicCommentThreads(view?.topicId, view?.messageId);
const topicId = view?.topicId;
+ const revalidateSummary = useTopicCommentStore((s) => s.revalidateTopicCommentSummary);
const refresh = useCallback(
() =>
topicId
- ? Promise.all([reload(), mutate(topicCommentKeys.summary(topicId))]).then(() => undefined)
+ ? Promise.all([reload(), revalidateSummary(topicId)]).then(() => undefined)
: Promise.resolve(),
- [reload, topicId],
+ [reload, revalidateSummary, topicId],
);
useTopicCommentEvents(topicId, refresh);
diff --git a/src/features/Portal/TopicComments/ThreadBody.tsx b/src/features/Portal/TopicComments/ThreadBody.tsx
index 5a54ecca54b..5e0db8a329e 100644
--- a/src/features/Portal/TopicComments/ThreadBody.tsx
+++ b/src/features/Portal/TopicComments/ThreadBody.tsx
@@ -11,10 +11,9 @@ import {
useTopicCommentReplies,
useTopicCommentReplyCount,
} from '@/features/TopicComment/hooks';
-import { mutate } from '@/libs/swr';
-import { topicCommentKeys } from '@/libs/swr/keys';
import { useChatStore } from '@/store/chat';
import { chatPortalSelectors } from '@/store/chat/selectors';
+import { useTopicCommentStore } from '@/store/topicComment';
import CommentCard from './CommentCard';
import Composer from './Composer';
@@ -44,15 +43,16 @@ const ThreadBody = memo(() => {
view?.rootCommentId,
replies.total ?? view?.initialReplyCount ?? replies.items.length,
);
+ const revalidateSummary = useTopicCommentStore((s) => s.revalidateTopicCommentSummary);
const refresh = useCallback(async () => {
if (!topicId) return;
await Promise.all([
rootMutate(),
hasFocusedReply ? focusedReplyMutate() : Promise.resolve(),
repliesReload(),
- mutate(topicCommentKeys.summary(topicId)),
+ revalidateSummary(topicId),
]);
- }, [focusedReplyMutate, hasFocusedReply, repliesReload, rootMutate, topicId]);
+ }, [focusedReplyMutate, hasFocusedReply, repliesReload, revalidateSummary, rootMutate, topicId]);
useTopicCommentEvents(topicId, refresh);
const listRef = useRef<HTMLDivElement>(null);
const visibleReplies = useMemo(() => {
diff --git a/src/features/TopicComment/hooks.test.ts b/src/features/TopicComment/hooks.test.ts
index 2c67f3fee5e..92a45e8ad10 100644
--- a/src/features/TopicComment/hooks.test.ts
+++ b/src/features/TopicComment/hooks.test.ts
@@ -1,11 +1,11 @@
/**
* @vitest-environment happy-dom
*/
-import type { TopicCommentItem } from '@lobechat/types';
+import type { TopicCommentItem, TopicCommentSummary, TopicCommentThread } from '@lobechat/types';
import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { useTopicCommentStore } from '@/store/topicComment';
+import { topicCommentThreadsKey, useTopicCommentStore } from '@/store/topicComment';
import {
useMessageCommentCount,
@@ -18,28 +18,29 @@ import {
} from './hooks';
const mocks = vi.hoisted(() => ({
- cacheGet: vi.fn(),
create: vi.fn(),
- infiniteResponse: {} as Record<string, unknown>,
+ get: vi.fn(),
listReplies: vi.fn(),
listThreads: vi.fn(),
mutate: vi.fn(),
remove: vi.fn(),
restore: vi.fn(),
- scopedMutate: vi.fn(),
+ syncError: undefined as unknown,
topicId: 'topic-1' as string | null,
update: vi.fn(),
+ useClientDataSWR: vi.fn(),
user: {
avatar: 'https://example.com/avatar.png',
fullName: 'Current User',
id: 'user-1',
username: 'current-user',
},
- useClientDataSWR: vi.fn(),
- useSWRInfinite: vi.fn(),
workspaceId: 'workspace-1' as string | null,
}));
+// The topic-comment reads are replicas: `useSync` only orchestrates fetching,
+// the store views are the source of truth. The mocked hook below stands in for
+// the sync driver, so tests seed the views directly (see the `seed*` helpers).
vi.mock('@/libs/swr', () => ({
mutate: mocks.mutate,
useClientDataSWR: mocks.useClientDataSWR,
@@ -49,6 +50,14 @@ vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({
useActiveWorkspaceId: () => mocks.workspaceId,
}));
+// Every replica resolves its identity partition through the app cache scope.
+// Pin it so the mocked user store below never has to answer the scope selectors.
+vi.mock('@/libs/swr/useCacheScope', () => ({
+ getCacheScope: () => 'user-1:workspace-1',
+ isScopeTrusted: () => false,
+ useCacheScope: () => 'user-1:workspace-1',
+}));
+
vi.mock('@/store/user', () => ({
useUserStore: (selector: (state: Record<string, unknown>) => unknown) =>
selector({ user: mocks.user }),
@@ -58,30 +67,16 @@ vi.mock('@/store/user/slices/auth/selectors', () => ({
userProfileSelectors: { userProfile: (state: { user: unknown }) => state.user },
}));
-vi.mock('swr', () => ({
- unstable_serialize: (key: unknown) => JSON.stringify(key),
- useSWRConfig: () => ({
- cache: { get: mocks.cacheGet },
- mutate: mocks.scopedMutate,
- }),
-}));
-
vi.mock('@/store/chat', () => ({
useChatStore: (selector: (state: Record<string, unknown>) => unknown) =>
selector({ activeTopicId: mocks.topicId }),
}));
-vi.mock('swr/infinite', () => ({
- default: (...args: unknown[]) => {
- mocks.useSWRInfinite(...args);
- return mocks.infiniteResponse;
- },
-}));
-
vi.mock('@/services/topicComment', () => ({
topicCommentService: {
create: mocks.create,
delete: mocks.remove,
+ get: mocks.get,
listReplies: mocks.listReplies,
listThreads: mocks.listThreads,
restore: mocks.restore,
@@ -89,6 +84,57 @@ vi.mock('@/services/topicComment', () => ({
},
}));
+/** Persisted root feed of one topic view, as the store view holds it. */
+const seedThreads = (
+ topicId: string,
+ items: TopicCommentThread[],
+ options: {
+ hasMore?: boolean;
+ isLoadingMore?: boolean;
+ loadMoreError?: unknown;
+ messageId?: string;
+ nextCursor?: string | null;
+ } = {},
+) =>
+ useTopicCommentStore.setState((state) => ({
+ threadFeedMap: {
+ ...state.threadFeedMap,
+ [topicCommentThreadsKey({ messageId: options.messageId, topicId })]: {
+ currentPage: 0,
+ hasMore: options.hasMore ?? false,
+ isLoadingMore: options.isLoadingMore,
+ items,
+ loadMoreError: options.loadMoreError,
+ nextCursor: options.nextCursor ?? null,
+ total: items.length,
+ },
+ },
+ }));
+
+const seedReplies = (rootCommentId: string, items: TopicCommentItem[], total?: number) =>
+ useTopicCommentStore.setState((state) => ({
+ replyFeedMap: {
+ ...state.replyFeedMap,
+ [rootCommentId]: {
+ currentPage: 0,
+ hasMore: false,
+ items,
+ nextCursor: null,
+ total: total ?? items.length,
+ },
+ },
+ }));
+
+const seedSummary = (topicId: string, summary: TopicCommentSummary) =>
+ useTopicCommentStore.setState((state) => ({
+ commentSummaryMap: { ...state.commentSummaryMap, [topicId]: summary },
+ }));
+
+const seedDetail = (comment: TopicCommentItem) =>
+ useTopicCommentStore.setState((state) => ({
+ commentDetailMap: { ...state.commentDetailMap, [comment.id]: comment },
+ }));
+
const createComment = (overrides: Partial<TopicCommentItem> = {}): TopicCommentItem => ({
anchorPreview: null,
author: {
@@ -119,24 +165,26 @@ const createComment = (overrides: Partial<TopicCommentItem> = {}): TopicCommentI
...overrides,
});
+const threadOf = (root: TopicCommentItem, replyCount = 0): TopicCommentThread => ({
+ replyCount,
+ root,
+});
+
describe('useTopicCommentMutations', () => {
beforeEach(() => {
vi.clearAllMocks();
useTopicCommentStore.getState().reset();
- mocks.infiniteResponse = {
- data: undefined,
- error: undefined,
- isLoading: true,
- isValidating: true,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 1,
- };
- mocks.cacheGet.mockReturnValue(undefined);
+ mocks.get.mockResolvedValue(undefined);
+ mocks.listReplies.mockResolvedValue({ items: [], nextCursor: null });
+ mocks.listThreads.mockResolvedValue({ items: [], nextCursor: null });
mocks.mutate.mockResolvedValue(undefined);
- mocks.scopedMutate.mockResolvedValue(undefined);
+ mocks.syncError = undefined;
mocks.topicId = 'topic-1';
- mocks.useClientDataSWR.mockReturnValue({ data: undefined });
+ mocks.useClientDataSWR.mockImplementation(() => ({
+ data: undefined,
+ error: mocks.syncError,
+ isValidating: false,
+ }));
mocks.workspaceId = 'workspace-1';
});
@@ -184,28 +232,13 @@ describe('useTopicCommentMutations', () => {
it('shows a topic comment immediately and reconciles it without waiting for refresh', async () => {
let resolveCreate: ((value: unknown) => void) | undefined;
- let resolveRefresh: (() => void) | undefined;
mocks.create.mockReturnValue(
new Promise((resolve) => {
resolveCreate = resolve;
}),
);
- mocks.mutate.mockImplementation((key) =>
- typeof key === 'function'
- ? new Promise<void>((resolve) => {
- resolveRefresh = resolve;
- })
- : Promise.resolve(undefined),
- );
- mocks.infiniteResponse = {
- data: [{ items: [], nextCursor: null }],
- error: undefined,
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 1,
- };
+ // The summary revalidation never settles: the list must update without it.
+ mocks.mutate.mockReturnValue(new Promise(() => undefined));
const mutations = renderHook(() => useTopicCommentMutations());
const threads = renderHook(() => useTopicCommentThreads('topic-1'));
@@ -245,19 +278,9 @@ describe('useTopicCommentMutations', () => {
expect(threads.result.current.pendingCommentIds.has('comment-1')).toBe(false);
expect(mutations.result.current.creating).toBe(false);
- await act(async () => resolveRefresh?.());
- expect(threads.result.current.items[0].root.id).toBe('comment-1');
-
+ // The confirmed row paints from the store, before the feed revalidates.
const reconciledRoot = threads.result.current.items[0].root;
- mocks.infiniteResponse = {
- data: [{ items: [{ replyCount: 0, root: reconciledRoot }], nextCursor: null }],
- error: undefined,
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 1,
- };
+ seedThreads('topic-1', [threadOf(reconciledRoot)]);
threads.rerender();
await waitFor(() =>
@@ -274,15 +297,6 @@ describe('useTopicCommentMutations', () => {
rejectCreate = reject;
}),
);
- mocks.infiniteResponse = {
- data: [{ items: [], nextCursor: null }],
- error: undefined,
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 1,
- };
const mutations = renderHook(() => useTopicCommentMutations());
const threads = renderHook(() => useTopicCommentThreads('topic-1'));
@@ -311,9 +325,7 @@ describe('useTopicCommentMutations', () => {
rejectCreate = reject;
}),
);
- mocks.useClientDataSWR.mockReturnValue({
- data: { countByMessage: {}, total: 4 },
- });
+ seedSummary('topic-1', { countByMessage: {}, total: 4 });
const mutations = renderHook(() => useTopicCommentMutations());
const summary = renderHook(() => useTopicCommentSummary('topic-1'));
@@ -342,18 +354,7 @@ describe('useTopicCommentMutations', () => {
resolveCreate = resolve;
}),
);
- mocks.useClientDataSWR.mockReturnValue({
- data: { countByMessage: {}, total: 4 },
- });
- mocks.infiniteResponse = {
- data: [{ items: [], nextCursor: null }],
- error: undefined,
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 1,
- };
+ seedSummary('topic-1', { countByMessage: {}, total: 4 });
const mutations = renderHook(() => useTopicCommentMutations());
const summary = renderHook(() => useTopicCommentSummary('topic-1'));
const threads = renderHook(() => useTopicCommentThreads('topic-1'));
@@ -381,11 +382,9 @@ describe('useTopicCommentMutations', () => {
expect(summary.result.current.data?.total).toBe(4);
expect(threads.result.current.pendingCommentIds.has('comment-1')).toBe(false);
- expect(
- mocks.mutate.mock.calls.some(([key]) =>
- Array.isArray(key) ? key[0] === 'topicComment:summary' : false,
- ),
- ).toBe(true);
+ // A duplicate only asks the summary entry to revalidate: it is never patched twice.
+ expect(mocks.mutate.mock.calls.some(([key]) => typeof key === 'function')).toBe(true);
+ expect(useTopicCommentStore.getState().commentSummaryMap['topic-1'].total).toBe(4);
});
it('shows a message comment in both its message scope and the topic-wide scope', async () => {
@@ -395,15 +394,6 @@ describe('useTopicCommentMutations', () => {
rejectCreate = reject;
}),
);
- mocks.infiniteResponse = {
- data: [{ items: [], nextCursor: null }],
- error: undefined,
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 1,
- };
const mutations = renderHook(() => useTopicCommentMutations());
const topicThreads = renderHook(() => useTopicCommentThreads('topic-1'));
const messageThreads = renderHook(() => useTopicCommentThreads('topic-1', 'message-1'));
@@ -436,15 +426,6 @@ describe('useTopicCommentMutations', () => {
rejectCreate = reject;
}),
);
- mocks.infiniteResponse = {
- data: [{ items: [], nextCursor: null }],
- error: undefined,
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 1,
- };
const mutations = renderHook(() => useTopicCommentMutations());
const threads = renderHook(() => useTopicCommentThreads('topic-1'));
const replies = renderHook(() => useTopicCommentReplies('root-comment-1'));
@@ -476,15 +457,7 @@ describe('useTopicCommentMutations', () => {
resolveCreate = resolve;
}),
);
- mocks.infiniteResponse = {
- data: [{ items: [{ replyCount: 2, root }], nextCursor: null }],
- error: undefined,
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 1,
- };
+ seedThreads('topic-1', [threadOf(root, 2)]);
const mutations = renderHook(() => useTopicCommentMutations());
const threads = renderHook(() => useTopicCommentThreads('topic-1'));
@@ -518,10 +491,7 @@ describe('useTopicCommentMutations', () => {
useTopicCommentStore.getState().optimisticReplyCountMutations['reply-client-1']?.pending,
).toBe(false);
- mocks.infiniteResponse = {
- ...mocks.infiniteResponse,
- data: [{ items: [{ replyCount: 3, root }], nextCursor: null }],
- };
+ seedThreads('topic-1', [threadOf(root, 3)]);
threads.rerender();
await waitFor(() =>
@@ -540,15 +510,7 @@ describe('useTopicCommentMutations', () => {
parentCommentId: root.id,
});
mocks.create.mockResolvedValue({ comment: reply, isDuplicate: true });
- mocks.infiniteResponse = {
- data: [{ items: [{ replyCount: 3, root }], nextCursor: null }],
- error: undefined,
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 1,
- };
+ seedThreads('topic-1', [threadOf(root, 3)]);
const mutations = renderHook(() => useTopicCommentMutations());
const threads = renderHook(() => useTopicCommentThreads('topic-1'));
@@ -577,15 +539,7 @@ describe('useTopicCommentMutations', () => {
rejectDelete = reject;
}),
);
- mocks.infiniteResponse = {
- data: [{ items: [{ replyCount: 2, root }], nextCursor: null }],
- error: undefined,
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 1,
- };
+ seedThreads('topic-1', [threadOf(root, 2)]);
const mutations = renderHook(() => useTopicCommentMutations());
const threads = renderHook(() => useTopicCommentThreads('topic-1'));
@@ -625,15 +579,7 @@ describe('useTopicCommentMutations', () => {
topicId: root.topicId,
workspaceId: root.workspaceId,
});
- mocks.infiniteResponse = {
- data: [{ items: [{ replyCount: 2, root }], nextCursor: null }],
- error: undefined,
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 1,
- };
+ seedThreads('topic-1', [threadOf(root, 2)]);
const threads = renderHook(() => useTopicCommentThreads('topic-1'));
@@ -646,21 +592,12 @@ describe('useTopicCommentMutations', () => {
it('shows an edit immediately, keeps it over stale data, and reconciles the server result', async () => {
const comment = createComment();
let resolveUpdate: ((value: TopicCommentItem) => void) | undefined;
- mocks.mutate.mockReturnValue(new Promise(() => undefined));
mocks.update.mockReturnValue(
new Promise((resolve) => {
resolveUpdate = resolve;
}),
);
- mocks.infiniteResponse = {
- data: [{ items: [{ replyCount: 0, root: comment }], nextCursor: null }],
- error: undefined,
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 1,
- };
+ seedThreads('topic-1', [threadOf(comment)]);
const mutations = renderHook(() => useTopicCommentMutations());
const threads = renderHook(() => useTopicCommentThreads('topic-1'));
@@ -686,15 +623,11 @@ describe('useTopicCommentMutations', () => {
});
expect(threads.result.current.items[0].root).toEqual(confirmed);
- expect(mocks.mutate).toHaveBeenCalledWith(['topicComment:detail', comment.id], confirmed, {
- revalidate: false,
- });
- expect(mocks.mutate.mock.calls.some(([key]) => typeof key === 'function')).toBe(false);
+ // The confirmed write lands in the by-id detail view, not in a detail SWR key.
+ expect(useTopicCommentStore.getState().commentDetailMap[comment.id]).toEqual(confirmed);
+ expect(mocks.mutate.mock.calls.some(([key]) => Array.isArray(key))).toBe(false);
- mocks.infiniteResponse = {
- ...mocks.infiniteResponse,
- data: [{ items: [{ replyCount: 0, root: confirmed }], nextCursor: null }],
- };
+ seedThreads('topic-1', [threadOf(confirmed)]);
threads.rerender();
await waitFor(() =>
expect(useTopicCommentStore.getState().optimisticMutations[comment.id]).toBeUndefined(),
@@ -710,15 +643,7 @@ describe('useTopicCommentMutations', () => {
rejectUpdate = reject;
}),
);
- mocks.infiniteResponse = {
- data: [{ items: [{ replyCount: 0, root: comment }], nextCursor: null }],
- error: undefined,
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 1,
- };
+ seedThreads('topic-1', [threadOf(comment)]);
const mutations = renderHook(() => useTopicCommentMutations());
const threads = renderHook(() => useTopicCommentThreads('topic-1'));
@@ -750,7 +675,7 @@ describe('useTopicCommentMutations', () => {
rejectUpdate = reject;
}),
);
- mocks.useClientDataSWR.mockReturnValue({ data: comment });
+ seedDetail(comment);
const mutations = renderHook(() => useTopicCommentMutations());
const detail = renderHook(() => useTopicCommentDetail(comment.id));
@@ -772,7 +697,7 @@ describe('useTopicCommentMutations', () => {
it('keeps a root visible during a pending hard delete and hides it after confirmation', () => {
const comment = createComment();
- mocks.useClientDataSWR.mockReturnValue({ data: comment });
+ seedDetail(comment);
useTopicCommentStore.getState().upsertOptimisticMutation({
comment,
deleteMode: 'hard',
@@ -799,10 +724,8 @@ describe('useTopicCommentMutations', () => {
it('clears retained detail data when revalidation reports not found', () => {
const comment = createComment({ id: 'deleted-reply', parentCommentId: 'comment-1' });
- mocks.useClientDataSWR.mockReturnValue({
- data: comment,
- error: { data: { code: 'NOT_FOUND' } },
- });
+ seedDetail(comment);
+ mocks.syncError = { data: { code: 'NOT_FOUND' } };
const detail = renderHook(() => useTopicCommentDetail(comment.id));
@@ -822,15 +745,7 @@ describe('useTopicCommentMutations', () => {
pending: false,
});
mocks.update.mockRejectedValue(new Error('network failed'));
- mocks.infiniteResponse = {
- data: [{ items: [{ replyCount: 0, root: staleComment }], nextCursor: null }],
- error: undefined,
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 1,
- };
+ seedThreads('topic-1', [threadOf(staleComment)]);
const mutations = renderHook(() => useTopicCommentMutations());
const threads = renderHook(() => useTopicCommentThreads('topic-1'));
@@ -857,18 +772,8 @@ describe('useTopicCommentMutations', () => {
rejectDelete = reject;
}),
);
- mocks.useClientDataSWR.mockReturnValue({
- data: { countByMessage: { 'message-1': 1 }, total: 1 },
- });
- mocks.infiniteResponse = {
- data: [{ items: [{ replyCount: 0, root: comment }], nextCursor: null }],
- error: undefined,
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 1,
- };
+ seedSummary('topic-1', { countByMessage: { 'message-1': 1 }, total: 1 });
+ seedThreads('topic-1', [threadOf(comment)]);
const mutations = renderHook(() => useTopicCommentMutations());
const threads = renderHook(() => useTopicCommentThreads('topic-1'));
const summary = renderHook(() => useTopicCommentSummary('topic-1'));
@@ -894,15 +799,8 @@ describe('useTopicCommentMutations', () => {
const comment = createComment();
mocks.remove.mockResolvedValue({ mode: 'hard' });
mocks.mutate.mockReturnValue(new Promise(() => undefined));
- mocks.infiniteResponse = {
- data: [{ items: [{ replyCount: 0, root: comment }], nextCursor: null }],
- error: undefined,
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 1,
- };
+ seedThreads('topic-1', [threadOf(comment)]);
+ seedDetail(comment);
const mutations = renderHook(() => useTopicCommentMutations());
const threads = renderHook(() => useTopicCommentThreads('topic-1'));
@@ -912,20 +810,12 @@ describe('useTopicCommentMutations', () => {
expect(threads.result.current.items).toEqual([]);
expect(useTopicCommentStore.getState().optimisticMutations[comment.id]?.pending).toBe(false);
- expect(
- mocks.mutate.mock.calls.filter(
- ([key]) => Array.isArray(key) && key[0] === 'topicComment:summary',
- ),
- ).toHaveLength(1);
- expect(mocks.mutate).toHaveBeenCalledWith(['topicComment:detail', comment.id], undefined, {
- revalidate: false,
- });
- expect(mocks.mutate.mock.calls.some(([key]) => typeof key === 'function')).toBe(false);
+ // The by-id detail view drops the row; the feed reconciles it on the next sync.
+ expect(useTopicCommentStore.getState().commentDetailMap[comment.id]).toBeUndefined();
+ expect(mocks.mutate.mock.calls.some(([key]) => typeof key === 'function')).toBe(true);
+ expect(mocks.mutate.mock.calls.some(([key]) => Array.isArray(key))).toBe(false);
- mocks.infiniteResponse = {
- ...mocks.infiniteResponse,
- data: [{ items: [], nextCursor: null }],
- };
+ seedThreads('topic-1', []);
threads.rerender();
await waitFor(() =>
expect(useTopicCommentStore.getState().optimisticMutations[comment.id]).toBeUndefined(),
@@ -946,18 +836,8 @@ describe('useTopicCommentMutations', () => {
resolveDelete = resolve;
}),
);
- mocks.useClientDataSWR.mockReturnValue({
- data: { countByMessage: { 'message-1': 1 }, total: 1 },
- });
- mocks.infiniteResponse = {
- data: [{ items: [{ replyCount: 0, root: comment }], nextCursor: null }],
- error: undefined,
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 1,
- };
+ seedSummary('topic-1', { countByMessage: { 'message-1': 1 }, total: 1 });
+ seedThreads('topic-1', [threadOf(comment)]);
const mutations = renderHook(() => useTopicCommentMutations());
const threads = renderHook(() => useTopicCommentThreads('topic-1'));
const summary = renderHook(() => useTopicCommentSummary('topic-1'));
@@ -985,9 +865,7 @@ describe('useTopicCommentMutations', () => {
});
expect(threads.result.current.items[0].root).toEqual(moderated);
- expect(mocks.mutate).toHaveBeenCalledWith(['topicComment:detail', comment.id], moderated, {
- revalidate: false,
- });
+ expect(useTopicCommentStore.getState().commentDetailMap[comment.id]).toEqual(moderated);
});
it('restores a moderated comment immediately and rolls back when restore fails', async () => {
@@ -1006,16 +884,8 @@ describe('useTopicCommentMutations', () => {
rejectRestore = reject;
}),
);
- mocks.useClientDataSWR.mockReturnValue({ data: { countByMessage: {}, total: 0 } });
- mocks.infiniteResponse = {
- data: [{ items: [{ replyCount: 0, root: comment }], nextCursor: null }],
- error: undefined,
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 1,
- };
+ seedSummary('topic-1', { countByMessage: {}, total: 0 });
+ seedThreads('topic-1', [threadOf(comment)]);
const mutations = renderHook(() => useTopicCommentMutations());
const threads = renderHook(() => useTopicCommentThreads('topic-1'));
const summary = renderHook(() => useTopicCommentSummary('topic-1'));
@@ -1048,25 +918,11 @@ describe('useTopicCommentMutations', () => {
kind: 'delete',
pending: false,
});
- mocks.infiniteResponse = {
- data: undefined,
- error: undefined,
- isLoading: true,
- isValidating: true,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 1,
- };
const threads = renderHook(() => useTopicCommentThreads('topic-1'));
expect(useTopicCommentStore.getState().optimisticMutations[comment.id]).toBeDefined();
- mocks.infiniteResponse = {
- ...mocks.infiniteResponse,
- data: [{ items: [], nextCursor: null }],
- isLoading: false,
- isValidating: false,
- };
+ seedThreads('topic-1', []);
threads.rerender();
await waitFor(() =>
expect(useTopicCommentStore.getState().optimisticMutations[comment.id]).toBeUndefined(),
@@ -1081,15 +937,7 @@ describe('useTopicCommentMutations', () => {
rejectDelete = reject;
}),
);
- mocks.infiniteResponse = {
- data: [{ items: [reply], nextCursor: null, total: 1 }],
- error: undefined,
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 1,
- };
+ seedReplies('comment-1', [reply], 1);
const mutations = renderHook(() => useTopicCommentMutations());
const replies = renderHook(() => useTopicCommentReplies('comment-1'));
@@ -1114,18 +962,8 @@ describe('useTopicCommentMutations', () => {
resolveDelete = resolve;
}),
);
- mocks.infiniteResponse = {
- data: [{ items: [{ replyCount: 2, root: comment }], nextCursor: null }],
- error: undefined,
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 1,
- };
- mocks.useClientDataSWR.mockReturnValue({
- data: { countByMessage: { 'message-1': 1 }, total: 2 },
- });
+ seedThreads('topic-1', [threadOf(comment, 2)]);
+ seedSummary('topic-1', { countByMessage: { 'message-1': 1 }, total: 2 });
const mutations = renderHook(() => useTopicCommentMutations());
const threads = renderHook(() => useTopicCommentThreads('topic-1'));
const summary = renderHook(() => useTopicCommentSummary('topic-1'));
@@ -1155,10 +993,7 @@ describe('useTopicCommentMutations', () => {
deletedAt: new Date('2026-07-21T00:00:00.000Z'),
updatedAt: new Date('2026-07-21T00:00:00.000Z'),
});
- mocks.infiniteResponse = {
- ...mocks.infiniteResponse,
- data: [{ items: [{ replyCount: 2, root: tombstone }], nextCursor: null }],
- };
+ seedThreads('topic-1', [threadOf(tombstone, 2)]);
threads.rerender();
await waitFor(() =>
@@ -1172,17 +1007,20 @@ describe('topic comment read hooks', () => {
beforeEach(() => {
vi.clearAllMocks();
useTopicCommentStore.getState().reset();
- mocks.cacheGet.mockReturnValue(undefined);
- mocks.scopedMutate.mockResolvedValue(undefined);
+ mocks.listReplies.mockResolvedValue({ items: [], nextCursor: null });
+ mocks.listThreads.mockResolvedValue({ items: [], nextCursor: null });
+ mocks.syncError = undefined;
mocks.topicId = 'topic-1';
+ mocks.useClientDataSWR.mockImplementation(() => ({
+ data: undefined,
+ error: mocks.syncError,
+ isValidating: false,
+ }));
mocks.workspaceId = 'workspace-1';
- mocks.useClientDataSWR.mockReturnValue({ data: undefined });
});
it('reads a message badge from the root-thread summary', () => {
- mocks.useClientDataSWR.mockReturnValue({
- data: { countByMessage: { 'message-1': 3 }, total: 8 },
- });
+ seedSummary('topic-1', { countByMessage: { 'message-1': 3 }, total: 8 });
const { result } = renderHook(() => useMessageCommentCount('message-1'));
@@ -1190,48 +1028,42 @@ describe('topic comment read hooks', () => {
});
it('warms and caches the topic first page before the summary loads', async () => {
- const page = { items: [{ replyCount: 0, root: { id: 'comment-1' } }], nextCursor: null };
+ const page = { items: [threadOf({ id: 'comment-1' } as TopicCommentItem)], nextCursor: null };
mocks.listThreads.mockResolvedValue(page);
- mocks.useClientDataSWR.mockImplementation((key, fetcher) => {
- if (Array.isArray(key) && key[0] === 'topicComment:warmup') void fetcher();
- return { data: undefined };
- });
renderHook(() => usePrefetchTopicCommentsOnTopicLoad('topic-1'));
await waitFor(() =>
- expect(mocks.scopedMutate).toHaveBeenCalledWith(
- ['topicComment:threads', 'workspace-1', 'topic-1', '', ''],
- page,
- { revalidate: false },
- ),
+ expect(
+ useTopicCommentStore.getState().threadFeedMap[
+ topicCommentThreadsKey({ topicId: 'topic-1' })
+ ]?.items,
+ ).toHaveLength(1),
);
+ expect(mocks.listThreads).toHaveBeenCalledWith({
+ cursor: undefined,
+ limit: 30,
+ messageId: undefined,
+ topicId: 'topic-1',
+ });
});
it('warms and caches first-page replies for roots that have replies', async () => {
const threadPage = {
items: [
- { replyCount: 2, root: { id: 'comment-1' } },
- { replyCount: 0, root: { id: 'comment-2' } },
+ threadOf({ id: 'comment-1' } as TopicCommentItem, 2),
+ threadOf({ id: 'comment-2' } as TopicCommentItem),
],
nextCursor: null,
};
- const replyPage = { items: [{ id: 'reply-1' }], nextCursor: null, total: 1 };
+ const replyPage = { items: [createComment({ id: 'reply-1' })], nextCursor: null, total: 1 };
mocks.listThreads.mockResolvedValue(threadPage);
mocks.listReplies.mockResolvedValue(replyPage);
- mocks.useClientDataSWR.mockImplementation((key, fetcher) => {
- if (Array.isArray(key) && key[0] === 'topicComment:warmup') void fetcher();
- return { data: undefined };
- });
renderHook(() => usePrefetchTopicCommentsOnTopicLoad('topic-1'));
await waitFor(() =>
- expect(mocks.scopedMutate).toHaveBeenCalledWith(
- ['topicComment:replies', 'workspace-1', 'comment-1', ''],
- replyPage,
- { revalidate: false },
- ),
+ expect(useTopicCommentStore.getState().replyFeedMap['comment-1']?.items).toHaveLength(1),
);
expect(mocks.listReplies).toHaveBeenCalledOnce();
expect(mocks.listReplies).toHaveBeenCalledWith({
@@ -1242,39 +1074,48 @@ describe('topic comment read hooks', () => {
});
it('keeps a failed topic warmup retryable and caches a later successful retry', async () => {
- const error = new Error('prefetch failed');
- const page = { items: [{ replyCount: 0, root: { id: 'comment-1' } }], nextCursor: null };
- let warmupFetcher: (() => Promise<boolean>) | undefined;
- mocks.listThreads.mockRejectedValueOnce(error).mockResolvedValueOnce(page);
- mocks.useClientDataSWR.mockImplementation((key, fetcher) => {
- if (Array.isArray(key) && key[0] === 'topicComment:warmup') warmupFetcher = fetcher;
- return { data: undefined };
- });
+ const page = { items: [threadOf({ id: 'comment-1' } as TopicCommentItem)], nextCursor: null };
+ mocks.listThreads
+ .mockRejectedValueOnce(new Error('prefetch failed'))
+ .mockResolvedValueOnce(page);
renderHook(() => usePrefetchTopicCommentsOnTopicLoad('topic-1'));
- await expect(warmupFetcher?.()).rejects.toBe(error);
- await expect(warmupFetcher?.()).resolves.toBe(true);
- expect(mocks.scopedMutate).toHaveBeenCalledWith(
- ['topicComment:threads', 'workspace-1', 'topic-1', '', ''],
- page,
- { revalidate: false },
- );
+ await waitFor(() => expect(mocks.listThreads).toHaveBeenCalledOnce());
+ expect(
+ useTopicCommentStore.getState().threadFeedMap[topicCommentThreadsKey({ topicId: 'topic-1' })],
+ ).toBeUndefined();
+
+ // The warmup is best-effort: a later attempt fills the same view.
+ await act(async () => {
+ await useTopicCommentStore.getState().prefetchTopicComments('topic-1');
+ });
+
+ expect(
+ useTopicCommentStore.getState().threadFeedMap[topicCommentThreadsKey({ topicId: 'topic-1' })]
+ ?.items,
+ ).toHaveLength(1);
});
- it('registers only the bounded topic-level warmup', () => {
+ it('warms only the bounded topic feed, not a warmup SWR key', async () => {
renderHook(() => usePrefetchTopicCommentsOnTopicLoad('topic-1'));
- expect(mocks.useClientDataSWR).toHaveBeenCalledOnce();
- expect(mocks.useClientDataSWR).toHaveBeenCalledWith(
- ['topicComment:warmup', 'workspace-1', 'topic-1'],
- expect.any(Function),
- { revalidateOnFocus: false },
- );
+ await waitFor(() => expect(mocks.listThreads).toHaveBeenCalledOnce());
+ expect(mocks.listThreads).toHaveBeenCalledWith({
+ cursor: undefined,
+ limit: 30,
+ messageId: undefined,
+ topicId: 'topic-1',
+ });
+ expect(
+ mocks.useClientDataSWR.mock.calls.some(([key]) =>
+ JSON.stringify(key ?? '').includes('topicComment:warmup'),
+ ),
+ ).toBe(false);
});
it('refreshes only the affected summary after a comment write', async () => {
- const response = { comment: { id: 'comment-1' }, isDuplicate: false };
+ const response = { comment: createComment({ id: 'comment-1' }), isDuplicate: false };
mocks.create.mockResolvedValue(response);
const { result } = renderHook(() => useTopicCommentMutations());
@@ -1286,109 +1127,69 @@ describe('topic comment read hooks', () => {
});
});
- expect(mocks.mutate.mock.calls.some(([key]) => typeof key === 'function')).toBe(false);
- expect(
- mocks.mutate.mock.calls.filter(
- ([key]) => Array.isArray(key) && key[0] === 'topicComment:summary',
- ),
- ).toHaveLength(1);
+ // The summary entry is revalidated through the replica match, never a raw SWR key.
+ expect(mocks.mutate.mock.calls.some(([key]) => typeof key === 'function')).toBe(true);
expect(
mocks.mutate.mock.calls.some(
- ([key]) => Array.isArray(key) && key[0] === 'topicComment:warmup',
+ ([key]) => Array.isArray(key) && key[0] === 'topicComment:summary',
),
).toBe(false);
});
- it('uses the summary as an immediate empty fallback while revalidating in the background', () => {
- mocks.useClientDataSWR.mockReturnValue({
- data: { countByMessage: {}, total: 0 },
- });
+ it('reads the persisted topic feed before the network confirms it', () => {
+ const thread = threadOf({ id: 'comment-1' } as TopicCommentItem);
+ seedThreads('topic-1', [thread]);
- renderHook(() => useTopicCommentThreads('topic-1', 'message-without-comments'));
+ const { result } = renderHook(() => useTopicCommentThreads('topic-1'));
- expect(mocks.useSWRInfinite).toHaveBeenCalledWith(
- expect.any(Function),
- expect.any(Function),
- expect.objectContaining({
- fallbackData: [{ items: [], nextCursor: null }],
- revalidateOnMount: true,
- }),
- );
+ expect(result.current.items).toEqual([thread]);
+ expect(result.current.isLoadingInitial).toBe(false);
});
- it('uses a zero reply snapshot as an immediate empty fallback while revalidating', () => {
- renderHook(() => useTopicCommentReplies('root-comment-1', 0));
+ it('reads the persisted reply feed before the network confirms it', () => {
+ const reply = createComment({ id: 'reply-1', parentCommentId: 'comment-1' });
+ seedReplies('comment-1', [reply], 1);
- expect(mocks.useSWRInfinite).toHaveBeenCalledWith(
- expect.any(Function),
- expect.any(Function),
- expect.objectContaining({
- fallbackData: [{ items: [], nextCursor: null, total: 0 }],
- revalidateOnMount: true,
- }),
- );
- });
+ const { result } = renderHook(() => useTopicCommentReplies('comment-1', 1));
- it('uses prefetched first-page replies as an immediate fallback while revalidating', () => {
- const page = { items: [{ id: 'reply-1' }], nextCursor: null, total: 1 };
- mocks.cacheGet.mockImplementation((key) =>
- key === JSON.stringify(['topicComment:replies', 'workspace-1', 'root-comment-1', ''])
- ? { data: page }
- : undefined,
- );
+ expect(result.current.items).toEqual([reply]);
+ expect(result.current.total).toBe(1);
+ });
- renderHook(() => useTopicCommentReplies('root-comment-1', 1));
+ it('shows an empty topic feed as loaded when the summary reports no comments', () => {
+ seedSummary('topic-1', { countByMessage: { 'message-without-comments': 0 }, total: 0 });
+ seedThreads('topic-1', [], { messageId: 'message-without-comments' });
- expect(mocks.useSWRInfinite).toHaveBeenCalledWith(
- expect.any(Function),
- expect.any(Function),
- expect.objectContaining({
- fallbackData: [page],
- revalidateOnMount: true,
- }),
+ const { result } = renderHook(() =>
+ useTopicCommentThreads('topic-1', 'message-without-comments'),
);
- });
- it('uses a prefetched first page as an immediate fallback while revalidating', () => {
- const page = { items: [{ replyCount: 0, root: { id: 'comment-1' } }], nextCursor: null };
- mocks.cacheGet.mockReturnValue({ data: page });
+ expect(result.current.items).toEqual([]);
+ expect(result.current.isLoadingInitial).toBe(false);
+ });
- renderHook(() => useTopicCommentThreads('topic-1', 'message-1'));
+ it('treats a zero reply snapshot as an immediate empty reply list', () => {
+ const { result } = renderHook(() => useTopicCommentReplies('root-comment-1', 0));
- expect(mocks.useSWRInfinite).toHaveBeenCalledWith(
- expect.any(Function),
- expect.any(Function),
- expect.objectContaining({
- fallbackData: [page],
- revalidateOnMount: true,
- }),
- );
+ expect(result.current.items).toEqual([]);
+ expect(result.current.total).toBe(0);
+ expect(result.current.isLoadingInitial).toBe(false);
});
- it('revalidates the first page when returning from a comment thread', () => {
- renderHook(() => useTopicCommentThreads('topic-1'));
+ it('reload revalidates the feed entry it is showing', async () => {
+ seedThreads('topic-1', [threadOf({ id: 'comment-1' } as TopicCommentItem)]);
+ const { result } = renderHook(() => useTopicCommentThreads('topic-1'));
- expect(mocks.useSWRInfinite).toHaveBeenCalledWith(
- expect.any(Function),
- expect.any(Function),
- expect.objectContaining({ revalidateOnMount: true }),
- );
+ await act(async () => {
+ await result.current.reload();
+ });
+
+ expect(mocks.mutate.mock.calls.some(([key]) => typeof key === 'function')).toBe(true);
});
it('keeps loaded threads visible while the next page is loading', () => {
- const thread = {
- replyCount: 2,
- root: { id: 'comment-1' },
- };
- mocks.infiniteResponse = {
- data: [{ items: [thread], nextCursor: 'next' }, undefined],
- error: undefined,
- isLoading: false,
- isValidating: true,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 2,
- };
+ const thread = threadOf({ id: 'comment-1' } as TopicCommentItem, 2);
+ seedThreads('topic-1', [thread], { hasMore: true, isLoadingMore: true });
const { result } = renderHook(() => useTopicCommentThreads('topic-1'));
@@ -1399,38 +1200,57 @@ describe('topic comment read hooks', () => {
it('exposes a tail error without turning it into an initial failure', () => {
const error = new Error('next page failed');
- const thread = {
- replyCount: 0,
- root: { id: 'comment-1' },
- };
- mocks.infiniteResponse = {
- data: [{ items: [thread], nextCursor: 'next' }, undefined],
- error,
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 2,
- };
+ const thread = threadOf({ id: 'comment-1' } as TopicCommentItem);
+ seedThreads('topic-1', [thread], { hasMore: true, loadMoreError: error, nextCursor: 'c2' });
const { result } = renderHook(() => useTopicCommentThreads('topic-1'));
expect(result.current.items).toEqual([thread]);
+ expect(result.current.error).toBe(error);
expect(result.current.isInitialError).toBe(false);
expect(result.current.isLoadingMore).toBe(false);
expect(result.current.hasMore).toBe(false);
});
+ it('retries the failed cursor request on reload instead of the head', async () => {
+ const error = new Error('next page failed');
+ const thread = threadOf({ id: 'comment-1' } as TopicCommentItem);
+ seedThreads('topic-1', [thread], { hasMore: true, loadMoreError: error, nextCursor: 'c2' });
+
+ const { result } = renderHook(() => useTopicCommentThreads('topic-1'));
+
+ await act(async () => {
+ await result.current.reload();
+ });
+
+ // The head-only revalidation cannot reach the page that failed: reload must
+ // re-issue the cursor request.
+ expect(mocks.listThreads).toHaveBeenCalledWith({
+ cursor: 'c2',
+ limit: 30,
+ messageId: undefined,
+ topicId: 'topic-1',
+ });
+ });
+
+ it('revalidates the head when there is no tail error to retry', async () => {
+ seedThreads('topic-1', [threadOf({ id: 'comment-1' } as TopicCommentItem)], {
+ hasMore: true,
+ nextCursor: 'c2',
+ });
+
+ const { result } = renderHook(() => useTopicCommentThreads('topic-1'));
+
+ await act(async () => {
+ await result.current.reload();
+ });
+
+ expect(mocks.mutate.mock.calls.some(([key]) => typeof key === 'function')).toBe(true);
+ expect(mocks.listThreads).not.toHaveBeenCalled();
+ });
+
it('marks a first-page failure as an initial error', () => {
- mocks.infiniteResponse = {
- data: undefined,
- error: new Error('first page failed'),
- isLoading: false,
- isValidating: false,
- mutate: vi.fn(),
- setSize: vi.fn(),
- size: 1,
- };
+ mocks.syncError = new Error('first page failed');
const { result } = renderHook(() => useTopicCommentThreads('topic-1'));
diff --git a/src/features/TopicComment/hooks.ts b/src/features/TopicComment/hooks.ts
index b220fcae7a2..34f1c5ae040 100644
--- a/src/features/TopicComment/hooks.ts
+++ b/src/features/TopicComment/hooks.ts
@@ -1,24 +1,18 @@
import type {
CreateTopicCommentInput,
TopicCommentItem,
- TopicCommentReplyPage,
- TopicCommentSummary,
- TopicCommentThreadPage,
UpdateTopicCommentInput,
} from '@lobechat/types';
import { useCallback, useEffect, useMemo, useState } from 'react';
-import { unstable_serialize, useSWRConfig } from 'swr';
-import type { ScopedMutator } from 'swr/_internal';
-import useSWRInfinite from 'swr/infinite';
import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';
-import { mutate, useClientDataSWR } from '@/libs/swr';
-import { topicCommentKeys } from '@/libs/swr/keys';
import { topicCommentService } from '@/services/topicComment';
import { useChatStore } from '@/store/chat';
import {
createTopicCommentDraftKey,
+ TOPIC_COMMENT_PAGE_SIZE,
topicCommentSelectors,
+ topicCommentThreadsKey,
useTopicCommentStore,
} from '@/store/topicComment';
import type {
@@ -29,15 +23,19 @@ import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/slices/auth/selectors';
import { isTrpcErrorCode } from '@/utils/trpcError';
-const PAGE_SIZE = 30;
-const PREFETCH_CONCURRENCY = 4;
-const EMPTY_TOPIC_COMMENT_THREAD_PAGES: TopicCommentThreadPage[] = [
- { items: [], nextCursor: null },
-];
+/**
+ * Topic comments are replicas: the feed of a topic, the replies of a root
+ * comment, the per-topic counts and one comment by id each paint their
+ * persisted copy on the first frame and are confirmed by the network in the
+ * background. The hooks below read the store views and layer the client-only
+ * optimistic overlays on top; `useSync` only orchestrates fetching.
+ */
+
const topicCommentClientKey = ({
authorUserId,
clientId,
}: Pick<TopicCommentItem, 'authorUserId' | 'clientId'>) => `${authorUserId ?? ''}:${clientId}`;
+
const isOptimisticMutationReconciled = (
mutation: OptimisticTopicCommentMutation,
remoteComment: TopicCommentItem | undefined,
@@ -78,54 +76,11 @@ const resolveReplyCount = (
return Math.max(0, lastMutation.baselineCount + lastMutation.delta);
};
-const fetchTopicCommentThreads = ([
- ,
- ,
- currentTopicId,
- currentMessageId,
- cursor,
-]: readonly string[]) =>
- topicCommentService.listThreads({
- cursor: cursor || undefined,
- limit: PAGE_SIZE,
- messageId: currentMessageId || undefined,
- topicId: currentTopicId,
- });
-
-const fetchTopicCommentReplies = ([, , currentRootCommentId, cursor]: readonly string[]) =>
- topicCommentService.listReplies({
- cursor: cursor || undefined,
- limit: PAGE_SIZE,
- rootCommentId: currentRootCommentId,
- });
-
-const preloadTopicCommentThreads = (
- populateCache: ScopedMutator,
- workspaceId: string,
- topicId: string,
- messageId?: string,
-) => {
- const key = topicCommentKeys.threads(workspaceId, topicId, messageId);
- return fetchTopicCommentThreads(key as readonly string[]).then(async (page) => {
- await populateCache(key, page, { revalidate: false });
- return page;
- });
-};
-
-const preloadTopicCommentReplies = (
- populateCache: ScopedMutator,
- workspaceId: string,
- rootCommentId: string,
-) => {
- const key = topicCommentKeys.replies(workspaceId, rootCommentId);
- return fetchTopicCommentReplies(key as readonly string[]).then(async (page) => {
- await populateCache(key, page, { revalidate: false });
- return page;
- });
-};
-
export const useTopicCommentSummary = (topicId?: string | null) => {
const workspaceId = useActiveWorkspaceId();
+ const useFetchSummary = useTopicCommentStore((s) => s.useFetchTopicCommentSummary);
+ const sync = useFetchSummary(topicId);
+ const stored = useTopicCommentStore((s) => (topicId ? s.commentSummaryMap[topicId] : undefined));
const pendingComments = useTopicCommentStore(
topicCommentSelectors.summaryPendingComments(workspaceId, topicId),
);
@@ -135,19 +90,14 @@ export const useTopicCommentSummary = (topicId?: string | null) => {
const pendingRestores = useTopicCommentStore(
topicCommentSelectors.summaryPendingRestores(workspaceId, topicId),
);
- const response = useClientDataSWR<TopicCommentSummary>(
- topicId ? topicCommentKeys.summary(topicId) : null,
- () => topicCommentService.summary(topicId!),
- { dedupingInterval: 30_000 },
- );
const data = useMemo(() => {
if (
- !response.data ||
+ !stored ||
(pendingComments.length === 0 && pendingDeletes.length === 0 && pendingRestores.length === 0)
)
- return response.data;
+ return stored;
- const countByMessage = { ...response.data.countByMessage };
+ const countByMessage = { ...stored.countByMessage };
for (const { comment } of pendingComments) {
if (comment.messageId)
countByMessage[comment.messageId] = (countByMessage[comment.messageId] ?? 0) + 1;
@@ -168,15 +118,12 @@ export const useTopicCommentSummary = (topicId?: string | null) => {
countByMessage,
total: Math.max(
0,
- response.data.total +
- pendingComments.length -
- pendingDeletes.length +
- pendingRestores.length,
+ stored.total + pendingComments.length - pendingDeletes.length + pendingRestores.length,
),
};
- }, [pendingComments, pendingDeletes, pendingRestores, response.data]);
+ }, [pendingComments, pendingDeletes, pendingRestores, stored]);
- return { ...response, data };
+ return { ...sync, data };
};
export const useMessageCommentCount = (messageId: string) => {
@@ -194,64 +141,49 @@ export const useTopicCommentDetail = (
commentId?: string | null,
fallbackData?: TopicCommentItem,
) => {
+ const useFetchDetail = useTopicCommentStore((s) => s.useFetchTopicCommentDetail);
+ const revalidateDetail = useTopicCommentStore((s) => s.revalidateTopicCommentDetail);
+ const sync = useFetchDetail(commentId);
+ const stored = useTopicCommentStore((s) =>
+ commentId ? s.commentDetailMap[commentId] : undefined,
+ );
const optimisticMutation = useTopicCommentStore(
topicCommentSelectors.optimisticMutation(commentId),
);
- const response = useClientDataSWR(
- commentId ? topicCommentKeys.detail(commentId) : null,
- () => topicCommentService.get(commentId!),
- { fallbackData },
- );
const isDeleting =
optimisticMutation?.kind === 'delete' && optimisticMutation.deleteMode === 'hard';
- const isNotFound = isTrpcErrorCode(response.error, 'NOT_FOUND');
+ const isNotFound = isTrpcErrorCode(sync.error, 'NOT_FOUND');
+ const data =
+ isNotFound || (isDeleting && !optimisticMutation?.pending)
+ ? undefined
+ : (optimisticMutation?.comment ?? stored ?? fallbackData);
+ const mutate = useCallback(
+ () => (commentId ? revalidateDetail(commentId) : Promise.resolve()),
+ [commentId, revalidateDetail],
+ );
return {
- ...response,
- data:
- isNotFound || (isDeleting && !optimisticMutation?.pending)
- ? undefined
- : (optimisticMutation?.comment ?? response.data),
+ data,
+ error: sync.error,
isDeleting,
+ // A validating sync with nothing to show for it is the loading state.
+ isLoading: sync.isValidating && data === undefined,
+ isValidating: sync.isValidating,
+ mutate,
};
};
export const usePrefetchTopicCommentsOnTopicLoad = (topicId: string | null | undefined) => {
const workspaceId = useActiveWorkspaceId();
- const { mutate: populateCache } = useSWRConfig();
- const topicParams = topicId && workspaceId ? { topicId, workspaceId } : undefined;
-
- useClientDataSWR(
- topicParams ? topicCommentKeys.warmup(topicParams.workspaceId, topicParams.topicId) : null,
- topicParams
- ? async () => {
- // Let the initial topic/message queries flush their tRPC batch first so this
- // background warmup starts immediately without delaying the primary payload.
- await new Promise<void>((resolve) => setTimeout(resolve, 0));
- const page = await preloadTopicCommentThreads(
- populateCache,
- topicParams.workspaceId,
- topicParams.topicId,
- );
- const rootCommentIds = page.items.flatMap(({ replyCount, root }) =>
- replyCount > 0 ? [root.id] : [],
- );
- for (let index = 0; index < rootCommentIds.length; index += PREFETCH_CONCURRENCY) {
- await Promise.all(
- rootCommentIds
- .slice(index, index + PREFETCH_CONCURRENCY)
- .map((rootCommentId) =>
- preloadTopicCommentReplies(populateCache, topicParams.workspaceId, rootCommentId),
- ),
- );
- }
- return true;
- }
- : null,
- {
- revalidateOnFocus: false,
- },
- );
+ const prefetchTopicComments = useTopicCommentStore((s) => s.prefetchTopicComments);
+
+ useEffect(() => {
+ if (!topicId || !workspaceId) return;
+ // Let the initial topic/message queries flush their tRPC batch first so this
+ // background warmup starts immediately without delaying the primary payload.
+ const timer = setTimeout(() => void prefetchTopicComments(topicId), 0);
+ return () => clearTimeout(timer);
+ }, [prefetchTopicComments, topicId, workspaceId]);
};
export const useTopicCommentReplyCount = (
@@ -276,8 +208,13 @@ export const useTopicCommentReplyCount = (
export const useTopicCommentThreads = (topicId?: string | null, messageId?: string) => {
const workspaceId = useActiveWorkspaceId();
- const { cache } = useSWRConfig();
+ const useFetchThreads = useTopicCommentStore((s) => s.useFetchTopicCommentThreads);
+ const loadMoreThreads = useTopicCommentStore((s) => s.loadMoreTopicCommentThreads);
+ const revalidateThreads = useTopicCommentStore((s) => s.revalidateTopicCommentThreads);
const { data: summary } = useTopicCommentSummary(workspaceId ? topicId : undefined);
+ const feed = useTopicCommentStore((s) =>
+ topicId ? s.threadFeedMap[topicCommentThreadsKey({ messageId, topicId })] : undefined,
+ );
const optimisticComments = useTopicCommentStore(
topicCommentSelectors.optimisticThreads(workspaceId, topicId, messageId),
);
@@ -295,47 +232,24 @@ export const useTopicCommentThreads = (topicId?: string | null, messageId?: stri
const isKnownEmpty = Boolean(
summary && (messageId ? (summary.countByMessage[messageId] ?? 0) === 0 : summary.total === 0),
);
- const firstPageKey =
- topicId && workspaceId
- ? unstable_serialize(topicCommentKeys.threads(workspaceId, topicId, messageId))
- : undefined;
- const cachedFirstPage = firstPageKey
- ? (cache.get(firstPageKey)?.data as TopicCommentThreadPage | undefined)
- : undefined;
- const getKey = useCallback(
- (_index: number, previous: TopicCommentThreadPage | null) => {
- if (!topicId || !workspaceId || previous?.nextCursor === null) return null;
- return topicCommentKeys.threads(
- workspaceId,
- topicId,
- messageId,
- previous?.nextCursor ?? undefined,
- );
- },
- [messageId, topicId, workspaceId],
+ const active = Boolean(topicId && workspaceId);
+ const params = useMemo(
+ () => (active ? { messageId, pageSize: TOPIC_COMMENT_PAGE_SIZE, topicId: topicId! } : null),
+ [active, messageId, topicId],
);
- const response = useSWRInfinite<TopicCommentThreadPage>(getKey, fetchTopicCommentThreads, {
- fallbackData: isKnownEmpty
- ? EMPTY_TOPIC_COMMENT_THREAD_PAGES
- : cachedFirstPage
- ? [cachedFirstPage]
- : undefined,
- revalidateFirstPage: false,
- revalidateOnMount: true,
- });
- const data = response.data;
+ const sync = useFetchThreads(params);
+
+ const data = feed;
useEffect(() => {
if (!data || optimisticComments.length === 0) return;
- const remoteClientKeys = new Set(
- data.flatMap((page) => page?.items.map(({ root }) => topicCommentClientKey(root)) ?? []),
- );
+ const remoteClientKeys = new Set(data.items.map(({ root }) => topicCommentClientKey(root)));
for (const { comment, targetKey } of optimisticComments) {
if (remoteClientKeys.has(topicCommentClientKey(comment))) {
removeOptimisticComment(targetKey, comment.clientId);
}
}
}, [data, optimisticComments, removeOptimisticComment]);
- const remoteItems = data?.flatMap((page) => page?.items ?? []) ?? [];
+ const remoteItems = data?.items ?? [];
useEffect(() => {
if (!data || optimisticMutations.length === 0) return;
const remoteById = new Map(remoteItems.map(({ root }) => [root.id, root]));
@@ -405,27 +319,34 @@ export const useTopicCommentThreads = (topicId?: string | null, messageId?: stri
const pendingCommentIds = new Set(
optimisticComments.filter(({ pending }) => pending).map(({ comment }) => comment.id),
);
- const lastPage = data?.findLast(Boolean);
- const hasLoadedPages = data !== undefined || optimisticComments.length > 0;
- const isInitialError = Boolean(response.error) && !hasLoadedPages;
- const isLoadingInitial = !response.error && response.isLoading && !hasLoadedPages;
- const isLoadingMore =
- !response.error &&
- hasLoadedPages &&
- response.size > 0 &&
- typeof data?.[response.size - 1] === 'undefined';
+ const hasLoadedPages = data !== undefined || optimisticComments.length > 0 || isKnownEmpty;
+ const error = sync.error ?? data?.loadMoreError;
+ const isInitialError = Boolean(sync.error) && !hasLoadedPages;
+ const isLoadingInitial = !sync.error && sync.isValidating && !hasLoadedPages;
+ const isLoadingMore = !sync.error && (data?.isLoadingMore ?? false);
+ const hasTailError = Boolean(data?.loadMoreError);
+ const loadMore = useCallback(
+ () => (params ? loadMoreThreads(params) : Promise.resolve()),
+ [loadMoreThreads, params],
+ );
+ const reload = useCallback(() => {
+ if (!params) return Promise.resolve();
+ // A failed cursor request is retried with its own cursor: a head-only
+ // revalidation cannot reach the page that failed.
+ return hasTailError ? loadMoreThreads(params) : revalidateThreads(params);
+ }, [hasTailError, loadMoreThreads, params, revalidateThreads]);
return {
- ...response,
- hasMore: !response.error && (lastPage ? lastPage.nextCursor !== null : false),
+ error,
+ hasMore: !error && (data?.hasMore ?? false),
isInitialError,
isLoadingInitial,
isLoadingMore,
- isRetrying: Boolean(response.error) && response.isValidating,
+ isRetrying: Boolean(error) && (sync.isValidating || Boolean(data?.isLoadingMore)),
items,
- loadMore: () => response.setSize((size) => size + 1),
+ loadMore,
pendingCommentIds,
- reload: response.mutate,
+ reload,
};
};
@@ -434,7 +355,12 @@ export const useTopicCommentReplies = (
initialReplyCount?: number,
) => {
const workspaceId = useActiveWorkspaceId();
- const { cache } = useSWRConfig();
+ const useFetchReplies = useTopicCommentStore((s) => s.useFetchTopicCommentReplies);
+ const loadMoreReplies = useTopicCommentStore((s) => s.loadMoreTopicCommentReplies);
+ const revalidateReplies = useTopicCommentStore((s) => s.revalidateTopicCommentReplies);
+ const feed = useTopicCommentStore((s) =>
+ rootCommentId ? s.replyFeedMap[rootCommentId] : undefined,
+ );
const optimisticComments = useTopicCommentStore(
topicCommentSelectors.optimisticReplies(workspaceId, rootCommentId),
);
@@ -443,47 +369,24 @@ export const useTopicCommentReplies = (
);
const removeOptimisticComment = useTopicCommentStore((s) => s.removeOptimisticComment);
const removeOptimisticMutation = useTopicCommentStore((s) => s.removeOptimisticMutation);
- const getKey = useCallback(
- (_index: number, previous: TopicCommentReplyPage | null) => {
- if (!rootCommentId || !workspaceId || previous?.nextCursor === null) return null;
- return topicCommentKeys.replies(
- workspaceId,
- rootCommentId,
- previous?.nextCursor ?? undefined,
- );
- },
- [rootCommentId, workspaceId],
+ const active = Boolean(rootCommentId && workspaceId);
+ const params = useMemo(
+ () => (active ? { pageSize: TOPIC_COMMENT_PAGE_SIZE, rootCommentId: rootCommentId! } : null),
+ [active, rootCommentId],
);
- const firstPageKey =
- rootCommentId && workspaceId
- ? unstable_serialize(topicCommentKeys.replies(workspaceId, rootCommentId))
- : undefined;
- const cachedFirstPage = firstPageKey
- ? (cache.get(firstPageKey)?.data as TopicCommentReplyPage | undefined)
- : undefined;
- const response = useSWRInfinite<TopicCommentReplyPage>(getKey, fetchTopicCommentReplies, {
- fallbackData:
- initialReplyCount === 0
- ? [{ items: [], nextCursor: null, total: 0 }]
- : cachedFirstPage
- ? [cachedFirstPage]
- : undefined,
- revalidateFirstPage: false,
- revalidateOnMount: true,
- });
- const data = response.data;
+ const sync = useFetchReplies(params);
+
+ const data = feed;
useEffect(() => {
if (!data || optimisticComments.length === 0) return;
- const remoteClientKeys = new Set(
- data.flatMap((page) => page?.items.map(topicCommentClientKey) ?? []),
- );
+ const remoteClientKeys = new Set(data.items.map(topicCommentClientKey));
for (const { comment, targetKey } of optimisticComments) {
if (remoteClientKeys.has(topicCommentClientKey(comment))) {
removeOptimisticComment(targetKey, comment.clientId);
}
}
}, [data, optimisticComments, removeOptimisticComment]);
- const remoteItems = data?.flatMap((page) => page?.items ?? []) ?? [];
+ const remoteItems = data?.items ?? [];
useEffect(() => {
if (!data || optimisticMutations.length === 0) return;
const remoteById = new Map(remoteItems.map((comment) => [comment.id, comment]));
@@ -514,28 +417,35 @@ export const useTopicCommentReplies = (
const pendingCommentIds = new Set(
optimisticComments.filter(({ pending }) => pending).map(({ comment }) => comment.id),
);
- const lastPage = data?.findLast(Boolean);
const hasLoadedPages = data !== undefined || optimisticComments.length > 0;
- const isInitialError = Boolean(response.error) && !hasLoadedPages;
- const isLoadingInitial = !response.error && response.isLoading && !hasLoadedPages;
- const isLoadingMore =
- !response.error &&
- hasLoadedPages &&
- response.size > 0 &&
- typeof data?.[response.size - 1] === 'undefined';
+ const error = sync.error ?? data?.loadMoreError;
+ const isInitialError = Boolean(sync.error) && !hasLoadedPages;
+ const isLoadingInitial = !sync.error && sync.isValidating && !hasLoadedPages;
+ const isLoadingMore = !sync.error && (data?.isLoadingMore ?? false);
+ const hasTailError = Boolean(data?.loadMoreError);
+ const loadMore = useCallback(
+ () => (params ? loadMoreReplies(params) : Promise.resolve()),
+ [loadMoreReplies, params],
+ );
+ const reload = useCallback(() => {
+ if (!params) return Promise.resolve();
+ // A failed cursor request is retried with its own cursor: a head-only
+ // revalidation cannot reach the page that failed.
+ return hasTailError ? loadMoreReplies(params) : revalidateReplies(params);
+ }, [hasTailError, loadMoreReplies, params, revalidateReplies]);
return {
- ...response,
- hasMore: !response.error && (lastPage ? lastPage.nextCursor !== null : false),
+ error,
+ hasMore: !error && (data?.hasMore ?? false),
isInitialError,
isLoadingInitial,
isLoadingMore,
- isRetrying: Boolean(response.error) && response.isValidating,
+ isRetrying: Boolean(error) && (sync.isValidating || Boolean(data?.isLoadingMore)),
items,
- loadMore: () => response.setSize((size) => size + 1),
+ loadMore,
pendingCommentIds,
- reload: response.mutate,
- total: data?.[0]?.total,
+ reload,
+ total: data?.total ?? (initialReplyCount === 0 ? 0 : undefined),
};
};
@@ -555,6 +465,14 @@ export const useTopicCommentMutations = () => {
s.removeOptimisticComment,
s.upsertOptimisticComment,
]);
+ const [applySummary, revalidateSummary, upsertDetail, removeDetail] = useTopicCommentStore(
+ (s) => [
+ s.applyTopicCommentSummary,
+ s.revalidateTopicCommentSummary,
+ s.upsertTopicCommentDetail,
+ s.removeTopicCommentDetail,
+ ],
+ );
const [creating, setCreating] = useState(false);
const [mutatingIds, setMutatingIds] = useState<ReadonlySet<string>>(new Set());
@@ -627,21 +545,16 @@ export const useTopicCommentMutations = () => {
const result = await topicCommentService.create(input);
if (targetKey && optimisticComment) {
if (!result.isDuplicate) {
- void mutate(
- topicCommentKeys.summary(input.topicId),
- (current: TopicCommentSummary | undefined) => {
- if (!current) return current;
- const countByMessage = { ...current.countByMessage };
- if (input.messageId) {
- countByMessage[input.messageId] = (countByMessage[input.messageId] ?? 0) + 1;
- }
- return { countByMessage, total: current.total + 1 };
- },
- { revalidate: true },
- ).catch(() => undefined);
- } else {
- void mutate(topicCommentKeys.summary(input.topicId)).catch(() => undefined);
+ applySummary(input.topicId, (current) => {
+ if (!current) return current;
+ const countByMessage = { ...current.countByMessage };
+ if (input.messageId) {
+ countByMessage[input.messageId] = (countByMessage[input.messageId] ?? 0) + 1;
+ }
+ return { countByMessage, total: current.total + 1 };
+ });
}
+ void revalidateSummary(input.topicId).catch(() => undefined);
upsertOptimisticComment({
comment: result.comment,
pending: false,
@@ -662,8 +575,10 @@ export const useTopicCommentMutations = () => {
}
},
[
+ applySummary,
removeOptimisticComment,
removeOptimisticReplyCountMutation,
+ revalidateSummary,
upsertOptimisticComment,
upsertOptimisticReplyCountMutation,
user,
@@ -703,9 +618,7 @@ export const useTopicCommentMutations = () => {
try {
const result = await topicCommentService.update(input);
upsertOptimisticMutation({ comment: result, kind: 'update', pending: false });
- void mutate(topicCommentKeys.detail(result.id), result, { revalidate: false }).catch(
- () => undefined,
- );
+ upsertDetail(result);
return result;
} catch (error) {
if (previousMutation) upsertOptimisticMutation(previousMutation);
@@ -713,7 +626,7 @@ export const useTopicCommentMutations = () => {
throw error;
}
}),
- [removeOptimisticMutation, runForId, upsertOptimisticMutation],
+ [removeOptimisticMutation, runForId, upsertDetail, upsertOptimisticMutation],
);
const remove = useCallback(
(
@@ -780,32 +693,26 @@ export const useTopicCommentMutations = () => {
pending: true,
};
upsertOptimisticMutation(confirmedMutation);
- void mutate(
- topicCommentKeys.summary(comment.topicId),
- (current: TopicCommentSummary | undefined) => {
- if (!current) return current;
- const countByMessage = { ...current.countByMessage };
- const removesMessageCount =
- result.mode === 'hard' ||
- (result.mode === 'moderated' && optimisticDeleteMode === 'hard');
- if (removesMessageCount && comment.messageId) {
- const nextCount = Math.max(0, (countByMessage[comment.messageId] ?? 0) - 1);
- if (nextCount > 0) countByMessage[comment.messageId] = nextCount;
- else delete countByMessage[comment.messageId];
- }
- return { countByMessage, total: Math.max(0, current.total - 1) };
- },
- { revalidate: true },
- ).catch(() => undefined);
+ applySummary(comment.topicId, (current) => {
+ if (!current) return current;
+ const countByMessage = { ...current.countByMessage };
+ const removesMessageCount =
+ result.mode === 'hard' ||
+ (result.mode === 'moderated' && optimisticDeleteMode === 'hard');
+ if (removesMessageCount && comment.messageId) {
+ const nextCount = Math.max(0, (countByMessage[comment.messageId] ?? 0) - 1);
+ if (nextCount > 0) countByMessage[comment.messageId] = nextCount;
+ else delete countByMessage[comment.messageId];
+ }
+ return { countByMessage, total: Math.max(0, current.total - 1) };
+ });
+ void revalidateSummary(comment.topicId).catch(() => undefined);
upsertOptimisticMutation({ ...confirmedMutation, pending: false });
if (replyCountMutation) {
upsertOptimisticReplyCountMutation({ ...replyCountMutation, pending: false });
}
- void mutate(
- topicCommentKeys.detail(comment.id),
- result.mode === 'hard' ? undefined : confirmedMutation.comment,
- { revalidate: false },
- ).catch(() => undefined);
+ if (result.mode === 'hard') removeDetail(comment.id);
+ else upsertDetail(confirmedMutation.comment);
return result;
} catch (error) {
if (previousMutation) upsertOptimisticMutation(previousMutation);
@@ -815,9 +722,13 @@ export const useTopicCommentMutations = () => {
}
}),
[
+ applySummary,
+ removeDetail,
removeOptimisticMutation,
removeOptimisticReplyCountMutation,
+ revalidateSummary,
runForId,
+ upsertDetail,
upsertOptimisticMutation,
upsertOptimisticReplyCountMutation,
workspaceId,
@@ -851,21 +762,16 @@ export const useTopicCommentMutations = () => {
kind: 'restore',
pending: false,
});
- void mutate(
- topicCommentKeys.summary(comment.topicId),
- (current: TopicCommentSummary | undefined) => {
- if (!current) return current;
- const countByMessage = { ...current.countByMessage };
- if (comment.messageId && options.rootReplyCount === 0) {
- countByMessage[comment.messageId] = (countByMessage[comment.messageId] ?? 0) + 1;
- }
- return { countByMessage, total: current.total + 1 };
- },
- { revalidate: true },
- ).catch(() => undefined);
- void mutate(topicCommentKeys.detail(comment.id), result, { revalidate: false }).catch(
- () => undefined,
- );
+ applySummary(comment.topicId, (current) => {
+ if (!current) return current;
+ const countByMessage = { ...current.countByMessage };
+ if (comment.messageId && options.rootReplyCount === 0) {
+ countByMessage[comment.messageId] = (countByMessage[comment.messageId] ?? 0) + 1;
+ }
+ return { countByMessage, total: current.total + 1 };
+ });
+ void revalidateSummary(comment.topicId).catch(() => undefined);
+ upsertDetail(result);
return result;
} catch (error) {
if (previousMutation) upsertOptimisticMutation(previousMutation);
@@ -873,7 +779,14 @@ export const useTopicCommentMutations = () => {
throw error;
}
}),
- [removeOptimisticMutation, runForId, upsertOptimisticMutation],
+ [
+ applySummary,
+ removeOptimisticMutation,
+ revalidateSummary,
+ runForId,
+ upsertDetail,
+ upsertOptimisticMutation,
+ ],
);
return { create, creating, mutatingIds, remove, restore, update };
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 5c5abcd879e..ff004d137ce 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -136,36 +136,6 @@ export const topicKeys = {
]),
};
-// ---- topic comment ------------------------------------------------------
-export const topicCommentKeys = {
- detail: def('topicComment:detail', (commentId: string) => ['topicComment:detail', commentId]),
- replies: def(
- 'topicComment:replies',
- (workspaceId: string | null, rootCommentId: string, cursor?: string) => [
- 'topicComment:replies',
- workspaceId ?? '',
- rootCommentId,
- cursor ?? '',
- ],
- ),
- summary: def('topicComment:summary', (topicId: string) => ['topicComment:summary', topicId]),
- threads: def(
- 'topicComment:threads',
- (workspaceId: string | null, topicId: string, messageId?: string, cursor?: string) => [
- 'topicComment:threads',
- workspaceId ?? '',
- topicId,
- messageId ?? '',
- cursor ?? '',
- ],
- ),
- warmup: def('topicComment:warmup', (workspaceId: string, topicId: string) => [
- 'topicComment:warmup',
- workspaceId,
- topicId,
- ]),
-};
-
// ---- acceptance comment -------------------------------------------------
export const acceptanceCommentKeys = {
list: def('acceptanceComment:list', (acceptanceId: string) => [
@@ -1462,7 +1432,6 @@ export const swrKeys = {
thread: threadKeys,
tool: toolKeys,
topic: topicKeys,
- topicComment: topicCommentKeys,
acceptanceComment: acceptanceCommentKeys,
documentComment: documentCommentKeys,
documentLike: documentLikeKeys,
diff --git a/src/store/topicComment/action.ts b/src/store/topicComment/action.ts
index a3538137a0d..914e189c3b8 100644
--- a/src/store/topicComment/action.ts
+++ b/src/store/topicComment/action.ts
@@ -1,3 +1,7 @@
+import type { TopicCommentItem, TopicCommentSummary } from '@lobechat/types';
+
+import { createReplicaSlice, recordLens, type ReplicaSyncResult } from '@/libs/replica';
+import { topicCommentService } from '@/services/topicComment';
import type { StoreSetter } from '@/store/types';
import {
@@ -7,26 +11,218 @@ import {
type OptimisticTopicCommentReplyCountMutation,
type TopicCommentDraft,
} from './initialState';
+import {
+ TOPIC_COMMENT_PAGE_SIZE,
+ topicCommentDetailResource,
+ type TopicCommentRepliesParams,
+ type TopicCommentReplyFeed,
+ topicCommentReplyResource,
+ topicCommentSummaryResource,
+ type TopicCommentThreadFeed,
+ topicCommentThreadResource,
+ topicCommentThreadsKey,
+ type TopicCommentThreadsParams,
+} from './projection';
import type { TopicCommentStore } from './store';
type Setter = StoreSetter<TopicCommentStore>;
+/** Roots preloaded per warmup round (the topic feed, then its reply threads). */
+const PREFETCH_CONCURRENCY = 4;
+
export const createTopicCommentSlice = (
set: Setter,
get: () => TopicCommentStore,
_api?: unknown,
) => new TopicCommentActionImpl(set, get, _api);
+/**
+ * The workspace topic-comment domain.
+ *
+ * Server state is a set of four replicas (`threadFeedMap` root feeds,
+ * `replyFeedMap` reply feeds, `commentSummaryMap` counts, `commentDetailMap`
+ * single comments): each paints its persisted copy on the first frame and is
+ * confirmed by the network in the background. The store also keeps the
+ * client-only drafts and optimistic overlays the comment UI writes through.
+ */
export class TopicCommentActionImpl {
+ readonly #detail;
readonly #get: () => TopicCommentStore;
+ /** Topics with a warmup in flight, so a remount cannot double-fetch the feed. */
+ readonly #prefetching = new Set<string>();
+ readonly #replies;
readonly #set: Setter;
+ readonly #summary;
+ readonly #thread;
constructor(set: Setter, get: () => TopicCommentStore, _api?: unknown) {
void _api;
this.#set = set;
this.#get = get;
+ this.#thread = createReplicaSlice(topicCommentThreadResource, {
+ actionPrefix: 'topicComment/threads',
+ fetcher: (params, cursor) => this.#fetchThreads(params, cursor),
+ get,
+ set,
+ stateKey: 'threadFeedReplica',
+ view: recordLens<TopicCommentStore, TopicCommentThreadFeed>('threadFeedMap'),
+ });
+ this.#replies = createReplicaSlice(topicCommentReplyResource, {
+ actionPrefix: 'topicComment/replies',
+ fetcher: (params, cursor) => this.#fetchReplies(params, cursor),
+ get,
+ set,
+ stateKey: 'replyFeedReplica',
+ view: recordLens<TopicCommentStore, TopicCommentReplyFeed>('replyFeedMap'),
+ });
+ this.#summary = createReplicaSlice(topicCommentSummaryResource, {
+ actionPrefix: 'topicComment/summary',
+ fetcher: (topicId) => topicCommentService.summary(topicId),
+ get,
+ set,
+ stateKey: 'commentSummaryReplica',
+ view: recordLens<TopicCommentStore, TopicCommentSummary>('commentSummaryMap'),
+ });
+ this.#detail = createReplicaSlice(topicCommentDetailResource, {
+ actionPrefix: 'topicComment/detail',
+ fetcher: (commentId) => topicCommentService.get(commentId),
+ get,
+ set,
+ stateKey: 'commentDetailReplica',
+ view: recordLens<TopicCommentStore, TopicCommentItem>('commentDetailMap'),
+ });
}
+ #fetchReplies = (params: TopicCommentRepliesParams, cursor?: string) =>
+ topicCommentService.listReplies({
+ cursor,
+ limit: params.pageSize ?? TOPIC_COMMENT_PAGE_SIZE,
+ rootCommentId: params.rootCommentId,
+ });
+
+ #prefetchReplies = async (rootCommentId: string, scope: string) => {
+ const params = { pageSize: TOPIC_COMMENT_PAGE_SIZE, rootCommentId };
+ const page = await this.#fetchReplies(params);
+ // `scope` was captured before the request (see `prefetchTopicComments`).
+ this.#replies.replace(params, page, scope);
+ };
+
+ #fetchThreads = (params: TopicCommentThreadsParams, cursor?: string) =>
+ topicCommentService.listThreads({
+ cursor,
+ limit: params.pageSize ?? TOPIC_COMMENT_PAGE_SIZE,
+ messageId: params.messageId,
+ topicId: params.topicId,
+ });
+
+ // ---- server reads (replica) -------------------------------------------
+
+ /** Hydrate + sync the topic comment summary. Returns flags only; read `commentSummaryMap`. */
+ useFetchTopicCommentSummary = (
+ topicId: string | null | undefined,
+ enabled = true,
+ ): ReplicaSyncResult =>
+ this.#summary.useSync(topicId ?? null, { dedupingInterval: 30_000, enabled });
+
+ /** Hydrate + sync the root-comment feed of one topic (optionally one message). */
+ useFetchTopicCommentThreads = (
+ params: TopicCommentThreadsParams | null | undefined,
+ enabled = true,
+ ): ReplicaSyncResult => this.#thread.useSync(params ?? null, { enabled });
+
+ /** Hydrate + sync the reply feed of one root comment. */
+ useFetchTopicCommentReplies = (
+ params: TopicCommentRepliesParams | null | undefined,
+ enabled = true,
+ ): ReplicaSyncResult => this.#replies.useSync(params ?? null, { enabled });
+
+ /** Hydrate + sync one comment by id (used by the standalone thread header). */
+ useFetchTopicCommentDetail = (
+ commentId: string | null | undefined,
+ enabled = true,
+ ): ReplicaSyncResult => this.#detail.useSync(commentId ?? null, { enabled });
+
+ loadMoreTopicCommentThreads = (params: TopicCommentThreadsParams) =>
+ this.#thread.loadMore(topicCommentThreadsKey(params), params);
+
+ loadMoreTopicCommentReplies = (params: TopicCommentRepliesParams) =>
+ this.#replies.loadMore(params.rootCommentId, params);
+
+ /**
+ * Re-read a feed after an event or an explicit refresh. A head-only
+ * revalidation keeps the already-loaded tail pages, so a change another
+ * member made to an older page would survive it — drop the tail first, then
+ * re-read the head; the next "load more" walks the pages below it again.
+ */
+ revalidateTopicCommentThreads = (params: TopicCommentThreadsParams) => {
+ const key = topicCommentThreadsKey(params);
+ this.#thread.collapse(key);
+ return this.#thread.revalidate(key);
+ };
+
+ revalidateTopicCommentReplies = (params: TopicCommentRepliesParams) => {
+ this.#replies.collapse(params.rootCommentId);
+ return this.#replies.revalidate(params.rootCommentId);
+ };
+
+ revalidateTopicCommentSummary = (topicId: string) => this.#summary.revalidate(topicId);
+
+ revalidateTopicCommentDetail = (commentId: string) => this.#detail.revalidate(commentId);
+
+ /**
+ * Patch the summary between a comment write and the revalidation that
+ * follows it, so the badge never lags the list. Kept out of persistence — the
+ * server value replaces it on the next sync.
+ */
+ applyTopicCommentSummary = (
+ topicId: string,
+ apply: (current: TopicCommentSummary | undefined) => TopicCommentSummary | undefined,
+ ) => this.#summary.update(topicId, apply, { persist: false });
+
+ /** Confirm a server-written comment into the by-id detail replica. */
+ upsertTopicCommentDetail = (comment: TopicCommentItem) =>
+ this.#detail.update(comment.id, () => comment);
+
+ /** Drop a hard-deleted comment from the by-id detail replica (view + storage). */
+ removeTopicCommentDetail = (commentId: string) => this.#detail.remove(commentId);
+
+ /**
+ * Warm the topic feed and the reply threads of its roots so opening the
+ * portal paints from the replica instead of a skeleton. Best-effort: a failed
+ * warmup is simply retried by the feed's own sync when it mounts.
+ */
+ prefetchTopicComments = async (topicId: string): Promise<void> => {
+ if (this.#prefetching.has(topicId)) return;
+ this.#prefetching.add(topicId);
+ try {
+ const params = { pageSize: TOPIC_COMMENT_PAGE_SIZE, topicId };
+ // Capture the partition before the request. A warmup that lands after a
+ // workspace / account switch must not paint, or persist, the previous
+ // identity's rows into the new one: resolving the scope at write time
+ // would target whatever partition is active when the response arrives.
+ const scope = topicCommentThreadResource.scope.get();
+ const threads = await this.#fetchThreads(params);
+ this.#thread.replace(params, threads, scope);
+
+ const rootCommentIds = threads.items.flatMap(({ replyCount, root }) =>
+ replyCount > 0 ? [root.id] : [],
+ );
+ for (let index = 0; index < rootCommentIds.length; index += PREFETCH_CONCURRENCY) {
+ await Promise.all(
+ rootCommentIds
+ .slice(index, index + PREFETCH_CONCURRENCY)
+ .map((rootCommentId) => this.#prefetchReplies(rootCommentId, scope)),
+ );
+ }
+ } catch {
+ // Warmup is an optimization; the mounted feeds own error handling.
+ } finally {
+ this.#prefetching.delete(topicId);
+ }
+ };
+
+ // ---- client-only state (drafts + optimistic overlays) ------------------
+
clearDraft = (key: string, expectedClientId?: string): void => {
if (expectedClientId && this.#get().drafts[key]?.clientId !== expectedClientId) return;
diff --git a/src/store/topicComment/index.ts b/src/store/topicComment/index.ts
index 9cf4b05671f..6e2982e7760 100644
--- a/src/store/topicComment/index.ts
+++ b/src/store/topicComment/index.ts
@@ -1,3 +1,10 @@
export { createTopicCommentDraftKey } from './initialState';
+export type {
+ TopicCommentRepliesParams,
+ TopicCommentReplyFeed,
+ TopicCommentThreadFeed,
+ TopicCommentThreadsParams,
+} from './projection';
+export { TOPIC_COMMENT_PAGE_SIZE, topicCommentThreadsKey } from './projection';
export { topicCommentSelectors } from './selectors';
export { useTopicCommentStore } from './store';
diff --git a/src/store/topicComment/initialState.ts b/src/store/topicComment/initialState.ts
index 72b27804740..e8e2d664d06 100644
--- a/src/store/topicComment/initialState.ts
+++ b/src/store/topicComment/initialState.ts
@@ -1,4 +1,8 @@
-import type { TopicCommentItem, TopicCommentJson } from '@lobechat/types';
+import type { TopicCommentItem, TopicCommentJson, TopicCommentSummary } from '@lobechat/types';
+
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+
+import type { TopicCommentReplyFeed, TopicCommentThreadFeed } from './projection';
export interface TopicCommentDraft {
clientId?: string;
@@ -31,17 +35,41 @@ export interface OptimisticTopicCommentReplyCountMutation {
}
export interface TopicCommentState {
+ /** One comment by id (`commentDetailMap[commentId]`), read by the standalone thread view. */
+ commentDetailMap: Record<string, TopicCommentItem>;
+ /** Replica bookkeeping for `commentDetailMap`. */
+ commentDetailReplica: ReplicaState<TopicCommentItem>;
+ /** Per-topic comment counts (`commentSummaryMap[topicId]`), read by the badge + list. */
+ commentSummaryMap: Record<string, TopicCommentSummary>;
+ /** Replica bookkeeping for `commentSummaryMap`. */
+ commentSummaryReplica: ReplicaState<TopicCommentSummary>;
drafts: Record<string, TopicCommentDraft>;
optimisticComments: Record<string, OptimisticTopicComment>;
optimisticMutations: Record<string, OptimisticTopicCommentMutation>;
optimisticReplyCountMutations: Record<string, OptimisticTopicCommentReplyCountMutation>;
+ /** Replies per root comment (`replyFeedMap[rootCommentId]`). */
+ replyFeedMap: Record<string, TopicCommentReplyFeed>;
+ /** Replica bookkeeping for `replyFeedMap`. */
+ replyFeedReplica: ReplicaState<TopicCommentReplyFeed>;
+ /** Root-comment feeds per (topic, message) (`threadFeedMap[threadKey]`). */
+ threadFeedMap: Record<string, TopicCommentThreadFeed>;
+ /** Replica bookkeeping for `threadFeedMap`. */
+ threadFeedReplica: ReplicaState<TopicCommentThreadFeed>;
}
export const initialState: TopicCommentState = {
+ commentDetailMap: {},
+ commentDetailReplica: createReplicaState(),
+ commentSummaryMap: {},
+ commentSummaryReplica: createReplicaState(),
drafts: {},
optimisticComments: {},
optimisticMutations: {},
optimisticReplyCountMutations: {},
+ replyFeedMap: {},
+ replyFeedReplica: createReplicaState(),
+ threadFeedMap: {},
+ threadFeedReplica: createReplicaState(),
};
export const createTopicCommentDraftKey = ({
diff --git a/src/store/topicComment/projection.ts b/src/store/topicComment/projection.ts
new file mode 100644
index 00000000000..a9e2e36aa91
--- /dev/null
+++ b/src/store/topicComment/projection.ts
@@ -0,0 +1,102 @@
+import type { TopicCommentItem, TopicCommentSummary, TopicCommentThread } from '@lobechat/types';
+
+import { definePagedReplica, defineReplica, type ReplicaPagedData } from '@/libs/replica';
+
+/** One server page of comments (`limit` caps it; the cursor walks backwards in time). */
+export const TOPIC_COMMENT_PAGE_SIZE = 30;
+
+/**
+ * Root-comment feed of one topic, optionally narrowed to a single message.
+ * The active workspace is part of the replica scope, so it is not repeated in
+ * the key — only the topic and the message narrow the row set.
+ */
+export interface TopicCommentThreadsParams {
+ messageId?: string;
+ pageSize?: number;
+ topicId: string;
+}
+
+/** Root-comment feed of one topic: `threadFeedMap[topicCommentThreadsKey(params)]`. */
+export type TopicCommentThreadFeed = ReplicaPagedData<TopicCommentThread, string>;
+
+/** Reply feed of one root comment: `replyFeedMap[rootCommentId]`. */
+export interface TopicCommentRepliesParams {
+ pageSize?: number;
+ rootCommentId: string;
+}
+
+/** Reply feed of one root comment (`total` = the canonical live-reply count, head page only). */
+export type TopicCommentReplyFeed = ReplicaPagedData<TopicCommentItem, string>;
+
+/**
+ * Feed identity of a root-comment thread view. A message-scoped view and the
+ * topic-wide view are distinct entries: mounting one must not reset the other.
+ */
+export const topicCommentThreadsKey = ({
+ messageId,
+ topicId,
+}: Pick<TopicCommentThreadsParams, 'messageId' | 'topicId'>) =>
+ messageId ? `${topicId}:message:${messageId}` : `${topicId}:all`;
+
+const threadPaging = {
+ direction: 'forward',
+ getId: (thread: TopicCommentThread) => thread.root.id,
+ mode: 'cursor',
+ // A reload repaints the head page the server would return, never a stale tail.
+ persist: { pages: 1 },
+} as const;
+
+const replyPaging = {
+ direction: 'forward',
+ getId: (comment: TopicCommentItem) => comment.id,
+ mode: 'cursor',
+ persist: { pages: 1 },
+} as const;
+
+/** Root-comment threads of one topic (`threadFeedMap`). */
+export const topicCommentThreadResource = definePagedReplica<
+ TopicCommentThreadsParams,
+ TopicCommentThread,
+ string
+>({
+ key: topicCommentThreadsKey,
+ name: 'topicCommentThreads',
+ paging: threadPaging,
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** Replies of one root comment (`replyFeedMap`). */
+export const topicCommentReplyResource = definePagedReplica<
+ TopicCommentRepliesParams,
+ TopicCommentItem,
+ string
+>({
+ key: ({ rootCommentId }) => rootCommentId,
+ name: 'topicCommentReplies',
+ paging: replyPaging,
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** Per-topic comment counts (`commentSummaryMap[topicId]`). */
+export const topicCommentSummaryResource = defineReplica<
+ string,
+ TopicCommentSummary,
+ TopicCommentSummary
+>({
+ key: (topicId) => topicId,
+ name: 'topicCommentSummary',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** One comment by id (`commentDetailMap[commentId]`), for the standalone thread view. */
+export const topicCommentDetailResource = defineReplica<string, TopicCommentItem, TopicCommentItem>(
+ {
+ key: (commentId) => commentId,
+ name: 'topicCommentDetail',
+ storage: 'indexedDB',
+ version: 1,
+ },
+);
diff --git a/src/store/topicComment/replica.test.ts b/src/store/topicComment/replica.test.ts
new file mode 100644
index 00000000000..636f6a74ef6
--- /dev/null
+++ b/src/store/topicComment/replica.test.ts
@@ -0,0 +1,392 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * `topicComment` is a `@lobechat/replica`-backed store. The root feed, the
+ * reply feed, the per-topic counts and one comment by id each paint their
+ * persisted row before the network answers, are confirmed and persisted by the
+ * response, page further through the engine, and are re-partitioned when the
+ * cache scope changes — instead of the hand-written SWR/infinite caches the
+ * four resources replaced.
+ */
+import { randomUUID } from 'node:crypto';
+
+import type { TopicCommentItem, TopicCommentThread } from '@lobechat/types';
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react';
+import type { PropsWithChildren } from 'react';
+import { createElement, useEffect } from 'react';
+import { SWRConfig, useSWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope } from '@/libs/replica';
+import { setScopedMutate } from '@/libs/swr/mutate';
+import { topicCommentService } from '@/services/topicComment';
+
+import { initialState } from './initialState';
+import {
+ topicCommentDetailResource,
+ topicCommentReplyResource,
+ topicCommentThreadResource,
+ topicCommentThreadsKey,
+} from './projection';
+import { useTopicCommentStore } from './store';
+
+const THREAD_PARAMS = { pageSize: 30, topicId: 'topic-1' };
+const THREAD_VIEW_KEY = topicCommentThreadsKey(THREAD_PARAMS);
+const THREAD_STORAGE_KEY = topicCommentThreadResource.storageKey(THREAD_PARAMS);
+
+const comment = (id: string, overrides: Partial<TopicCommentItem> = {}): TopicCommentItem => ({
+ anchorPreview: null,
+ author: {
+ avatar: null,
+ fullName: 'Current User',
+ id: 'user-1',
+ status: 'active',
+ username: 'current-user',
+ },
+ authorUserId: 'user-1',
+ canDelete: true,
+ canEdit: true,
+ canRestore: false,
+ clientId: `client-${id}`,
+ content: id,
+ createdAt: new Date('2026-07-20T00:00:00.000Z'),
+ deletedAt: null,
+ editorData: null,
+ id,
+ messageId: null,
+ moderatedAt: null,
+ moderationExpiresAt: null,
+ moderationIsOwn: false,
+ parentCommentId: null,
+ topicId: 'topic-1',
+ updatedAt: new Date('2026-07-20T00:00:00.000Z'),
+ workspaceId: 'workspace-1',
+ ...overrides,
+});
+
+const thread = (id: string, replyCount = 0): TopicCommentThread => ({
+ replyCount,
+ root: comment(id),
+});
+
+const ids = (feed?: { items: TopicCommentThread[] }) => feed?.items.map(({ root }) => root.id);
+
+/** Never-resolving fetch: the first frame can only come from storage. */
+const pending = () => new Promise<never>(() => {});
+
+const MutateBridge = () => {
+ const { mutate } = useSWRConfig();
+ useEffect(() => setScopedMutate(mutate), [mutate]);
+ return null;
+};
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(
+ SWRConfig,
+ { value: { dedupingInterval: 0, provider: () => new Map() } },
+ createElement(MutateBridge),
+ children,
+ );
+
+describe('topicComment replicas', () => {
+ const scopes = new Set<string>();
+ let scope = '';
+ let listThreadsSpy: ReturnType<typeof vi.spyOn>;
+ let listRepliesSpy: ReturnType<typeof vi.spyOn>;
+
+ const useScope = (next: string) => {
+ scope = next;
+ scopes.add(next);
+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);
+ };
+
+ beforeEach(() => {
+ useScope(`topic-user-${randomUUID()}:personal`);
+ listThreadsSpy = vi.spyOn(topicCommentService, 'listThreads');
+ listRepliesSpy = vi.spyOn(topicCommentService, 'listReplies');
+ act(() => useTopicCommentStore.setState(initialState));
+ });
+
+ afterEach(async () => {
+ cleanup();
+ await Promise.all(
+ [...scopes].flatMap((value) => [
+ topicCommentThreadResource.storage!.remove({ queryKey: THREAD_STORAGE_KEY, scope: value }),
+ topicCommentReplyResource.storage!.remove({ queryKey: 'root-1', scope: value }),
+ topicCommentDetailResource.storage!.remove({ queryKey: 'comment-1', scope: value }),
+ ]),
+ );
+ scopes.clear();
+ vi.restoreAllMocks();
+ vi.clearAllMocks();
+ });
+
+ it('paints the persisted root feed before the network answers', async () => {
+ const cached = {
+ currentPage: 0,
+ hasMore: true,
+ items: [thread('cached-1', 2)],
+ nextCursor: 'c1',
+ total: 5,
+ };
+ await topicCommentThreadResource.storage!.set(
+ { queryKey: THREAD_STORAGE_KEY, scope },
+ { data: cached, updatedAt: 1 },
+ );
+ listThreadsSpy.mockImplementation(pending);
+
+ const hook = renderHook(
+ () => ({
+ feed: useTopicCommentStore((s) => s.threadFeedMap[THREAD_VIEW_KEY]),
+ sync: useTopicCommentStore((s) => s.useFetchTopicCommentThreads)(THREAD_PARAMS),
+ }),
+ { wrapper },
+ );
+
+ await waitFor(() =>
+ expect(ids(useTopicCommentStore.getState().threadFeedMap[THREAD_VIEW_KEY])).toEqual([
+ 'cached-1',
+ ]),
+ );
+ expect(hook.result.current.sync.isHydrated).toBe(true);
+ expect(hook.result.current.sync.isValidating).toBe(true);
+ });
+
+ it('replaces the head page with the server response and persists it', async () => {
+ listThreadsSpy.mockResolvedValue({
+ items: [thread('a'), thread('b')],
+ nextCursor: 'next',
+ });
+
+ renderHook(() => useTopicCommentStore((s) => s.useFetchTopicCommentThreads)(THREAD_PARAMS), {
+ wrapper,
+ });
+
+ await waitFor(() =>
+ expect(ids(useTopicCommentStore.getState().threadFeedMap[THREAD_VIEW_KEY])).toEqual([
+ 'a',
+ 'b',
+ ]),
+ );
+ expect(useTopicCommentStore.getState().threadFeedMap[THREAD_VIEW_KEY]).toMatchObject({
+ currentPage: 0,
+ hasMore: true,
+ });
+
+ await waitFor(async () => {
+ const row = await topicCommentThreadResource.storage!.get({
+ queryKey: THREAD_STORAGE_KEY,
+ scope,
+ });
+ expect(ids(row?.data as { items: TopicCommentThread[] })).toEqual(['a', 'b']);
+ });
+ });
+
+ it('appends the next page through the engine cursor', async () => {
+ listThreadsSpy
+ .mockResolvedValueOnce({ items: [thread('a')], nextCursor: 'c1' })
+ .mockResolvedValueOnce({ items: [thread('b')], nextCursor: null });
+
+ renderHook(() => useTopicCommentStore((s) => s.useFetchTopicCommentThreads)(THREAD_PARAMS), {
+ wrapper,
+ });
+ await waitFor(() =>
+ expect(ids(useTopicCommentStore.getState().threadFeedMap[THREAD_VIEW_KEY])).toEqual(['a']),
+ );
+
+ await act(async () => {
+ await useTopicCommentStore.getState().loadMoreTopicCommentThreads(THREAD_PARAMS);
+ });
+
+ expect(ids(useTopicCommentStore.getState().threadFeedMap[THREAD_VIEW_KEY])).toEqual(['a', 'b']);
+ expect(listThreadsSpy).toHaveBeenLastCalledWith({
+ cursor: 'c1',
+ limit: 30,
+ messageId: undefined,
+ topicId: 'topic-1',
+ });
+ });
+
+ it('warms the topic feed and its reply threads into the views and persists them', async () => {
+ listThreadsSpy.mockResolvedValue({ items: [thread('root-1', 2)], nextCursor: null });
+ listRepliesSpy.mockResolvedValue({
+ items: [comment('reply-1', { parentCommentId: 'root-1' })],
+ nextCursor: null,
+ total: 1,
+ });
+
+ await act(async () => {
+ await useTopicCommentStore.getState().prefetchTopicComments('topic-1');
+ });
+
+ expect(ids(useTopicCommentStore.getState().threadFeedMap[THREAD_VIEW_KEY])).toEqual(['root-1']);
+ expect(useTopicCommentStore.getState().replyFeedMap['root-1']?.items).toHaveLength(1);
+ expect(listRepliesSpy).toHaveBeenCalledWith({
+ cursor: undefined,
+ limit: 30,
+ rootCommentId: 'root-1',
+ });
+
+ await waitFor(async () => {
+ const threadRow = await topicCommentThreadResource.storage!.get({
+ queryKey: THREAD_STORAGE_KEY,
+ scope,
+ });
+ const replyRow = await topicCommentReplyResource.storage!.get({
+ queryKey: 'root-1',
+ scope,
+ });
+ expect(ids(threadRow?.data as { items: TopicCommentThread[] })).toEqual(['root-1']);
+ expect((replyRow?.data as { items: TopicCommentItem[] }).items).toHaveLength(1);
+ });
+ });
+
+ it('drops the previous identity feed when the cache scope changes', async () => {
+ listThreadsSpy.mockResolvedValue({ items: [thread('a')], nextCursor: null });
+
+ const hook = renderHook(
+ () => useTopicCommentStore((s) => s.useFetchTopicCommentThreads)(THREAD_PARAMS),
+ { wrapper },
+ );
+ await waitFor(() =>
+ expect(ids(useTopicCommentStore.getState().threadFeedMap[THREAD_VIEW_KEY])).toEqual(['a']),
+ );
+
+ useScope(`topic-user-${randomUUID()}:personal`);
+ listThreadsSpy.mockImplementation(pending);
+ hook.rerender();
+
+ await waitFor(() =>
+ expect(useTopicCommentStore.getState().threadFeedMap[THREAD_VIEW_KEY]).toBeUndefined(),
+ );
+ });
+
+ it('drops the loaded tail when the feed is revalidated for an event', async () => {
+ listThreadsSpy
+ .mockResolvedValueOnce({ items: [thread('a')], nextCursor: 'c1' })
+ .mockResolvedValueOnce({ items: [thread('b')], nextCursor: null })
+ .mockResolvedValueOnce({ items: [thread('a')], nextCursor: 'c1' });
+
+ renderHook(() => useTopicCommentStore((s) => s.useFetchTopicCommentThreads)(THREAD_PARAMS), {
+ wrapper,
+ });
+ await waitFor(() =>
+ expect(ids(useTopicCommentStore.getState().threadFeedMap[THREAD_VIEW_KEY])).toEqual(['a']),
+ );
+
+ await act(async () => {
+ await useTopicCommentStore.getState().loadMoreTopicCommentThreads(THREAD_PARAMS);
+ });
+ expect(ids(useTopicCommentStore.getState().threadFeedMap[THREAD_VIEW_KEY])).toEqual(['a', 'b']);
+ expect(useTopicCommentStore.getState().threadFeedMap[THREAD_VIEW_KEY]?.currentPage).toBe(1);
+
+ await act(async () => {
+ await useTopicCommentStore.getState().revalidateTopicCommentThreads(THREAD_PARAMS);
+ });
+
+ // A head-only refresh would keep the stale tail: the view collapses to the
+ // refreshed head page instead.
+ await waitFor(() =>
+ expect(useTopicCommentStore.getState().threadFeedMap[THREAD_VIEW_KEY]?.currentPage).toBe(0),
+ );
+ expect(ids(useTopicCommentStore.getState().threadFeedMap[THREAD_VIEW_KEY])).toEqual(['a']);
+ });
+
+ it('does not paint a warmup that lands after the cache scope changed', async () => {
+ let resolveThreads: ((page: unknown) => void) | undefined;
+ listThreadsSpy
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveThreads = resolve;
+ }),
+ )
+ .mockImplementation(pending);
+
+ const prefetch = useTopicCommentStore.getState().prefetchTopicComments('topic-1');
+ await waitFor(() => expect(resolveThreads).toBeDefined());
+
+ // The identity changes while the warmup is in flight, and a consumer mounts
+ // in the new partition — that partition's replica slot is now the active one.
+ useScope(`topic-user-${randomUUID()}:personal`);
+ renderHook(() => useTopicCommentStore((s) => s.useFetchTopicCommentThreads)(THREAD_PARAMS), {
+ wrapper,
+ });
+
+ await act(async () => {
+ resolveThreads!({ items: [thread('late')], nextCursor: null });
+ await prefetch;
+ });
+
+ expect(useTopicCommentStore.getState().threadFeedMap[THREAD_VIEW_KEY]).toBeUndefined();
+ });
+
+ it('does not paint a warmup reply that lands after the cache scope changed', async () => {
+ // The warmup passes the scope it captured to every replacement, not only the
+ // root feed: the reply fetched for a root under one identity must be rejected
+ // when the identity changes before it lands, so it can neither paint nor
+ // persist into the new partition.
+ let resolveReplies: ((page: unknown) => void) | undefined;
+ listThreadsSpy.mockResolvedValue({ items: [thread('root-1', 1)], nextCursor: null });
+ listRepliesSpy.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ resolveReplies = resolve;
+ }),
+ );
+
+ const prefetch = useTopicCommentStore.getState().prefetchTopicComments('topic-1');
+ await waitFor(() => expect(resolveReplies).toBeDefined());
+
+ // The root feed was already replaced under the identity it was fetched for,
+ // and the reply prefetch it triggered is the request now in flight.
+ expect(ids(useTopicCommentStore.getState().threadFeedMap[THREAD_VIEW_KEY])).toEqual(['root-1']);
+
+ const nextScope = `topic-user-${randomUUID()}:personal`;
+ useScope(nextScope);
+
+ await act(async () => {
+ resolveReplies!({
+ items: [comment('reply-1', { parentCommentId: 'root-1' })],
+ nextCursor: null,
+ total: 1,
+ });
+ await prefetch;
+ });
+
+ expect(useTopicCommentStore.getState().replyFeedMap['root-1']).toBeUndefined();
+ await waitFor(async () => {
+ const row = await topicCommentReplyResource.storage!.get({
+ queryKey: 'root-1',
+ scope: nextScope,
+ });
+ expect(row).toBeUndefined();
+ });
+ });
+
+ it('keeps one comment by id in the detail view and drops it from view and storage', async () => {
+ act(() => useTopicCommentStore.getState().upsertTopicCommentDetail(comment('comment-1')));
+
+ expect(useTopicCommentStore.getState().commentDetailMap['comment-1']?.id).toBe('comment-1');
+ await waitFor(async () => {
+ const row = await topicCommentDetailResource.storage!.get({
+ queryKey: 'comment-1',
+ scope,
+ });
+ expect(row?.data).toMatchObject({ id: 'comment-1' });
+ });
+
+ act(() => useTopicCommentStore.getState().removeTopicCommentDetail('comment-1'));
+
+ expect(useTopicCommentStore.getState().commentDetailMap['comment-1']).toBeUndefined();
+ await waitFor(async () => {
+ const row = await topicCommentDetailResource.storage!.get({
+ queryKey: 'comment-1',
+ scope,
+ });
+ expect(row).toBeUndefined();
+ });
+ });
+});