π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β»οΈ refactor(page-editor): persist document comments, likes and history through @lobechat/replica (#21114)
Arvin Xu40f68583c83c
diff --git a/src/features/PageEditor/DocumentComments/Gutter/index.tsx b/src/features/PageEditor/DocumentComments/Gutter/index.tsxindex b8d1ec4f45d..959cbd18788 100644--- a/src/features/PageEditor/DocumentComments/Gutter/index.tsx+++ b/src/features/PageEditor/DocumentComments/Gutter/index.tsx@@ -31,9 +31,7 @@ const PanelBody = memo<{ state: DocumentCommentsState }>(({ state }) => {focus,gutterThreads,handleCreate,- handlePinnedRootUpdate,handleReplyFocusMissing,- handleUpdate,isAnchoredInitialError,isAnchoredLoading,isAnchoredRetrying,@@ -42,9 +40,6 @@ const PanelBody = memo<{ state: DocumentCommentsState }>(({ state }) => {refresh,refreshPinned,reloadAnchored,- updatePinnedReplyCount,- updateReplyCount,- updateSummaryTotal,} = state;const { selectedRootId, selectRoot } = useCommentAnchors();const { allowed: canComment } = usePermission('create_content');@@ -143,9 +138,6 @@ const PanelBody = memo<{ state: DocumentCommentsState }>(({ state }) => {root={pinnedThreadInGutter.root}onFocusMissing={handleReplyFocusMissing}onMutated={refreshPinned}- onReplyCountChange={updatePinnedReplyCount}- onRootUpdate={handlePinnedRootUpdate}- onSummaryChange={updateSummaryTotal}/>,)}{gutterThreads.map(({ replyCount, root }) =>@@ -160,9 +152,6 @@ const PanelBody = memo<{ state: DocumentCommentsState }>(({ state }) => {root={root}onFocusMissing={handleReplyFocusMissing}onMutated={refresh}- onReplyCountChange={updateReplyCount}- onRootUpdate={handleUpdate}- onSummaryChange={updateSummaryTotal}/>,),)}diff --git a/src/features/PageEditor/DocumentComments/Thread.tsx b/src/features/PageEditor/DocumentComments/Thread.tsxindex d05c9685211..6f2956de589 100644--- a/src/features/PageEditor/DocumentComments/Thread.tsx+++ b/src/features/PageEditor/DocumentComments/Thread.tsx@@ -4,23 +4,18 @@ import { Fragment, memo, useCallback, useEffect, useMemo, useState } from 'reactimport { useTranslation } from 'react-i18next';import AsyncError from '@/components/AsyncError';-import { documentCommentService } from '@/services/documentComment';+import { documentCommentActions } from '@/store/documentComment';import CommentCard from './CommentCard';import Composer from './Composer';import {+ handleDocumentCommentUpdate,useDocumentCommentDetail,useDocumentCommentReplies,useOptimisticDocumentComment,} from './hooks';-import type { DocumentCommentSubmitInput, DocumentCommentUpdateHandler } from './optimistic';-import {- appendOptimisticReply,- isOptimisticDocumentComment,- removeOptimisticReply,- replaceOptimisticReply,- replaceReplyComment,-} from './optimistic';+import type { DocumentCommentSubmitInput } from './optimistic';+import { isOptimisticDocumentComment } from './optimistic';import { styles } from './styles';import { useAutoLoadReplies } from './useAutoLoadReplies';import type {@@ -37,9 +32,6 @@ interface ThreadProps extends DocumentCommentThread {/** The deep-linked reply is gone from this thread ('missing') or could not be loaded ('failed'). */onFocusMissing?: (reason: DocumentCommentFocusMissReason) => void;onMutated: () => void | Promise<void>;- onReplyCountChange: (rootCommentId: string, delta: number) => void | Promise<unknown>;- onRootUpdate: DocumentCommentUpdateHandler;- onSummaryChange: (delta: number) => void | Promise<unknown>;}/** At most this many placeholder rows while a thread's replies load. */@@ -67,18 +59,7 @@ const ReplySkeleton = memo<{ compact: boolean; count: number }>(({ compact, counReplySkeleton.displayName = 'DocumentCommentReplySkeleton';const Thread = memo<ThreadProps>(- ({- compact = false,- documentId,- focus,- onFocusMissing,- onMutated,- onReplyCountChange,- onRootUpdate,- onSummaryChange,- replyCount,- root,- }) => {+ ({ compact = false, documentId, focus, onFocusMissing, onMutated, replyCount, root }) => {const { t } = useTranslation('file');const [replyTargetId, setReplyTargetId] = useState<string | null>(null);const { containerRef, shouldLoad } = useAutoLoadReplies(replyCount > 0);@@ -95,32 +76,22 @@ const Thread = memo<ThreadProps>(}, [wantsReplies]);const replies = useDocumentCommentReplies(root.id, wantsReplies || repliesLatched);const createOptimistic = useOptimisticDocumentComment();- const mutateReplies = replies.mutate;const reloadReplies = replies.reload;// The linked reply is fetched by id and shown first until it appears on a loaded page- // (replies are oldest-first). It lives in its own cache entry, so thread refreshes+ // (replies are oldest-first). It lives in its own replica entry, so thread refreshes// revalidate it too β a deleted pinned reply must not linger.const hasFocusedReply =Boolean(focusedReplyId) && replies.items.some((item) => item.id === focusedReplyId);const focusedReply = useDocumentCommentDetail(hasFocusedReply ? undefined : focusedReplyId);- const mutateFocusedReply = focusedReply.mutate;+ const pinnedReplyId = hasFocusedReply ? undefined : focusedReplyId;const refreshThread = useCallback(async () => {// A post-delete 404 on the detail entry flows through `isNotFound`; it is not a failure.await Promise.all([reloadReplies(),- mutateFocusedReply().catch(() => undefined),+ pinnedReplyId ? documentCommentActions.revalidateDetail(pinnedReplyId) : undefined,onMutated(),]);- }, [mutateFocusedReply, onMutated, reloadReplies]);- // Reply edits patch the paginated cache; mirror them into the pinned detail entry too.- const patchFocusedReply = useCallback(- (next: DocumentCommentItem) =>- mutateFocusedReply(- (current) => (current && current.id === next.id ? { ...current, ...next } : current),- { revalidate: false },- ),- [mutateFocusedReply],- );+ }, [onMutated, pinnedReplyId, reloadReplies]);// The deep-link target while it is not on a loaded page. It renders on its own, so a// pending or failed page request never hides a reply that was already fetched.const pinnedReply = useMemo(() => {@@ -153,94 +124,20 @@ const Thread = memo<ThreadProps>(replyTo:replyTarget.id === root.id ? null : { author: replyTarget.author, id: replyTarget.id },});- await Promise.all([- mutateReplies((pages) => appendOptimisticReply(pages, optimisticComment), {- revalidate: false,- }),- onReplyCountChange(root.id, 1),- onSummaryChange(1),- ]);-- let created: Awaited<ReturnType<typeof documentCommentService.create>>;- try {- created = await documentCommentService.create({+ // A duplicate (retried) submit re-reads the thread inside the store.+ await documentCommentActions.createReply({+ input: {clientId,content,documentId: replyTarget.documentId,editorData,parentCommentId: replyTarget.id,- });- if (!created) throw new Error('Document comment reply creation returned no result');- } catch (error) {- await Promise.all([- mutateReplies((pages) => removeOptimisticReply(pages, clientId), {- revalidate: false,- }),- onReplyCountChange(root.id, -1),- onSummaryChange(-1),- ]);- throw error;- }-- try {- await mutateReplies((pages) => replaceOptimisticReply(pages, created.comment), {- revalidate: false,- });- } catch (error) {- console.error('Failed to reconcile the created document comment reply', error);- void reloadReplies();- }- if (created.isDuplicate) void refreshThread();- },- [- createOptimistic,- mutateReplies,- onReplyCountChange,- onSummaryChange,- refreshThread,- reloadReplies,- replyTargetId,- root,- visibleReplies,- ],- );- const handleReplyUpdate: DocumentCommentUpdateHandler = useCallback(- async (comment, value) => {- const optimisticComment = { ...comment, ...value, updatedAt: new Date() };- await Promise.all([- mutateReplies((pages) => replaceReplyComment(pages, optimisticComment), {- revalidate: false,- }),- patchFocusedReply(optimisticComment),- ]);-- let updated: Awaited<ReturnType<typeof documentCommentService.update>>;- try {- updated = await documentCommentService.update({ ...value, id: comment.id });- if (!updated) throw new Error('Document comment reply update returned no result');- } catch (error) {- await Promise.all([- mutateReplies((pages) => replaceReplyComment(pages, comment), {- revalidate: false,- }),- patchFocusedReply(comment),- ]);- throw error;- }-- try {- await Promise.all([- mutateReplies((pages) => replaceReplyComment(pages, updated), {- revalidate: false,- }),- patchFocusedReply(updated),- ]);- } catch (error) {- console.error('Failed to reconcile the updated document comment reply', error);- void reloadReplies();- }+ },+ optimisticComment,+ rootCommentId: root.id,+ });},- [mutateReplies, patchFocusedReply, reloadReplies],+ [createOptimistic, replyTargetId, root, visibleReplies],);// NOT_FOUND, or a reply from another thread, means the linked reply is gone; any other@@ -272,7 +169,7 @@ const Thread = memo<ThreadProps>(variant={'reply'}onMutated={refreshThread}onReply={() => toggleReplyTarget(reply.id)}- onUpdate={handleReplyUpdate}+ onUpdate={handleDocumentCommentUpdate}/>{replyTargetId === reply.id && (<Composer@@ -298,7 +195,7 @@ const Thread = memo<ThreadProps>(replying={replyTargetId === root.id}onMutated={onMutated}onReply={() => toggleReplyTarget(root.id)}- onUpdate={onRootUpdate}+ onUpdate={handleDocumentCommentUpdate}/>{(replyCount > 0 || replyTargetId || focusedReplyId) && (diff --git a/src/features/PageEditor/DocumentComments/hooks.test.ts b/src/features/PageEditor/DocumentComments/hooks.test.tsindex 7c4730f338a..d970f3a6674 100644--- a/src/features/PageEditor/DocumentComments/hooks.test.ts+++ b/src/features/PageEditor/DocumentComments/hooks.test.ts@@ -1,7 +1,9 @@import type { DocumentCommentThreadPage } from '@lobechat/types';import { describe, expect, it } from 'vitest';-import { ANCHORED_EAGER_PAGE_LIMIT, nextEagerPageCount, partitionThreadPage } from './hooks';+import { partitionThreadPage } from '@/store/documentComment';++import { ANCHORED_EAGER_PAGE_LIMIT, getFeedPaginationState, shouldLoadEagerPage } from './hooks';const thread = (id: string, anchored: boolean) =>({@@ -17,25 +19,68 @@ const mixedPage: DocumentCommentThreadPage = {nextCursor: 'next',};-describe('nextEagerPageCount', () => {- it('requests one more page while under the budget', () => {- expect(nextEagerPageCount(1, ANCHORED_EAGER_PAGE_LIMIT)).toBe(2);- expect(nextEagerPageCount(ANCHORED_EAGER_PAGE_LIMIT - 1, ANCHORED_EAGER_PAGE_LIMIT)).toBe(- ANCHORED_EAGER_PAGE_LIMIT,- );+const feed = (overrides: Partial<Parameters<typeof shouldLoadEagerPage>[0] & object> = {}) => ({+ currentPage: 0,+ hasMore: true,+ items: [],+ pageSize: 50,+ ...overrides,+});++describe('shouldLoadEagerPage', () => {+ it('asks for one more page while under the budget', () => {+ expect(shouldLoadEagerPage(feed(), ANCHORED_EAGER_PAGE_LIMIT)).toBe(true);+ expect(+ shouldLoadEagerPage(+ feed({ currentPage: ANCHORED_EAGER_PAGE_LIMIT - 2 }),+ ANCHORED_EAGER_PAGE_LIMIT,+ ),+ ).toBe(true);});it('stops at the budget instead of draining every page', () => {- expect(nextEagerPageCount(ANCHORED_EAGER_PAGE_LIMIT, ANCHORED_EAGER_PAGE_LIMIT)).toBe(- ANCHORED_EAGER_PAGE_LIMIT,- );- expect(nextEagerPageCount(ANCHORED_EAGER_PAGE_LIMIT + 3, ANCHORED_EAGER_PAGE_LIMIT)).toBe(- ANCHORED_EAGER_PAGE_LIMIT + 3,- );+ expect(+ shouldLoadEagerPage(+ feed({ currentPage: ANCHORED_EAGER_PAGE_LIMIT - 1 }),+ ANCHORED_EAGER_PAGE_LIMIT,+ ),+ ).toBe(false);});it('never fetches ahead with a zero budget (the panel is closed or it is the document list)', () => {- expect(nextEagerPageCount(1, 0)).toBe(1);+ expect(shouldLoadEagerPage(feed(), 0)).toBe(false);+ });++ it('waits while a page is loading, stops on a failed page, and stops when exhausted', () => {+ expect(shouldLoadEagerPage(feed({ isLoadingMore: true }), 4)).toBe(false);+ expect(shouldLoadEagerPage(feed({ loadMoreError: new Error('x') }), 4)).toBe(false);+ expect(shouldLoadEagerPage(feed({ hasMore: false }), 4)).toBe(false);+ expect(shouldLoadEagerPage(undefined, 4)).toBe(false);+ });+});++describe('getFeedPaginationState', () => {+ it('shows a loading placeholder only while nothing has painted', () => {+ const state = { enabled: true, error: undefined, isValidating: true };+ expect(getFeedPaginationState(undefined, state).isLoadingInitial).toBe(true);+ // A feed hydrated from the replica paints at once, even while revalidating.+ expect(getFeedPaginationState(feed(), state).isLoadingInitial).toBe(false);+ });++ it('keeps a painted feed on a refresh failure and reports an initial error otherwise', () => {+ const state = { enabled: true, error: new Error('offline'), isValidating: false };+ expect(getFeedPaginationState(feed(), state)).toMatchObject({+ hasMore: false,+ isInitialError: false,+ });+ expect(getFeedPaginationState(undefined, state).isInitialError).toBe(true);+ });++ it('is idle while disabled', () => {+ expect(+ getFeedPaginationState(undefined, { enabled: false, error: undefined, isValidating: false })+ .isLoadingInitial,+ ).toBe(false);});});diff --git a/src/features/PageEditor/DocumentComments/hooks.ts b/src/features/PageEditor/DocumentComments/hooks.tsindex 73218ca1a49..48bcf33cff3 100644--- a/src/features/PageEditor/DocumentComments/hooks.ts+++ b/src/features/PageEditor/DocumentComments/hooks.ts@@ -1,100 +1,51 @@-import type {- DocumentCommentAnchorList,- DocumentCommentDetail,- DocumentCommentItem,- DocumentCommentReplyPage,- DocumentCommentSelectionAnchor,- DocumentCommentSummary,- DocumentCommentThreadPage,-} from '@lobechat/types';-import { useCallback, useEffect } from 'react';-import useSWRInfinite from 'swr/infinite';+import type { DocumentCommentItem, DocumentCommentSelectionAnchor } from '@lobechat/types';+import { useCallback, useEffect, useMemo } from 'react';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';-import { useClientDataSWR } from '@/libs/swr';-import { documentCommentKeys } from '@/libs/swr/keys';-import { documentCommentService } from '@/services/documentComment';+import type { ReplicaPagedData } from '@/libs/replica';+import {+ documentCommentActions,+ documentCommentSelectors,+ type DocumentCommentThreadScope,+ useDocumentCommentStore,+} from '@/store/documentComment';import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';import { isTrpcErrorCode } from '@/utils/trpcError';import {createOptimisticComment,+ type DocumentCommentUpdateHandler,flattenDocumentCommentReplies,flattenDocumentCommentThreads,} from './optimistic';-const PAGE_SIZE = 20;-/**- * The gutter needs every anchored thread mounted at once (each card sits at- * its own height), so its pages are fetched at the router's cap and drained- * in the background rather than behind a "load more" button.- */-const ANCHORED_PAGE_SIZE = 50;--export type DocumentCommentThreadScope = 'all' | 'anchored' | 'document';+export type { DocumentCommentThreadScope } from '@/store/documentComment';/**- * Keeps a page to its scope's own subset even when the backend ignored the- * `anchored` parameter β a production server predating it strips the unknown- * key and answers both scopes with the same mixed pages (the documented debug- * proxy runs the latest SPA against exactly that). Without this, the two- * caches overlap and the list below the body renders every such thread- * twice. The cursor still walks the server's own order, so paging stays- * consistent; a page may just carry fewer items than asked for.+ * Paging flags of a replica feed. The feed entry is the data: `undefined`+ * means nothing has painted yet (neither the persisted copy nor the network),+ * which is the only state that shows a loading placeholder.*/-export const partitionThreadPage = (- page: DocumentCommentThreadPage,- scope: DocumentCommentThreadScope,-): DocumentCommentThreadPage => {- if (scope === 'all') return page;- const wantsAnchored = scope === 'anchored';- const items = page.items.filter(({ root }) => Boolean(root.selectionAnchor) === wantsAnchored);- return items.length === page.items.length ? page : { ...page, items };-};--const fetchThreads = async ([, , documentId, cursor, scope]: readonly string[]) => {- const page = await documentCommentService.listThreads({- anchored: scope === 'all' ? undefined : scope === 'anchored',- cursor: cursor || undefined,- documentId,- limit: scope === 'anchored' ? ANCHORED_PAGE_SIZE : PAGE_SIZE,- });- return partitionThreadPage(page, scope as DocumentCommentThreadScope);-};--const fetchReplies = ([, , rootCommentId, cursor]: readonly string[]) =>- documentCommentService.listReplies({- cursor: cursor || undefined,- limit: PAGE_SIZE,- rootCommentId,- });--const getPaginationState = <T extends { nextCursor: string | null }>(- data: T[] | undefined,- error: unknown,- isLoading: boolean,- isValidating: boolean,- size: number,+export const getFeedPaginationState = (+ feed: ReplicaPagedData<unknown, string> | undefined,+ { enabled, error, isValidating }: { enabled: boolean; error: unknown; isValidating: boolean },) => {- const hasLoadedPages = data !== undefined;- const lastPage = data?.findLast(Boolean);-+ const hasError = Boolean(error);return {- hasMore: !error && Boolean(lastPage?.nextCursor),- isInitialError: Boolean(error) && !hasLoadedPages,- isLoadingInitial: !error && isLoading && !hasLoadedPages,- isLoadingMore: !error && hasLoadedPages && size > 0 && typeof data?.[size - 1] === 'undefined',- isRetrying: Boolean(error) && isValidating,+ hasMore: !hasError && Boolean(feed?.hasMore),+ isInitialError: hasError && !feed,+ isLoadingInitial: enabled && !hasError && !feed,+ isLoadingMore: !hasError && Boolean(feed?.isLoadingMore),+ isRetrying: hasError && isValidating,};};-export const useDocumentCommentSummary = (documentId?: string | null) =>- useClientDataSWR<DocumentCommentSummary>(- documentId ? documentCommentKeys.summary(documentId) : null,- () => documentCommentService.summary(documentId!),- { dedupingInterval: 30_000 },- );+export const useDocumentCommentSummary = (documentId?: string | null) => {+ const sync = documentCommentActions.useFetchSummary(documentId);+ const data = useDocumentCommentStore(documentCommentSelectors.summary(documentId));+ return { data, error: sync.error, isLoading: Boolean(documentId) && !data && !sync.error };+};/*** One comment by id. Lists are oldest-first and a notification usually points@@ -103,12 +54,21 @@ export const useDocumentCommentSummary = (documentId?: string | null) =>*/export const useDocumentCommentDetail = (commentId?: string | null) => {const workspaceId = useActiveWorkspaceId();- const response = useClientDataSWR<DocumentCommentDetail>(- commentId && workspaceId ? documentCommentKeys.detail(workspaceId, commentId) : null,- () => documentCommentService.get(commentId!),- );+ const enabledId = workspaceId ? commentId : undefined;+ const sync = documentCommentActions.useFetchDetail(enabledId);+ const data = useDocumentCommentStore(documentCommentSelectors.detail(enabledId));++ return {+ data,+ error: sync.error,+ isNotFound: isTrpcErrorCode(sync.error, 'NOT_FOUND'),+ revalidate: sync.revalidate,+ };+};- return { ...response, isNotFound: isTrpcErrorCode(response.error, 'NOT_FOUND') };+/** Edits go through the store, which patches every painted copy of the comment. */+export const handleDocumentCommentUpdate: DocumentCommentUpdateHandler = async (comment, value) => {+ await documentCommentActions.updateComment(comment, value);};export const useOptimisticDocumentComment = () => {@@ -166,10 +126,9 @@ export const useOptimisticDocumentComment = () => {*/export const useDocumentCommentAnchorList = (documentId?: string | null) => {const workspaceId = useActiveWorkspaceId();- return useClientDataSWR<DocumentCommentAnchorList>(- documentId && workspaceId ? documentCommentKeys.anchors(workspaceId, documentId) : null,- () => documentCommentService.listAnchors(documentId!),- );+ const enabledId = workspaceId ? documentId : undefined;+ documentCommentActions.useFetchAnchors(enabledId);+ return useDocumentCommentStore(documentCommentSelectors.anchorList(enabledId));};/**@@ -181,9 +140,17 @@ export const useDocumentCommentAnchorList = (documentId?: string | null) => {*/export const ANCHORED_EAGER_PAGE_LIMIT = 4;-/** The page count to request next while draining ahead of demand, capped at `limit`. */-export const nextEagerPageCount = (current: number, limit: number) =>- current < limit ? current + 1 : current;+/** Whether the eager drain should ask for the next page now. */+export const shouldLoadEagerPage = (+ feed: ReplicaPagedData<unknown, string> | undefined,+ limit: number,+) =>+ Boolean(feed) &&+ feed!.hasMore &&+ !feed!.isLoadingMore &&+ // A failed page stops the drain; the reader retries it explicitly.+ !feed!.loadMoreError &&+ feed!.currentPage + 1 < limit;export const useDocumentCommentThreads = (documentId?: string | null,@@ -199,46 +166,48 @@ export const useDocumentCommentThreads = (} = {},) => {const workspaceId = useActiveWorkspaceId();- const getKey = useCallback(- (_index: number, previous: DocumentCommentThreadPage | null) => {- if (!documentId || !workspaceId || previous?.nextCursor === null) return null;- return documentCommentKeys.threads(- workspaceId,- documentId,- previous?.nextCursor ?? undefined,- scope,- );- },+ const params = useMemo(+ () => (documentId && workspaceId ? { documentId, scope } : null),[documentId, scope, workspaceId],);- const response = useSWRInfinite<DocumentCommentThreadPage>(getKey, fetchThreads, {- revalidateFirstPage: false,+ const sync = documentCommentActions.useFetchThreads(params);+ const feed = useDocumentCommentStore(documentCommentSelectors.threadFeed(params));+ // A head refresh failure, or a failed "load more" page.+ const error = (sync.error ?? feed?.loadMoreError) as Error | undefined;+ const pagination = getFeedPaginationState(feed, {+ enabled: Boolean(params),+ error,+ isValidating: sync.isValidating,});- const pagination = getPaginationState(- response.data,- response.error,- response.isLoading,- response.isValidating,- response.size,- );- const { setSize, size } = response;- const { hasMore, isLoadingMore } = pagination;// Fetch ahead of demand up to the caller's budget: for the gutter, a card// it has not loaded is a highlight with nothing beside it. The budget keeps// a document with hundreds of anchored roots from mounting every one of- // them (twice β gutter and list) before the reader has looked at any.+ // them (twice β gutter and list) before the reader has looked at any. A+ // feed painted from storage does not page until the network confirms its+ // head (its cursor may be stale); the confirmed head re-runs this.useEffect(() => {- if (!hasMore || isLoadingMore || size >= eagerPageLimit) return;- void setSize((current) => nextEagerPageCount(current, eagerPageLimit));- }, [eagerPageLimit, hasMore, isLoadingMore, setSize, size]);+ if (!params || !shouldLoadEagerPage(feed, eagerPageLimit)) return;+ void documentCommentActions.loadMoreThreads(params);+ }, [eagerPageLimit, feed, params]);++ const items = useMemo(() => flattenDocumentCommentThreads(feed?.items), [feed?.items]);+ const loadMore = useCallback(+ () => (params ? documentCommentActions.loadMoreThreads(params) : Promise.resolve()),+ [params],+ );+ const reload = useCallback(+ () => (params ? documentCommentActions.revalidateThreads(params) : Promise.resolve()),+ [params],+ );return {- ...response,...pagination,- items: flattenDocumentCommentThreads(response.data),- loadMore: () => setSize((current) => current + 1),- reload: () => response.mutate(),+ error,+ isValidating: sync.isValidating,+ items,+ loadMore,+ reload,};};@@ -247,32 +216,34 @@ export const useDocumentCommentReplies = (enabled: boolean,) => {const workspaceId = useActiveWorkspaceId();- const getKey = useCallback(- (_index: number, previous: DocumentCommentReplyPage | null) => {- if (!enabled || !rootCommentId || !workspaceId || previous?.nextCursor === null) return null;- return documentCommentKeys.replies(- workspaceId,- rootCommentId,- previous?.nextCursor ?? undefined,- );- },- [enabled, rootCommentId, workspaceId],+ const enabledId = workspaceId ? rootCommentId : undefined;+ const sync = documentCommentActions.useFetchReplies(enabledId, enabled);+ const feed = useDocumentCommentStore(+ documentCommentSelectors.replyFeed(enabled ? enabledId : undefined),+ );+ // A head refresh failure, or a failed "load more" page.+ const error = (sync.error ?? feed?.loadMoreError) as Error | undefined;++ const items = useMemo(() => flattenDocumentCommentReplies(feed?.items), [feed?.items]);+ const loadMore = useCallback(+ () => (enabledId ? documentCommentActions.loadMoreReplies(enabledId) : Promise.resolve()),+ [enabledId],+ );+ const reload = useCallback(+ () => (enabledId ? documentCommentActions.revalidateReplies(enabledId) : Promise.resolve()),+ [enabledId],);- const response = useSWRInfinite<DocumentCommentReplyPage>(getKey, fetchReplies, {- revalidateFirstPage: false,- });return {- ...response,- ...getPaginationState(- response.data,- response.error,- response.isLoading,- response.isValidating,- response.size,- ),- items: flattenDocumentCommentReplies(response.data),- loadMore: () => response.setSize((current) => current + 1),- reload: () => response.mutate(),+ error,+ isValidating: sync.isValidating,+ ...getFeedPaginationState(feed, {+ enabled: enabled && Boolean(enabledId),+ error,+ isValidating: sync.isValidating,+ }),+ items,+ loadMore,+ reload,};};diff --git a/src/features/PageEditor/DocumentComments/index.tsx b/src/features/PageEditor/DocumentComments/index.tsxindex 07798ca6223..5d9c61ef407 100644--- a/src/features/PageEditor/DocumentComments/index.tsx+++ b/src/features/PageEditor/DocumentComments/index.tsx@@ -48,9 +48,7 @@ const DocumentCommentList = memo<{ state: DocumentCommentsState }>(({ state }) =focus,gutterThreads,handleCreate,- handlePinnedRootUpdate,handleReplyFocusMissing,- handleUpdate,hasMoreListThreads,isAnchoredInitialError,isAnchoredLoading,@@ -65,9 +63,6 @@ const DocumentCommentList = memo<{ state: DocumentCommentsState }>(({ state }) =refreshPinned,reloadAnchored,summary,- updatePinnedReplyCount,- updateReplyCount,- updateSummaryTotal,} = state;const isLoadingInitial = documentThreads.isLoadingInitial || isAnchoredLoading;const isHeaderLoading = isLoadingInitial || (summary.isLoading && !summary.data);@@ -127,9 +122,6 @@ const DocumentCommentList = memo<{ state: DocumentCommentsState }>(({ state }) =replyCount={pinnedThreadInList.replyCount}root={pinnedThreadInList.root}onMutated={refreshPinned}- onReplyCountChange={updatePinnedReplyCount}- onRootUpdate={handlePinnedRootUpdate}- onSummaryChange={updateSummaryTotal}onFocusMissing={listThreadOwnsFocusMiss(gutterShownIds, pinnedThreadInList.root.id)? handleReplyFocusMissing@@ -146,9 +138,6 @@ const DocumentCommentList = memo<{ state: DocumentCommentsState }>(({ state }) =replyCount={replyCount}root={root}onMutated={refresh}- onReplyCountChange={updateReplyCount}- onRootUpdate={handleUpdate}- onSummaryChange={updateSummaryTotal}onFocusMissing={listThreadOwnsFocusMiss(gutterShownIds, root.id)? handleReplyFocusMissingdiff --git a/src/features/PageEditor/DocumentComments/optimistic.test.ts b/src/features/PageEditor/DocumentComments/optimistic.test.tsindex f8435b5f07e..7c1a78cecb8 100644--- a/src/features/PageEditor/DocumentComments/optimistic.test.ts+++ b/src/features/PageEditor/DocumentComments/optimistic.test.ts@@ -2,18 +2,9 @@ import type { DocumentCommentItem } from '@lobechat/types';import { describe, expect, it } from 'vitest';import {- appendOptimisticReply,- appendOptimisticThread,- createOptimisticComment,flattenDocumentCommentReplies,+ flattenDocumentCommentThreads,isOptimisticDocumentComment,- removeOptimisticReply,- removeOptimisticThread,- replaceOptimisticReply,- replaceOptimisticThread,- replaceReplyComment,- replaceThreadComment,- updateThreadReplyCount,} from './optimistic';const createComment = (@@ -51,55 +42,32 @@ describe('document comment optimistic cache', () => {expect(isOptimisticDocumentComment({ id: 'dcm_server' })).toBe(false);});- it('adds, reconciles, and rolls back a root comment without a refetch', () => {- const optimistic = createOptimisticComment({- author: createComment('author').author,- clientId: 'pending-root',- content: 'pending',- documentId: 'document-1',- editorData: null,- userId: 'user-1',- workspaceId: 'workspace-1',- });- const initial = [- { items: [{ replyCount: 0, root: createComment('root-1') }], nextCursor: null },- ];- const inserted = appendOptimisticThread(initial, optimistic);-- expect(inserted[0].items.map(({ root }) => root.id)).toEqual([- 'root-1',- 'optimistic:pending-root',- ]);-- const serverComment = { ...optimistic, canDelete: true, canEdit: true, id: 'root-2' };- expect(replaceOptimisticThread(inserted, serverComment)?.[0].items.at(-1)?.root).toEqual(- serverComment,- );- expect(removeOptimisticThread(inserted, optimistic.clientId)?.[0].items).toHaveLength(1);- });-- it('keeps optimistic replies oldest-first across paginated data and maintains totals', () => {+ it('keeps replies oldest-first, an optimistic one last', () => {const first = createComment('reply-1', new Date('2026-01-01T00:00:01Z'));const second = createComment('reply-2', new Date('2026-01-01T00:00:02Z'));const optimistic = createComment('optimistic:pending', new Date('2026-01-01T00:00:03Z'));- optimistic.clientId = 'pending-reply';- const initial = [{ items: [first], nextCursor: 'next', total: 2 }];- const inserted = appendOptimisticReply(initial, optimistic);- const withNextPage = [...inserted, { items: [second], nextCursor: null }];- expect(flattenDocumentCommentReplies(withNextPage).map(({ id }) => id)).toEqual([+ expect(flattenDocumentCommentReplies([second, optimistic, first]).map(({ id }) => id)).toEqual(['reply-1','reply-2','optimistic:pending',]);- expect(inserted[0].total).toBe(3);+ });++ it('sorts roots oldest-first and drops duplicate rows', () => {+ const older = createComment('root-1', new Date('2026-01-01T00:00:01Z'));+ const newer = createComment('root-2', new Date('2026-01-01T00:00:02Z'));- const serverComment = { ...optimistic, id: 'reply-3' };- expect(replaceOptimisticReply(inserted, serverComment)?.[0].items.at(-1)).toEqual(- serverComment,- );- const rolledBack = removeOptimisticReply(inserted, optimistic.clientId);- expect(rolledBack?.[0]).toMatchObject({ items: [first], total: 2 });+ expect(+ flattenDocumentCommentThreads([+ { replyCount: 0, root: newer },+ { replyCount: 0, root: older },+ { replyCount: 1, root: newer },+ ]).map(({ replyCount, root }) => [root.id, replyCount]),+ ).toEqual([+ ['root-1', 0],+ ['root-2', 1],+ ]);});it('places replies to replies next to their target while keeping a single flat list', () => {@@ -119,44 +87,9 @@ describe('document comment optimistic cache', () => {};expect(- flattenDocumentCommentReplies([- { items: [first, second, child, grandchild, sibling], nextCursor: null },- ]).map(({ id }) => id),+ flattenDocumentCommentReplies([first, second, child, grandchild, sibling]).map(+ ({ id }) => id,+ ),).toEqual(['reply-1', 'reply-1-child', 'reply-1-grandchild', 'reply-1-sibling', 'reply-2']);});-- it('updates a thread reply count without affecting other threads', () => {- const pages = [- {- items: [- { replyCount: 1, root: createComment('root-1') },- { replyCount: 3, root: createComment('root-2') },- ],- nextCursor: null,- },- ];-- expect(updateThreadReplyCount(pages, 'root-1', 1)?.[0].items).toMatchObject([- { replyCount: 2, root: { id: 'root-1' } },- { replyCount: 3, root: { id: 'root-2' } },- ]);- });-- it('optimistically replaces root and reply content by their server ids', () => {- const root = createComment('root-1');- const reply = createComment('reply-1');- const updatedRoot = { ...root, content: 'updated root' };- const updatedReply = { ...reply, content: 'updated reply' };-- expect(- replaceThreadComment(- [{ items: [{ replyCount: 1, root }], nextCursor: null }],- updatedRoot,- )?.[0].items[0].root.content,- ).toBe('updated root');- expect(- replaceReplyComment([{ items: [reply], nextCursor: null }], updatedReply)?.[0].items[0]- .content,- ).toBe('updated reply');- });});diff --git a/src/features/PageEditor/DocumentComments/optimistic.ts b/src/features/PageEditor/DocumentComments/optimistic.tsindex df53e2c566e..7e1747b754d 100644--- a/src/features/PageEditor/DocumentComments/optimistic.ts+++ b/src/features/PageEditor/DocumentComments/optimistic.ts@@ -2,11 +2,12 @@ import type {DocumentCommentAuthor,DocumentCommentItem,DocumentCommentJson,- DocumentCommentReplyPage,DocumentCommentSelectionAnchor,- DocumentCommentThreadPage,+ DocumentCommentThread,} from '@lobechat/types';+import type { DocumentCommentEditorValue } from '@/store/documentComment';+interface CreateOptimisticCommentParams {author: DocumentCommentAuthor;clientId: string;@@ -28,10 +29,7 @@ export interface DocumentCommentSubmitInput {selectionAnchor?: DocumentCommentSelectionAnchor;}-export interface DocumentCommentEditorValue {- content: string;- editorData: DocumentCommentJson;-}+export type { DocumentCommentEditorValue };export type DocumentCommentUpdateHandler = (comment: DocumentCommentItem,@@ -46,17 +44,17 @@ const compareComments = (first: DocumentCommentItem, second: DocumentCommentItemreturn timeDelta || first.id.localeCompare(second.id);};-export const flattenDocumentCommentThreads = (pages: DocumentCommentThreadPage[] | undefined) => {- const threads = new Map<string, DocumentCommentThreadPage['items'][number]>();- for (const thread of pages?.flatMap((page) => page.items) ?? []) {- threads.set(thread.root.id, thread);- }+/** A feed's roots, oldest first (an optimistic root sorts by its client-side time). */+export const flattenDocumentCommentThreads = (items: DocumentCommentThread[] | undefined) => {+ const threads = new Map<string, DocumentCommentThread>();+ for (const thread of items ?? []) threads.set(thread.root.id, thread);return [...threads.values()].sort((first, second) => compareComments(first.root, second.root));};-export const flattenDocumentCommentReplies = (pages: DocumentCommentReplyPage[] | undefined) => {+/** A thread's replies, oldest first, each reply-to-reply placed right after its target. */+export const flattenDocumentCommentReplies = (items: DocumentCommentItem[] | undefined) => {const replies = new Map<string, DocumentCommentItem>();- for (const reply of pages?.flatMap((page) => page.items) ?? []) replies.set(reply.id, reply);+ for (const reply of items ?? []) replies.set(reply.id, reply);const chronologicalReplies = [...replies.values()].sort(compareComments);const childrenByReplyId = new Map<string, DocumentCommentItem[]>();const threadReplies: DocumentCommentItem[] = [];@@ -120,116 +118,3 @@ export const createOptimisticComment = ({workspaceId,};};--export const appendOptimisticThread = (- pages: DocumentCommentThreadPage[] | undefined,- comment: DocumentCommentItem,-): DocumentCommentThreadPage[] => {- if (!pages?.length) return [{ items: [{ replyCount: 0, root: comment }], nextCursor: null }];- if (pages.some((page) => page.items.some(({ root }) => root.clientId === comment.clientId))) {- return pages;- }-- const nextPages = [...pages];- const lastPage = nextPages.at(-1)!;- nextPages[nextPages.length - 1] = {- ...lastPage,- items: [...lastPage.items, { replyCount: 0, root: comment }],- };- return nextPages;-};--export const replaceOptimisticThread = (- pages: DocumentCommentThreadPage[] | undefined,- comment: DocumentCommentItem,-) =>- pages?.map((page) => ({- ...page,- items: page.items.map((thread) =>- thread.root.clientId === comment.clientId ? { ...thread, root: comment } : thread,- ),- }));--export const replaceThreadComment = (- pages: DocumentCommentThreadPage[] | undefined,- comment: DocumentCommentItem,-) =>- pages?.map((page) => ({- ...page,- items: page.items.map((thread) =>- thread.root.id === comment.id ? { ...thread, root: comment } : thread,- ),- }));--export const removeOptimisticThread = (- pages: DocumentCommentThreadPage[] | undefined,- clientId: string,-) =>- pages?.map((page) => ({- ...page,- items: page.items.filter(({ root }) => root.clientId !== clientId),- }));--export const appendOptimisticReply = (- pages: DocumentCommentReplyPage[] | undefined,- comment: DocumentCommentItem,-): DocumentCommentReplyPage[] => {- if (!pages?.length) return [{ items: [comment], nextCursor: null, total: 1 }];- if (pages.some((page) => page.items.some((item) => item.clientId === comment.clientId))) {- return pages;- }-- const nextPages = [...pages];- const lastPage = nextPages.at(-1)!;- nextPages[nextPages.length - 1] = {- ...lastPage,- items: [...lastPage.items, comment],- ...(lastPage.total === undefined ? {} : { total: lastPage.total + 1 }),- };- return nextPages;-};--export const replaceOptimisticReply = (- pages: DocumentCommentReplyPage[] | undefined,- comment: DocumentCommentItem,-) =>- pages?.map((page) => ({- ...page,- items: page.items.map((item) => (item.clientId === comment.clientId ? comment : item)),- }));--export const replaceReplyComment = (- pages: DocumentCommentReplyPage[] | undefined,- comment: DocumentCommentItem,-) =>- pages?.map((page) => ({- ...page,- items: page.items.map((item) => (item.id === comment.id ? comment : item)),- }));--export const removeOptimisticReply = (- pages: DocumentCommentReplyPage[] | undefined,- clientId: string,-) =>- pages?.map((page) => {- const removedCount = page.items.filter((item) => item.clientId === clientId).length;- return {- ...page,- items: page.items.filter((item) => item.clientId !== clientId),- ...(page.total === undefined ? {} : { total: Math.max(0, page.total - removedCount) }),- };- });--export const updateThreadReplyCount = (- pages: DocumentCommentThreadPage[] | undefined,- rootCommentId: string,- delta: number,-) =>- pages?.map((page) => ({- ...page,- items: page.items.map((thread) =>- thread.root.id === rootCommentId- ? { ...thread, replyCount: Math.max(0, thread.replyCount + delta) }- : thread,- ),- }));diff --git a/src/features/PageEditor/DocumentComments/useDocumentCommentsState.ts b/src/features/PageEditor/DocumentComments/useDocumentCommentsState.tsindex 60bcc459ecd..687f2a55821 100644--- a/src/features/PageEditor/DocumentComments/useDocumentCommentsState.ts+++ b/src/features/PageEditor/DocumentComments/useDocumentCommentsState.ts@@ -1,16 +1,12 @@'use client';-import type {- DocumentCommentAnchorItem,- DocumentCommentThread,- DocumentCommentThreadPage,-} from '@lobechat/types';+import type { DocumentCommentAnchorItem, DocumentCommentThread } from '@lobechat/types';import { toast } from '@lobehub/ui';import { type RefObject, useCallback, useEffect, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';-import { documentCommentService } from '@/services/documentComment';+import { documentCommentActions } from '@/store/documentComment';import { useDocumentCommentAnchors } from './anchor/useDocumentCommentAnchors';import {@@ -21,23 +17,12 @@ import {useDocumentCommentThreads,useOptimisticDocumentComment,} from './hooks';-import type { DocumentCommentSubmitInput, DocumentCommentUpdateHandler } from './optimistic';-import {- appendOptimisticThread,- removeOptimisticThread,- replaceOptimisticThread,- replaceThreadComment,- updateThreadReplyCount,-} from './optimistic';+import type { DocumentCommentSubmitInput } from './optimistic';import {type DocumentCommentFocusMissReason,useDocumentCommentDeepLink,} from './useDocumentCommentDeepLink';-type PageMutator = (- pages: DocumentCommentThreadPage[] | undefined,-) => DocumentCommentThreadPage[] | undefined;-export interface DocumentCommentsStateOptions {documentId: string;/**@@ -53,12 +38,11 @@ export interface DocumentCommentsStateOptions {}/**- * Everything the two comment surfaces share: the paged thread caches, the- * optimistic write-through handlers, the deep-link landing and the anchor- * resolution. Anchored roots and document-level roots are paged separately- * (see `listThreads`' `anchored` filter) because they render in different- * places; a write goes to whichever cache the comment belongs in, and a patch- * that could apply to either is applied to both.+ * Everything the two comment surfaces share: the root feeds, the write+ * handlers, the deep-link landing and the anchor resolution. Anchored roots+ * and document-level roots are separate replica feeds (see `listThreads`'+ * `anchored` filter) because they render in different places; the store+ * routes each write to the feed the comment belongs in.*/export const useDocumentCommentsState = ({documentId,@@ -80,142 +64,22 @@ export const useDocumentCommentsState = ({const anchorList = useDocumentCommentAnchorList(enabledDocumentId);const createOptimistic = useOptimisticDocumentComment();const { clearFocus, focus, focusRoot, focusThread } = useDocumentCommentDeepLink(documentId);- const reloadSummary = summary.mutate;const reloadAnchored = anchoredThreads.reload;- const reloadDocument = documentThreads.reload;- const mutateAnchored = anchoredThreads.mutate;- const mutateDocument = documentThreads.mutate;- const mutateAnchors = anchorList.mutate;- const mutateBoth = useCallback(- (mutator: PageMutator) =>- Promise.all([- mutateAnchored(mutator, { revalidate: false }),- mutateDocument(mutator, { revalidate: false }),- ]),- [mutateAnchored, mutateDocument],- );- const reloadThreads = useCallback(- () => Promise.all([reloadAnchored(), reloadDocument()]),- [reloadAnchored, reloadDocument],- );- const refresh = useCallback(async () => {- await Promise.all([reloadThreads(), reloadSummary(), mutateAnchors()]);- }, [mutateAnchors, reloadSummary, reloadThreads]);- const updateSummaryTotal = useCallback(- (delta: number) =>- reloadSummary(- (current) =>- current ? { ...current, total: Math.max(0, current.total + delta) } : current,- { revalidate: false },- ),- [reloadSummary],- );- const updateReplyCount = useCallback(- (rootCommentId: string, delta: number) =>- mutateBoth((pages) => updateThreadReplyCount(pages, rootCommentId, delta)),- [mutateBoth],+ const refresh = useCallback(+ () => documentCommentActions.revalidateDocument(documentId),+ [documentId],);const handleCreate = useCallback(async ({ clientId, content, editorData, selectionAnchor }: DocumentCommentSubmitInput) => {- // A root lives in exactly one of the two caches, decided by its anchor.- const mutateOwn = selectionAnchor ? mutateAnchored : mutateDocument;- const reloadOwn = selectionAnchor ? reloadAnchored : reloadDocument;- const optimisticComment = createOptimistic({- clientId,- content,- documentId,- editorData,- selectionAnchor,+ const input = { clientId, content, documentId, editorData, selectionAnchor };+ await documentCommentActions.createRootComment({+ input,+ optimisticComment: createOptimistic(input),});- await Promise.all([- mutateOwn((pages) => appendOptimisticThread(pages, optimisticComment), {- revalidate: false,- }),- updateSummaryTotal(1),- ]);-- let created: Awaited<ReturnType<typeof documentCommentService.create>>;- try {- created = await documentCommentService.create({- clientId,- content,- documentId,- editorData,- selectionAnchor,- });- if (!created) throw new Error('Document comment creation returned no result');- } catch (error) {- await Promise.all([- mutateOwn((pages) => removeOptimisticThread(pages, clientId), { revalidate: false }),- updateSummaryTotal(-1),- ]);- throw error;- }-- try {- await mutateOwn((pages) => replaceOptimisticThread(pages, created.comment), {- revalidate: false,- });- } catch (error) {- console.error('Failed to reconcile the created document comment', error);- void reloadOwn();- }- if (created.isDuplicate) void reloadSummary();- // The body paints from the document-wide anchor list, so the new root- // joins it here rather than waiting for the next revalidation.- const createdAnchor = created.comment.selectionAnchor;- if (createdAnchor) {- void mutateAnchors(- (current) =>- current && !current.items.some(({ id }) => id === created.comment.id)- ? {- items: [- ...current.items,- { id: created.comment.id, selectionAnchor: createdAnchor },- ],- }- : current,- { revalidate: false },- );- }},- [- createOptimistic,- documentId,- mutateAnchored,- mutateAnchors,- mutateDocument,- reloadAnchored,- reloadDocument,- reloadSummary,- updateSummaryTotal,- ],+ [createOptimistic, documentId],);- const handleUpdate: DocumentCommentUpdateHandler = useCallback(- async (comment, value) => {- const optimisticComment = { ...comment, ...value, updatedAt: new Date() };- await mutateBoth((pages) => replaceThreadComment(pages, optimisticComment));-- let updated: Awaited<ReturnType<typeof documentCommentService.update>>;- try {- updated = await documentCommentService.update({ ...value, id: comment.id });- if (!updated) throw new Error('Document comment update returned no result');- } catch (error) {- await mutateBoth((pages) => replaceThreadComment(pages, comment));- throw error;- }-- try {- await mutateBoth((pages) => replaceThreadComment(pages, updated));- } catch (error) {- console.error('Failed to reconcile the updated document comment', error);- void reloadThreads();- }- },- [mutateBoth, reloadThreads],- );-// Deep-link landing. Lists are oldest-first and a notification usually points at the// newest comment, so the target root is fetched by id and pinned above the list until it// shows up on a loaded page. NOT_FOUND, a non-root id, or a root from another document@@ -244,7 +108,7 @@ export const useDocumentCommentsState = ({// root has no server row yet, and a pinned root may predate the last fetch.const anchorItems = useMemo(() => {const byId = new Map<string, DocumentCommentAnchorItem>();- for (const { id, selectionAnchor } of anchorList.data?.items ?? []) {+ for (const { id, selectionAnchor } of anchorList?.items ?? []) {byId.set(id, { id, selectionAnchor });}const loaded = pinnedThread ? [pinnedThread, ...anchoredThreads.items] : anchoredThreads.items;@@ -254,7 +118,7 @@ export const useDocumentCommentsState = ({}}return [...byId.values()];- }, [anchorList.data, pinnedThread, anchoredThreads.items]);+ }, [anchorList, pinnedThread, anchoredThreads.items]);const anchors = useDocumentCommentAnchors(anchorItems, {hasGutter: panelAvailable,onPickUnloaded: focusThread,@@ -288,41 +152,15 @@ export const useDocumentCommentsState = ({if (isFocusedRootMissing) handleFocusMissing();else if (isFocusedRootFailed) handleFocusFailed();}, [handleFocusFailed, handleFocusMissing, isFocusedRootFailed, isFocusedRootMissing]);- // The pinned root lives in its own detail entry, so the list handlers (which only patch- // the paginated caches) are mirrored into it; a post-delete 404 flows through- // `isNotFound` and is not a refresh failure.- const mutateFocusedRoot = focusedRoot.mutate;+ // The pinned root lives in its own detail entry, which the store patches on+ // every write; a refresh re-reads it too, and a post-delete 404 flows+ // through `isNotFound` β it is not a refresh failure.const refreshPinned = useCallback(async () => {- await Promise.all([mutateFocusedRoot().catch(() => undefined), refresh()]);- }, [mutateFocusedRoot, refresh]);- const updatePinnedReplyCount = useCallback(- async (rootCommentId: string, delta: number) => {- await Promise.all([- updateReplyCount(rootCommentId, delta),- mutateFocusedRoot(- (current) =>- current && current.id === rootCommentId- ? { ...current, replyCount: Math.max(0, current.replyCount + delta) }- : current,- { revalidate: false },- ),- ]);- },- [mutateFocusedRoot, updateReplyCount],- );- const handlePinnedRootUpdate: DocumentCommentUpdateHandler = useCallback(- async (comment, value) => {- await handleUpdate(comment, value);- await mutateFocusedRoot(- (current) =>- current && current.id === comment.id- ? { ...current, ...value, updatedAt: new Date() }- : current,- { revalidate: false },- );- },- [handleUpdate, mutateFocusedRoot],- );+ await Promise.all([+ focusRootCommentId ? documentCommentActions.revalidateDetail(focusRootCommentId) : undefined,+ refresh(),+ ]);+ }, [focusRootCommentId, refresh]);/** A thread belongs in the gutter when it has a run to sit beside. */const isGutterThread = useCallback(@@ -371,9 +209,7 @@ export const useDocumentCommentsState = ({gutterEnabled,gutterThreads,handleCreate,- handlePinnedRootUpdate,handleReplyFocusMissing,- handleUpdate,hasMoreListThreads,isAnchoredInitialError: anchoredThreads.isInitialError,isAnchoredLoading: anchoredThreads.isLoadingInitial,@@ -390,9 +226,6 @@ export const useDocumentCommentsState = ({refreshPinned,reloadAnchored,summary,- updatePinnedReplyCount,- updateReplyCount,- updateSummaryTotal,workspaceId,};};diff --git a/src/features/PageEditor/DocumentLikes/index.tsx b/src/features/PageEditor/DocumentLikes/index.tsxindex a345c8dd808..06309df25c7 100644--- a/src/features/PageEditor/DocumentLikes/index.tsx+++ b/src/features/PageEditor/DocumentLikes/index.tsx@@ -9,9 +9,12 @@ import { useTranslation } from 'react-i18next';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import AsyncError from '@/components/AsyncError';import UserAvatar from '@/components/UserAvatar';-import { useClientDataSWR } from '@/libs/swr';-import { documentLikeKeys } from '@/libs/swr/keys';import { documentLikeService } from '@/services/documentLike';+import {+ documentCommentActions,+ documentCommentSelectors,+ useDocumentCommentStore,+} from '@/store/documentComment';import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';@@ -109,18 +112,22 @@ const styles = createStaticStyles(({ css }) => ({`,}));-const useDocumentLikeSummary = (workspaceId: string | null, documentId?: string | null) =>- useClientDataSWR<DocumentLikeSummary>(- workspaceId && documentId ? documentLikeKeys.summary(workspaceId, documentId) : null,- () => documentLikeService.summary(documentId!),- { dedupingInterval: 30_000 },- );+/**+ * The like summary paints from its replica: a reload shows the last confirmed+ * count and likers on the first frame, and the network confirms it.+ */+const useDocumentLikeSummary = (workspaceId: string | null, documentId?: string | null) => {+ const enabledId = workspaceId ? documentId : undefined;+ const { error, revalidate } = documentCommentActions.useFetchLikeSummary(enabledId);+ const data = useDocumentCommentStore(documentCommentSelectors.likeSummary(enabledId));+ return { data, error, isLoading: Boolean(enabledId) && !data && !error, revalidate };+};const DocumentLikes = memo<{ documentId: string }>(({ documentId }) => {const { t } = useTranslation('file');const workspaceId = useActiveWorkspaceId();const user = useUserStore(userProfileSelectors.userProfile);- const { data, error, isLoading, mutate } = useDocumentLikeSummary(workspaceId, documentId);+ const { data, error, isLoading, revalidate } = useDocumentLikeSummary(workspaceId, documentId);// Last user-intended liked state; null when the UI matches the server.const targetRef = useRef<boolean | null>(null);const inFlightRef = useRef(false);@@ -132,6 +139,8 @@ const DocumentLikes = memo<{ documentId: string }>(({ documentId }) => {const drain = useCallback(async () => {if (inFlightRef.current) return;inFlightRef.current = true;+ // Answers settle under the identity this drain started in (see beginLikeSettle).+ const settle = documentCommentActions.beginLikeSettle(documentId);let sent: boolean | undefined;try {let summary: DocumentLikeSummary | undefined;@@ -142,7 +151,7 @@ const DocumentLikes = memo<{ documentId: string }>(({ documentId }) => {: await documentLikeService.unlike(documentId);}targetRef.current = null;- if (summary) await mutate(summary, { revalidate: false });+ if (summary) settle.confirm(summary);} catch (toggleError) {console.error('Failed to toggle document like', toggleError);targetRef.current = null;@@ -150,13 +159,13 @@ const DocumentLikes = memo<{ documentId: string }>(({ documentId }) => {// Recover the truth from the server rather than guessing a rollback// point across coalesced toggles. The recovery fetch itself can fail// (e.g. an outage) β swallow it so drain() never rejects out of a void- // call; SWR revalidates again on the next focus/interval and corrects+ // call; the replica revalidates again on the next focus and corrects// any stale optimistic state then.- await mutate().catch(() => undefined);+ await settle.refresh().catch(() => undefined);} finally {inFlightRef.current = false;}- }, [documentId, mutate, t]);+ }, [documentId, t]);const toggle = useCallback(() => {if (!data) return;@@ -164,33 +173,29 @@ const DocumentLikes = memo<{ documentId: string }>(({ documentId }) => {const nextLiked = !(targetRef.current ?? data.liked);targetRef.current = nextLiked;- void mutate(- (previous) => {- if (!previous) return previous;- return nextLiked- ? {- liked: true,- likers: [- {- avatar: user?.avatar ?? null,- fullName: user?.fullName ?? null,- id: user?.id ?? 'me',- username: user?.username ?? null,- },- ...previous.likers.filter((liker) => liker.id !== (user?.id ?? 'me')),- ],- total: previous.total + 1,- }- : {- liked: false,- likers: previous.likers.filter((liker) => liker.id !== (user?.id ?? 'me')),- total: Math.max(0, previous.total - 1),- };- },- { revalidate: false },+ documentCommentActions.applyLikeSummary(documentId, (previous) =>+ nextLiked+ ? {+ liked: true,+ likers: [+ {+ avatar: user?.avatar ?? null,+ fullName: user?.fullName ?? null,+ id: user?.id ?? 'me',+ username: user?.username ?? null,+ },+ ...previous.likers.filter((liker) => liker.id !== (user?.id ?? 'me')),+ ],+ total: previous.total + 1,+ }+ : {+ liked: false,+ likers: previous.likers.filter((liker) => liker.id !== (user?.id ?? 'me')),+ total: Math.max(0, previous.total - 1),+ },);void drain();- }, [data, drain, mutate, user?.avatar, user?.fullName, user?.id, user?.username]);+ }, [data, documentId, drain, user?.avatar, user?.fullName, user?.id, user?.username]);if (!workspaceId) return null;@@ -202,7 +207,7 @@ const DocumentLikes = memo<{ documentId: string }>(({ documentId }) => {if (sectionState === 'error')return (<Flexbox data-document-likes align={'center'} className={styles.section} gap={16}>- <AsyncError error={error} variant={'inline'} onRetry={() => void mutate()} />+ <AsyncError error={error} variant={'inline'} onRetry={() => void revalidate()} /></Flexbox>);diff --git a/src/features/PageEditor/History/DocumentHistoryDiff.tsx b/src/features/PageEditor/History/DocumentHistoryDiff.tsxindex f30b5bd8dfb..3c814ba042e 100644--- a/src/features/PageEditor/History/DocumentHistoryDiff.tsx+++ b/src/features/PageEditor/History/DocumentHistoryDiff.tsx@@ -9,9 +9,6 @@ import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';import CircleLoading from '@/components/Loading/CircleLoading';-import { useClientDataSWR } from '@/libs/swr';-import type { CompareHistoryItemsOutput } from '@/server/routers/lambda/_schema/documentHistory';-import { documentService } from '@/services/document';import { useDocumentStore } from '@/store/document';import { editorSelectors } from '@/store/document/slices/editor';@@ -63,15 +60,9 @@ const DocumentHistoryDiff = memo<DocumentHistoryDiffProps>(({ documentId, histor(s) => editorSelectors.lastUpdatedTime(documentId)(s) ?? null,);- const { data, error, isLoading } = useClientDataSWR<CompareHistoryItemsOutput>(- ['page-editor-document-history-compare', documentId, historyId, lastUpdatedTime],- async () =>- documentService.compareDocumentHistoryItems({- documentId,- fromHistoryId: 'head',- toHistoryId: historyId,- }),- );+ const useFetchDocumentHistoryCompare = useDocumentStore((s) => s.useFetchDocumentHistoryCompare);+ const params = useMemo(() => ({ documentId, historyId }), [documentId, historyId]);+ const { data, error, isLoading } = useFetchDocumentHistoryCompare(params, lastUpdatedTime);const labels = useMemo<NonNullable<LexicalDiffProps['labels']>>(() => ({diff --git a/src/features/PageEditor/History/index.tsx b/src/features/PageEditor/History/index.tsxindex c659e1cfd08..de5af57aa0d 100644--- a/src/features/PageEditor/History/index.tsx+++ b/src/features/PageEditor/History/index.tsx@@ -17,15 +17,12 @@ import { memo, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import SurfaceSkeleton from '@/components/Skeleton/Surface';-import { DOCUMENT_HISTORY_QUERY_LIST_LIMIT } from '@/const/documentHistory';import NavHeader from '@/features/NavHeader';import ToggleRightPanelButton from '@/features/RightPanel/ToggleRightPanelButton';import { useEventCallback } from '@/hooks/useEventCallback';-import { useClientDataSWR } from '@/libs/swr';import type {DocumentHistoryListItem,DocumentHistorySaveSource,- ListHistoryOutput,} from '@/server/routers/lambda/_schema/documentHistory';import { documentService } from '@/services/document';import { useDocumentStore } from '@/store/document';@@ -103,16 +100,10 @@ const HistoryPanel = memo(() => {const [restoringHistoryId, setRestoringHistoryId] = useState<string | null>(null);const compareInstanceRef = useRef<ModalInstance | null>(null);- const { data, isLoading } = useClientDataSWR<ListHistoryOutput>(- documentId ? ['page-editor-document-history', documentId, lastUpdatedTime] : null,- async () =>- documentService.listDocumentHistory({- documentId: documentId!,- includeCurrent: true,- limit: DOCUMENT_HISTORY_QUERY_LIST_LIMIT,- }),- { keepPreviousData: true },- );+ // Painted from the document store's history replica; a save re-reads it+ // while the last list stays on screen.+ const useFetchDocumentHistory = useDocumentStore((s) => s.useFetchDocumentHistory);+ const { data, isLoading } = useFetchDocumentHistory(documentId, lastUpdatedTime);const items = useMemo(() => data?.items ?? [], [data?.items]);const historyItemsById = useMemo<Record<string, DocumentHistoryListItem>>(() => {diff --git a/src/features/PageEditor/useResourceEvents.ts b/src/features/PageEditor/useResourceEvents.tsindex b257d1ed785..49613422afa 100644--- a/src/features/PageEditor/useResourceEvents.ts+++ b/src/features/PageEditor/useResourceEvents.ts@@ -4,10 +4,9 @@ import { fetchEventSource } from '@lobechat/utils/client';import { useEffect } from 'react';import { revalidateReplica } from '@/libs/replica';-import { mutate } from '@/libs/swr';-import { documentLikeKeys, isDocumentCommentKeyForEvent } from '@/libs/swr/keys';import { documentService } from '@/services/document';import { documentDetailResource } from '@/store/document/slices/document/projection';+import { documentCommentActions } from '@/store/documentComment';import { pageSelectors, usePageStore } from '@/store/page';import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/slices/auth/selectors';@@ -90,16 +89,15 @@ export const useResourceEvents = () => {// Re-fetch; DocumentIdMode re-hydrates the editor on the new// version when the local editor isn't dirty.void revalidateReplica(documentDetailResource, documentId);- } else if (parsed.type === 'document.commentsChanged' && workspaceId) {- void mutate((key) =>- isDocumentCommentKeyForEvent(key, {- documentId,- rootCommentId: parsed.data?.rootCommentId,- workspaceId,- }),- );- } else if (parsed.type === 'document.likesChanged' && workspaceId) {- void mutate(documentLikeKeys.summary(workspaceId, documentId));+ } else if (parsed.type === 'document.commentsChanged') {+ // The replicas are partitioned by the active workspace, so only+ // this document's (and the named thread's) entries are re-read.+ void documentCommentActions.revalidateForCommentEvent({+ documentId,+ rootCommentId: parsed.data?.rootCommentId,+ });+ } else if (parsed.type === 'document.likesChanged') {+ void documentCommentActions.revalidateLikeSummary(documentId);} else if (parsed.type === 'lock.changed') {// Store the holder verbatim; "locked by other" is derived against// the current user/session at read time (usePageLockedByOther).diff --git a/src/store/document/slices/history/action.test.ts b/src/store/document/slices/history/action.test.tsnew file mode 100644index 00000000000..81952382da6--- /dev/null+++ b/src/store/document/slices/history/action.test.ts@@ -0,0 +1,148 @@+/**+ * @vitest-environment happy-dom+ *+ * The page editor's version list and head-vs-version diff live in the document+ * store's replicas: a reload paints the last list from storage instead of a+ * skeleton, and a save re-reads it while the painted list stays on screen.+ */+import { randomUUID } from 'node:crypto';++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 type { ListHistoryOutput } from '@/server/routers/lambda/_schema/documentHistory';+import { documentService } from '@/services/document';++import { useDocumentStore } from '../../store';+import { documentHistoryCompareResource, documentHistoryListResource } from './projection';++const DOCUMENT_ID = 'doc-history-1';++const list = (...ids: string[]): ListHistoryOutput => ({+ items: ids.map((id, index) => ({+ id,+ isCurrent: index === 0,+ savedAt: `2026-10-0${index + 1}T00:00:00.000Z`,+ saveSource: 'autosave',+ userId: 'user-1',+ })),+});++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('document history replicas', () => {+ let scope = '';++ beforeEach(() => {+ scope = `doc-history-user-${randomUUID()}:personal`;+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ act(() => useDocumentStore.getState().reset());+ });++ afterEach(async () => {+ cleanup();+ await documentHistoryListResource.storage!.remove({ queryKey: DOCUMENT_ID, scope });+ await documentHistoryCompareResource.storage!.remove({+ queryKey: documentHistoryCompareResource.storageKey({+ documentId: DOCUMENT_ID,+ historyId: 'h2',+ }),+ scope,+ });+ vi.restoreAllMocks();+ });++ it('paints the persisted version list before the network answers', async () => {+ await documentHistoryListResource.storage!.set(+ { queryKey: DOCUMENT_ID, scope },+ { data: list('h1', 'h2'), updatedAt: 1 },+ );+ vi.spyOn(documentService, 'listDocumentHistory').mockImplementation(pending);++ const hook = renderHook(+ () => useDocumentStore.getState().useFetchDocumentHistory(DOCUMENT_ID, 'rev-1'),+ { wrapper },+ );++ await waitFor(() =>+ expect(hook.result.current.data?.items.map(({ id }) => id)).toEqual(['h1', 'h2']),+ );+ expect(hook.result.current.isLoading).toBe(false);+ });++ it('re-reads the list after a save while keeping the painted one', async () => {+ const listHistory = vi+ .spyOn(documentService, 'listDocumentHistory')+ .mockResolvedValueOnce(list('h1'))+ .mockResolvedValueOnce(list('h0', 'h1'));++ const hook = renderHook(+ ({ revision }) => useDocumentStore.getState().useFetchDocumentHistory(DOCUMENT_ID, revision),+ { initialProps: { revision: 'rev-1' }, wrapper },+ );+ await waitFor(() => expect(hook.result.current.data?.items).toHaveLength(1));++ hook.rerender({ revision: 'rev-2' });+ expect(hook.result.current.data?.items).toHaveLength(1);++ await waitFor(() =>+ expect(hook.result.current.data?.items.map(({ id }) => id)).toEqual(['h0', 'h1']),+ );+ expect(listHistory).toHaveBeenCalledTimes(2);+ expect(listHistory).toHaveBeenLastCalledWith({+ documentId: DOCUMENT_ID,+ includeCurrent: true,+ limit: expect.any(Number),+ });+ await waitFor(async () => {+ const row = await documentHistoryListResource.storage!.get({ queryKey: DOCUMENT_ID, scope });+ expect((row?.data as ListHistoryOutput).items).toHaveLength(2);+ });+ });++ it('fetches a head-vs-version diff into its replica entry', async () => {+ const compare = {+ from: { editorData: { root: { children: [] } } },+ to: { editorData: { root: { children: [] } } },+ };+ const compareSpy = vi+ .spyOn(documentService, 'compareDocumentHistoryItems')+ .mockResolvedValue(compare as never);++ const hook = renderHook(+ () =>+ useDocumentStore+ .getState()+ .useFetchDocumentHistoryCompare({ documentId: DOCUMENT_ID, historyId: 'h2' }, 'rev-1'),+ { wrapper },+ );++ await waitFor(() => expect(hook.result.current.data).toEqual(compare));+ expect(compareSpy).toHaveBeenCalledWith({+ documentId: DOCUMENT_ID,+ fromHistoryId: 'head',+ toHistoryId: 'h2',+ });+ });+});diff --git a/src/store/document/slices/history/action.ts b/src/store/document/slices/history/action.tsnew file mode 100644index 00000000000..0ea142c2cff--- /dev/null+++ b/src/store/document/slices/history/action.ts@@ -0,0 +1,140 @@+'use client';++import { useEffect, useRef } from 'react';++import { DOCUMENT_HISTORY_QUERY_LIST_LIMIT } from '@/const/documentHistory';+import { createReplicaSlice, recordLens } from '@/libs/replica';+import type {+ CompareHistoryItemsOutput,+ ListHistoryOutput,+} from '@/server/routers/lambda/_schema/documentHistory';+import { documentService } from '@/services/document';+import type { StoreSetter } from '@/store/types';+import { setNamespace } from '@/utils/storeDebug';++import type { DocumentStore } from '../../store';+import { useDocumentStore } from '../../store';+import {+ documentHistoryCompareKey,+ type DocumentHistoryCompareParams,+ documentHistoryCompareResource,+ documentHistoryListResource,+} from './projection';++const n = setNamespace('document/history');++type Setter = StoreSetter<DocumentStore>;++export interface UseFetchDocumentHistoryResult<TData> {+ data: TData | undefined;+ error: unknown;+ /** No value painted yet (neither the persisted copy nor the network) and no error. */+ isLoading: boolean;+}++/**+ * Re-read an entry whenever the document's saved revision moves on while the+ * view is mounted. The first render only syncs (mount revalidation); the+ * revision is not part of the replica key, so a save keeps the painted list+ * on screen while the new one loads instead of falling back to a skeleton.+ */+const useRevalidateOnRevision = (+ key: string | undefined,+ revision: string | null | undefined,+ revalidate: (key: string) => Promise<unknown>,+) => {+ const seen = useRef({ key, revision });+ useEffect(() => {+ const previous = seen.current;+ seen.current = { key, revision };+ if (!key || previous.key !== key || previous.revision === revision) return;+ void revalidate(key);+ }, [key, revision, revalidate]);+};++export const createDocumentHistorySlice = (set: Setter, get: () => DocumentStore, _api?: unknown) =>+ new DocumentHistoryActionImpl(set, get, _api);++/**+ * The version history of a document: its version list and head-vs-version+ * diffs live in replicas next to the document detail, so reopening the+ * history panel (or a compare) after a reload paints the last copy first.+ */+export class DocumentHistoryActionImpl {+ readonly #compare;+ readonly #list;++ constructor(set: Setter, get: () => DocumentStore, _api?: unknown) {+ void _api;+ this.#list = createReplicaSlice(documentHistoryListResource, {+ actionPrefix: n('historyList'),+ fetcher: (documentId) =>+ documentService.listDocumentHistory({+ documentId,+ includeCurrent: true,+ limit: DOCUMENT_HISTORY_QUERY_LIST_LIMIT,+ }),+ get,+ set,+ stateKey: 'historyListReplica',+ view: recordLens<DocumentStore, ListHistoryOutput>('historyListMap'),+ });+ this.#compare = createReplicaSlice(documentHistoryCompareResource, {+ actionPrefix: n('historyCompare'),+ fetcher: ({ documentId, historyId }) =>+ documentService.compareDocumentHistoryItems({+ documentId,+ fromHistoryId: 'head',+ toHistoryId: historyId,+ }),+ get,+ set,+ stateKey: 'historyCompareReplica',+ view: recordLens<DocumentStore, CompareHistoryItemsOutput>('historyCompareMap'),+ });+ }++ #revalidateList = (key: string) => this.#list.revalidate(key);++ #revalidateCompare = (key: string) => this.#compare.revalidate(key);++ /**+ * The version list of `documentId`; `revision` (the document's last saved+ * time) re-reads it after every save.+ */+ useFetchDocumentHistory = (+ documentId: string | null | undefined,+ revision?: string | null,+ ): UseFetchDocumentHistoryResult<ListHistoryOutput> => {+ const data = useDocumentStore((s) => (documentId ? s.historyListMap[documentId] : undefined));+ const sync = this.#list.useSync(documentId || null);+ useRevalidateOnRevision(documentId || undefined, revision, this.#revalidateList);++ return {+ data,+ error: sync.error,+ isLoading: Boolean(documentId) && !data && !sync.error,+ };+ };++ /**+ * The diff between the document head and one version; `revision` re-reads+ * it when the head moves on.+ */+ useFetchDocumentHistoryCompare = (+ params: DocumentHistoryCompareParams | null | undefined,+ revision?: string | null,+ ): UseFetchDocumentHistoryResult<CompareHistoryItemsOutput> => {+ const key = params ? documentHistoryCompareKey(params) : undefined;+ const data = useDocumentStore((s) => (key ? s.historyCompareMap[key] : undefined));+ const sync = this.#compare.useSync(params ?? null);+ useRevalidateOnRevision(key, revision, this.#revalidateCompare);++ return { data, error: sync.error, isLoading: Boolean(key) && !data && !sync.error };+ };+}++export type DocumentHistoryAction = Pick<+ DocumentHistoryActionImpl,+ keyof DocumentHistoryActionImpl+>;diff --git a/src/store/document/slices/history/index.ts b/src/store/document/slices/history/index.tsnew file mode 100644index 00000000000..5638bf7f31d--- /dev/null+++ b/src/store/document/slices/history/index.ts@@ -0,0 +1,11 @@+export {+ createDocumentHistorySlice,+ type DocumentHistoryAction,+ type UseFetchDocumentHistoryResult,+} from './action';+export { type DocumentHistoryState, initialDocumentHistoryState } from './initialState';+export {+ type DocumentHistoryCompareParams,+ documentHistoryCompareResource,+ documentHistoryListResource,+} from './projection';diff --git a/src/store/document/slices/history/initialState.ts b/src/store/document/slices/history/initialState.tsnew file mode 100644index 00000000000..20582853fbf--- /dev/null+++ b/src/store/document/slices/history/initialState.ts@@ -0,0 +1,21 @@+import { createReplicaState, type ReplicaState } from '@/libs/replica';+import type {+ CompareHistoryItemsOutput,+ ListHistoryOutput,+} from '@/server/routers/lambda/_schema/documentHistory';++export interface DocumentHistoryState {+ /** Head-vs-version diffs, keyed by `documentHistoryCompareKey`. */+ historyCompareMap: Record<string, CompareHistoryItemsOutput>;+ historyCompareReplica: ReplicaState<CompareHistoryItemsOutput>;+ /** Version list per document. */+ historyListMap: Record<string, ListHistoryOutput>;+ historyListReplica: ReplicaState<ListHistoryOutput>;+}++export const initialDocumentHistoryState: DocumentHistoryState = {+ historyCompareMap: {},+ historyCompareReplica: createReplicaState(),+ historyListMap: {},+ historyListReplica: createReplicaState(),+};diff --git a/src/store/document/slices/history/projection.ts b/src/store/document/slices/history/projection.tsnew file mode 100644index 00000000000..3e09a3e74c8--- /dev/null+++ b/src/store/document/slices/history/projection.ts@@ -0,0 +1,48 @@+import { defineReplica } from '@/libs/replica';+import type {+ CompareHistoryItemsOutput,+ ListHistoryOutput,+} from '@/server/routers/lambda/_schema/documentHistory';++/** How many documents keep a persisted version list (`persist.maxEntries`). */+export const MAX_PERSISTED_HISTORY_LISTS = 20;+/**+ * How many version comparisons survive a reload. Each row holds two full+ * editor states, so the set is kept small.+ */+export const MAX_PERSISTED_HISTORY_COMPARES = 10;++export interface DocumentHistoryCompareParams {+ documentId: string;+ /** The version compared against the document head. */+ historyId: string;+}++export const documentHistoryCompareKey = ({+ documentId,+ historyId,+}: DocumentHistoryCompareParams) => `${documentId}:${historyId}`;++/**+ * The version list of one document (`historyListMap[documentId]`). A reload+ * opens the history panel on the last list it showed; the network confirms it.+ */+export const documentHistoryListResource = defineReplica<string, ListHistoryOutput>({+ key: (documentId) => documentId,+ name: 'documentHistoryList',+ persist: { maxEntries: MAX_PERSISTED_HISTORY_LISTS },+ storage: 'indexedDB',+ version: 1,+});++/** The head-vs-version diff (`historyCompareMap[documentHistoryCompareKey(params)]`). */+export const documentHistoryCompareResource = defineReplica<+ DocumentHistoryCompareParams,+ CompareHistoryItemsOutput+>({+ key: documentHistoryCompareKey,+ name: 'documentHistoryCompare',+ persist: { maxEntries: MAX_PERSISTED_HISTORY_COMPARES },+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/document/store.ts b/src/store/document/store.tsindex a46f22e20fb..a1ba66d2d50 100644--- a/src/store/document/store.ts+++ b/src/store/document/store.ts@@ -14,12 +14,21 @@ import {} from './slices/document';import { type EditorAction, type EditorState } from './slices/editor';import { createEditorSlice, initialEditorState } from './slices/editor';+import {+ createDocumentHistorySlice,+ type DocumentHistoryAction,+ type DocumentHistoryState,+ initialDocumentHistoryState,+} from './slices/history';// State type-export type DocumentState = EditorState & DocumentDetailSliceState;+export type DocumentState = EditorState & DocumentDetailSliceState & DocumentHistoryState;// Action type-export type DocumentStoreAction = DocumentAction & EditorAction & ResetableStore;+export type DocumentStoreAction = DocumentAction &+ DocumentHistoryAction &+ EditorAction &+ ResetableStore;// Full store typeexport type DocumentStore = DocumentState & DocumentStoreAction;@@ -28,6 +37,7 @@ export type DocumentStore = DocumentState & DocumentStoreAction;const initialState: DocumentState = {...initialEditorState,...initialDocumentDetailSliceState,+ ...initialDocumentHistoryState,};class DocumentStoreResetAction extends ResetableStoreAction<DocumentStore> {@@ -40,6 +50,7 @@ const createStore: StateCreator<DocumentStore, [['zustand/devtools', never]]> =...initialState,...flattenActions<DocumentStoreAction>([createDocumentSlice(...parameters),+ createDocumentHistorySlice(...parameters),createEditorSlice(...parameters),new DocumentStoreResetAction(...parameters),]),diff --git a/src/store/documentComment/action.ts b/src/store/documentComment/action.tsnew file mode 100644index 00000000000..df4af373bc7--- /dev/null+++ b/src/store/documentComment/action.ts@@ -0,0 +1,469 @@+import type {+ CreateDocumentCommentInput,+ DocumentCommentDetail,+ DocumentCommentItem,+ DocumentCommentJson,+ DocumentCommentThread,+ DocumentLikeSummary,+} from '@lobechat/types';++import { type ReplicaPagedData, type ReplicaSyncResult } from '@/libs/replica';+import { documentCommentService } from '@/services/documentComment';+import type { StoreSetter } from '@/store/types';+import { setNamespace } from '@/utils/storeDebug';++import { type DocumentCommentState, initialState } from './initialState';+import { DocumentCommentPrivateAction } from './privateAction';+import {+ type DocumentCommentThreadScope,+ documentCommentThreadsKey,+ type DocumentCommentThreadsParams,+ documentLikeSummaryResource,+} from './projection';+import {+ appendReply,+ appendThread,+ raiseThreadReplyCount,+ replaceReply,+ replaceThreadRoot,+} from './reducers';+import { useDocumentCommentStore } from './store';++const n = setNamespace('documentComment');++type Setter = StoreSetter<DocumentCommentState>;++type CreatedComment = NonNullable<Awaited<ReturnType<typeof documentCommentService.create>>>;++/** The feeds a root can sit in: anchored roots in the gutter's, the rest in the list's. */+const ROOT_SCOPES: DocumentCommentThreadScope[] = ['anchored', 'document'];++/** Patch a feed's rows, keeping the feed object when no row changed. */+const patchItems =+ <TItem>(fn: (items: TItem[]) => TItem[]) =>+ <TFeed extends ReplicaPagedData<TItem, string>>(feed: TFeed): TFeed => {+ const items = fn(feed.items);+ return items === feed.items ? feed : { ...feed, items };+ };++/** Append a reply and keep the feed's live-reply `total` in step with it. */+const appendReplyToFeed =+ (comment: DocumentCommentItem) =>+ <TFeed extends ReplicaPagedData<DocumentCommentItem, string>>(feed: TFeed): TFeed => {+ const items = appendReply(feed.items, comment);+ if (items === feed.items) return feed;+ return { ...feed, items, ...(feed.total === undefined ? {} : { total: feed.total + 1 }) };+ };++/**+ * A counter overlay for one new comment: "at least what it was when the write+ * began, plus one". A `+1` would be replayed over a base an event revalidation+ * already moved past (the server counted the comment before `create()`+ * settled), and committing it would persist a count one too high.+ */+const countedOnce = (baseline: number | undefined) => (current: number) =>+ baseline === undefined ? current + 1 : Math.max(current, baseline + 1);++export interface DocumentCommentEditorValue {+ content: string;+ editorData: DocumentCommentJson;+}++export interface CreateDocumentCommentParams {+ input: CreateDocumentCommentInput;+ /** The row painted until the server answers (`createOptimisticComment`). */+ optimisticComment: DocumentCommentItem;+}++export interface CreateDocumentCommentReplyParams extends CreateDocumentCommentParams {+ rootCommentId: string;+}++/**+ * The document comment and like domain.+ *+ * Server state lives in six replicas (root feeds per scope, reply feeds,+ * comment summary, anchor list, deep-link details, like summary): each paints+ * its persisted copy on the first frame and is confirmed by the network in the+ * background. Writes go through optimistic overlays, so a failed request rolls+ * back to the confirmed value and a revalidation landing mid-request cannot+ * drop the pending row.+ */+export class DocumentCommentActionImpl {+ readonly #get: () => DocumentCommentState;+ /**+ * Reply creates in flight per root, and whether two of them overlapped. An+ * overlapping reply reads its counter baseline with the other's `+1` still+ * applied, so a failure of one leaves the other's floor one too high; the+ * root's counters are re-read from the server once the last one settles.+ */+ readonly #pendingReplies = new Map<string, { overlapped: boolean; pending: number }>();+ readonly #private: DocumentCommentPrivateAction;+ readonly #set: Setter;++ constructor(+ set: Setter,+ get: () => DocumentCommentState,+ privateAction: DocumentCommentPrivateAction,+ ) {+ this.#get = get;+ this.#set = set;+ this.#private = privateAction;+ }++ // ---- server reads (replica) -------------------------------------------++ /** Hydrate + sync a document's comment count. Read `summaryMap`. */+ useFetchSummary = (documentId: string | null | undefined): ReplicaSyncResult =>+ this.#private.summary.useSync(documentId || null, { dedupingInterval: 30_000 });++ /** Hydrate + sync every anchored root of a document. Read `anchorListMap`. */+ useFetchAnchors = (documentId: string | null | undefined): ReplicaSyncResult =>+ this.#private.anchors.useSync(documentId || null);++ /** Hydrate + sync one root feed. Read `threadFeedMap`. */+ useFetchThreads = (params: DocumentCommentThreadsParams | null | undefined): ReplicaSyncResult =>+ this.#private.thread.useSync(params ?? null);++ /** Hydrate + sync the replies of one root. Read `replyFeedMap`. */+ useFetchReplies = (rootCommentId: string | null | undefined, enabled = true): ReplicaSyncResult =>+ this.#private.replies.useSync(rootCommentId ? { rootCommentId } : null, { enabled });++ /** Hydrate + sync one comment by id (a deep-link target). Read `detailMap`. */+ useFetchDetail = (commentId: string | null | undefined): ReplicaSyncResult =>+ this.#private.detail.useSync(commentId || null);++ /** Hydrate + sync a document's like summary. Read `likeSummaryMap`. */+ useFetchLikeSummary = (documentId: string | null | undefined): ReplicaSyncResult =>+ this.#private.likeSummary.useSync(documentId || null, { dedupingInterval: 30_000 });++ loadMoreThreads = (params: DocumentCommentThreadsParams) =>+ this.#private.thread.loadMore(documentCommentThreadsKey(params), params);++ loadMoreReplies = (rootCommentId: string) =>+ this.#private.replies.loadMore(rootCommentId, { rootCommentId });++ /**+ * Re-read a root feed after a write or an explicit retry. A head-only+ * revalidation keeps the already-loaded tail pages, so a change in an older+ * page would survive it β drop the tail first; the next "load more" (or the+ * gutter's eager drain) walks the pages below the head again.+ */+ revalidateThreads = (params: DocumentCommentThreadsParams) => {+ const key = documentCommentThreadsKey(params);+ this.#private.thread.collapse(key);+ return this.#private.thread.revalidate(key);+ };++ revalidateReplies = (rootCommentId: string) => {+ this.#private.replies.collapse(rootCommentId);+ return this.#private.replies.revalidate(rootCommentId);+ };++ revalidateSummary = (documentId: string) => this.#private.summary.revalidate(documentId);++ revalidateAnchors = (documentId: string) => this.#private.anchors.revalidate(documentId);++ /** Re-read one deep-link target, or every mounted one without an id. */+ revalidateDetail = (commentId?: string) => this.#private.detail.revalidate(commentId);++ /** Re-read everything a document's comment surfaces show except the reply feeds. */+ revalidateDocument = async (documentId: string) => {+ await Promise.all([+ ...ROOT_SCOPES.map((scope) => this.revalidateThreads({ documentId, scope })),+ this.revalidateSummary(documentId),+ this.revalidateAnchors(documentId),+ ]);+ };++ /**+ * Another member (or another window) changed a document's comments. The+ * event carries the affected root when it is a reply change; deep-link+ * details are few and the event does not name the comment, so every mounted+ * one is re-read.+ */+ revalidateForCommentEvent = async ({+ documentId,+ rootCommentId,+ }: {+ documentId: string;+ rootCommentId?: string;+ }) => {+ await Promise.all([+ this.revalidateDocument(documentId),+ this.revalidateDetail(),+ rootCommentId ? this.revalidateReplies(rootCommentId) : this.#private.replies.revalidate(),+ ]);+ };++ revalidateLikeSummary = (documentId: string) => this.#private.likeSummary.revalidate(documentId);++ /**+ * Bind a like toggle's server answers to the identity it was sent from. A+ * toggle that settles after an account / workspace switch belongs to the+ * previous identity: its summary (with that user's `liked` and likers) must+ * not land in β or persist into β the new partition. The engine drops a+ * write or read captured under a scope that is no longer active.+ */+ beginLikeSettle = (documentId: string) => {+ const scope = documentLikeSummaryResource.scope.get();+ return {+ /** Confirm the server's summary after the last toggle request. */+ confirm: (summary: DocumentLikeSummary) => {+ this.#private.likeSummary.replace(documentId, summary, scope);+ },+ /** Re-read the summary after a failed toggle (rejects once the scope moved on). */+ refresh: () => this.#private.likeSummary.fetch(documentId, { fresh: true, scope }),+ };+ };++ /**+ * Show a like / unlike right away. Memory only: the server answer replaces+ * it through {@link beginLikeSettle}, and a reload repaints the last+ * confirmed value.+ */+ applyLikeSummary = (+ documentId: string,+ apply: (current: DocumentLikeSummary) => DocumentLikeSummary,+ ) =>+ this.#private.likeSummary.update(documentId, (current) => current && apply(current), {+ persist: false,+ });++ // ---- writes ------------------------------------------------------------++ /**+ * Create a root comment. It shows at the end of its feed (anchored or+ * document-level, by its selection anchor) and in the count right away; a+ * failed request rolls both back and rethrows.+ */+ createRootComment = async ({+ input,+ optimisticComment,+ }: CreateDocumentCommentParams): Promise<CreatedComment> => {+ const { documentId } = input;+ const threadParams: DocumentCommentThreadsParams = {+ documentId,+ scope: input.selectionAnchor ? 'anchored' : 'document',+ };+ const key = documentCommentThreadsKey(threadParams);+ // An optimistic write onto a feed that has no view yet (still loading, or+ // its fetch failed) is dropped, so the created row would stay invisible.+ const threadUnloaded = !this.#get().threadFeedMap[key];+ const thread = this.#private.thread.beginOptimistic(+ key,+ patchItems<DocumentCommentThread>((threads) => appendThread(threads, optimisticComment)),+ );+ const summaryTotal = countedOnce(this.#get().summaryMap[documentId]?.total);+ const summary = this.#private.summary.beginOptimistic(documentId, (current) => ({+ ...current,+ total: summaryTotal(current.total),+ }));++ let created: CreatedComment;+ try {+ const result = await documentCommentService.create(input);+ if (!result) throw new Error('Document comment creation returned no result');+ created = result;+ } catch (error) {+ thread.rollback();+ summary.rollback();+ throw error;+ }++ thread.commit(+ patchItems<DocumentCommentThread>((threads) => appendThread(threads, created.comment)),+ );+ if (threadUnloaded) void this.revalidateThreads(threadParams);+ // A retried submit the server already had: the count did not grow.+ if (created.isDuplicate) summary.rollback();+ else summary.commit();+ // Converge on the server's count (another member may have commented meanwhile).+ void this.revalidateSummary(documentId);++ // The body paints from the document-wide anchor list, so the new root+ // joins it now rather than on the next revalidation.+ const createdAnchor = created.comment.selectionAnchor;+ if (createdAnchor) {+ this.#private.anchors.update(documentId, (current) =>+ current && !current.items.some(({ id }) => id === created.comment.id)+ ? {+ items: [...current.items, { id: created.comment.id, selectionAnchor: createdAnchor }],+ }+ : current,+ );+ }+ return created;+ };++ /**+ * Reply inside a thread. The reply, its root's reply count (in the feeds and+ * in a pinned deep-link root) and the document count move together, and+ * roll back together when the request fails.+ */+ createReply = async ({+ input,+ optimisticComment,+ rootCommentId,+ }: CreateDocumentCommentReplyParams): Promise<CreatedComment> => {+ const { documentId } = input;+ const settleCounts = this.#trackReply(rootCommentId);+ // See createRootComment: a feed with no view drops the optimistic write.+ const repliesUnloaded = !this.#get().replyFeedMap[rootCommentId];+ const replies = this.#private.replies.beginOptimistic(+ rootCommentId,+ appendReplyToFeed(optimisticComment),+ );+ // Baselines are read now, before the request: see `countedOnce`.+ const state = this.#get();+ const replyCountOf = (scope: DocumentCommentThreadScope) =>+ state.threadFeedMap[documentCommentThreadsKey({ documentId, scope })]?.items.find(+ ({ root }) => root.id === rootCommentId,+ )?.replyCount;+ const detailReplyCount = countedOnce(state.detailMap[rootCommentId]?.replyCount);+ const summaryTotal = countedOnce(state.summaryMap[documentId]?.total);+ const counts = [+ ...ROOT_SCOPES.map((scope) => {+ const baseline = replyCountOf(scope);+ return this.#private.thread.beginOptimistic(+ documentCommentThreadsKey({ documentId, scope }),+ patchItems<DocumentCommentThread>((threads) => {+ const current = threads.find(({ root }) => root.id === rootCommentId)?.replyCount;+ return current === undefined+ ? threads+ : raiseThreadReplyCount(threads, rootCommentId, countedOnce(baseline)(current));+ }),+ );+ }),+ this.#private.detail.beginOptimistic(rootCommentId, (detail) => ({+ ...detail,+ replyCount: detailReplyCount(detail.replyCount),+ })),+ this.#private.summary.beginOptimistic(documentId, (current) => ({+ ...current,+ total: summaryTotal(current.total),+ })),+ ];++ let created: CreatedComment;+ try {+ const result = await documentCommentService.create(input);+ if (!result) throw new Error('Document comment reply creation returned no result');+ created = result;+ } catch (error) {+ replies.rollback();+ for (const token of counts) token.rollback();+ if (settleCounts()) void this.#reconcileReplyCounts(documentId, rootCommentId);+ throw error;+ }++ replies.commit(appendReplyToFeed(created.comment));+ if (repliesUnloaded) void this.revalidateReplies(rootCommentId);+ if (created.isDuplicate) {+ for (const token of counts) token.rollback();+ // The re-reads below already cover what a reconcile would re-read.+ settleCounts();+ void this.revalidateReplies(rootCommentId);+ void this.revalidateDetail(rootCommentId);+ void this.revalidateDocument(documentId);+ } else {+ for (const token of counts) token.commit();+ if (settleCounts()) void this.#reconcileReplyCounts(documentId, rootCommentId);+ // Converge on the server's count (another member may have commented meanwhile).+ else void this.revalidateSummary(documentId);+ }+ return created;+ };++ /** Count a reply create in flight; the returned settle says whether a reconcile is due. */+ #trackReply = (rootCommentId: string) => {+ const entry = this.#pendingReplies.get(rootCommentId) ?? { overlapped: false, pending: 0 };+ entry.pending += 1;+ if (entry.pending > 1) entry.overlapped = true;+ this.#pendingReplies.set(rootCommentId, entry);+ let settled = false;+ return (): boolean => {+ if (settled) return false;+ settled = true;+ entry.pending -= 1;+ if (entry.pending > 0) return false;+ this.#pendingReplies.delete(rootCommentId);+ return entry.overlapped;+ };+ };++ /** Re-read a root's reply count (both root feeds, a pinned copy) and the document count. */+ #reconcileReplyCounts = async (documentId: string, rootCommentId: string) => {+ await Promise.all([+ ...ROOT_SCOPES.map((scope) =>+ this.#private.thread.revalidate(documentCommentThreadsKey({ documentId, scope })),+ ),+ this.revalidateDetail(rootCommentId),+ this.revalidateSummary(documentId),+ ]);+ };++ /**+ * Edit a root or a reply. The new content shows wherever the comment is+ * painted (its feed and a pinned deep-link copy); a failed request rolls+ * every copy back and rethrows.+ */+ updateComment = async (+ comment: DocumentCommentItem,+ value: DocumentCommentEditorValue,+ ): Promise<DocumentCommentItem> => {+ const optimisticComment: DocumentCommentItem = { ...comment, ...value, updatedAt: new Date() };+ const { replies, thread, detail } = this.#private;+ const rootKeys = ROOT_SCOPES.map((scope) =>+ documentCommentThreadsKey({ documentId: comment.documentId, scope }),+ );+ const replyKey = comment.parentCommentId;+ const replaceInReplies = (next: DocumentCommentItem) =>+ patchItems<DocumentCommentItem>((items) => replaceReply(items, next));+ const replaceInThreads = (next: DocumentCommentItem) =>+ patchItems<DocumentCommentThread>((threads) => replaceThreadRoot(threads, next));+ const patchDetail = (next: DocumentCommentItem) => (current: DocumentCommentDetail) => ({+ ...current,+ ...next,+ replyCount: current.replyCount,+ });+ // A reply lives in its root's reply feed; a root in one of the two root feeds.+ const replyToken = replyKey+ ? replies.beginOptimistic(replyKey, replaceInReplies(optimisticComment))+ : undefined;+ const threadTokens = replyKey+ ? []+ : rootKeys.map((key) => thread.beginOptimistic(key, replaceInThreads(optimisticComment)));+ const detailToken = detail.beginOptimistic(comment.id, patchDetail(optimisticComment));++ let updated: DocumentCommentItem;+ try {+ const result = await documentCommentService.update({ ...value, id: comment.id });+ if (!result) throw new Error('Document comment update returned no result');+ updated = result;+ } catch (error) {+ replyToken?.rollback();+ for (const token of threadTokens) token.rollback();+ detailToken.rollback();+ throw error;+ }++ // Settle on the server's row (its `updatedAt`, normalized content).+ replyToken?.commit(replaceInReplies(updated));+ for (const token of threadTokens) token.commit(replaceInThreads(updated));+ detailToken.commit(patchDetail(updated));+ return updated;+ };++ reset = (): void => {+ this.#set(initialState, false, n('reset'));+ };+}++const { getState, setState } = useDocumentCommentStore;++export const documentCommentActions = new DocumentCommentActionImpl(+ setState,+ getState,+ new DocumentCommentPrivateAction(setState, getState),+);diff --git a/src/store/documentComment/index.ts b/src/store/documentComment/index.tsnew file mode 100644index 00000000000..c07c5dbcec9--- /dev/null+++ b/src/store/documentComment/index.ts@@ -0,0 +1,18 @@+export {+ type CreateDocumentCommentParams,+ type CreateDocumentCommentReplyParams,+ documentCommentActions,+ type DocumentCommentEditorValue,+} from './action';+export type { DocumentCommentState } from './initialState';+export {+ DOCUMENT_COMMENT_ANCHORED_PAGE_SIZE,+ DOCUMENT_COMMENT_PAGE_SIZE,+ type DocumentCommentReplyFeed,+ type DocumentCommentThreadFeed,+ type DocumentCommentThreadScope,+ type DocumentCommentThreadsParams,+ partitionThreadPage,+} from './projection';+export { documentCommentSelectors } from './selectors';+export { useDocumentCommentStore } from './store';diff --git a/src/store/documentComment/initialState.ts b/src/store/documentComment/initialState.tsnew file mode 100644index 00000000000..d2a3e2b7c40--- /dev/null+++ b/src/store/documentComment/initialState.ts@@ -0,0 +1,46 @@+import type {+ DocumentCommentAnchorList,+ DocumentCommentDetail,+ DocumentCommentSummary,+ DocumentLikeSummary,+} from '@lobechat/types';++import { createReplicaState, type ReplicaState } from '@/libs/replica';++import type { DocumentCommentReplyFeed, DocumentCommentThreadFeed } from './projection';++export interface DocumentCommentState {+ /** Anchored roots per document (`anchorListMap[documentId]`), painted as body highlights. */+ anchorListMap: Record<string, DocumentCommentAnchorList>;+ anchorListReplica: ReplicaState<DocumentCommentAnchorList>;+ /** One comment by id (`detailMap[commentId]`), read by a deep-link landing. */+ detailMap: Record<string, DocumentCommentDetail>;+ detailReplica: ReplicaState<DocumentCommentDetail>;+ /** Like summary per document (`likeSummaryMap[documentId]`). */+ likeSummaryMap: Record<string, DocumentLikeSummary>;+ likeSummaryReplica: ReplicaState<DocumentLikeSummary>;+ /** Replies per root comment (`replyFeedMap[rootCommentId]`). */+ replyFeedMap: Record<string, DocumentCommentReplyFeed>;+ replyFeedReplica: ReplicaState<DocumentCommentReplyFeed>;+ /** Comment count per document (`summaryMap[documentId]`). */+ summaryMap: Record<string, DocumentCommentSummary>;+ summaryReplica: ReplicaState<DocumentCommentSummary>;+ /** Root feeds per (document, scope) (`threadFeedMap[documentCommentThreadsKey(params)]`). */+ threadFeedMap: Record<string, DocumentCommentThreadFeed>;+ threadFeedReplica: ReplicaState<DocumentCommentThreadFeed>;+}++export const initialState: DocumentCommentState = {+ anchorListMap: {},+ anchorListReplica: createReplicaState(),+ detailMap: {},+ detailReplica: createReplicaState(),+ likeSummaryMap: {},+ likeSummaryReplica: createReplicaState(),+ replyFeedMap: {},+ replyFeedReplica: createReplicaState(),+ summaryMap: {},+ summaryReplica: createReplicaState(),+ threadFeedMap: {},+ threadFeedReplica: createReplicaState(),+};diff --git a/src/store/documentComment/privateAction.ts b/src/store/documentComment/privateAction.tsnew file mode 100644index 00000000000..0288365a8fe--- /dev/null+++ b/src/store/documentComment/privateAction.ts@@ -0,0 +1,133 @@+import type {+ DocumentCommentAnchorList,+ DocumentCommentDetail,+ DocumentCommentSummary,+ DocumentLikeSummary,+} from '@lobechat/types';++import { createReplicaSlice, recordLens } from '@/libs/replica';+import { documentCommentService } from '@/services/documentComment';+import { documentLikeService } from '@/services/documentLike';+import type { StoreSetter } from '@/store/types';+import { isTrpcErrorCode } from '@/utils/trpcError';++import type { DocumentCommentState } from './initialState';+import {+ DOCUMENT_COMMENT_PAGE_SIZE,+ documentCommentAnchorResource,+ documentCommentDetailResource,+ type DocumentCommentReplyFeed,+ documentCommentReplyResource,+ documentCommentSummaryResource,+ type DocumentCommentThreadFeed,+ documentCommentThreadPageSize,+ documentCommentThreadResource,+ documentLikeSummaryResource,+ fetchThreadPage,+} from './projection';++type Setter = StoreSetter<DocumentCommentState>;++/** The server no longer shows this entry to the reader: a cached copy must stop painting. */+const isGone = (error: unknown) =>+ isTrpcErrorCode(error, 'NOT_FOUND') || isTrpcErrorCode(error, 'FORBIDDEN');++/**+ * Replica slices of the document comment domain. Every read paints its+ * persisted copy first and is confirmed by the network in the background;+ * transient failures keep the copy (stale-while-revalidate), while a document+ * or comment the server reports gone is dropped from memory and storage so a+ * reload cannot resurrect it.+ */+export class DocumentCommentPrivateAction {+ readonly anchors;+ readonly detail;+ readonly likeSummary;+ readonly replies;+ readonly summary;+ readonly thread;++ constructor(set: Setter, get: () => DocumentCommentState) {+ const dropWhenGone =+ (remove: (key: string, scope?: string) => void) =>+ (+ error: unknown,+ _params: unknown,+ { key, scope }: { key: string | undefined; scope: string },+ ) => {+ if (key && isGone(error)) remove(key, scope);+ };++ this.thread = createReplicaSlice(documentCommentThreadResource, {+ actionPrefix: 'documentComment/threads',+ effects: { onError: dropWhenGone((key, scope) => this.thread.remove(key, scope)) },+ fetcher: ({ documentId, scope }, cursor) =>+ fetchThreadPage(+ (next) =>+ documentCommentService.listThreads({+ anchored: scope === 'all' ? undefined : scope === 'anchored',+ cursor: next,+ documentId,+ limit: documentCommentThreadPageSize(scope),+ }),+ scope,+ cursor,+ ),+ get,+ set,+ stateKey: 'threadFeedReplica',+ view: recordLens<DocumentCommentState, DocumentCommentThreadFeed>('threadFeedMap'),+ });+ this.replies = createReplicaSlice(documentCommentReplyResource, {+ actionPrefix: 'documentComment/replies',+ effects: { onError: dropWhenGone((key, scope) => this.replies.remove(key, scope)) },+ fetcher: ({ rootCommentId }, cursor) =>+ documentCommentService.listReplies({+ cursor,+ limit: DOCUMENT_COMMENT_PAGE_SIZE,+ rootCommentId,+ }),+ get,+ set,+ stateKey: 'replyFeedReplica',+ view: recordLens<DocumentCommentState, DocumentCommentReplyFeed>('replyFeedMap'),+ });+ this.summary = createReplicaSlice(documentCommentSummaryResource, {+ actionPrefix: 'documentComment/summary',+ effects: { onError: dropWhenGone((key, scope) => this.summary.remove(key, scope)) },+ fetcher: (documentId) => documentCommentService.summary(documentId),+ get,+ set,+ stateKey: 'summaryReplica',+ view: recordLens<DocumentCommentState, DocumentCommentSummary>('summaryMap'),+ });+ this.anchors = createReplicaSlice(documentCommentAnchorResource, {+ actionPrefix: 'documentComment/anchors',+ effects: { onError: dropWhenGone((key, scope) => this.anchors.remove(key, scope)) },+ fetcher: (documentId) => documentCommentService.listAnchors(documentId),+ get,+ set,+ stateKey: 'anchorListReplica',+ view: recordLens<DocumentCommentState, DocumentCommentAnchorList>('anchorListMap'),+ });+ this.detail = createReplicaSlice(documentCommentDetailResource, {+ actionPrefix: 'documentComment/detail',+ // A deleted deep-link target must not paint from storage on the next visit.+ effects: { onError: dropWhenGone((key, scope) => this.detail.remove(key, scope)) },+ fetcher: (commentId) => documentCommentService.get(commentId),+ get,+ set,+ stateKey: 'detailReplica',+ view: recordLens<DocumentCommentState, DocumentCommentDetail>('detailMap'),+ });+ this.likeSummary = createReplicaSlice(documentLikeSummaryResource, {+ actionPrefix: 'documentComment/likeSummary',+ effects: { onError: dropWhenGone((key, scope) => this.likeSummary.remove(key, scope)) },+ fetcher: (documentId) => documentLikeService.summary(documentId),+ get,+ set,+ stateKey: 'likeSummaryReplica',+ view: recordLens<DocumentCommentState, DocumentLikeSummary>('likeSummaryMap'),+ });+ }+}diff --git a/src/store/documentComment/projection.test.ts b/src/store/documentComment/projection.test.tsnew file mode 100644index 00000000000..04af0ded605--- /dev/null+++ b/src/store/documentComment/projection.test.ts@@ -0,0 +1,54 @@+import type { DocumentCommentThread, DocumentCommentThreadPage } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import { fetchThreadPage, MAX_EMPTY_THREAD_PAGE_HOPS } from './projection';++const thread = (id: string, anchored: boolean) =>+ ({+ replyCount: 0,+ root: { id, selectionAnchor: anchored ? { end: 5, quote: 'hello', start: 0 } : null },+ }) as unknown as DocumentCommentThread;++describe('fetchThreadPage', () => {+ // A server predating `anchored` answers both scopes with the same mixed+ // pages. A page holding only the other scope's roots filters down to+ // nothing, and the replica reads an empty page as the end of the feed.+ it('follows the server cursor past pages that filter down to nothing', async () => {+ const pages: Record<string, DocumentCommentThreadPage> = {+ '': { items: [thread('doc-1', false), thread('doc-2', false)], nextCursor: 'c1' },+ 'c1': { items: [thread('doc-3', false)], nextCursor: 'c2' },+ 'c2': { items: [thread('anchored-1', true), thread('doc-4', false)], nextCursor: 'c3' },+ };+ const listThreads = vi.fn(async (cursor?: string) => pages[cursor ?? '']);++ const page = await fetchThreadPage(listThreads, 'anchored');++ expect(page.items.map(({ root }) => root.id)).toEqual(['anchored-1']);+ expect(page.nextCursor).toBe('c3');+ expect(listThreads.mock.calls.map(([cursor]) => cursor)).toEqual([undefined, 'c1', 'c2']);+ });++ it('returns the end of the feed when the server runs out', async () => {+ const listThreads = vi+ .fn()+ .mockResolvedValueOnce({ items: [thread('doc-1', false)], nextCursor: 'c1' })+ .mockResolvedValueOnce({ items: [], nextCursor: null });++ const page = await fetchThreadPage(listThreads, 'anchored', 'c0');++ expect(page).toEqual({ items: [], nextCursor: null });+ expect(listThreads.mock.calls.map(([cursor]) => cursor)).toEqual(['c0', 'c1']);+ });++ it('stops after a bounded number of empty pages', async () => {+ let index = 0;+ const listThreads = vi.fn(async () => ({+ items: [thread(`doc-${index}`, false)],+ nextCursor: `c${++index}`,+ }));++ await fetchThreadPage(listThreads, 'anchored');++ expect(listThreads).toHaveBeenCalledTimes(MAX_EMPTY_THREAD_PAGE_HOPS + 1);+ });+});diff --git a/src/store/documentComment/projection.ts b/src/store/documentComment/projection.tsnew file mode 100644index 00000000000..7647f6d365b--- /dev/null+++ b/src/store/documentComment/projection.ts@@ -0,0 +1,179 @@+import type {+ DocumentCommentAnchorList,+ DocumentCommentDetail,+ DocumentCommentItem,+ DocumentCommentSummary,+ DocumentCommentThread,+ DocumentCommentThreadPage,+ DocumentLikeSummary,+} from '@lobechat/types';++import { definePagedReplica, defineReplica, type ReplicaPagedData } from '@/libs/replica';++/** One server page of document-level roots and of replies. */+export const DOCUMENT_COMMENT_PAGE_SIZE = 20;+/**+ * The gutter needs every anchored thread mounted at once (each card sits at+ * its own height), so its pages are fetched at the router's cap and drained+ * in the background rather than behind a "load more" button.+ */+export const DOCUMENT_COMMENT_ANCHORED_PAGE_SIZE = 50;++/**+ * `'anchored'` / `'document'` page one subset of a document's roots (the+ * gutter beside the text / the list below the body); `'all'` pages every root.+ */+export type DocumentCommentThreadScope = 'all' | 'anchored' | 'document';++/**+ * Root-comment feed of one document. The active workspace is part of the+ * replica scope, so it is not repeated in the key.+ */+export interface DocumentCommentThreadsParams {+ documentId: string;+ scope: DocumentCommentThreadScope;+}++export interface DocumentCommentRepliesParams {+ rootCommentId: string;+}++/** Root-comment feed: `threadFeedMap[documentCommentThreadsKey(params)]`. */+export type DocumentCommentThreadFeed = ReplicaPagedData<DocumentCommentThread, string>;++/** Reply feed of one root: `replyFeedMap[rootCommentId]`. */+export type DocumentCommentReplyFeed = ReplicaPagedData<DocumentCommentItem, string>;++export const documentCommentThreadsKey = ({ documentId, scope }: DocumentCommentThreadsParams) =>+ `${documentId}:${scope}`;++export const documentCommentThreadPageSize = (scope: DocumentCommentThreadScope) =>+ scope === 'anchored' ? DOCUMENT_COMMENT_ANCHORED_PAGE_SIZE : DOCUMENT_COMMENT_PAGE_SIZE;++/**+ * Keeps a page to its scope's own subset even when the backend ignored the+ * `anchored` parameter β a production server predating it strips the unknown+ * key and answers both scopes with the same mixed pages (the documented debug+ * proxy runs the latest SPA against exactly that). Without this, the two+ * feeds overlap and the list below the body renders every such thread+ * twice. The cursor still walks the server's own order, so paging stays+ * consistent; a page may just carry fewer items than asked for.+ */+export const partitionThreadPage = (+ page: DocumentCommentThreadPage,+ scope: DocumentCommentThreadScope,+): DocumentCommentThreadPage => {+ if (scope === 'all') return page;+ const wantsAnchored = scope === 'anchored';+ const items = page.items.filter(({ root }) => Boolean(root.selectionAnchor) === wantsAnchored);+ return items.length === page.items.length ? page : { ...page, items };+};++/**+ * Server pages a scope may skip in one fetch. A page that filters down to+ * nothing (see {@link partitionThreadPage}) would end the feed β the replica+ * reads an empty page as the last one β so the fetch follows its cursor until+ * a page keeps a row or the server runs out. Bounded so a document with many+ * roots of the other scope cannot fan out into an unbounded request chain.+ */+export const MAX_EMPTY_THREAD_PAGE_HOPS = 10;++/** One page of a scope's roots, following the server cursor past pages filtered to nothing. */+export const fetchThreadPage = async (+ listThreads: (cursor: string | undefined) => Promise<DocumentCommentThreadPage>,+ scope: DocumentCommentThreadScope,+ cursor?: string,+): Promise<DocumentCommentThreadPage> => {+ let page = partitionThreadPage(await listThreads(cursor), scope);+ for (+ let hop = 0;+ page.items.length === 0 && page.nextCursor && hop < MAX_EMPTY_THREAD_PAGE_HOPS;+ hop+++ ) {+ page = partitionThreadPage(await listThreads(page.nextCursor), scope);+ }+ return page;+};++/** Persisted rows per resource and scope; the least recently used beyond it are evicted. */+const MAX_PERSISTED_DOCUMENTS = 50;+/** Reply feeds are per root, so a few documents already hold many of them. */+const MAX_PERSISTED_REPLY_FEEDS = 200;+/** Deep-link targets only: a pinned root or reply. */+const MAX_PERSISTED_DETAILS = 20;++/** Root-comment threads of one document, per scope (`threadFeedMap`). */+export const documentCommentThreadResource = definePagedReplica<+ DocumentCommentThreadsParams,+ DocumentCommentThread,+ string+>({+ key: documentCommentThreadsKey,+ name: 'documentCommentThreads',+ paging: {+ direction: 'forward',+ getId: (thread) => thread.root.id,+ mode: 'cursor',+ // A reload repaints the head page the server would return, never a stale tail.+ persist: { pages: 1 },+ },+ // Two scopes per document.+ persist: { maxEntries: MAX_PERSISTED_DOCUMENTS * 2 },+ storage: 'indexedDB',+ version: 1,+});++/** Replies of one root comment (`replyFeedMap`). */+export const documentCommentReplyResource = definePagedReplica<+ DocumentCommentRepliesParams,+ DocumentCommentItem,+ string+>({+ key: ({ rootCommentId }) => rootCommentId,+ name: 'documentCommentReplies',+ paging: {+ direction: 'forward',+ getId: (comment) => comment.id,+ mode: 'cursor',+ persist: { pages: 1 },+ },+ persist: { maxEntries: MAX_PERSISTED_REPLY_FEEDS },+ storage: 'indexedDB',+ version: 1,+});++/** Per-document comment count (`summaryMap[documentId]`). */+export const documentCommentSummaryResource = defineReplica<string, DocumentCommentSummary>({+ key: (documentId) => documentId,+ name: 'documentCommentSummary',+ persist: { maxEntries: MAX_PERSISTED_DOCUMENTS },+ storage: 'indexedDB',+ version: 1,+});++/** Every anchored root of a document, for the body highlights (`anchorListMap[documentId]`). */+export const documentCommentAnchorResource = defineReplica<string, DocumentCommentAnchorList>({+ key: (documentId) => documentId,+ name: 'documentCommentAnchors',+ persist: { maxEntries: MAX_PERSISTED_DOCUMENTS },+ storage: 'indexedDB',+ version: 1,+});++/** One comment by id, for a deep-link target (`detailMap[commentId]`). */+export const documentCommentDetailResource = defineReplica<string, DocumentCommentDetail>({+ key: (commentId) => commentId,+ name: 'documentCommentDetail',+ persist: { maxEntries: MAX_PERSISTED_DETAILS },+ storage: 'indexedDB',+ version: 1,+});++/** Like count, likers and the reader's own like (`likeSummaryMap[documentId]`). */+export const documentLikeSummaryResource = defineReplica<string, DocumentLikeSummary>({+ key: (documentId) => documentId,+ name: 'documentLikeSummary',+ persist: { maxEntries: MAX_PERSISTED_DOCUMENTS },+ storage: 'indexedDB',+ version: 1,+});diff --git a/src/store/documentComment/reducers.ts b/src/store/documentComment/reducers.tsnew file mode 100644index 00000000000..615415f27ea--- /dev/null+++ b/src/store/documentComment/reducers.ts@@ -0,0 +1,63 @@+import type { DocumentCommentItem, DocumentCommentThread } from '@lobechat/types';++/**+ * Pure item-level patches of the comment feeds. They run inside replica+ * optimistic overlays and confirms, so each returns the same array when+ * nothing matched β an overlay that changes nothing must not repaint.+ */++const mapChanged = <T>(items: T[], fn: (item: T) => T): T[] => {+ let changed = false;+ const next = items.map((item) => {+ const mapped = fn(item);+ if (mapped !== item) changed = true;+ return mapped;+ });+ return changed ? next : items;+};++/** Append a new root at the end (feeds are oldest-first); a root already there is kept. */+export const appendThread = (+ threads: DocumentCommentThread[],+ comment: DocumentCommentItem,+): DocumentCommentThread[] =>+ threads.some(+ ({ root }) =>+ root.id === comment.id || (comment.clientId && root.clientId === comment.clientId),+ )+ ? threads+ : [...threads, { replyCount: 0, root: comment }];++/** Swap the root matching `comment` by id. */+export const replaceThreadRoot = (threads: DocumentCommentThread[], comment: DocumentCommentItem) =>+ mapChanged(threads, (thread) =>+ thread.root.id === comment.id ? { ...thread, root: comment } : thread,+ );++/**+ * Raise a root's reply count to at least `min`. Unlike a `+1`, this is+ * idempotent across a rebase: a server count that already includes the reply+ * (an event revalidated it while the create was in flight) is left as is.+ */+export const raiseThreadReplyCount = (+ threads: DocumentCommentThread[],+ rootCommentId: string,+ min: number,+) =>+ mapChanged(threads, (thread) =>+ thread.root.id === rootCommentId && thread.replyCount < min+ ? { ...thread, replyCount: min }+ : thread,+ );++/** Append a new reply at the end; a reply already there (same id or client id) is kept. */+export const appendReply = (replies: DocumentCommentItem[], comment: DocumentCommentItem) =>+ replies.some(+ (item) => item.id === comment.id || (comment.clientId && item.clientId === comment.clientId),+ )+ ? replies+ : [...replies, comment];++/** Swap the reply matching `comment` by id. */+export const replaceReply = (replies: DocumentCommentItem[], comment: DocumentCommentItem) =>+ mapChanged(replies, (item) => (item.id === comment.id ? comment : item));diff --git a/src/store/documentComment/replica.test.ts b/src/store/documentComment/replica.test.tsnew file mode 100644index 00000000000..fe51ef5ed57--- /dev/null+++ b/src/store/documentComment/replica.test.ts@@ -0,0 +1,789 @@+/**+ * @vitest-environment happy-dom+ *+ * `documentComment` is a `@lobechat/replica`-backed store. The root feeds, the+ * reply feeds, the comment summary, the anchor list, deep-link details and the+ * like summary paint their persisted row before the network answers and are+ * confirmed (and persisted) by the response β instead of the SWR caches they+ * replaced, which painted a skeleton on every cold start.+ */+import { randomUUID } from 'node:crypto';++import type {+ DocumentCommentItem,+ DocumentCommentThread,+ DocumentLikeSummary,+} 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 { documentCommentService } from '@/services/documentComment';+import { documentLikeService } from '@/services/documentLike';++import { documentCommentActions } from './action';+import { initialState } from './initialState';+import {+ documentCommentDetailResource,+ documentCommentReplyResource,+ documentCommentSummaryResource,+ documentCommentThreadResource,+ documentCommentThreadsKey,+ documentLikeSummaryResource,+} from './projection';+import { useDocumentCommentStore } from './store';++const DOCUMENT_ID = 'document-1';+const ANCHORED = { documentId: DOCUMENT_ID, scope: 'anchored' } as const;+const LIST = { documentId: DOCUMENT_ID, scope: 'document' } as const;+const ANCHORED_KEY = documentCommentThreadsKey(ANCHORED);+const LIST_KEY = documentCommentThreadsKey(LIST);++const anchor = { end: 5, quote: 'hello', start: 0 };++const comment = (+ id: string,+ overrides: Partial<DocumentCommentItem> = {},+): DocumentCommentItem => ({+ author: { avatar: null, fullName: 'Lin', id: 'user-1', status: 'active', username: 'lin' },+ authorUserId: 'user-1',+ canDelete: true,+ canEdit: true,+ clientId: `client-${id}`,+ content: id,+ createdAt: new Date('2026-10-01T00:00:00.000Z'),+ deletedAt: null,+ documentId: DOCUMENT_ID,+ editorData: null,+ id,+ parentCommentId: null,+ replyTo: null,+ replyToCommentId: null,+ selectionAnchor: null,+ updatedAt: new Date('2026-10-01T00:00:00.000Z'),+ workspaceId: 'workspace-1',+ ...overrides,+});++const thread = (id: string, replyCount = 0, overrides?: Partial<DocumentCommentItem>) =>+ ({ replyCount, root: comment(id, overrides) }) satisfies DocumentCommentThread;++const rootIds = (feed?: { items: DocumentCommentThread[] }) =>+ feed?.items.map(({ root }) => root.id);++/** Never-resolving fetch: the first frame can only come from storage. */+const pending = () => new Promise<never>(() => {});++const deferred = <T>() => {+ let resolve!: (value: T) => void;+ let reject!: (error: unknown) => void;+ const promise = new Promise<T>((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, reject, resolve };+};++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,+ );++const state = () => useDocumentCommentStore.getState();++describe('documentComment replicas', () => {+ const scopes = new Set<string>();+ let scope = '';++ beforeEach(() => {+ scope = `doc-comment-user-${randomUUID()}:workspace-1`;+ scopes.add(scope);+ vi.spyOn(cacheScope, 'get').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'use').mockImplementation(() => scope);+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(true);+ act(() => useDocumentCommentStore.setState(initialState));+ });++ afterEach(async () => {+ cleanup();+ await Promise.all(+ [...scopes].flatMap((value) => [+ documentCommentThreadResource.storage!.remove({+ queryKey: documentCommentThreadResource.storageKey(ANCHORED),+ scope: value,+ }),+ documentCommentThreadResource.storage!.remove({+ queryKey: documentCommentThreadResource.storageKey(LIST),+ scope: value,+ }),+ documentCommentReplyResource.storage!.remove({ queryKey: 'root-1', scope: value }),+ documentCommentSummaryResource.storage!.remove({ queryKey: DOCUMENT_ID, scope: value }),+ documentCommentDetailResource.storage!.remove({ queryKey: 'comment-1', scope: value }),+ documentLikeSummaryResource.storage!.remove({ queryKey: DOCUMENT_ID, scope: value }),+ ]),+ );+ scopes.clear();+ vi.restoreAllMocks();+ });++ describe('reads', () => {+ it('paints the persisted thread feed and summary before the network answers', async () => {+ await documentCommentThreadResource.storage!.set(+ { queryKey: documentCommentThreadResource.storageKey(LIST), scope },+ {+ data: { currentPage: 0, hasMore: false, items: [thread('cached-1', 2)], pageSize: 20 },+ updatedAt: 1,+ },+ );+ await documentCommentSummaryResource.storage!.set(+ { queryKey: DOCUMENT_ID, scope },+ { data: { total: 3 }, updatedAt: 1 },+ );+ vi.spyOn(documentCommentService, 'listThreads').mockImplementation(pending);+ vi.spyOn(documentCommentService, 'summary').mockImplementation(pending);++ renderHook(+ () => {+ documentCommentActions.useFetchThreads(LIST);+ documentCommentActions.useFetchSummary(DOCUMENT_ID);+ },+ { wrapper },+ );++ await waitFor(() => expect(rootIds(state().threadFeedMap[LIST_KEY])).toEqual(['cached-1']));+ await waitFor(() => expect(state().summaryMap[DOCUMENT_ID]).toEqual({ total: 3 }));+ });++ it('keeps each scope to its own subset and persists the confirmed head page', async () => {+ const listThreads = vi.spyOn(documentCommentService, 'listThreads').mockResolvedValue({+ // A server predating `anchored` answers with a mixed page.+ items: [thread('a', 0, { selectionAnchor: anchor }), thread('b')],+ nextCursor: null,+ });++ renderHook(() => documentCommentActions.useFetchThreads(ANCHORED), { wrapper });++ await waitFor(() => expect(rootIds(state().threadFeedMap[ANCHORED_KEY])).toEqual(['a']));+ expect(listThreads).toHaveBeenCalledWith({+ anchored: true,+ cursor: undefined,+ documentId: DOCUMENT_ID,+ limit: 50,+ });+ await waitFor(async () => {+ const row = await documentCommentThreadResource.storage!.get({+ queryKey: documentCommentThreadResource.storageKey(ANCHORED),+ scope,+ });+ expect(rootIds(row?.data as { items: DocumentCommentThread[] })).toEqual(['a']);+ });+ });++ it('pages a confirmed feed through the engine cursor', async () => {+ const listThreads = vi+ .spyOn(documentCommentService, 'listThreads')+ .mockResolvedValueOnce({ items: [thread('a')], nextCursor: 'c1' })+ .mockResolvedValueOnce({ items: [thread('b')], nextCursor: null });++ renderHook(() => documentCommentActions.useFetchThreads(LIST), { wrapper });+ await waitFor(() => expect(rootIds(state().threadFeedMap[LIST_KEY])).toEqual(['a']));++ await act(() => documentCommentActions.loadMoreThreads(LIST));++ expect(rootIds(state().threadFeedMap[LIST_KEY])).toEqual(['a', 'b']);+ expect(listThreads).toHaveBeenLastCalledWith({+ anchored: false,+ cursor: 'c1',+ documentId: DOCUMENT_ID,+ limit: 20,+ });+ });++ it('drops a persisted deep-link target the server reports gone', async () => {+ await documentCommentDetailResource.storage!.set(+ { queryKey: 'comment-1', scope },+ { data: { ...comment('comment-1'), replyCount: 0 }, updatedAt: 1 },+ );+ vi.spyOn(documentCommentService, 'get').mockRejectedValue({ data: { code: 'NOT_FOUND' } });++ renderHook(() => documentCommentActions.useFetchDetail('comment-1'), { wrapper });++ await waitFor(async () => {+ const row = await documentCommentDetailResource.storage!.get({+ queryKey: 'comment-1',+ scope,+ });+ expect(row).toBeUndefined();+ });+ expect(state().detailMap['comment-1']).toBeUndefined();+ });++ it('re-reads the document feeds, summary and anchors on a comment event', async () => {+ const listThreads = vi+ .spyOn(documentCommentService, 'listThreads')+ .mockResolvedValue({ items: [], nextCursor: null });+ const summary = vi.spyOn(documentCommentService, 'summary').mockResolvedValue({ total: 0 });+ vi.spyOn(documentCommentService, 'listAnchors').mockResolvedValue({ items: [] });++ renderHook(+ () => {+ documentCommentActions.useFetchThreads(LIST);+ documentCommentActions.useFetchSummary(DOCUMENT_ID);+ documentCommentActions.useFetchAnchors(DOCUMENT_ID);+ },+ { wrapper },+ );+ await waitFor(() => expect(state().threadFeedMap[LIST_KEY]).toBeDefined());+ const before = listThreads.mock.calls.length;+ summary.mockResolvedValue({ total: 4 });++ await act(() =>+ documentCommentActions.revalidateForCommentEvent({ documentId: DOCUMENT_ID }),+ );++ await waitFor(() => expect(state().summaryMap[DOCUMENT_ID]).toEqual({ total: 4 }));+ expect(listThreads.mock.calls.length).toBeGreaterThan(before);+ });+ });++ describe('writes', () => {+ const seed = () =>+ act(() => {+ useDocumentCommentStore.setState({+ ...initialState,+ threadFeedMap: {+ [LIST_KEY]: {+ currentPage: 0,+ hasMore: false,+ items: [thread('root-1', 1)],+ pageSize: 20,+ },+ },+ replyFeedMap: {+ 'root-1': {+ currentPage: 0,+ hasMore: false,+ items: [comment('reply-1', { parentCommentId: 'root-1' })],+ pageSize: 20,+ total: 1,+ },+ },+ summaryMap: { [DOCUMENT_ID]: { total: 2 } },+ });+ });++ it('shows a new root at once and settles it on the server row', async () => {+ seed();+ const request = deferred<{ comment: DocumentCommentItem; isDuplicate: boolean }>();+ vi.spyOn(documentCommentService, 'create').mockReturnValue(request.promise as never);+ const optimisticComment = comment('optimistic:new', { clientId: 'new' });++ let done!: Promise<unknown>;+ act(() => {+ done = documentCommentActions.createRootComment({+ input: { clientId: 'new', content: 'new', documentId: DOCUMENT_ID },+ optimisticComment,+ });+ });++ expect(rootIds(state().threadFeedMap[LIST_KEY])).toEqual(['root-1', 'optimistic:new']);+ expect(state().summaryMap[DOCUMENT_ID]).toEqual({ total: 3 });++ await act(async () => {+ request.resolve({ comment: comment('root-2', { clientId: 'new' }), isDuplicate: false });+ await done;+ });++ expect(rootIds(state().threadFeedMap[LIST_KEY])).toEqual(['root-1', 'root-2']);+ expect(state().summaryMap[DOCUMENT_ID]).toEqual({ total: 3 });+ });++ it('rolls a failed root back out of the feed and the count', async () => {+ seed();+ vi.spyOn(documentCommentService, 'create').mockRejectedValue(new Error('offline'));++ await act(async () => {+ await expect(+ documentCommentActions.createRootComment({+ input: { clientId: 'new', content: 'new', documentId: DOCUMENT_ID },+ optimisticComment: comment('optimistic:new', { clientId: 'new' }),+ }),+ ).rejects.toThrow('offline');+ });++ expect(rootIds(state().threadFeedMap[LIST_KEY])).toEqual(['root-1']);+ expect(state().summaryMap[DOCUMENT_ID]).toEqual({ total: 2 });+ });++ it('moves a reply, its root reply count and the summary together, and rolls them back together', async () => {+ seed();+ const create = vi+ .spyOn(documentCommentService, 'create')+ .mockResolvedValueOnce({+ comment: comment('reply-2', { clientId: 'r2', parentCommentId: 'root-1' }),+ isDuplicate: false,+ })+ .mockRejectedValueOnce(new Error('offline'));++ await act(() =>+ documentCommentActions.createReply({+ input: {+ clientId: 'r2',+ content: 'r2',+ documentId: DOCUMENT_ID,+ parentCommentId: 'root-1',+ },+ optimisticComment: comment('optimistic:r2', {+ clientId: 'r2',+ parentCommentId: 'root-1',+ }),+ rootCommentId: 'root-1',+ }),+ );++ expect(state().replyFeedMap['root-1']?.items.map(({ id }) => id)).toEqual([+ 'reply-1',+ 'reply-2',+ ]);+ expect(state().replyFeedMap['root-1']?.total).toBe(2);+ expect(state().threadFeedMap[LIST_KEY]?.items[0].replyCount).toBe(2);+ expect(state().summaryMap[DOCUMENT_ID]).toEqual({ total: 3 });++ await act(async () => {+ await expect(+ documentCommentActions.createReply({+ input: {+ clientId: 'r3',+ content: 'r3',+ documentId: DOCUMENT_ID,+ parentCommentId: 'root-1',+ },+ optimisticComment: comment('optimistic:r3', {+ clientId: 'r3',+ parentCommentId: 'root-1',+ }),+ rootCommentId: 'root-1',+ }),+ ).rejects.toThrow('offline');+ });++ expect(create).toHaveBeenCalledTimes(2);+ expect(state().replyFeedMap['root-1']?.items).toHaveLength(2);+ expect(state().threadFeedMap[LIST_KEY]?.items[0].replyCount).toBe(2);+ expect(state().summaryMap[DOCUMENT_ID]).toEqual({ total: 3 });+ });++ it('re-reads a root feed that had no view when the root was sent', async () => {+ const created = comment('root-2', { clientId: 'new' });+ const listThreads = vi+ .spyOn(documentCommentService, 'listThreads')+ .mockRejectedValueOnce(new Error('offline'))+ .mockResolvedValue({ items: [{ replyCount: 0, root: created }], nextCursor: null });+ vi.spyOn(documentCommentService, 'create').mockResolvedValue({+ comment: created,+ isDuplicate: false,+ });++ renderHook(() => documentCommentActions.useFetchThreads(LIST), { wrapper });+ await waitFor(() => expect(listThreads).toHaveBeenCalledTimes(1));+ expect(state().threadFeedMap[LIST_KEY]).toBeUndefined();++ await act(() =>+ documentCommentActions.createRootComment({+ input: { clientId: 'new', content: 'new', documentId: DOCUMENT_ID },+ optimisticComment: comment('optimistic:new', { clientId: 'new' }),+ }),+ );++ await waitFor(() => expect(rootIds(state().threadFeedMap[LIST_KEY])).toEqual(['root-2']));+ });++ it('re-reads a reply feed that had no view when the reply was sent', async () => {+ const created = comment('reply-2', { clientId: 'r2', parentCommentId: 'root-1' });+ const listReplies = vi+ .spyOn(documentCommentService, 'listReplies')+ .mockRejectedValueOnce(new Error('offline'))+ .mockResolvedValue({ hasMore: false, items: [created], total: 1 } as never);+ vi.spyOn(documentCommentService, 'create').mockResolvedValue({+ comment: created,+ isDuplicate: false,+ });++ renderHook(() => documentCommentActions.useFetchReplies('root-1'), { wrapper });+ await waitFor(() => expect(listReplies).toHaveBeenCalledTimes(1));+ expect(state().replyFeedMap['root-1']).toBeUndefined();++ await act(() =>+ documentCommentActions.createReply({+ input: {+ clientId: 'r2',+ content: 'r2',+ documentId: DOCUMENT_ID,+ parentCommentId: 'root-1',+ },+ optimisticComment: comment('optimistic:r2', {+ clientId: 'r2',+ parentCommentId: 'root-1',+ }),+ rootCommentId: 'root-1',+ }),+ );++ await waitFor(() =>+ expect(state().replyFeedMap['root-1']?.items.map(({ id }) => id)).toEqual(['reply-2']),+ );+ });++ it('rolls a failed edit back on every painted copy', async () => {+ seed();+ act(() =>+ useDocumentCommentStore.setState({+ detailMap: { 'root-1': { ...comment('root-1'), replyCount: 1 } },+ }),+ );+ const request = deferred<DocumentCommentItem>();+ vi.spyOn(documentCommentService, 'update').mockReturnValue(request.promise as never);++ let done!: Promise<unknown>;+ act(() => {+ done = documentCommentActions.updateComment(comment('root-1'), {+ content: 'edited',+ editorData: null,+ });+ });+ expect(state().threadFeedMap[LIST_KEY]?.items[0].root.content).toBe('edited');+ expect(state().detailMap['root-1']?.content).toBe('edited');++ await act(async () => {+ request.reject(new Error('offline'));+ await done.catch(() => undefined);+ });++ expect(state().threadFeedMap[LIST_KEY]?.items[0].root.content).toBe('root-1');+ expect(state().detailMap['root-1']).toMatchObject({ content: 'root-1', replyCount: 1 });+ });+ });++ describe('counters rebased mid-create', () => {+ // The creator window gets its own `document.commentsChanged` fanout, so an+ // event revalidation can land the server count that already includes the+ // new comment while `create()` is still in flight.+ it('does not count a new root twice when the summary is re-read mid-create', async () => {+ vi.spyOn(documentCommentService, 'listThreads').mockResolvedValue({+ items: [thread('root-1')],+ nextCursor: null,+ });+ const summary = vi.spyOn(documentCommentService, 'summary').mockResolvedValue({ total: 2 });+ renderHook(+ () => {+ documentCommentActions.useFetchThreads(LIST);+ documentCommentActions.useFetchSummary(DOCUMENT_ID);+ },+ { wrapper },+ );+ await waitFor(() => expect(state().summaryMap[DOCUMENT_ID]).toEqual({ total: 2 }));+ await waitFor(() => expect(state().threadFeedMap[LIST_KEY]).toBeDefined());++ const request = deferred<{ comment: DocumentCommentItem; isDuplicate: boolean }>();+ vi.spyOn(documentCommentService, 'create').mockReturnValue(request.promise as never);+ let done!: Promise<unknown>;+ act(() => {+ done = documentCommentActions.createRootComment({+ input: { clientId: 'new', content: 'new', documentId: DOCUMENT_ID },+ optimisticComment: comment('optimistic:new', { clientId: 'new' }),+ });+ });+ expect(state().summaryMap[DOCUMENT_ID]).toEqual({ total: 3 });++ // The server already counts the new root.+ summary.mockResolvedValue({ total: 3 });+ await act(() => documentCommentActions.revalidateSummary(DOCUMENT_ID));+ expect(state().summaryMap[DOCUMENT_ID]).toEqual({ total: 3 });++ await act(async () => {+ request.resolve({ comment: comment('root-2', { clientId: 'new' }), isDuplicate: false });+ await done;+ });+ await act(() => new Promise((resolve) => setTimeout(resolve, 0)));+ expect(state().summaryMap[DOCUMENT_ID]).toEqual({ total: 3 });+ });++ it('does not count a new reply twice when the thread and summary are re-read mid-create', async () => {+ const listThreads = vi.spyOn(documentCommentService, 'listThreads').mockResolvedValue({+ items: [thread('root-1', 1)],+ nextCursor: null,+ });+ const summary = vi.spyOn(documentCommentService, 'summary').mockResolvedValue({ total: 2 });+ renderHook(+ () => {+ documentCommentActions.useFetchThreads(LIST);+ documentCommentActions.useFetchSummary(DOCUMENT_ID);+ },+ { wrapper },+ );+ await waitFor(() => expect(state().threadFeedMap[LIST_KEY]?.items[0].replyCount).toBe(1));+ await waitFor(() => expect(state().summaryMap[DOCUMENT_ID]).toEqual({ total: 2 }));++ const request = deferred<{ comment: DocumentCommentItem; isDuplicate: boolean }>();+ vi.spyOn(documentCommentService, 'create').mockReturnValue(request.promise as never);+ vi.spyOn(documentCommentService, 'listReplies').mockResolvedValue({+ items: [],+ nextCursor: null,+ });+ let done!: Promise<unknown>;+ act(() => {+ done = documentCommentActions.createReply({+ input: {+ clientId: 'r2',+ content: 'r2',+ documentId: DOCUMENT_ID,+ parentCommentId: 'root-1',+ },+ optimisticComment: comment('optimistic:r2', {+ clientId: 'r2',+ parentCommentId: 'root-1',+ }),+ rootCommentId: 'root-1',+ });+ });+ expect(state().threadFeedMap[LIST_KEY]?.items[0].replyCount).toBe(2);++ // The server already counts the new reply.+ listThreads.mockResolvedValue({ items: [thread('root-1', 2)], nextCursor: null });+ summary.mockResolvedValue({ total: 3 });+ await act(() =>+ Promise.all([+ documentCommentActions.revalidateThreads(LIST),+ documentCommentActions.revalidateSummary(DOCUMENT_ID),+ ]),+ );+ expect(state().threadFeedMap[LIST_KEY]?.items[0].replyCount).toBe(2);+ expect(state().summaryMap[DOCUMENT_ID]).toEqual({ total: 3 });++ await act(async () => {+ request.resolve({+ comment: comment('reply-2', { clientId: 'r2', parentCommentId: 'root-1' }),+ isDuplicate: false,+ });+ await done;+ });+ await act(() => new Promise((resolve) => setTimeout(resolve, 0)));+ expect(state().threadFeedMap[LIST_KEY]?.items[0].replyCount).toBe(2);+ expect(state().summaryMap[DOCUMENT_ID]).toEqual({ total: 3 });+ });++ it('re-reads the reply counts when an overlapping reply fails', async () => {+ const listThreads = vi.spyOn(documentCommentService, 'listThreads').mockResolvedValue({+ items: [thread('root-1', 1)],+ nextCursor: null,+ });+ const summary = vi.spyOn(documentCommentService, 'summary').mockResolvedValue({ total: 2 });+ renderHook(+ () => {+ documentCommentActions.useFetchThreads(LIST);+ documentCommentActions.useFetchSummary(DOCUMENT_ID);+ },+ { wrapper },+ );+ await waitFor(() => expect(state().threadFeedMap[LIST_KEY]?.items[0].replyCount).toBe(1));+ await waitFor(() => expect(state().summaryMap[DOCUMENT_ID]).toEqual({ total: 2 }));++ const first = deferred<{ comment: DocumentCommentItem; isDuplicate: boolean }>();+ const second = deferred<{ comment: DocumentCommentItem; isDuplicate: boolean }>();+ vi.spyOn(documentCommentService, 'create')+ .mockReturnValueOnce(first.promise as never)+ .mockReturnValueOnce(second.promise as never);+ vi.spyOn(documentCommentService, 'listReplies').mockResolvedValue({+ items: [],+ nextCursor: null,+ });+ const reply = (clientId: string) =>+ documentCommentActions.createReply({+ input: {+ clientId,+ content: clientId,+ documentId: DOCUMENT_ID,+ parentCommentId: 'root-1',+ },+ optimisticComment: comment(`optimistic:${clientId}`, {+ clientId,+ parentCommentId: 'root-1',+ }),+ rootCommentId: 'root-1',+ });++ let firstDone!: Promise<unknown>;+ let secondDone!: Promise<unknown>;+ act(() => {+ firstDone = reply('r2').catch(() => undefined);+ secondDone = reply('r3');+ });+ expect(state().threadFeedMap[LIST_KEY]?.items[0].replyCount).toBe(3);++ // Only the second reply lands on the server.+ listThreads.mockResolvedValue({ items: [thread('root-1', 2)], nextCursor: null });+ summary.mockResolvedValue({ total: 3 });+ await act(async () => {+ first.reject(new Error('offline'));+ await firstDone;+ second.resolve({+ comment: comment('reply-3', { clientId: 'r3', parentCommentId: 'root-1' }),+ isDuplicate: false,+ });+ await secondDone;+ });++ await waitFor(() => expect(state().threadFeedMap[LIST_KEY]?.items[0].replyCount).toBe(2));+ await waitFor(() => expect(state().summaryMap[DOCUMENT_ID]).toEqual({ total: 3 }));+ });++ it('still reconciles overlapping replies after a duplicate reply', async () => {+ const listThreads = vi.spyOn(documentCommentService, 'listThreads').mockResolvedValue({+ items: [thread('root-1', 1)],+ nextCursor: null,+ });+ const summary = vi.spyOn(documentCommentService, 'summary').mockResolvedValue({ total: 2 });+ vi.spyOn(documentCommentService, 'listAnchors').mockResolvedValue({ items: [] });+ vi.spyOn(documentCommentService, 'listReplies').mockResolvedValue({+ items: [],+ nextCursor: null,+ });+ renderHook(+ () => {+ documentCommentActions.useFetchThreads(LIST);+ documentCommentActions.useFetchSummary(DOCUMENT_ID);+ },+ { wrapper },+ );+ await waitFor(() => expect(state().threadFeedMap[LIST_KEY]?.items[0].replyCount).toBe(1));+ await waitFor(() => expect(state().summaryMap[DOCUMENT_ID]).toEqual({ total: 2 }));++ const reply = (clientId: string) =>+ documentCommentActions.createReply({+ input: {+ clientId,+ content: clientId,+ documentId: DOCUMENT_ID,+ parentCommentId: 'root-1',+ },+ optimisticComment: comment(`optimistic:${clientId}`, {+ clientId,+ parentCommentId: 'root-1',+ }),+ rootCommentId: 'root-1',+ });++ // A retried submit the server already had.+ const create = vi.spyOn(documentCommentService, 'create').mockResolvedValueOnce({+ comment: comment('reply-1', { clientId: 'r1', parentCommentId: 'root-1' }),+ isDuplicate: true,+ });+ await act(() => reply('r1'));+ await waitFor(() => expect(state().threadFeedMap[LIST_KEY]?.items[0].replyCount).toBe(1));++ const first = deferred<{ comment: DocumentCommentItem; isDuplicate: boolean }>();+ const second = deferred<{ comment: DocumentCommentItem; isDuplicate: boolean }>();+ create+ .mockReturnValueOnce(first.promise as never)+ .mockReturnValueOnce(second.promise as never);+ let firstDone!: Promise<unknown>;+ let secondDone!: Promise<unknown>;+ act(() => {+ firstDone = reply('r2').catch(() => undefined);+ secondDone = reply('r3');+ });+ expect(state().threadFeedMap[LIST_KEY]?.items[0].replyCount).toBe(3);++ // Only r3 lands on the server.+ listThreads.mockResolvedValue({ items: [thread('root-1', 2)], nextCursor: null });+ summary.mockResolvedValue({ total: 3 });+ await act(async () => {+ first.reject(new Error('offline'));+ await firstDone;+ second.resolve({+ comment: comment('reply-3', { clientId: 'r3', parentCommentId: 'root-1' }),+ isDuplicate: false,+ });+ await secondDone;+ });++ await waitFor(() => expect(state().threadFeedMap[LIST_KEY]?.items[0].replyCount).toBe(2));+ });+ });++ describe('likes', () => {+ const summary: DocumentLikeSummary = { liked: true, likers: [], total: 7 };++ it('paints the persisted like summary before the network answers', async () => {+ await documentLikeSummaryResource.storage!.set(+ { queryKey: DOCUMENT_ID, scope },+ { data: summary, updatedAt: 1 },+ );+ vi.spyOn(documentLikeService, 'summary').mockImplementation(pending);++ renderHook(() => documentCommentActions.useFetchLikeSummary(DOCUMENT_ID), { wrapper });++ await waitFor(() => expect(state().likeSummaryMap[DOCUMENT_ID]).toEqual(summary));+ });++ it('keeps an optimistic toggle in memory and persists only the server answer', async () => {+ act(() =>+ useDocumentCommentStore.setState({+ likeSummaryMap: { [DOCUMENT_ID]: { liked: false, likers: [], total: 6 } },+ }),+ );++ act(() => {+ documentCommentActions.applyLikeSummary(DOCUMENT_ID, (current) => ({+ ...current,+ liked: true,+ total: current.total + 1,+ }));+ });+ expect(state().likeSummaryMap[DOCUMENT_ID]).toMatchObject({ liked: true, total: 7 });++ act(() => {+ documentCommentActions.beginLikeSettle(DOCUMENT_ID).confirm(summary);+ });+ await waitFor(async () => {+ const row = await documentLikeSummaryResource.storage!.get({+ queryKey: DOCUMENT_ID,+ scope,+ });+ expect(row?.data).toEqual(summary);+ });+ });+ it('drops a like answer that settles after an account / workspace switch', async () => {+ const previous = scope;+ const settle = documentCommentActions.beginLikeSettle(DOCUMENT_ID);++ // The identity changes while the like request is in flight.+ scope = `doc-comment-user-${randomUUID()}:workspace-2`;+ scopes.add(scope);+ const refreshed = vi.spyOn(documentLikeService, 'summary');++ act(() => settle.confirm(summary));+ await expect(settle.refresh()).rejects.toThrow();++ expect(state().likeSummaryMap[DOCUMENT_ID]).toBeUndefined();+ expect(refreshed).not.toHaveBeenCalled();+ await new Promise((resolve) => setTimeout(resolve, 20));+ const row = await documentLikeSummaryResource.storage!.get({ queryKey: DOCUMENT_ID, scope });+ expect(row).toBeUndefined();+ expect(previous).not.toBe(scope);+ });+ });+});diff --git a/src/store/documentComment/selectors.ts b/src/store/documentComment/selectors.tsnew file mode 100644index 00000000000..f599813fd15--- /dev/null+++ b/src/store/documentComment/selectors.ts@@ -0,0 +1,31 @@+import type { DocumentCommentState } from './initialState';+import { documentCommentThreadsKey, type DocumentCommentThreadsParams } from './projection';++const anchorList = (documentId: string | null | undefined) => (s: DocumentCommentState) =>+ documentId ? s.anchorListMap[documentId] : undefined;++const detail = (commentId: string | null | undefined) => (s: DocumentCommentState) =>+ commentId ? s.detailMap[commentId] : undefined;++const likeSummary = (documentId: string | null | undefined) => (s: DocumentCommentState) =>+ documentId ? s.likeSummaryMap[documentId] : undefined;++const replyFeed = (rootCommentId: string | null | undefined) => (s: DocumentCommentState) =>+ rootCommentId ? s.replyFeedMap[rootCommentId] : undefined;++const summary = (documentId: string | null | undefined) => (s: DocumentCommentState) =>+ documentId ? s.summaryMap[documentId] : undefined;++const threadFeed =+ (params: DocumentCommentThreadsParams | null | undefined) => (s: DocumentCommentState) =>+ params ? s.threadFeedMap[documentCommentThreadsKey(params)] : undefined;++/** Every read returns the replica view; `undefined` means nothing is loaded for it yet. */+export const documentCommentSelectors = {+ anchorList,+ detail,+ likeSummary,+ replyFeed,+ summary,+ threadFeed,+};diff --git a/src/store/documentComment/store.ts b/src/store/documentComment/store.tsnew file mode 100644index 00000000000..f3e927c77a6--- /dev/null+++ b/src/store/documentComment/store.ts@@ -0,0 +1,15 @@+import { shallow } from 'zustand/shallow';+import { createWithEqualityFn } from 'zustand/traditional';++import { createDevtools } from '../middleware/createDevtools';+import { expose } from '../middleware/expose';+import { type DocumentCommentState, initialState } from './initialState';++const devtools = createDevtools('documentComment');++export const useDocumentCommentStore = createWithEqualityFn<DocumentCommentState>()(+ devtools(() => initialState),+ shallow,+);++expose('documentComment', useDocumentCommentStore);diff --git a/src/store/utils/userDataStores.ts b/src/store/utils/userDataStores.tsindex a3bdb0a9819..6b9f3c87ec7 100644--- a/src/store/utils/userDataStores.ts+++ b/src/store/utils/userDataStores.ts@@ -9,6 +9,7 @@ import { useChatStore } from '@/store/chat';import { resetGatewayMuxRegistry } from '@/store/chat/slices/agentRun/actions/transports/gateway/muxRegistry';import { useDiscoverStore } from '@/store/discover';import { useDocumentStore } from '@/store/document';+import { documentCommentActions } from '@/store/documentComment';import { useEvalStore } from '@/store/eval';import { expertiseActions } from '@/store/expertise';import { useFileStore } from '@/store/file';@@ -65,6 +66,7 @@ const resetableActions: ResetableStore[] = [expertiseActions,integrationActions,messengerActions,+ documentCommentActions,pageActions,projectFileActions,resourcePermissionActions,